问:
Purpose of throttle with parameter Func<TSource, IObservable<TThrottle>> throttleDurationSelector
All the documentation I found about rx.net throttling does not cover the overload with a parameter Func<TSource, IObservable<TThrottle>> throttleDurationSelector. So all I have available are the XML-comments. This suggests, that throttleDurationSelector is called on every new element in the source sequence. The expected return value would be a IObservable<TThrottle>. (My understanding) This enables the possibility to change the throttle-delay on every new element. But, this understanding does not match the runtime experience I discover.

```<code>var s = new Subject<string>();
s.Throttle(_ => Observable.Return(TimeSpan.FromMilliseconds(500))) // for simplicity of this demo, always return the same delay
    .Subscribe(_ => Console.WriteLine($"{DateTime.Now}.{DateTime.Now.Millisecond} event {_}"));

for (int i = 0; i < 5; i++)
    s.OnNext("a");

Thread.Sleep(1000);

for (int i = 0; i < 5; i++)
    s.OnNext("b");

Thread.Sleep(1000);
</code>```

According to the previously mentioned understanding (which is obviously wrong), I'd have expected the following output.

```<code>10.02.2022 11:47:54.386 event a
10.02.2022 11:47:55.388 event b
</code>```

Instead this output is generated. It seems that there is no throttling applied at all.

```<code>10.02.2022 11:46:49.431 event a
10.02.2022 11:46:49.432 event a
10.02.2022 11:46:49.432 event a
10.02.2022 11:46:49.432 event a
10.02.2022 11:46:49.432 event a
10.02.2022 11:46:50.448 event b
10.02.2022 11:46:50.448 event b
10.02.2022 11:46:50.448 event b
10.02.2022 11:46:50.448 event b
10.02.2022 11:46:50.449 event b
</code>```

What is the purpose of this overload, if not dynamically changing the throttle-delay (which is what I need)?

Also, why the 'complicated' syntax of Func<TSource, IObservable<TThrottle>> throttleDurationSelector where a simpler parameter Func<TSource, TThrottle> throttleDurationSelector would be good enough?

答:
We are talking about this overload of the Throttle operator:

```<code>public static IObservable<TSource> Throttle<TSource, TThrottle>(
    this IObservable<TSource> source,
    Func<TSource, IObservable<TThrottle>> throttleDurationSelector);
</code>```

The intention of the throttleDurationSelector parameter is to give you maximum flexibility at how you define the throttle duration for each element. The value of the TThrottle is not important. What is important is when it emits an element (any element), or when it completes. This is how the duration is defined, by observing dynamically the TThrottle sequence, and waiting it to emit any kind of notification.

Going back to your code, you are returning an Observable.Return as the throttling sequence. This sequence emits a TimeSpan element immediately, causing the associated string element of the source s sequence to be also emitted immediately. The result is that no throttling occurs. It is equivalent to throttling with a TimeSpan.Zero argument, or with removing the Throttle operator altogether.

To fix your code, you must replace the Observable.Return with a sequence that emits an element with a delay, like an Observable.Timer sequence. So if you know the throttling duration immediately after receiving a TSource element, and let's say for simplicity that it is always 500 milliseconds, you can just replace this:

```<code>s.Throttle(_ => Observable.Return(TimeSpan.FromMilliseconds(500)))
</code>```

...with this:

```<code>s.Throttle(_ => Observable.Timer(TimeSpan.FromMilliseconds(500)))
</code>```

Body:
All the documentation I found about rx.net throttling does not cover the overload with a parameter Func<TSource, IObservable<TThrottle>> throttleDurationSelector. So all I have available are the XML-comments. This suggests, that throttleDurationSelector is called on every new element in the source sequence. The expected return value would be a IObservable<TThrottle>. (My understanding) This enables the possibility to change the throttle-delay on every new element. But, this understanding does not match the runtime experience I discover.

var s = new Subject<string>();
s.Throttle(_ => Observable.Return(TimeSpan.FromMilliseconds(500))) // for simplicity of this demo, always return the same delay
    .Subscribe(_ => Console.WriteLine($"{DateTime.Now}.{DateTime.Now.Millisecond} event {_}"));

for (int i = 0; i < 5; i++)
    s.OnNext("a");

Thread.Sleep(1000);

for (int i = 0; i < 5; i++)
    s.OnNext("b");

Thread.Sleep(1000);

According to the previously mentioned understanding (which is obviously wrong), I'd have expected the following output.

10.02.2022 11:47:54.386 event a
10.02.2022 11:47:55.388 event b

Instead this output is generated. It seems that there is no throttling applied at all.

10.02.2022 11:46:49.431 event a
10.02.2022 11:46:49.432 event a
10.02.2022 11:46:49.432 event a
10.02.2022 11:46:49.432 event a
10.02.2022 11:46:49.432 event a
10.02.2022 11:46:50.448 event b
10.02.2022 11:46:50.448 event b
10.02.2022 11:46:50.448 event b
10.02.2022 11:46:50.448 event b
10.02.2022 11:46:50.449 event b

What is the purpose of this overload, if not dynamically changing the throttle-delay (which is what I need)?

Also, why the 'complicated' syntax of Func<TSource, IObservable<TThrottle>> throttleDurationSelector where a simpler parameter Func<TSource, TThrottle> throttleDurationSelector would be good enough?

Body:
We are talking about this overload of the Throttle operator:

public static IObservable<TSource> Throttle<TSource, TThrottle>(
    this IObservable<TSource> source,
    Func<TSource, IObservable<TThrottle>> throttleDurationSelector);

The intention of the throttleDurationSelector parameter is to give you maximum flexibility at how you define the throttle duration for each element. The value of the TThrottle is not important. What is important is when it emits an element (any element), or when it completes. This is how the duration is defined, by observing dynamically the TThrottle sequence, and waiting it to emit any kind of notification.

Going back to your code, you are returning an Observable.Return as the throttling sequence. This sequence emits a TimeSpan element immediately, causing the associated string element of the source s sequence to be also emitted immediately. The result is that no throttling occurs. It is equivalent to throttling with a TimeSpan.Zero argument, or with removing the Throttle operator altogether.

To fix your code, you must replace the Observable.Return with a sequence that emits an element with a delay, like an Observable.Timer sequence. So if you know the throttling duration immediately after receiving a TSource element, and let's say for simplicity that it is always 500 milliseconds, you can just replace this:

s.Throttle(_ => Observable.Return(TimeSpan.FromMilliseconds(500)))

...with this:

s.Throttle(_ => Observable.Timer(TimeSpan.FromMilliseconds(500)))


来源: stackexchange

问:
TypeScript support in modern browsers
I've just read some advertisement information related to TypeScript and besides that I have no experience with this superset of JavaScript. So I have some basic questions:

What is the status of native TypeScript support by the modern browsers?

What are the positions of the major browser vendors for the future support of TypeScript natively?

What is the relation between TypeScript and ECMAScript 6 and does TypeScript provide much more features than ECMAScript 6?

答:
I know it's currently not supported and there are no plans to support TypeScript natively in the browser but there is a huge (in my opinion) problem with tooling in the frontend (JavaScript) ecosystem - there's too much of it. Bundling, module resolution, transpiling, and more.

I think it makes development much slower, because there are a lot of issues with configurations, versions mismatch, compatibility and a lot of obscure issues (Stack Overflow and GitHub are full of such topics) that stem from the tooling, not implementing features.

I would call it a crisis, but it has been like this for a while and I know this is the way of doing things now.

I think there are a few things that need to happen.

We need to be able to use native ES6 modules (import/export) in the browser. I know it's supported, but only a relative or URL imports work. I know there is work on "import maps" or whatever they are called.

It would be great if browsers (Chrome) can read TypeScript code. It doesn’t have to interpret or enforce any typing - essentially treat it like JavaScript with some additional nonsense that the browser just ignores. It could be just a "developer mode" in the browser but we would be able to achieve 0-transpiling during development.

Simplify eager resource loading (to avoid bundling)

Again, this is just for development benefit. I know a lot of these tools have their place in production builds, older browser support, etc.

ContentLicense: CC BY-SA 4.0

Title: TypeScript support in modern browsers


问:
Preformat date from database before compare with date from user input in laravel
I have an table where I'm storing downloads of the user, columns - created_at and updated_at.
What I'm trying to do is simple filter where I can choose from datepicker From-To dates and show all downloads for given time range.

This is what I have in my function

```<code>$dateStart = new DateTime($request->startDate); // '2022-02-01';
$dateEnd = new DateTime($request->dateEnd); //'2022-02-08';
        //dd($dateStart);

$downloadsbyuser = DB::table('downloads')
   ->select('user_id as downloader_id', DB::raw('COUNT(id) as count_by_user_id'))
   ->whereBetween('downloads.updated_at', [$dateStart, $dateEnd])
   ->groupBy('user_id');
</code>```

So, in database, the columns are defaultfor laravel and timestamp. The date coming from datepicker is in 2022-02-01.

This is what I have in database

```<code>ID  user_id   created_at             updated_at
1   34        2022-02-06 10:17:39    2022-02-06 10:17:39
2   34        2022-02-08 10:17:39    2022-02-08 10:17:39
3   20        2022-02-02 10:17:39    2022-02-05 10:17:39
4   34        2022-02-02 10:17:39    2022-02-05 10:17:39
</code>```

When I search dates 2022-02-01 to 2022-02-06 as you can see I should get 3 results - ID's 1,3 and 4 but instead I've got 2 results. When I search 2022-02-01 to 2022-02-07 then I've got correct 3 results but this means that if there is entry with date 2022-02-07 it wont show.

Why is this happen? Is it because of the whereBetween clause?

答:
Try SQL DATE function</p>
```<code>$dateStart = new DateTime($request->startDate); // '2022-02-01';
$dateEnd = new DateTime($request->dateEnd); //'2022-02-08';
//dd($dateStart);
$downloadsbyuser = DB::table('downloads')
   ->select('user_id as downloader_id', DB::raw('COUNT(id) as count_by_user_id'))
   ->whereBetween('DATE(downloads.updated_at)', [$dateStart->format('Y-m-d'), $dateEnd->format('Y-m-d')])
   ->groupBy('user_id');
</code>```

Body:
I have an table where I'm storing downloads of the user, columns - created_at and updated_at.
What I'm trying to do is simple filter where I can choose from datepicker From-To dates and show all downloads for given time range.

This is what I have in my function

$dateStart = new DateTime($request->startDate); // '2022-02-01';
$dateEnd = new DateTime($request->dateEnd); //'2022-02-08';
        //dd($dateStart);

$downloadsbyuser = DB::table('downloads')
   ->select('user_id as downloader_id', DB::raw('COUNT(id) as count_by_user_id'))
   ->whereBetween('downloads.updated_at', [$dateStart, $dateEnd])
   ->groupBy('user_id');

So, in database, the columns are defaultfor laravel and timestamp. The date coming from datepicker is in 2022-02-01.

This is what I have in database

ID  user_id   created_at             updated_at
1   34        2022-02-06 10:17:39    2022-02-06 10:17:39
2   34        2022-02-08 10:17:39    2022-02-08 10:17:39
3   20        2022-02-02 10:17:39    2022-02-05 10:17:39
4   34        2022-02-02 10:17:39    2022-02-05 10:17:39

When I search dates 2022-02-01 to 2022-02-06 as you can see I should get 3 results - ID's 1,3 and 4 but instead I've got 2 results. When I search 2022-02-01 to 2022-02-07 then I've got correct 3 results but this means that if there is entry with date 2022-02-07 it wont show.

Why is this happen? Is it because of the whereBetween clause?

Body:
Try SQL DATE function

$dateStart = new DateTime($request->startDate); // '2022-02-01';
$dateEnd = new DateTime($request->dateEnd); //'2022-02-08';
//dd($dateStart);
$downloadsbyuser = DB::table('downloads')
   ->select('user_id as downloader_id', DB::raw('COUNT(id) as count_by_user_id'))
   ->whereBetween('DATE(downloads.updated_at)', [$dateStart->format('Y-m-d'), $dateEnd->format('Y-m-d')])
   ->groupBy('user_id');


问:
flutter image picker not working and crashing app without error on debug
I'm currently using these versions:
flutter : 2.16.0
image_picker : ^0.8.4+7

The image picker is not working. After running the app, when I click on the button to activate the pickImage function, running suddenly stops and the app crashes and stops. On debug, the only message I get is:

Lost connection to device.

Here's the code:

```<code>import 'dart:io';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:hipocampus_editors/widgets/textformfield_widget.dart';
import 'package:image_picker/image_picker.dart';

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

  @override
  _AddSystemPageState createState() => _AddSystemPageState();
}

class _AddSystemPageState extends State<AddSystemPage> {
  final _formKey = GlobalKey<FormState>();
File? image1;

  Future pickImage() async{

final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null)  return;
final imageTemporary = File(image.path);
setState(() {
  image1 = imageTemporary;
});

    }
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
      child: Scaffold(
        appBar: AppBar(title: const Text('System',),),

        body: SafeArea(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 5),
            child: Form(
              key: _formKey,
              child: Container(
                width: MediaQuery.of(context).size.width,
                padding: const EdgeInsets.symmetric(horizontal: 10),
                child: SingleChildScrollView(
                    child: Column(
                  children: [

                    ElevatedButton(onPressed: (){
                      pickImage();
                                          }, child: Text('Select image'))

                  ],
                )),
              ),
            ),
          ),
        ),
      ),
    );
    }
    }
</code>```

答:
Add this to iOS>runner>Info.plist</p>
```<code><key>NSPhotoLibraryUsageDescription</key>
<string>Allow access to photo library</string>
</code>```

Body:
I'm currently using these versions:
flutter : 2.16.0
image_picker : ^0.8.4+7

The image picker is not working. After running the app, when I click on the button to activate the pickImage function, running suddenly stops and the app crashes and stops. On debug, the only message I get is:

Lost connection to device.

Here's the code:

import 'dart:io';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:hipocampus_editors/widgets/textformfield_widget.dart';
import 'package:image_picker/image_picker.dart';

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

  @override
  _AddSystemPageState createState() => _AddSystemPageState();
}

class _AddSystemPageState extends State<AddSystemPage> {
  final _formKey = GlobalKey<FormState>();
File? image1;

  Future pickImage() async{

final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null)  return;
final imageTemporary = File(image.path);
setState(() {
  image1 = imageTemporary;
});

    }
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
      child: Scaffold(
        appBar: AppBar(title: const Text('System',),),

        body: SafeArea(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 5),
            child: Form(
              key: _formKey,
              child: Container(
                width: MediaQuery.of(context).size.width,
                padding: const EdgeInsets.symmetric(horizontal: 10),
                child: SingleChildScrollView(
                    child: Column(
                  children: [

                    ElevatedButton(onPressed: (){
                      pickImage();
                                          }, child: Text('Select image'))

                  ],
                )),
              ),
            ),
          ),
        ),
      ),
    );
    }
    }

Body:
Add this to iOS>runner>Info.plist

<key>NSPhotoLibraryUsageDescription</key>
<string>Allow access to photo library</string>


问:
Conditionally replace value in a single row or replace value of following rows with values from previous row group in R
I have a huge datatable with over 20'000 rows with a column for each time point t and for each customer with id and I am looking for a way to replace the values in y for t=5:8 each customer id by the value by copy pasting the value of y when t=3&4.

The data set below is a short version of my data set:

```<code>Dt=data.table(
t=rep(1:8, times=3),
y=c(0,1,0,0,0,1,1,0,0,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0),
id=rep(1:3, each=8))

   t y id
 1: 1 0  1
 2: 2 1  1
 3: 3 0  1
 4: 4 0  1
 5: 5 0  1
 6: 6 1  1
 7: 7 1  1
 8: 8 0  1
 9: 1 0  2
10: 2 0  2
11: 3 0  2
12: 4 1  2
13: 5 0  2
14: 6 0  2
15: 7 1  2
16: 8 0  2
17: 1 0  3
18: 2 1  3
19: 3 1  3
20: 4 1  3
21: 5 0  3
22: 6 1  3
23: 7 0  3
24: 8 0  3

</code>```

In the end it should look like this:

```<code>    t y id
 1: 1 0  1
 2: 2 1  1
 3: 3 0  1
 4: 4 0  1
 5: 5 0  1
 6: 6 0  1
 7: 7 0  1
 8: 8 0  1
 9: 1 0  2
10: 2 0  2
11: 3 0  2
12: 4 1  2
13: 5 0  2
14: 6 1  2
15: 7 0  2
16: 8 1  2
17: 1 0  3
18: 2 1  3
19: 3 1  3
20: 4 1  3
21: 5 1  3
22: 6 1  3
23: 7 1  3
24: 8 1  3

</code>```

Do you maybe have an idea how I could solve this? I thought of doing 2 for loops with the range of t and customer id, but I imagine that for this dataset it would take too long.
Thank you in advance!

答:
Your data does not exactly match what is displayed in your post (particularly rows where t is 3 and 4 within id 3). You could try replace in the following approach, though not sure how efficient this is generating a copy with :=.

```<code>library(data.table)

Dt[ , y := replace(y, t %in% 5:8, y[t %in% 3:4]), by = id]
Dt
</code>```

Output

```<code>    t y id
 1: 1 0  1
 2: 2 1  1
 3: 3 0  1
 4: 4 0  1
 5: 5 0  1
 6: 6 0  1
 7: 7 0  1
 8: 8 0  1
 9: 1 0  2
10: 2 0  2
11: 3 0  2
12: 4 1  2
13: 5 0  2
14: 6 1  2
15: 7 0  2
16: 8 1  2
17: 1 0  3
18: 2 1  3
19: 3 0  3
20: 4 0  3
21: 5 0  3
22: 6 0  3
23: 7 0  3
24: 8 0  3
    t y id
</code>```

Body:
I have a huge datatable with over 20'000 rows with a column for each time point t and for each customer with id and I am looking for a way to replace the values in y for t=5:8 each customer id by the value by copy pasting the value of y when t=3&4.

The data set below is a short version of my data set:

Dt=data.table(
t=rep(1:8, times=3),
y=c(0,1,0,0,0,1,1,0,0,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0),
id=rep(1:3, each=8))

   t y id
 1: 1 0  1
 2: 2 1  1
 3: 3 0  1
 4: 4 0  1
 5: 5 0  1
 6: 6 1  1
 7: 7 1  1
 8: 8 0  1
 9: 1 0  2
10: 2 0  2
11: 3 0  2
12: 4 1  2
13: 5 0  2
14: 6 0  2
15: 7 1  2
16: 8 0  2
17: 1 0  3
18: 2 1  3
19: 3 1  3
20: 4 1  3
21: 5 0  3
22: 6 1  3
23: 7 0  3
24: 8 0  3

In the end it should look like this:

    t y id
 1: 1 0  1
 2: 2 1  1
 3: 3 0  1
 4: 4 0  1
 5: 5 0  1
 6: 6 0  1
 7: 7 0  1
 8: 8 0  1
 9: 1 0  2
10: 2 0  2
11: 3 0  2
12: 4 1  2
13: 5 0  2
14: 6 1  2
15: 7 0  2
16: 8 1  2
17: 1 0  3
18: 2 1  3
19: 3 1  3
20: 4 1  3
21: 5 1  3
22: 6 1  3
23: 7 1  3
24: 8 1  3

Do you maybe have an idea how I could solve this? I thought of doing 2 for loops with the range of t and customer id, but I imagine that for this dataset it would take too long.
Thank you in advance!

Body:
Your data does not exactly match what is displayed in your post (particularly rows where t is 3 and 4 within id 3). You could try replace in the following approach, though not sure how efficient this is generating a copy with :=.

library(data.table)

Dt[ , y := replace(y, t %in% 5:8, y[t %in% 3:4]), by = id]
Dt

Output

    t y id
 1: 1 0  1
 2: 2 1  1
 3: 3 0  1
 4: 4 0  1
 5: 5 0  1
 6: 6 0  1
 7: 7 0  1
 8: 8 0  1
 9: 1 0  2
10: 2 0  2
11: 3 0  2
12: 4 1  2
13: 5 0  2
14: 6 1  2
15: 7 0  2
16: 8 1  2
17: 1 0  3
18: 2 1  3
19: 3 0  3
20: 4 0  3
21: 5 0  3
22: 6 0  3
23: 7 0  3
24: 8 0  3
    t y id


问:
How to save Tempfile to External storage using ACTION_OPEN_DOCUMENT_TREE?
unable to save the zip file to external storage after picking a folder using ACTION_OPEN_DOCUMENT_TREE.

I'm creating a project which creates and manipulate files and document, in that task I want to save that stuff in external storage but I can't do that with android developer documentation, so please explain additionally.

I want to save this file

```<code>/data/user/0/com.mobilix.docscanner/cache/abc.zip
</code>```

to

```<code>content://com.android.externalstorage.documents/tree/primary%3ADocument
</code>```

what should I do?

here is my code,

- code for picking a directory to save a file into.

```<code>saveBinding.btnInternalStorage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);

                startActivityForResult(intent, PICKER_RESULT);
            }
        });
</code>```

- Code to be executed after selecting a directory,

```<code>@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            if (requestCode == PICKER_RESULT) {

                if (data != null) {
                    Uri uri = data.getData();
                    String path = uri.getPath();
                    Log.d(TAG, "onActivityResult: uri -> " + uri);
                    Log.d(TAG, "onActivityResult: path -> " + path);

                    getContentResolver().takePersistableUriPermission(
                            uri,
                            Intent.FLAG_GRANT_READ_URI_PERMISSION
                    );

                    new BgExecuter().execute(new Runnable() {
                        @Override
                        public void run() {
                            FileManager.saveFile(PDFTools.this,selectedFile, Uri); //selectedFile is that file that is saved by default in the Temp directory
                        }
                    });
                }
            }else {
                Toast.makeText(PDFTools.this, "dome thing happen great", Toast.LENGTH_SHORT).show();
            }
        }
    }
</code>```

method saveFile

```<code>public static void saveFile(Activity context, File selectedFile, Uri uri) {
        context.getContentResolver().getPersistedUriPermissions();

        try {
            InputStream inputStream = context.getContentResolver().openInputStream(Uri.fromFile(selectedFile));
            OutputStream outputStream = context.getContentResolver().openOutputStream(uri);

            // get the content in bytes
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
            byte[] byteArray = new byte[1024];
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            try {
                byte bytes = (byte) bufferedInputStream.read(byteArray);
                if (bytes >= 0) {
                    bufferedOutputStream.write(byteArray, 0, bytes);
                    bufferedOutputStream.flush();
                }
                inputStream.close();
                outputStream.close();
                bufferedOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
</code>```

答:
String path = uri.getPath();

No no no.

You got a nice uri. Use it.

Create a DocumentFile instance for this tree uri.

Then use DocumentFile.createFile().

Body:
unable to save the zip file to external storage after picking a folder using ACTION_OPEN_DOCUMENT_TREE.

I'm creating a project which creates and manipulate files and document, in that task I want to save that stuff in external storage but I can't do that with android developer documentation, so please explain additionally.

I want to save this file

/data/user/0/com.mobilix.docscanner/cache/abc.zip

to

content://com.android.externalstorage.documents/tree/primary%3ADocument

what should I do?

here is my code,

- code for picking a directory to save a file into.

saveBinding.btnInternalStorage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);

                startActivityForResult(intent, PICKER_RESULT);
            }
        });

- Code to be executed after selecting a directory,

@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            if (requestCode == PICKER_RESULT) {

                if (data != null) {
                    Uri uri = data.getData();
                    String path = uri.getPath();
                    Log.d(TAG, "onActivityResult: uri -> " + uri);
                    Log.d(TAG, "onActivityResult: path -> " + path);

                    getContentResolver().takePersistableUriPermission(
                            uri,
                            Intent.FLAG_GRANT_READ_URI_PERMISSION
                    );

                    new BgExecuter().execute(new Runnable() {
                        @Override
                        public void run() {
                            FileManager.saveFile(PDFTools.this,selectedFile, Uri); //selectedFile is that file that is saved by default in the Temp directory
                        }
                    });
                }
            }else {
                Toast.makeText(PDFTools.this, "dome thing happen great", Toast.LENGTH_SHORT).show();
            }
        }
    }

method saveFile

public static void saveFile(Activity context, File selectedFile, Uri uri) {
        context.getContentResolver().getPersistedUriPermissions();

        try {
            InputStream inputStream = context.getContentResolver().openInputStream(Uri.fromFile(selectedFile));
            OutputStream outputStream = context.getContentResolver().openOutputStream(uri);

            // get the content in bytes
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
            byte[] byteArray = new byte[1024];
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            try {
                byte bytes = (byte) bufferedInputStream.read(byteArray);
                if (bytes >= 0) {
                    bufferedOutputStream.write(byteArray, 0, bytes);
                    bufferedOutputStream.flush();
                }
                inputStream.close();
                outputStream.close();
                bufferedOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }


问:
looping through arrays of arrays
I have an arrays of arrays (some thing like graph), How to iterate all arrays?

```<code>var parentArray = [
 [[1,2,3],[4,5,6],[7,8,9]],
 [[10,11,12],[13,14,15],[16,17,18]],
 [[19,20,21],[22,23,24],[26,27,28]]
];
</code>```

Its just an example array, actual can contains any number of array and then arrays. How to print all those numbers? Its similar to html objects DOM

答:
You would use nested for loops here. The outer loop would iterate the parent array, giving you one of the internal arrays each time. The inner loop would give you the items within each array.
Example:</p>

```<code>for(childArray in parentArray){
    for(item in childArray){
        //do stuff here to each number
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: looping through arrays of arrays

Body:
I have an arrays of arrays (some thing like graph), How to iterate all arrays?

var parentArray = [
 [[1,2,3],[4,5,6],[7,8,9]],
 [[10,11,12],[13,14,15],[16,17,18]],
 [[19,20,21],[22,23,24],[26,27,28]]
];

Its just an example array, actual can contains any number of array and then arrays. How to print all those numbers? Its similar to html objects DOM

Body:
You would use nested for loops here. The outer loop would iterate the parent array, giving you one of the internal arrays each time. The inner loop would give you the items within each array.
Example:

for(childArray in parentArray){
    for(item in childArray){
        //do stuff here to each number
    }
}


问:
Dockerfile: how to Download a file using curl and copy into the container
in this example, I copy wait-for-it.sh inside /app/wait-for-it.sh
But, I don't want to save wait-for-it.sh in my local directory. I want to download it using curl and then copy into /app/wait-for-it.sh

```<code>FROM prismagraphql/prisma:1.34.8
COPY ./wait-for-it.sh /app/wait-for-it.sh
RUN chmod +x /app/wait-for-it.sh
ENTRYPOINT ["/bin/sh","-c","/app/wait-for-it.sh mysql:3306 --timeout=0 -- /app/start.sh"]
</code>```

What I have tried is this, but how can I get the wait-for-it.sh after downloading the file using curl command:

```<code>FROM prismagraphql/prisma:1.34.8

FROM node:11-slim

RUN apt-get update && apt-get install -yq build-essential dumb-init

RUN curl -LJO https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh

COPY wait-for-it.sh /app/wait-for-it.sh

RUN chmod +x /wait-for-it.sh

ENTRYPOINT ["/bin/sh","-c","/wait-for-it.sh mysql:3306 --timeout=0 -- /app/start.sh"]
</code>```

答:
Not related but an easier way to handle downloads during build time is to use Docker's ADD directive without curl or wget.

```<code>RUN https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh /tmp
COPY /tmp/wait-for-it.sh /app/wait-for-it.sh
</code>```

Right now, we recommend using Docker's ADD directive instead of running wget or curl in a RUN directive - Docker is able to handle the https URL when you use ADD, whereas your base image might not be able to use https, or might not even have wget or curl installed at all.

https://github.com/just-containers/s6-overlay#usage

Body:
in this example, I copy wait-for-it.sh inside /app/wait-for-it.sh
But, I don't want to save wait-for-it.sh in my local directory. I want to download it using curl and then copy into /app/wait-for-it.sh

FROM prismagraphql/prisma:1.34.8
COPY ./wait-for-it.sh /app/wait-for-it.sh
RUN chmod +x /app/wait-for-it.sh
ENTRYPOINT ["/bin/sh","-c","/app/wait-for-it.sh mysql:3306 --timeout=0 -- /app/start.sh"]

What I have tried is this, but how can I get the wait-for-it.sh after downloading the file using curl command:

FROM prismagraphql/prisma:1.34.8

FROM node:11-slim

RUN apt-get update && apt-get install -yq build-essential dumb-init

RUN curl -LJO https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh

COPY wait-for-it.sh /app/wait-for-it.sh

RUN chmod +x /wait-for-it.sh

ENTRYPOINT ["/bin/sh","-c","/wait-for-it.sh mysql:3306 --timeout=0 -- /app/start.sh"]

Body:
Not related but an easier way to handle downloads during build time is to use Docker's ADD directive without curl or wget.

RUN https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh /tmp
COPY /tmp/wait-for-it.sh /app/wait-for-it.sh

Right now, we recommend using Docker's ADD directive instead of running wget or curl in a RUN directive - Docker is able to handle the https URL when you use ADD, whereas your base image might not be able to use https, or might not even have wget or curl installed at all.

https://github.com/just-containers/s6-overlay#usage


问:
The body of view to be destroyed gets called (but it shouldn't)
While verifying how binding invalidates a view (indirectly), I find an unexpected behavior.

If the view hierarchy is

```<code> list view -> detail view
</code>```

it works fine (as expected) to press a button in the detail view to delete the item.

However, if the view hierarchy is

```<code>list view -> detail view -> another detail view (containing the same item)
</code>```

it crashes when I press a button in the top-most detail view to delete the item. The crash occurs in the first detail view (the underlying one), because its body gets called.

To put it in another way, the behavior is:

If the detail view is the top-most view in the navigation stack, its body doesn't get called.

Otherwise, its body gets called.

I can't think out any reason for this behavior. My debugging showed below are what happened before the crash:

I pressed a button in top-most detail view to delete the item.

The ListView's body got called (as a result of ContentView body got called). It created only the detail view for the left item.

Then the first DetailView's body get called. This is what caused the crash. I can't think out why this occurred, because it certainly didn't occur for the top-most detail view.

Below is the code. Note the ListView and DetailView contains only binding and regular properties (they don't contain observable object or environment object, which I'm aware complicate the view invalidation behavior).

```<code>import SwiftUI

struct Foo: Identifiable {
    var id: Int
    var value: Int
}

// Note that I use forced unwrapping in data model's APIs. This is intentional. The rationale: the caller of data model API should make sure it passes a valid id.
extension Array where Element == Foo {
    func get(_ id: Int) -> Foo {
        return first(where: { $0.id == id })!
    }

    mutating func remove(_ id: Int) {
        let index = firstIndex(where: { $0.id == id })!
        remove(at: index)
    }
}

class DataModel: ObservableObject {
    @Published var foos: [Foo] = [Foo(id: 1, value: 1), Foo(id: 2, value: 2)]
}

struct ListView: View {
    @Binding var foos: [Foo]

    var body: some View {
        NavigationView {
            List {
                ForEach(foos) { foo in
                    NavigationLink {
                        DetailView(foos: $foos, fooID: foo.id, label: "First detail view")
                    } label: {
                        Text("\(foo.value)")
                    }
                }
            }
        }
    }
}

struct DetailView: View {
    @Binding var foos: [Foo]
    var fooID: Int
    var label: String

    var body: some View {
        // The two print() calls are for debugging only.
        print(Self._printChanges())
        print(label)
        print(fooID)

        return VStack {
            Text(label)
            Divider()
            Text("Value: \(foos.get(fooID).value)")
            NavigationLink {
                DetailView(foos: $foos, fooID: fooID, label: "Another detail view")
            } label: {
                Text("Create another detail view")
            }
            Button("Delete It") {
                foos.remove(fooID)
            }
        }
    }
}

struct ContentView: View {
    @StateObject var dataModel = DataModel()

    var body: some View {
        ListView(foos: $dataModel.foos)
    }
}
</code>```

Test 1: Start the app, click on an item in the list view to go to the detail view, then click on "Delete It" button. This works fine.

The view hierarchy: list view -> detail view

Test 2: Start the app, click on an item in the list view to go to the detail view, then click on "Create another detail view" to go to another detail view. Then click on "Delete It" button. The crashes the first detail view.

The view hierarchy: list view -> detail view -> another detail view

Could it be just another bug of @Binding? Is there any robust way to work around the issue?

答:
This is a version that uses Paul's approach but still uses binding. Note both versions don't really "solve" the issue (the behavior I described in my original question still exists) but instead "avoid" the crash by not accessing data model when rendering the view hierarchy in the body. I think this is a key point to use a framework successfully - don't fight it.

Regarding the use of binding in the code example, I'm aware most people use ObservableObject or EnvironmentObject. I used to do that too. I noticed the use of binding in Apple's demo app. But I may consider to switch back to the view model approach.

```<code>import SwiftUI

struct Foo: Identifiable {
    var id: Int
    var value: Int
}

// Note that I use forced unwrapping in data model's APIs. This is intentional. The rationale: the caller of data model API should make sure it passes a valid id.
extension Array where Element == Foo {
    func get(_ id: Int) -> Foo {
        return first(where: { $0.id == id })!
    }

    mutating func remove(_ id: Int) {
        let index = firstIndex(where: { $0.id == id })!
        remove(at: index)
    }
}

class DataModel: ObservableObject {
    @Published var foos: [Foo] = [Foo(id: 1, value: 1), Foo(id: 2, value: 2)]
}

struct ListView: View {
    @Binding var foos: [Foo]

    var body: some View {
        NavigationView {
            List {
                ForEach(foos) { foo in
                    NavigationLink {
                        DetailView(foos: $foos, foo: foo, label: "First detail view")
                    } label: {
                        Text("\(foo.value)")
                    }
                }
            }
        }
    }
}

struct DetailView: View {
    @Binding var foos: [Foo]
    var foo: Foo
    var label: String

    var body: some View {
        // The two print() calls are for debugging only.
        print(Self._printChanges())
        print(label)
        print(foo)

        return VStack {
            Text(label)
            Divider()
            Text("Value: \(foo.value)")
            NavigationLink {
                DetailView(foos: $foos, foo: foo, label: "Another detail view")
            } label: {
                Text("Create another detail view")
            }
            Button("Delete It") {
                foos.remove(foo.id)
            }
        }
    }
}

struct ContentView: View {
    @StateObject var dataModel = DataModel()

    var body: some View {
        ListView(foos: $dataModel.foos)
    }
}
</code>```

Body:
While verifying how binding invalidates a view (indirectly), I find an unexpected behavior.

If the view hierarchy is

 list view -> detail view

it works fine (as expected) to press a button in the detail view to delete the item.

However, if the view hierarchy is

list view -> detail view -> another detail view (containing the same item)

it crashes when I press a button in the top-most detail view to delete the item. The crash occurs in the first detail view (the underlying one), because its body gets called.

To put it in another way, the behavior is:

If the detail view is the top-most view in the navigation stack, its body doesn't get called.

Otherwise, its body gets called.

I can't think out any reason for this behavior. My debugging showed below are what happened before the crash:

I pressed a button in top-most detail view to delete the item.

The ListView's body got called (as a result of ContentView body got called). It created only the detail view for the left item.

Then the first DetailView's body get called. This is what caused the crash. I can't think out why this occurred, because it certainly didn't occur for the top-most detail view.

Below is the code. Note the ListView and DetailView contains only binding and regular properties (they don't contain observable object or environment object, which I'm aware complicate the view invalidation behavior).

import SwiftUI

struct Foo: Identifiable {
    var id: Int
    var value: Int
}

// Note that I use forced unwrapping in data model's APIs. This is intentional. The rationale: the caller of data model API should make sure it passes a valid id.
extension Array where Element == Foo {
    func get(_ id: Int) -> Foo {
        return first(where: { $0.id == id })!
    }

    mutating func remove(_ id: Int) {
        let index = firstIndex(where: { $0.id == id })!
        remove(at: index)
    }
}

class DataModel: ObservableObject {
    @Published var foos: [Foo] = [Foo(id: 1, value: 1), Foo(id: 2, value: 2)]
}

struct ListView: View {
    @Binding var foos: [Foo]

    var body: some View {
        NavigationView {
            List {
                ForEach(foos) { foo in
                    NavigationLink {
                        DetailView(foos: $foos, fooID: foo.id, label: "First detail view")
                    } label: {
                        Text("\(foo.value)")
                    }
                }
            }
        }
    }
}

struct DetailView: View {
    @Binding var foos: [Foo]
    var fooID: Int
    var label: String

    var body: some View {
        // The two print() calls are for debugging only.
        print(Self._printChanges())
        print(label)
        print(fooID)

        return VStack {
            Text(label)
            Divider()
            Text("Value: \(foos.get(fooID).value)")
            NavigationLink {
                DetailView(foos: $foos, fooID: fooID, label: "Another detail view")
            } label: {
                Text("Create another detail view")
            }
            Button("Delete It") {
                foos.remove(fooID)
            }
        }
    }
}

struct ContentView: View {
    @StateObject var dataModel = DataModel()

    var body: some View {
        ListView(foos: $dataModel.foos)
    }
}

Test 1: Start the app, click on an item in the list view to go to the detail view, then click on "Delete It" button. This works fine.

The view hierarchy: list view -> detail view

Test 2: Start the app, click on an item in the list view to go to the detail view, then click on "Create another detail view" to go to another detail view. Then click on "Delete It" button. The crashes the first detail view.

The view hierarchy: list view -> detail view -> another detail view

Could it be just another bug of @Binding? Is there any robust way to work around the issue?

Body:
This is a version that uses Paul's approach but still uses binding. Note both versions don't really "solve" the issue (the behavior I described in my original question still exists) but instead "avoid" the crash by not accessing data model when rendering the view hierarchy in the body. I think this is a key point to use a framework successfully - don't fight it.

Regarding the use of binding in the code example, I'm aware most people use ObservableObject or EnvironmentObject. I used to do that too. I noticed the use of binding in Apple's demo app. But I may consider to switch back to the view model approach.

import SwiftUI

struct Foo: Identifiable {
    var id: Int
    var value: Int
}

// Note that I use forced unwrapping in data model's APIs. This is intentional. The rationale: the caller of data model API should make sure it passes a valid id.
extension Array where Element == Foo {
    func get(_ id: Int) -> Foo {
        return first(where: { $0.id == id })!
    }

    mutating func remove(_ id: Int) {
        let index = firstIndex(where: { $0.id == id })!
        remove(at: index)
    }
}

class DataModel: ObservableObject {
    @Published var foos: [Foo] = [Foo(id: 1, value: 1), Foo(id: 2, value: 2)]
}

struct ListView: View {
    @Binding var foos: [Foo]

    var body: some View {
        NavigationView {
            List {
                ForEach(foos) { foo in
                    NavigationLink {
                        DetailView(foos: $foos, foo: foo, label: "First detail view")
                    } label: {
                        Text("\(foo.value)")
                    }
                }
            }
        }
    }
}

struct DetailView: View {
    @Binding var foos: [Foo]
    var foo: Foo
    var label: String

    var body: some View {
        // The two print() calls are for debugging only.
        print(Self._printChanges())
        print(label)
        print(foo)

        return VStack {
            Text(label)
            Divider()
            Text("Value: \(foo.value)")
            NavigationLink {
                DetailView(foos: $foos, foo: foo, label: "Another detail view")
            } label: {
                Text("Create another detail view")
            }
            Button("Delete It") {
                foos.remove(foo.id)
            }
        }
    }
}

struct ContentView: View {
    @StateObject var dataModel = DataModel()

    var body: some View {
        ListView(foos: $dataModel.foos)
    }
}


问:
Android Wifi direct multiple connection ad-hoc
I try to create an ad-hoc network between many Android devices, but I can't find documentation to do that.

I thought Wifi direct could work for what I want, but is it possible to have multiple connection on one device ? I saw that we could do a device acting like an access point and communicate with many devices, but can we communicate from one client device to two access point devices ?

I have for example 3 devices: A -> B -> C

The "A" device need to communicate with "C" device but he's too far away, so I want to have ad-hoc wifi direct connection between A&B and ad-hoc wifi direct connection between B&C, so A can communicate with C. It should also work with more than 3 devices.

Thanks !

答: Well You might be interested in looking at AllJoyn. It is qualcoms SDK for android OS which includes wi-fi peer-to-peer implementations by creating adhoc connections. This is same as Wi-Fi Direct.</p>

ContentLicense: CC BY-SA 2.5


问:
How to replace Line Tabulation (\\u000B or ) in String using Java?

The Data looks somewhat like following in database: ()

When record is fetched from database and rest service responded it looks like :

```<code>ICT0637256 Onboarding questionnaire for internal transfers & dashboard\u000BOnboarding
</code>```

Another wrapper service which returns soap response; when call this rest service, then it returns following response :

```<code><ns7:TaskDescription>ICT0637256 Onboarding questionnaire for internal transfers & dashboardOnboarding</ns7:TaskDescription>
</code>```

I searched on internet and found \u000B is line tabulation.

Now on soap service level, i am trying to replace character comes from Rest Service:

```<code>  public String replaceUnnecessaryCharacters(String text) {
        if(StringUtils.isNotEmpty(text)) {
            text = text.replaceAll("\\\\u000B", " ");
            text = text.replaceAll("", " ");
            text = text.replaceAll("<0x0b>", " ");
            text = text.replaceAll("\\^K", " ");
        }
        return text;
    }

    if(task.getProjectId() == 5130764) {
        LOG.info("getTasks: DescriptionDetails:5130764" + task.getDescription()); //<-- This comes from Rest API in code
        LOG.info("getTasks: DescriptionDetails:5130764" + replaceUnnecessaryCharacters(task.getDescription())); <--- Here it doesn't show \u00B but blank space
    }soapResponsetsk.setTaskDescription(replaceUnnecessaryCharacters(task.getDescription()));
</code>```

When i copy it in notepad, it looks like

When i copy it to VI Editor in linux then it shows ^K

I am like lost how to replace this character using Java? Can you please suggest how to fix the same?

答:
Since you are not really using any of regex syntax (like + * quantifiers, \w character classes, etc.) instead of replaceAll you can use replace method.

Also since you want to replace single character with another character you can use replace(char oldChar, char newChar) like

```<code>text = text.replace('\u000B', ' ');
</code>```

Body:
The Data looks somewhat like following in database: ()

When record is fetched from database and rest service responded it looks like :

ICT0637256 Onboarding questionnaire for internal transfers & dashboard\u000BOnboarding

Another wrapper service which returns soap response; when call this rest service, then it returns following response :

<ns7:TaskDescription>ICT0637256 Onboarding questionnaire for internal transfers & dashboardOnboarding</ns7:TaskDescription>

I searched on internet and found \u000B is line tabulation.

Now on soap service level, i am trying to replace character comes from Rest Service:

  public String replaceUnnecessaryCharacters(String text) {
        if(StringUtils.isNotEmpty(text)) {
            text = text.replaceAll("\\\\u000B", " ");
            text = text.replaceAll("", " ");
            text = text.replaceAll("<0x0b>", " ");
            text = text.replaceAll("\\^K", " ");
        }
        return text;
    }

    if(task.getProjectId() == 5130764) {
        LOG.info("getTasks: DescriptionDetails:5130764" + task.getDescription()); //<-- This comes from Rest API in code
        LOG.info("getTasks: DescriptionDetails:5130764" + replaceUnnecessaryCharacters(task.getDescription())); <--- Here it doesn't show \u00B but blank space
    }soapResponsetsk.setTaskDescription(replaceUnnecessaryCharacters(task.getDescription()));

When i copy it in notepad, it looks like

When i copy it to VI Editor in linux then it shows ^K

I am like lost how to replace this character using Java? Can you please suggest how to fix the same?

Body:
Since you are not really using any of regex syntax (like + * quantifiers, \w character classes, etc.) instead of replaceAll you can use replace method.

Also since you want to replace single character with another character you can use replace(char oldChar, char newChar) like

text = text.replace('\u000B', ' ');


问:
Add Brackets to Each Element in Row
I do have a dataframe containing multiple rows where the first row contains parameter estimates and the row below contains the respective t-statistics.

```<code>Row 1: Par. Est. 1 | Par. Est. 2 | Par. Est. 3 ...
Row 2:   t-Stat 1  |   t-Stat 2  |   t-Stat 3  ...
Row 3: Par. Est. 1 | Par. Est. 2 | Par. Est. 3 ...
Row 4:   t-Stat 1  |   t-Stat 2  |   t-Stat 3  ...
</code>```

I want to modify the rows with the t-Stats so that the values are all individually displayed in brackets, i.e. so that it looks like this:

```<code>Row 1: Par. Est. 1 | Par. Est. 2 | Par. Est. 3 ...
Row 2:  (t-Stat 1) |  (t-Stat 2) |  (t-Stat 3) ...
Row 3: Par. Est. 1 | Par. Est. 2 | Par. Est. 3 ...
Row 4:  (t-Stat 1) |  (t-Stat 2) |  (t-Stat 3) ...
</code>```

I literally have no idea how to start or how to do it.

答:
If I understand correctly, you can use</p>
```<code>df.iloc[1::2,:] = df.iloc[1::2,:].add(')').radd('(')
</code>```

Title: Add Brackets to Each Element in Row

Body:
I do have a dataframe containing multiple rows where the first row contains parameter estimates and the row below contains the respective t-statistics.

Row 1: Par. Est. 1 | Par. Est. 2 | Par. Est. 3 ...
Row 2:   t-Stat 1  |   t-Stat 2  |   t-Stat 3  ...
Row 3: Par. Est. 1 | Par. Est. 2 | Par. Est. 3 ...
Row 4:   t-Stat 1  |   t-Stat 2  |   t-Stat 3  ...

I want to modify the rows with the t-Stats so that the values are all individually displayed in brackets, i.e. so that it looks like this:

Row 1: Par. Est. 1 | Par. Est. 2 | Par. Est. 3 ...
Row 2:  (t-Stat 1) |  (t-Stat 2) |  (t-Stat 3) ...
Row 3: Par. Est. 1 | Par. Est. 2 | Par. Est. 3 ...
Row 4:  (t-Stat 1) |  (t-Stat 2) |  (t-Stat 3) ...

I literally have no idea how to start or how to do it.

Body:
If I understand correctly, you can use

df.iloc[1::2,:] = df.iloc[1::2,:].add(')').radd('(')


问:
Make only one row selectable at a time in React Table 7.1.0
I am trying to implement react table with just one row selectable at at time. I have gone through a lot of examples for multiple rows selection in a react table but in my case, the user can select only one row when the user clicks on the radio button but currently all the rows can be selected. Could anyone help me out on this to implement ?

答:
This is an old one, but here is my solution:

Get toggleAllRowsSelected from table instance.

```<code>  const {
    allColumns,
    getTableBodyProps,
    getTableProps,
    headerGroups,
    prepareRow,
    rows,
    state,
    toggleAllRowsSelected,
  } = useTable(
    {
      columns,
      data,
    },
    useRowSelect
  );
</code>```

Then add onClick like in code below to your tr-component (in my code tr has been styled with emotion and named StyledTableRow). This will first set all selected rows to false and then toggle current row isSelected value if it was false initially, if it was true then it has already been set to false.

If you don't want to allow clicking selected row to unselect it (eg. for radio buttons), just use the isSelected === true to block any action here.

```<code>{rows.map((row, i) => {
            prepareRow(row);
            // const isRowSelected = isSelected(row.id);
            const { isSelected, getRowProps, getToggleRowSelectedProps, toggleRowSelected } = row;
            const {
              onChange,
              indeterminate,
              ...toggleRowSelectedProps
            } = getToggleRowSelectedProps();
            console.log(row);
            return (
              <StyledTableRow
                hover
                {...getRowProps()}
                {...toggleRowSelectedProps}
                selected={isSelected}
                onClick={() => {
                  const current = isSelected;
                  toggleAllRowsSelected(false);
                  if (!current) {
                    toggleRowSelected();
                  }
                }}
              >
                {row.cells.map((cell, key) => (
</code>```

Body:
This is an old one, but here is my solution:

Get toggleAllRowsSelected from table instance.

  const {
    allColumns,
    getTableBodyProps,
    getTableProps,
    headerGroups,
    prepareRow,
    rows,
    state,
    toggleAllRowsSelected,
  } = useTable(
    {
      columns,
      data,
    },
    useRowSelect
  );

Then add onClick like in code below to your tr-component (in my code tr has been styled with emotion and named StyledTableRow). This will first set all selected rows to false and then toggle current row isSelected value if it was false initially, if it was true then it has already been set to false.

If you don't want to allow clicking selected row to unselect it (eg. for radio buttons), just use the isSelected === true to block any action here.

{rows.map((row, i) => {
            prepareRow(row);
            // const isRowSelected = isSelected(row.id);
            const { isSelected, getRowProps, getToggleRowSelectedProps, toggleRowSelected } = row;
            const {
              onChange,
              indeterminate,
              ...toggleRowSelectedProps
            } = getToggleRowSelectedProps();
            console.log(row);
            return (
              <StyledTableRow
                hover
                {...getRowProps()}
                {...toggleRowSelectedProps}
                selected={isSelected}
                onClick={() => {
                  const current = isSelected;
                  toggleAllRowsSelected(false);
                  if (!current) {
                    toggleRowSelected();
                  }
                }}
              >
                {row.cells.map((cell, key) => (


问:
Setting an attribute from a parents attribute
I have this HTML and i am trying to convert the href from photo.php to #photo etc for each

```<code><ul id="menu">
    <li id="home" class="tab_selected"><a href="home.php">Home</a></li>
    <li id="portfolio"><a href="portfolio.php">Portfolio</a></li>
    <li id="music"><a href="music.php">Music</a></li>
    <li id="video"><a href="video.php">Video</a></li>
    <li id="photo"><a href="photo.php">Photo</a></li>
</ul>
</code>```

I have been trying something like this:

```<code>$('#menu li a').attr('href', "#"+$(this).parent().attr('id'));
</code>```

But the href always comes out undefined.

I am storing the hash in the li#id but if i could not do this it would be even better.

Thanks.

答:
$(this) does not refer to the object you think it refers to.

With .attr you can use a function as a second argument to compute new attribute values for each matched element, like this:

```<code>// i == index, val == value of href at index i
$('#menu li a').attr('href', function(i, val) {
    return '#' + $(this).parent().attr('id');
});
</code>```

In the above example, this refers to the correct context (the currently iterated anchor element).

You can try it here.

Body:
I have this HTML and i am trying to convert the href from photo.php to #photo etc for each

Home

Portfolio

Music

Video

Photo

I have been trying something like this:

$('#menu li a').attr('href', "#"+$(this).parent().attr('id'));

But the href always comes out undefined.

I am storing the hash in the li#id but if i could not do this it would be even better.

Thanks.

Body:
$(this) does not refer to the object you think it refers to.

With .attr you can use a function as a second argument to compute new attribute values for each matched element, like this:

// i == index, val == value of href at index i
$('#menu li a').attr('href', function(i, val) {
    return '#' + $(this).parent().attr('id');
});

In the above example, this refers to the correct context (the currently iterated anchor element).

You can try it here.


问:
SpringBoot 3.0.0-M1 + SpringCloud 2022.0.0-M1 [ERROR] 'dependency.version' for org.springframework.cloud:spring-cloud-starter-sleuth:jar is missing
With the exciting releases of both SpringBoot 3.0.0-M1 and SpringCloud 2022.0.0-M1, I went ahead to bump the versions up.

https://spring.io/blog/2022/01/20/spring-boot-3-0-0-m1-is-now-available

https://spring.io/blog/2022/01/27/spring-cloud-2022-0-0-m1-codename-kilburn-has-been-released

While things worked perfectly fine on my SpringBoot 2.6.3 + Jubilee, the exact same code, with just the version change on the pom file to the new pair SpringBoot 3.0.0-M1 + SpringCloud 2022.0.0-M1, the following error is observed.

```<code>/Library/Java/JavaVirtualMachines/jdk-17.0.2.jdk/Contents/Home/bin/java -Dmaven.multiModuleProjectDirectory=abc -Dmaven.home=maven3 [...] -Didea.version=2021.3.1 clean install
[INFO] Scanning for projects...
[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[ERROR] 'dependencies.dependency.version' for org.springframework.cloud:spring-cloud-starter-sleuth:jar is missing. @ line xx, column 21
[ERROR] 'dependencies.dependency.version' for org.springframework.cloud:spring-cloud-sleuth-zipkin:jar is missing. @ line xx, column 21
 @
</code>```

Per Spring Cloud official documentation:

```<code>Spring Cloud Sleuth

Spring Cloud Sleuth’s last minor version is 3.1. You can check the 3.1.x branch for the latest commits.

The core of this project got moved to Micrometer Tracing project and the instrumentations will be moved to Micrometer and all respective projects (no longer all instrumentations will be done in a single repository.
</code>```

I am having a hard time understanding. Does it mean from 3.0/2022.0 onward, there is no Sleuth anymore? We need to use Micrometer instead?

How to keep existing features offered by Sleuth please?

Thank you

答:
I am having a hard time understanding. Does it mean from 3.0/2022.0 onward, there is no Sleuth anymore? We need to use Micrometer instead?

Yes

How to keep existing features offered by Sleuth please?

We will be providing support for those via Micrometer & Micrometer Tracing.

does it means we can just remove the Sleuth dependency from the pom file, and instead add/replace with the micrometer one, and things will be the same, still be working?

If you don't have any custom Sleuth configuration then there should be nothing that you should do for observability to work. If you had custom Sleuth configuration you will need to port it to Micrometer Tracing which essentially is a copy of Sleuth so that should be mostly a package change. If you were doing Brave customizations then most likely you'll have nothing to change.

UPDATE:

Here you can find a link to the Sleuth to Micrometer Tracing migration guide https://github.com/micrometer-metrics/tracing/wiki/Spring-Cloud-Sleuth-3.1-Migration-Guide

Body:
With the exciting releases of both SpringBoot 3.0.0-M1 and SpringCloud 2022.0.0-M1, I went ahead to bump the versions up.

https://spring.io/blog/2022/01/20/spring-boot-3-0-0-m1-is-now-available

https://spring.io/blog/2022/01/27/spring-cloud-2022-0-0-m1-codename-kilburn-has-been-released

While things worked perfectly fine on my SpringBoot 2.6.3 + Jubilee, the exact same code, with just the version change on the pom file to the new pair SpringBoot 3.0.0-M1 + SpringCloud 2022.0.0-M1, the following error is observed.

/Library/Java/JavaVirtualMachines/jdk-17.0.2.jdk/Contents/Home/bin/java -Dmaven.multiModuleProjectDirectory=abc -Dmaven.home=maven3 [...] -Didea.version=2021.3.1 clean install
[INFO] Scanning for projects...
[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[ERROR] 'dependencies.dependency.version' for org.springframework.cloud:spring-cloud-starter-sleuth:jar is missing. @ line xx, column 21
[ERROR] 'dependencies.dependency.version' for org.springframework.cloud:spring-cloud-sleuth-zipkin:jar is missing. @ line xx, column 21
 @

Per Spring Cloud official documentation:

Spring Cloud Sleuth

Spring Cloud Sleuth’s last minor version is 3.1. You can check the 3.1.x branch for the latest commits.

The core of this project got moved to Micrometer Tracing project and the instrumentations will be moved to Micrometer and all respective projects (no longer all instrumentations will be done in a single repository.

I am having a hard time understanding. Does it mean from 3.0/2022.0 onward, there is no Sleuth anymore? We need to use Micrometer instead?

How to keep existing features offered by Sleuth please?

Thank you


问:
How to reverse a string in Oracle (11g) SQL without using REVERSE() function
I am trying to reverse a string without using REVERSE function. I came across one example which is something like:

```<code>select listagg(letter) within group(order by lvl)
from
 (SELECT LEVEL lvl, SUBSTR ('hello', LEVEL*-1, 1) letter
 FROM   dual
 CONNECT BY LEVEL <= length('hello'));
</code>```

Apart from this approach,is there any other better approach to do this?

答:
```<code>select listagg(rev)within group(order by rownum)
from
(select substr('Oracle',level*-1,1)rev from dual
connect by level<=length('Oracle'));
</code>```

Body:
I am trying to reverse a string without using REVERSE function. I came across one example which is something like:

select listagg(letter) within group(order by lvl)
from
 (SELECT LEVEL lvl, SUBSTR ('hello', LEVEL*-1, 1) letter
 FROM   dual
 CONNECT BY LEVEL <= length('hello'));

Apart from this approach,is there any other better approach to do this?


问:
index.php and protecting of its content
What are the chances hackers are able to download index.php file from the server (not the result, but the content of index.php file)? Do you recommend to put the content of index.php to modules/index_content.php, where modules folder is .htaccess protected AND index.php contains the only string <?php require_once('modules/index_content.php') ?> ?  Does it make sense?

答: If *.php files are being treated as PHP files by Apache (i.e., rendered as normal), then no, they can't access the source, at least not without access to the server through some other script or means (in which case adding the script to modules/index_content.php won't make a difference).</p>

Title: index.php and protecting of its content


问:
Databricks Python handling with delimiter
I am using Python in order to make a dataframe based on a CSV file.

The input CSV file looks like this:

After running the following code:

```<code>dataframe_sales = spark.read.format('csv').options(header='true',inferSchema='true').load('/mnt/sadwhpostgre001/excel/goud/sales_file.csv')
</code>```

I see that the  some characters on of the column CompanyName moved to the right.

See the output file:

How can I make a dataframe that just keeps the structure of the values on the record? So after making a dataframe the structure must be the same as the input CSV file.

答:
This is because you have a , (comma) in the name.

Suggestion: Change the default delimiter to ; or | or something else when you save the file as a CSV.

Then read it from Databricks with the delimiter option enabled:

```<code>.option("delimiter","your_delimiter_here")
</code>```

Please update your code and change the default delimiter by adding the option:

```<code>    dataframe_sales = spark.read.format('csv').options(header='true',inferSchema='true').option("delimiter",",").("quote","\"").load('/mnt/sadwhpostgre001/excel/goud/sales_file.csv')
</code>```

Body:
I am using Python in order to make a dataframe based on a CSV file.

The input CSV file looks like this:

After running the following code:

dataframe_sales = spark.read.format('csv').options(header='true',inferSchema='true').load('/mnt/sadwhpostgre001/excel/goud/sales_file.csv')

I see that the  some characters on of the column CompanyName moved to the right.

See the output file:

How can I make a dataframe that just keeps the structure of the values on the record? So after making a dataframe the structure must be the same as the input CSV file.

Body:
This is because you have a , (comma) in the name.

Suggestion: Change the default delimiter to ; or | or something else when you save the file as a CSV.

Then read it from Databricks with the delimiter option enabled:

.option("delimiter","your_delimiter_here")

Please update your code and change the default delimiter by adding the option:

    dataframe_sales = spark.read.format('csv').options(header='true',inferSchema='true').option("delimiter",",").("quote","\"").load('/mnt/sadwhpostgre001/excel/goud/sales_file.csv')


问:
How to open destination window on nav_graph android studio
I mistakenly closed window with destinations in navigation graph and i have no idea how to open it again.I have this

And i need this

答:
Choose this one

and then add the fragment which you want. Or add new fragment and then this menu will recreate


问:
Why am I running into org.codehaus.mojo:exec-maven-plugin:1.2.1:exec error?
I have the following simple pom.xml. When I run the application it runs into following error, I read many answers for this problem but they did not work out.

```<code>    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource resource = client.resource("Query Request Goes Here");
    List<Output> allOutputs = resource.get(new GenericType<List<Output>>(){});
    System.out.println(allOutputs.size());

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec (default-cli) on project eBaytest: Command execution failed. Process exited with an error: 1 (Exit value: 1) -> [Help 1]

To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.
</code>```

POM.XML

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mycompany</groupId>
    <artifactId>Test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>eBaytest</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>1.18</version>
            <type>jar</type>
        </dependency>
    </dependencies>
</project>
</code>```

答: if you trying create new model table, and by mistake add two @id column tag sometime this error occurs, check the model class and delete unnecessary one the problem will disappear.</p>

Body:
I have the following simple pom.xml. When I run the application it runs into following error, I read many answers for this problem but they did not work out.

    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource resource = client.resource("Query Request Goes Here");
    List<Output> allOutputs = resource.get(new GenericType<List<Output>>(){});
    System.out.println(allOutputs.size());

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec (default-cli) on project eBaytest: Command execution failed. Process exited with an error: 1 (Exit value: 1) -> [Help 1]

To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.

POM.XML

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mycompany</groupId>
    <artifactId>Test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>eBaytest</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>1.18</version>
            <type>jar</type>
        </dependency>
    </dependencies>
</project>


答:
It has no sense.

If anyone has an access to your index.php source, he has also access to all of included files' sources.

Title: index.php and protecting of its content

Body: What are the chances hackers are able to download index.php file from the server (not the result, but the content of index.php file)? Do you recommend to put the content of index.php to modules/index_content.php, where modules folder is .htaccess protected AND index.php contains the only string <?php require_once('modules/index_content.php') ?> ?  Does it make sense?


问:
I have a problem with a promise inside a function and a forEach method
I have these water names and I want that putting an input with a water name, the promise will return me a result. The problem is that it doesn't return anything, how can I fix it?

const water = [
  { nome: "Sant'anna", inStore: true },
  { nome: "Levissima", inStore: false },
  { nome: "Lete", inStore: true },
];

let inStoreTrue = [];
let inStoreFalse = [];
water.forEach(({ nome, inStore }) => {
  if (inStore === true) {
    inStoreTrue.push({ nome });
  } else {
    inStoreFalse.push({ nome });
  }
});

function checkWater(enter) {
  return new Promise((resolve, reject) => {
    if (enter === inStoreTrue) {
      resolve("la tua acqua è disponibile");
    } else if (enter === inStoreFalse) {
      reject("La tua acqua non è disponibile");
    }
  });
}

let prom = checkWater("Sant'anna");
prom
  .then((risultato) => {
    console.log(risultato);
  })
  .catch((err) => {
    console.log(err);
  });```

答:
The issue is with checking enter === inStoreTrue and enter === inStoreFalse

inStoreTrue and inStoreFalse are arrays. So you cannot simply equate a string with an array. You have to check whether the string is there in the array with some array methods. I used Array.some for that.

const water = [
  { nome: "Sant'anna", inStore: true },
  { nome: "Levissima", inStore: false },
  { nome: "Lete", inStore: true },
];

let inStoreTrue = [];
let inStoreFalse = [];
water.forEach(({ nome, inStore }) => {
  if (inStore === true) {
    inStoreTrue.push({ nome });
  } else {
    inStoreFalse.push({ nome });
  }
});

function checkWater(enter) {
  return new Promise((resolve, reject) => {
    if (inStoreTrue.some((item) => item.nome === enter)) {
      resolve("la tua acqua è disponibile");
    } else if (inStoreFalse.some((item) => item.nome === enter)) {
      reject("La tua acqua non è disponibile");
    }
  });
}

let prom = checkWater("Sant'anna");
prom
  .then((risultato) => {
    console.log(risultato);
  })
  .catch((err) => {
    console.log(err);
  });```


问:
Can I use the data studio API to pull data from a report?
Is there a way to pull the data from a report in Google Data Studio through the API? One of my clients wants to generate a report in data studio and then export it to Google Sheets so he can run additional functions. I can't seem to find any documentation that talks about how to do that. Alternatively, is it easier to skip the report, query the data sources directly, and do the uploading that way?</p>

答:
At the moment you can only get the info about reports, but not report data.

The API is available here: https://developers.google.com/datastudio/api/reference


问:
my-appname| /bin/sh: 1: /app/tmpmain.exe: not found | air
I'm facing an issue, am trying to run my go fiber project inside docker with air but am getting this error

uni-blog  | /bin/sh: 1: /app/tmpmain.exe: not found

am using
Windows 11
Docker desktop
golang latest
air  1.27.10
fiber latest

Here is my docker compose and dockerfile

```<code># docker-compose up -d --build
version: "3.8"

services:
  app:
    container_name: uni-blog
    image: app-dev
    build:
      context: .
      target: development
    volumes:
      - ./:/app
    ports:
      - 3000:3000

</code>```
```<code>FROM golang:1.17 as development

RUN apt update && apt upgrade -y && \
  apt install -y git \
  make openssh-client

RUN curl -fLo install.sh https://raw.githubusercontent.com/cosmtrek/air/master/install.sh \
    && chmod +x install.sh && sh install.sh && cp ./bin/air /bin/air

RUN air -v

WORKDIR /app

COPY go.mod go.sum ./

RUN go mod download

COPY . .

EXPOSE 3000

CMD air
</code>```

I also tried installing air following the readME instructions still it gives me this error

Please help

Thanks in advance

答:
The volumes: mount you have replaces the /app directory in the image with content from the host.  If the binary is built in the Dockerfile, that volumes: mount hides it; if you don't have a matching compatible binary on the host in the same place, you'll get an error like what you see.

I'd remove that volumes: block so you're actually running the binary that's built into the image.  The docker-compose.yml file can be reduced to as little as:

version: '3.8'
services:
  app:
    build: .
    ports:
      - '3000:3000'
```

Body:
I'm facing an issue, am trying to run my go fiber project inside docker with air but am getting this error

uni-blog  | /bin/sh: 1: /app/tmpmain.exe: not found

am using
Windows 11
Docker desktop
golang latest
air  1.27.10
fiber latest

Here is my docker compose and dockerfile

# docker-compose up -d --build
version: "3.8"

services:
  app:
    container_name: uni-blog
    image: app-dev
    build:
      context: .
      target: development
    volumes:
      - ./:/app
    ports:
      - 3000:3000

FROM golang:1.17 as development

RUN apt update && apt upgrade -y && \
  apt install -y git \
  make openssh-client

RUN curl -fLo install.sh https://raw.githubusercontent.com/cosmtrek/air/master/install.sh \
    && chmod +x install.sh && sh install.sh && cp ./bin/air /bin/air

RUN air -v

WORKDIR /app

COPY go.mod go.sum ./

RUN go mod download

COPY . .

EXPOSE 3000

CMD air

I also tried installing air following the readME instructions still it gives me this error

Please help

Thanks in advance


问:
Generate Variable Inside Loop Dplyr
I am trying to generate a variable inside a loop using mutate. This variable should simply be the concatenate of the word period and the loop iteration number i.

Unfortunately the following code generates the variable p instead of period1, period2, and so on.

Does anyone know how can I get the name as period1 instead of simply p?

The expected outcome is the following:

```<code>Fr1 <- data.frame (v1  = c("a", "b", "c"),
                  v2 = c("1", "2", "a"),
                  v3 = c("2", "4", "c"),
                  period1 = c("Yes", "Yes", "Yes")
)

Fr2 <- data.frame (v1  = c("a", "b", "c"),
                   v2 = c("1", "2", "a"),
                   v3 = c("2", "4", "c"),
                   period2 = c("Yes", "Yes", "Yes")
)
</code>```
```<code>countries <- c("Fr", "Be", "De")
df <- data.frame (v1  = c("a", "b", "c"),
                  v2 = c("1", "2", "a"),
                  v3 = c("2", "4", "c")
)

for(c in countries) {
  for(i in 1:6) {
     p <- paste0("period", i)
     new <- "Yes"
     a <- df %>%
       mutate(p = new)
     assign(paste0(c,i), a)
  }
}
</code>```

答:
I think you are looking for something like this -

```<code>library(tidyverse)

countries <- c("Fr", "Be", "De")
df <- data.frame (v1  = c("a", "b", "c"),
                  v2 = c("1", "2", "a"),
                  v3 = c("2", "4", "c")
)

for(c in countries) {
  for(i in 1:6) {
    p <- paste0("period", i)
    new <- "Yes"
    a <- df %>%  mutate(!!p := new)
    assign(paste0(c,i), a)
  }
}
</code>```

However, it is not a good practice to create so many dataframes in global environment, use lists instead.

Something like this -

```<code>pmap(expand_grid(countries, n), function(...) {
  df %>% mutate(!!paste0("period", ..2) := 'new')
})
</code>```

Title: Generate Variable Inside Loop Dplyr

Body:
I am trying to generate a variable inside a loop using mutate. This variable should simply be the concatenate of the word period and the loop iteration number i.

Unfortunately the following code generates the variable p instead of period1, period2, and so on.

Does anyone know how can I get the name as period1 instead of simply p?

The expected outcome is the following:

Fr1 <- data.frame (v1  = c("a", "b", "c"),
                  v2 = c("1", "2", "a"),
                  v3 = c("2", "4", "c"),
                  period1 = c("Yes", "Yes", "Yes")
)

Fr2 <- data.frame (v1  = c("a", "b", "c"),
                   v2 = c("1", "2", "a"),
                   v3 = c("2", "4", "c"),
                   period2 = c("Yes", "Yes", "Yes")
)

countries <- c("Fr", "Be", "De")
df <- data.frame (v1  = c("a", "b", "c"),
                  v2 = c("1", "2", "a"),
                  v3 = c("2", "4", "c")
)

for(c in countries) {
  for(i in 1:6) {
     p <- paste0("period", i)
     new <- "Yes"
     a <- df %>%
       mutate(p = new)
     assign(paste0(c,i), a)
  }
}

Body:
I think you are looking for something like this -

library(tidyverse)

countries <- c("Fr", "Be", "De")
df <- data.frame (v1  = c("a", "b", "c"),
                  v2 = c("1", "2", "a"),
                  v3 = c("2", "4", "c")
)

for(c in countries) {
  for(i in 1:6) {
    p <- paste0("period", i)
    new <- "Yes"
    a <- df %>%  mutate(!!p := new)
    assign(paste0(c,i), a)
  }
}

However, it is not a good practice to create so many dataframes in global environment, use lists instead.

Something like this -

pmap(expand_grid(countries, n), function(...) {
  df %>% mutate(!!paste0("period", ..2) := 'new')
})


问:
First three items of of NSArray into an NSString?
What would be the most efficient way of turning the first three objects (or 1 or 2 if that's how big the array is) of an array, into a string, which is comma-separated. I've got a feeling there is a way to this with blocks, but I can't work it out

The objects are Bands, stored in bandArray, and the attributes of each band include a bandName.

So the output would be something like

```<code>String
"Abba"                    <- when there is one object
"Abba, Kiss"              <- when there is two objects
"Abba, Kiss, Nirvana"     <- when there is three objects
"Abba, Kiss, Nirvana"     <- when there is four objects. after three, names are ignored
</code>```

答:
May not be the quickest but the simplest, and who know apple apple may do some smarts when creating subarrays.</p>

```<code>[[array subarrayWithRange:NSMakeRange(0,MIN(array.length,3)] componentsJoinedByString:@","];
</code>```

Body:
What would be the most efficient way of turning the first three objects (or 1 or 2 if that's how big the array is) of an array, into a string, which is comma-separated. I've got a feeling there is a way to this with blocks, but I can't work it out

The objects are Bands, stored in bandArray, and the attributes of each band include a bandName.

So the output would be something like

String
"Abba"                    <- when there is one object
"Abba, Kiss"              <- when there is two objects
"Abba, Kiss, Nirvana"     <- when there is three objects
"Abba, Kiss, Nirvana"     <- when there is four objects. after three, names are ignored

Body:
May not be the quickest but the simplest, and who know apple apple may do some smarts when creating subarrays.

[[array subarrayWithRange:NSMakeRange(0,MIN(array.length,3)] componentsJoinedByString:@","];


问:
How to enable C++17 in CMake
I'm using VS 15.3, which supports integrated CMake 3.8. How can I target C++17 without writing flags for each specific compilers? My current global settings don't work:

```<code># https://cmake.org/cmake/help/latest/prop_tgt/CXX_STANDARD.html
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

# expected behaviour
#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /std:c++latest")
</code>```

I expected CMake to add "/std:c++lastest" or equivalents when generating VS solution files, but no c++17 flags was found, resulted in compiler error:

```<code>C1189 #error: class template optional is only available with C++17.
</code>```

答:
Bash command line in CMake flags:</p>
```<code>-DCMAKE_CXX_STANDARD=17 \
-DCMAKE_CXX_STANDARD_REQUIRED=ON \
-DCMAKE_CXX_EXTENSIONS=OFF \
</code>```

Title: How to enable C++17 in CMake

Body:
I'm using VS 15.3, which supports integrated CMake 3.8. How can I target C++17 without writing flags for each specific compilers? My current global settings don't work:

# https://cmake.org/cmake/help/latest/prop_tgt/CXX_STANDARD.html
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

# expected behaviour
#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /std:c++latest")

I expected CMake to add "/std:c++lastest" or equivalents when generating VS solution files, but no c++17 flags was found, resulted in compiler error:

C1189 #error: class template optional is only available with C++17.

Body:
Bash command line in CMake flags:

-DCMAKE_CXX_STANDARD=17 \
-DCMAKE_CXX_STANDARD_REQUIRED=ON \
-DCMAKE_CXX_EXTENSIONS=OFF \


问:
Gstreamer x-raw to h264 mp4
The documentation for some software I'm using says to use this gstreamer pipeline to stream video from a camera:

```<code>gst-launch-1.0 v4l2src device=/dev/video5 ! video/x-raw ! videoconvert ! v4l2h264enc ! h264parse config-interval=3 ! rtph264pay mtu=1024 ! udpsink host=127.0.0.1 port=5600
</code>```

If I wanted to adapted this to pipe to a .mp4, I thought something like this would work:

```<code>gst-launch-1.0 v4l2src device=/dev/video5 ! video/x-raw ! videoconvert ! v4l2h264enc ! h264parse config-interval=3 ! filesink location=test.mp4
</code>```

but the resulting file is not playable in vlc.

What am I missing?

Thanks in advance.

答:
You would use a container (such as qtmux here) :</p>
```<code># For recording 100 frames:
gst-launch-1.0 v4l2src device=/dev/video5 num-buffers=100 ! video/x-raw ! videoconvert ! v4l2h264enc ! h264parse config-interval=3 ! qtmux ! filesink location=test.mp4

# If you want to stop mnaually with Ctrl-C, add EOS:
gst-launch-1.0 -e v4l2src device=/dev/video5 ! video/x-raw ! videoconvert ! v4l2h264enc ! h264parse config-interval=3 ! qtmux ! filesink location=test.mp4
</code>```

Title: Gstreamer x-raw to h264 mp4

Body:
The documentation for some software I'm using says to use this gstreamer pipeline to stream video from a camera:

gst-launch-1.0 v4l2src device=/dev/video5 ! video/x-raw ! videoconvert ! v4l2h264enc ! h264parse config-interval=3 ! rtph264pay mtu=1024 ! udpsink host=127.0.0.1 port=5600

If I wanted to adapted this to pipe to a .mp4, I thought something like this would work:

gst-launch-1.0 v4l2src device=/dev/video5 ! video/x-raw ! videoconvert ! v4l2h264enc ! h264parse config-interval=3 ! filesink location=test.mp4

but the resulting file is not playable in vlc.

What am I missing?

Thanks in advance.

Body:
You would use a container (such as qtmux here) :

# For recording 100 frames:
gst-launch-1.0 v4l2src device=/dev/video5 num-buffers=100 ! video/x-raw ! videoconvert ! v4l2h264enc ! h264parse config-interval=3 ! qtmux ! filesink location=test.mp4

# If you want to stop mnaually with Ctrl-C, add EOS:
gst-launch-1.0 -e v4l2src device=/dev/video5 ! video/x-raw ! videoconvert ! v4l2h264enc ! h264parse config-interval=3 ! qtmux ! filesink location=test.mp4


问:
Preformat date from database before compare with date from user input in laravel
I have an table where I'm storing downloads of the user, columns - created_at and updated_at.
What I'm trying to do is simple filter where I can choose from datepicker From-To dates and show all downloads for given time range.

This is what I have in my function

```<code>$dateStart = new DateTime($request->startDate); // '2022-02-01';
$dateEnd = new DateTime($request->dateEnd); //'2022-02-08';
        //dd($dateStart);

$downloadsbyuser = DB::table('downloads')
   ->select('user_id as downloader_id', DB::raw('COUNT(id) as count_by_user_id'))
   ->whereBetween('downloads.updated_at', [$dateStart, $dateEnd])
   ->groupBy('user_id');
</code>```

So, in database, the columns are defaultfor laravel and timestamp. The date coming from datepicker is in 2022-02-01.

This is what I have in database

```<code>ID  user_id   created_at             updated_at
1   34        2022-02-06 10:17:39    2022-02-06 10:17:39
2   34        2022-02-08 10:17:39    2022-02-08 10:17:39
3   20        2022-02-02 10:17:39    2022-02-05 10:17:39
4   34        2022-02-02 10:17:39    2022-02-05 10:17:39
</code>```

When I search dates 2022-02-01 to 2022-02-06 as you can see I should get 3 results - ID's 1,3 and 4 but instead I've got 2 results. When I search 2022-02-01 to 2022-02-07 then I've got correct 3 results but this means that if there is entry with date 2022-02-07 it wont show.

Why is this happen? Is it because of the whereBetween clause?

答:
Try MySql date_format function!

```<code>$dateStart = new DateTime($request->startDate); // '2022-02-01';
$dateEnd = new DateTime($request->dateEnd); //'2022-02-08';

$downloadsbyuser = DB::table('downloads')
   ->select('user_id as downloader_id', DB::raw('COUNT(id) as count_by_user_id'))
   ->whereBetween(DB::raw("DATE_FORMAT(downloads.updated_at, '%Y-%m-%d')"), [$dateStart, $dateEnd])
   ->groupBy('user_id');
</code>```

Body:
I have an table where I'm storing downloads of the user, columns - created_at and updated_at.
What I'm trying to do is simple filter where I can choose from datepicker From-To dates and show all downloads for given time range.

This is what I have in my function

$dateStart = new DateTime($request->startDate); // '2022-02-01';
$dateEnd = new DateTime($request->dateEnd); //'2022-02-08';
        //dd($dateStart);

$downloadsbyuser = DB::table('downloads')
   ->select('user_id as downloader_id', DB::raw('COUNT(id) as count_by_user_id'))
   ->whereBetween('downloads.updated_at', [$dateStart, $dateEnd])
   ->groupBy('user_id');

So, in database, the columns are defaultfor laravel and timestamp. The date coming from datepicker is in 2022-02-01.

This is what I have in database

ID  user_id   created_at             updated_at
1   34        2022-02-06 10:17:39    2022-02-06 10:17:39
2   34        2022-02-08 10:17:39    2022-02-08 10:17:39
3   20        2022-02-02 10:17:39    2022-02-05 10:17:39
4   34        2022-02-02 10:17:39    2022-02-05 10:17:39

When I search dates 2022-02-01 to 2022-02-06 as you can see I should get 3 results - ID's 1,3 and 4 but instead I've got 2 results. When I search 2022-02-01 to 2022-02-07 then I've got correct 3 results but this means that if there is entry with date 2022-02-07 it wont show.

Why is this happen? Is it because of the whereBetween clause?

Body:
Try MySql date_format function!

$dateStart = new DateTime($request->startDate); // '2022-02-01';
$dateEnd = new DateTime($request->dateEnd); //'2022-02-08';

$downloadsbyuser = DB::table('downloads')
   ->select('user_id as downloader_id', DB::raw('COUNT(id) as count_by_user_id'))
   ->whereBetween(DB::raw("DATE_FORMAT(downloads.updated_at, '%Y-%m-%d')"), [$dateStart, $dateEnd])
   ->groupBy('user_id');


问:
How to implement a generic macro in C?
```<code>FUNC(param);
</code>```

When param is char *,dispatch to func_string.

when it's int,dispatch to func_int

I think there may be a solution to this,as variable types are known at compile time..

答:
my definition of a generic:
a structured abstract type which can only be fully defined with an input of other concrete types

this sounds exactly like a macro to me

pardon the psudo c code, my c is rusty

#include <stdio.h>

// todo: ret=self needs vec3##generic_t##_copy(self, ret);
// not to mention we should probably be using __builtin_add_overflow
// __builtin_add_overflow might actually itself be a reasonably generics method example
// please bear with me
#define GENERIC_VEC3_ADD(generic_t) \
    generic_t vec3##generic_t##_add(generic_t self, generic_t other) {\
        generic_t ret = self;\
        ret[0] += other [0];;\
        ret[1] += other [1];\
        ret[2] += other [2];\
        return ret;\
    }

#define GENERIC_VEC3_FREPR(generic_t, printf_ts) \
    int vec3##generic_t##_frepr(generic_t self, FILE fd)\
        rerurn fprintf(fd, "<vec3##generic_t (##printf_ts##, printf_ts##, printf_ts##)>", \
        self[0], self[1], self[2]);\
    }

// here is the generic typedef, with some methods
#define GENERIC_VEC3(genetic_t, printf_ts) \
    typedef vec3##generic_t generic_t[3];\
    GENERIC_VEC3_ADD(generic_t) \
    GENERIC_VEC3_FREPR(generic_t, printf_ts)

// later we decide what types we want this genic for
GENERIC_VEC3(int, %ul)

// and use our generic
int main()
{
    vec3int foo = { 1, 2, 3 };;
    vec3int bar = { 1, 2, 3 };;
    vec3int sum = vec3int_add(foo, bar);
    vec3int_frepr(sum, stderr);
    fprintf(stderr, "\n");
    exit EXIT_SUCCESS;
}
```

Title: How to implement a generic macro in C?

Body:
FUNC(param);

When param is char *,dispatch to func_string.

when it's int,dispatch to func_int

I think there may be a solution to this,as variable types are known at compile time..


问:
How to compare two dates in different formats
I have a two dates in one format 19/02/2026, 07/02/2012 and third date in

```<code>2021-05-19T12:51:11.630Z
</code>```

It's YYYY-MM-DDTHH:mm:ss.SSSSZ.
And i need to check third date if it is between those to dates.
But the problem is that i cannot find way how to do it with different formats.
I tried to use moment() isBetween, isBefore(), isAfter() functions but it didn't work correctly because of different formats

I tried to convert them all to miliseconds

```<code>moment('19/02/2026').valueOf()
</code>```

But from time to time instead of miliseconds i recieve NaaN value.
I also tried to use

```<code>Date().parse()
</code>```

But it gives Invalid Date most of the time.
I could do something like this, but i think it's wrong way.

```<code>let currentDate = moment( moment('2021-05-19T12:51:11.630Z').format('DD/MM/YYYY'))
</code>```

Is there are any simple ways to do it with Date or moment ?

答:
To parse a string which is not either an RFC2822 or ISO8601 format, you will need to specify the format to use:

```<code>const d = moment('19/02/2026', 'DD/MM/YYYY');
</code>```

Rather than using valueOf, you can test whether one moment instance is between two other moment instances by using isBetween:

```<code>const startDate = moment('07/02/2012', 'DD/MM/YYYY');
const endDate = moment('19/02/2026', 'DD/MM/YYYY');
const dateToTest = moment('2021-05-19T12:51:11.630Z');
if (dateToTest.isBetween(startDate, endDate)) {
    alert("Between");
} else {
    alert("Not between");
}
</code>```

String + Format | Moment.js | Docs

Is Between | Moment.js | Docs

Body:
I have a two dates in one format 19/02/2026, 07/02/2012 and third date in

2021-05-19T12:51:11.630Z

It's YYYY-MM-DDTHH:mm:ss.SSSSZ.
And i need to check third date if it is between those to dates.
But the problem is that i cannot find way how to do it with different formats.
I tried to use moment() isBetween, isBefore(), isAfter() functions but it didn't work correctly because of different formats

I tried to convert them all to miliseconds

moment('19/02/2026').valueOf()

But from time to time instead of miliseconds i recieve NaaN value.
I also tried to use

Date().parse()

But it gives Invalid Date most of the time.
I could do something like this, but i think it's wrong way.

let currentDate = moment( moment('2021-05-19T12:51:11.630Z').format('DD/MM/YYYY'))

Is there are any simple ways to do it with Date or moment ?

Body:
To parse a string which is not either an RFC2822 or ISO8601 format, you will need to specify the format to use:

const d = moment('19/02/2026', 'DD/MM/YYYY');

Rather than using valueOf, you can test whether one moment instance is between two other moment instances by using isBetween:

const startDate = moment('07/02/2012', 'DD/MM/YYYY');
const endDate = moment('19/02/2026', 'DD/MM/YYYY');
const dateToTest = moment('2021-05-19T12:51:11.630Z');
if (dateToTest.isBetween(startDate, endDate)) {
    alert("Between");
} else {
    alert("Not between");
}

String + Format | Moment.js | Docs

Is Between | Moment.js | Docs


答:
There is no way for a .php file to be downloaded through http, assuming that your server configuration does not change (e.g the handler for PHP files is removed). If this does happen, then it is possible that .php files could be downloaded as plain text files.

You should put all core files outside of the public directory (public_html, htdocs etc.) and call them using their path.

Title: index.php and protecting of its content


问:
Reverting one file in GitKraken
It is possible in GitKraken to revert changes of a single file to an earlier commit instead of reverting an entire commit?</p>

答:
GitKraken 7.3.0 (probably older versions too) does allow for effectively running git checkout on a single file in the UI: Right click on the file under "unstaged files" and select "discard changes". Works on folders as well.

(This answer was previously a comment to the accepted answer)

Title: Reverting one file in GitKraken


问:
Run rspec on VS Code
I have rspec test code like this

```<code>describe 'Utils' do

  puts 1111
  describe '#time_condition' do
    puts 2221
    it do
      puts 'aaa'
    end
    puts 2223
  end
end
</code>```

my launch.json like this

```<code>{
  "name": "RSpec - all",
  "type": "Ruby",
  "request": "launch",
  "cwd": "${workspaceRoot}",
  "program": "${workspaceRoot}/spec/*_rspec.rb",
  "args": [
    "--pattern",
    "*_rspec.rb"
  ]
},
</code>```

when I run test on vscode, I got

```<code>1111
2221
2223
</code>```

when I run test by command, got

```<code>>rspec spec --pattern *_rspec.rb
1111
2221
2223
aaa
.

Finished in 0.003 seconds (files took 0.23602 seconds to load)
1 example, 0 failures
</code>```

As your can see, no 'aaa' output, means no 'it' was executed.
So...How can I make 'it' to run on vscode?

by the way, my spec config files (generated by rspec --init)like

.rspec

```<code>--color
--require spec_helper
</code>```

spec\spec_helper.rb

```<code>RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end

  config.profile_examples = 10

  config.order = :random

  Kernel.srand config.seed
end
</code>```

VScode : 1.4.0

Ruby Extensions : 0.5.3

thanks

答:
I switched to using the debug gem. Seems to be quite straightforward and future proof.

Install the gem and this extension: https://marketplace.visualstudio.com/items?itemName=KoichiSasada.vscode-rdbg

In launch.json I use a current line rspec call:

```<code>{
  "type": "rdbg",
  "name": "Run rake spec",
  "request": "launch",
  "command": "bundle exec rspec",
  "script": "${file}:${lineNumber}",
  "args": [],
  "askParameters": false
}
</code>```

I haven't tested this extensively but haven't had any issues yet on Ruby 3.0.2

Title: Run rspec on VS Code

Body:
I have rspec test code like this

describe 'Utils' do

  puts 1111
  describe '#time_condition' do
    puts 2221
    it do
      puts 'aaa'
    end
    puts 2223
  end
end

my launch.json like this

{
  "name": "RSpec - all",
  "type": "Ruby",
  "request": "launch",
  "cwd": "${workspaceRoot}",
  "program": "${workspaceRoot}/spec/*_rspec.rb",
  "args": [
    "--pattern",
    "*_rspec.rb"
  ]
},

when I run test on vscode, I got

1111
2221
2223

when I run test by command, got

>rspec spec --pattern *_rspec.rb
1111
2221
2223
aaa
.

Finished in 0.003 seconds (files took 0.23602 seconds to load)
1 example, 0 failures

As your can see, no 'aaa' output, means no 'it' was executed.
So...How can I make 'it' to run on vscode?

by the way, my spec config files (generated by rspec --init)like

.rspec

--color
--require spec_helper

spec\spec_helper.rb

RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end

  config.profile_examples = 10

  config.order = :random

  Kernel.srand config.seed
end

VScode : 1.4.0

Ruby Extensions : 0.5.3

thanks

Body:
I switched to using the debug gem. Seems to be quite straightforward and future proof.

Install the gem and this extension: https://marketplace.visualstudio.com/items?itemName=KoichiSasada.vscode-rdbg

In launch.json I use a current line rspec call:

{
  "type": "rdbg",
  "name": "Run rake spec",
  "request": "launch",
  "command": "bundle exec rspec",
  "script": "${file}:${lineNumber}",
  "args": [],
  "askParameters": false
}

I haven't tested this extensively but haven't had any issues yet on Ruby 3.0.2