问:
In a for loop : Append different string format to a varaible in bash
I want to construct this string:

```<code>"reconfig -add  server.3=(some_value),4=(some_value),5=(some_value)"
</code>```

How to do I construct this over a for loop?

```<code>starting_value=3
end_value=6

for (i=${starting_value};i<${end_value};i++)
do
   # constuct the string above where my "reconfig -add  server." is constant
done;
</code>```

conditions to satisfy:

if I have to loop once, say i=3 and i<4, I only want "reconfig -add  server.3=(some_value)"

if I have to loop twice, say i=3 and i<5 I want "reconfig -add  server.3=(some_value),4=(some_value)"

This should apply for any start or end value and also "comma" should not be placed after the end of string.

答:
```<code>#!/bin/bash
starting_value=3
end_value=6

s="reconfig -add  server."

for (( i=${starting_value};i<${end_value};i++ ))
do
    s+=$i="(some_value)"
    s+=','
done;

# Remove last comma
s=${s::-1}
echo $s
</code>```

Body:
I want to construct this string:

"reconfig -add  server.3=(some_value),4=(some_value),5=(some_value)"

How to do I construct this over a for loop?

starting_value=3
end_value=6

for (i=${starting_value};i<${end_value};i++)
do
   # constuct the string above where my "reconfig -add  server." is constant
done;

conditions to satisfy:

if I have to loop once, say i=3 and i<4, I only want "reconfig -add  server.3=(some_value)"

if I have to loop twice, say i=3 and i<5 I want "reconfig -add  server.3=(some_value),4=(some_value)"

This should apply for any start or end value and also "comma" should not be placed after the end of string.


来源: stackexchange

问:
C# new operator - different between assignment to variable and without

What is conceptual different between creation of a new instances of a Example class with assignment to variables and without new Example(); new Example();

    public class Example
    {
    }

    Example someVariableFirst = new Example();
    Example someVariableSecond = new Example();
    //vs
    new Example();
    new Example();
```

How to view this in Visual Studio during app running?  Assignment to variable I'll see in Debug->Locals, but how to see new Example(); new Example()?

答: You don't. Creating that object has no side effects, and the reference is never stored. So not only may it be garbage collected immediately after creation, the runtime is free to elide its creation entirely.</p>

ContentLicense: CC BY-SA 4.0

Body:
What is conceptual different between creation of a new instances of a Example class with assignment to variables and without new Example(); new Example();

    public class Example
    {
    }

    Example someVariableFirst = new Example();
    Example someVariableSecond = new Example();
    //vs
    new Example();
    new Example();

How to view this in Visual Studio during app running?  Assignment to variable I'll see in Debug->Locals, but how to see new Example(); new Example()?


问:
Flutter - Firebase RTDB read issue for node at index 0, 1 and 2
In my Flutter code, I have a dropdown list linked to a list of cars. Once a car is selected I want to retrieve the brand associated to the car. But for some reason the code used to read the firebase RTDB has to be different for Index 0, index 1 and Index 2 and above. My sample tree taken as is from my RTDB is as follows:

```<code>[ {
  "Brand" : "Alfa Romeo",
  "Car" : "Alfa Romeo Guilia 2.9 V6 BiTurbo Quadrifoglioli Automatic Petrol Sedan RWD",

}, {
  "Brand" : "Alfa Romeo",
  "Car" : "Alfa Romeo Guilia 2.0T Standard Automatic Petrol Sedan RWD",

}, {
 "Brand" : "Alfa Romeo",
 "Car" : "Alfa Romeo Guilia 2.0T Super Automatic Petrol Sedan RWD",

}, {
  "Brand" : "Alfa Romeo",
  "Car" : "Alfa Romeo Stelvio 2.0 Turbo Super Automatic Petrol SUV AWD",

}, {
  "Brand" : "Alfa Romeo",
  "Car" : "Alfa Romeo Stelvio 2.0 Turbo First Edition Automatic Petrol SUV AWD",

}, {
  "Brand" : "Alfa Romeo",
  "Car" : "Alfa Romeo 4C 1750Tbi N/A TCT Petrol Coupe RWD",

}]
</code>```

The parent of the above is `CarList2'

In my flutter code I have to use the following to retrieve the brand:

```<code>final dbRef = FirebaseDatabase.instance.reference().child('CarList2');

void CreateNewDeal(String selectedcar) async{

await dbRef.orderByChild('Car').equalTo(selectedcar).once().then((DataSnapshot snap) {

    print('length - ${snap.value.length}');

    List<dynamic> brand = [];

// Code for Index 0 and index 1

    snap.value.forEach((v1) {

      brand.add(v1);
      if(snap.value.length == 1 && brand[0]['Brand'] != null){

        selectedbrand = brand[0]['Brand'];
        print('brand index0 - ${brand[0]['Brand']}');

      }

      else if(snap.value.length == 2){

        print('brand index 1 - ${snap.value[1]['Brand']}');
      }

    });

/**
        following code gets the brand for index 1-->
     */

    Map<dynamic,dynamic> values = snap.value;

    values.forEach((key, v2) {

      selectedbrand = v2['Brand'];
      print('Brand index 2>:(${v2['Brand']})');

    });

  });

}catch(e){
  print(e.toString());

   }
}
</code>```

In the above, I cannot run the index 0 and index 2 the same time as index 1 if the index 1 car is selected because the code will return a null on the index 0 or 2 and then never makes it to the code for index 1.

I also get variable lengths of the snapshot for the children as follows:

Index 0 = length 1
Index 1 - length 2
Index 2 and above = length 1

Am I doing something wrong or am I meant to be reading this in a different way?

答:
For anyone looking for a similar solution, take note of Frank van Puffelen's answer he provided me in the comments. read the article, but in short, stay clear of numbered indexes.

Frank gave me the direction to essentially re-structure my tree which is quite easy to do. export using firebase, use a Json to CSV converter (can be found online - i used https://www.convertcsv.com/csv-to-json.htm). once in CSV format, add a key column as the first column. add any sequential string as the keys. Then convert again using an online CSV to Json converter. I used this one (https://csvjson.com/csv2json) because what you want is to create the new tree as a hashmap (at least in my instance) you do not want a numbered index created between the key and the children again which the other website ended up doing.

By doing this you now able to retrieve the child for all nodes without the null error i was getting between Index 0,1 and 2.

NOTE: this was a specific issue for me because my list is static and gets created outside of the app and only updated once in a while. if you creating your list via the app then you should not be getting an error like this.

Body:
In my Flutter code, I have a dropdown list linked to a list of cars. Once a car is selected I want to retrieve the brand associated to the car. But for some reason the code used to read the firebase RTDB has to be different for Index 0, index 1 and Index 2 and above. My sample tree taken as is from my RTDB is as follows:

[ {
  "Brand" : "Alfa Romeo",
  "Car" : "Alfa Romeo Guilia 2.9 V6 BiTurbo Quadrifoglioli Automatic Petrol Sedan RWD",

}, {
  "Brand" : "Alfa Romeo",
  "Car" : "Alfa Romeo Guilia 2.0T Standard Automatic Petrol Sedan RWD",

}, {
 "Brand" : "Alfa Romeo",
 "Car" : "Alfa Romeo Guilia 2.0T Super Automatic Petrol Sedan RWD",

}, {
  "Brand" : "Alfa Romeo",
  "Car" : "Alfa Romeo Stelvio 2.0 Turbo Super Automatic Petrol SUV AWD",

}, {
  "Brand" : "Alfa Romeo",
  "Car" : "Alfa Romeo Stelvio 2.0 Turbo First Edition Automatic Petrol SUV AWD",

}, {
  "Brand" : "Alfa Romeo",
  "Car" : "Alfa Romeo 4C 1750Tbi N/A TCT Petrol Coupe RWD",

}]

The parent of the above is `CarList2'

In my flutter code I have to use the following to retrieve the brand:

final dbRef = FirebaseDatabase.instance.reference().child('CarList2');

void CreateNewDeal(String selectedcar) async{

await dbRef.orderByChild('Car').equalTo(selectedcar).once().then((DataSnapshot snap) {

    print('length - ${snap.value.length}');

    List<dynamic> brand = [];

// Code for Index 0 and index 1

    snap.value.forEach((v1) {

      brand.add(v1);
      if(snap.value.length == 1 && brand[0]['Brand'] != null){

        selectedbrand = brand[0]['Brand'];
        print('brand index0 - ${brand[0]['Brand']}');

      }

      else if(snap.value.length == 2){

        print('brand index 1 - ${snap.value[1]['Brand']}');
      }

    });

/**
        following code gets the brand for index 1-->
     */

    Map<dynamic,dynamic> values = snap.value;

    values.forEach((key, v2) {

      selectedbrand = v2['Brand'];
      print('Brand index 2>:(${v2['Brand']})');

    });

  });

}catch(e){
  print(e.toString());

   }
}

In the above, I cannot run the index 0 and index 2 the same time as index 1 if the index 1 car is selected because the code will return a null on the index 0 or 2 and then never makes it to the code for index 1.

I also get variable lengths of the snapshot for the children as follows:

Index 0 = length 1
Index 1 - length 2
Index 2 and above = length 1

Am I doing something wrong or am I meant to be reading this in a different way?


问:
What is the correct Device Definition for Google Glass (for a simulator in Eclipse or Android studio)?
Yes I will test on the actual device (when it arrives) but would be nice to know now:

How to setup a device definition so I can run an emulator that is something like glass.

Critical are:

Size: What size does glass "report" itself as: Small, Normal, Large,    XLarge

Screen Ratio: notlong or Long?

Density bucket: xxhdpi? or what?

Other: does setting it up for DPad input help at all or come close to the nav on Glass? Other tips?

Note: Yes I know about the mirror API playground, but I'm developing APKs not mirror-api.

答:
As for Enterprise Edition 2, according to Tech Specs, I configured new hardware profile for virtual device as following:

Hardware profile:

System image:

ContentLicense: CC BY-SA 3.0


问:
query with sql max function
table view with 4 records

Would the following query work if I wanted to select the 2nd and 3rd records?

```<code>select driver_name, driver_city, driver_email, max(due_date), max(completion_date)
from TableX
group by driver_name,driver_city,driver_email
</code>```

答:
As your date values are not in well formatted, you need to first convert your values into DATE and then apply other logic. Please check my updated script now-

Issues:

You value in completion_date column is string. as a result, MAX was returning the value considering STRING, not DATE.

You have no YEAR value in the completion_date column. As a result, I just added '2020' to the value so that DATE value generated properly. At the end, the added year has no impact on the output. And this is considering all DTAEs are from the single (any) YEAR only.

But if you have YEAR value in some other column, avoid adding static '2020' and use the value from that column

Check DEMO HERE

```<code>    SELECT A.*
FROM TableX A
INNER JOIN (
    SELECT driver_email,
    MAX(STR_TO_DATE(
        CONCAT(
        REPLACE(
            REPLACE(REPLACE(completion_date,'rd ','-'),
            'st ',
            '-'
        ),
        'th ',
        '-'
    ),'-2020') ,'%d-%b-%Y')) completion_date
    FROM TableX
    GROUP BY driver_email
) B ON A.driver_email = B.driver_email
AND STR_TO_DATE(
        CONCAT(
        REPLACE(
            REPLACE(REPLACE(A.completion_date,'rd ','-'),
            'st ',
            '-'
        ),
        'th ',
        '-'
    ),'-2020') ,'%d-%b-%Y') = B.completion_date
</code>```

Title: query with sql max function

Body:
table view with 4 records

Would the following query work if I wanted to select the 2nd and 3rd records?

select driver_name, driver_city, driver_email, max(due_date), max(completion_date)
from TableX
group by driver_name,driver_city,driver_email

Body:
As your date values are not in well formatted, you need to first convert your values into DATE and then apply other logic. Please check my updated script now-

Issues:

You value in completion_date column is string. as a result, MAX was returning the value considering STRING, not DATE.

You have no YEAR value in the completion_date column. As a result, I just added '2020' to the value so that DATE value generated properly. At the end, the added year has no impact on the output. And this is considering all DTAEs are from the single (any) YEAR only.

But if you have YEAR value in some other column, avoid adding static '2020' and use the value from that column

Check DEMO HERE

    SELECT A.*
FROM TableX A
INNER JOIN (
    SELECT driver_email,
    MAX(STR_TO_DATE(
        CONCAT(
        REPLACE(
            REPLACE(REPLACE(completion_date,'rd ','-'),
            'st ',
            '-'
        ),
        'th ',
        '-'
    ),'-2020') ,'%d-%b-%Y')) completion_date
    FROM TableX
    GROUP BY driver_email
) B ON A.driver_email = B.driver_email
AND STR_TO_DATE(
        CONCAT(
        REPLACE(
            REPLACE(REPLACE(A.completion_date,'rd ','-'),
            'st ',
            '-'
        ),
        'th ',
        '-'
    ),'-2020') ,'%d-%b-%Y') = B.completion_date


问:
How to Create a C# COM Object using Visual Studio 2019
I have upgraded from Windows 7/Visual Studio 2015 to Windows10/Visual Studio 2019.
I wish to create a C# COM object which I can call from Excel(365) VBA code.

Using Win 7/Visual Studio 2015 the following very simple code compiles as a C# class library and creates a COM object that I can call successfully from Excel 2013 VBA:-

```<code>using System.Runtime.InteropServices;
namespace TestLib {
    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.AutoDual)]
    public class C_Hello {
        public string Hello() {
            return "Hello";
        }
    }
}
</code>```

In the Assembly Info I have ticked the checkbox "Make the Assembly COM Visible" and in the Build info I have ticked the checkbox "Register for COM interop"

The Excel 2013 VBA code is equally simple:

```<code>Sub Test()
    Dim x As TestLib.C_Hello
    Set x = New TestLib.C_Hello
    ActiveSheet.Range("C3").Value = x.Hello
End Sub
</code>```

where TestLib is the C# COM module created in Visual Studio.

In the Win 7/VS2015/Excel 2013 environment everything works fine, but under after transferring and compiling under Win 10/ VS2019 the Excel 365 VBA code errors at the line:-

```<code>Set x = New TestLib.C_Hello
</code>```

with the error message

Run Time error '-2147221164 (80040154)'

Class not registered

Can anyone tell me what I have to do to get this working in the Windows 10 / VS2019 / Excel 365 environment.? Is it Windows 10 or Visual Studio 2019 that is doing things differently?

答:
The solution in the Win10 / VS2019 environemnt was to change the Platform Target in VS's Build Tab from Any CPU to x64, and then it worked.

In the Win7 / VS2015 environment a Platform Target of Any CPU worked fine.

Body:
I have upgraded from Windows 7/Visual Studio 2015 to Windows10/Visual Studio 2019.
I wish to create a C# COM object which I can call from Excel(365) VBA code.

Using Win 7/Visual Studio 2015 the following very simple code compiles as a C# class library and creates a COM object that I can call successfully from Excel 2013 VBA:-

using System.Runtime.InteropServices;
namespace TestLib {
    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.AutoDual)]
    public class C_Hello {
        public string Hello() {
            return "Hello";
        }
    }
}

In the Assembly Info I have ticked the checkbox "Make the Assembly COM Visible" and in the Build info I have ticked the checkbox "Register for COM interop"

The Excel 2013 VBA code is equally simple:

Sub Test()
    Dim x As TestLib.C_Hello
    Set x = New TestLib.C_Hello
    ActiveSheet.Range("C3").Value = x.Hello
End Sub

where TestLib is the C# COM module created in Visual Studio.

In the Win 7/VS2015/Excel 2013 environment everything works fine, but under after transferring and compiling under Win 10/ VS2019 the Excel 365 VBA code errors at the line:-

Set x = New TestLib.C_Hello

with the error message

Run Time error '-2147221164 (80040154)'

Class not registered

Can anyone tell me what I have to do to get this working in the Windows 10 / VS2019 / Excel 365 environment.? Is it Windows 10 or Visual Studio 2019 that is doing things differently?


问:
Python pathlib make directories if they don’t exist
If I wanted to specify a path to save files to and make directories that don’t exist in that path, is it possible to do this using the pathlib library in one line of code?</p>

答:
This gives additional control for the case that the path is already there:

path = Path.cwd() / 'new' / 'hi' / 'there'
try:
    path.mkdir(parents=True, exist_ok=False)
except FileExistsError:
    print("Folder is already there")
else:
    print("Folder was created")
```


问:
Android Slow File Download vs iOS & BlackBerry - DefaultHttpClient
I am using the following code to download files, and I am finding that the performance is really really slow compared with virtually the same code on iOS and BlackBerry.

As well as testing on various different SDK versions and OSX vs Windows, I have also tried the App on various devices - HTC Desire, Samsung Galaxy, Huwei Pulse, HTC Wildfire - all with terrible performance vs. iPhone and BlackBerry devices.

Check out this video I made to compare the speeds on the 3 emulators:
  Android vs. iOS and BlackBerry

Here is the Android code:

```<code>FileOutputStream fos = null;
InputStream input = null;

try {
fos = new FileOutputStream("XXXX");

        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("XXXX");
        HttpResponse response = httpclient.execute(httpget);
        input = response.getEntity().getContent();

byte[] buffer = new byte[8192];
int readBytes;
while (((readBytes = input.read(buffer, 0, buffer.length)) != -1)
&& !thePackage.getPackageStatus().equals(
PackageStatus.STATUS_CANCEL_DOWNLOAD)) {
fos.write(buffer, 0, readBytes);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
}
}

if (input != null) {
try {
input.close();
} catch (IOException e) {
}

    }
}
</code>```

I've tried BufferedHttpEntity and other buffering/threading strategies, but this version of the code is the best performing out of any of the different options we've tried. I've run extensive code profiling, and can't see too much time being lost between the top level functions and the native code in Dalvik/Apache Harmony.

Any ideas would be fantastic, because the bad performance is making our application virtually unusable.

Thanks,

Nick

答:
The android documentations states that the FileOutputStream is not buffered and should be wrapped in a BufferedOutputStream.

```<code>    OutputStream out = null;
    try {
        out = new BufferedOutputStream(new FileOutputStream("XXXX"));

        // write to out

    } finally {
        if (out != null) {
            out.close();
        }

    }
</code>```

More info at FileOutputStream

Body:
I am using the following code to download files, and I am finding that the performance is really really slow compared with virtually the same code on iOS and BlackBerry.

As well as testing on various different SDK versions and OSX vs Windows, I have also tried the App on various devices - HTC Desire, Samsung Galaxy, Huwei Pulse, HTC Wildfire - all with terrible performance vs. iPhone and BlackBerry devices.

Check out this video I made to compare the speeds on the 3 emulators:
  Android vs. iOS and BlackBerry

Here is the Android code:

FileOutputStream fos = null;
InputStream input = null;

try {
fos = new FileOutputStream("XXXX");

        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("XXXX");
        HttpResponse response = httpclient.execute(httpget);
        input = response.getEntity().getContent();

byte[] buffer = new byte[8192];
int readBytes;
while (((readBytes = input.read(buffer, 0, buffer.length)) != -1)
&& !thePackage.getPackageStatus().equals(
PackageStatus.STATUS_CANCEL_DOWNLOAD)) {
fos.write(buffer, 0, readBytes);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
}
}

if (input != null) {
try {
input.close();
} catch (IOException e) {
}

    }
}

I've tried BufferedHttpEntity and other buffering/threading strategies, but this version of the code is the best performing out of any of the different options we've tried. I've run extensive code profiling, and can't see too much time being lost between the top level functions and the native code in Dalvik/Apache Harmony.

Any ideas would be fantastic, because the bad performance is making our application virtually unusable.

Thanks,

Nick

Body:
The android documentations states that the FileOutputStream is not buffered and should be wrapped in a BufferedOutputStream.

    OutputStream out = null;
    try {
        out = new BufferedOutputStream(new FileOutputStream("XXXX"));

        // write to out

    } finally {
        if (out != null) {
            out.close();
        }

    }

More info at FileOutputStream


问:
Why is jquery event delegation not working?
I have the following html:

```<code>        <ul id="contain">
         <li class="active_one"></li>
         <li class="two"></li>
        </ul>
</code>```

And the following jquery:

```<code>$contain = $('#contain'); //going to use a lot

$contain.on('click','li.two', function(){
                console.log('working');
                //plus do other stuff
                });
</code>```

The above does not work, but When I change it to:

```<code>$('body').on('click','li.two', function(){
                    console.log('working');
                    //plus do other stuff
                    });
</code>```

Then it works, but I know the best practice is to drill as close as possible to the parent element of what I am trying to work with, yet every time I try to do that, I am clearly doing something wrong because my parent level selectors are not working.

答:
So, I will try to explain how jquery on(change) works,

if you have

$(document).on('parameter 1','parameter 2', function(){} )

essentially, jquery will check if event mentioned in parameter 1 is executed or not. Then it will check if parameter 2 is present,

if so, Then it will check if the event mentioned in parameter 1 was triggered in the element mentioned in parameter 2. hence you can prevent on(change) events whenever the document changes.

this will help you to bind dynamically loaded elements by making sure the loaded elem has id and then binding events to that id alone. and whenever a document event occurs, the dynamic one will be executed.

Body:
I have the following html:

And the following jquery:

$contain = $('#contain'); //going to use a lot

$contain.on('click','li.two', function(){
                console.log('working');
                //plus do other stuff
                });

The above does not work, but When I change it to:

$('body').on('click','li.two', function(){
                    console.log('working');
                    //plus do other stuff
                    });

Then it works, but I know the best practice is to drill as close as possible to the parent element of what I am trying to work with, yet every time I try to do that, I am clearly doing something wrong because my parent level selectors are not working.


问:
Regex for Decimal number not working in flutter TextFormField inputFormatters
The requirement for Regex:

Max length of the number is 12 character

If there is a decimal point in number then the user can add a maximum of 4 digits after the decimal point and minimum 1 digit.

Valid Inputs: - 222244445555, 22223333.3333, 5555.33, 1.2, 0.33, 11112222333.3

InValid Inputs: 22., .11, 2222333344443,444445555544.,333344445.1234

I have tried to generate regex for the same on RegExr and it satisfied my requirements but when I applied the same for the flutter form TextFormField it not working.

Regex: ^[[0-9]{0,8}(\.[0-9]{1,4})?$|^[[0-9]{0,9}(\.[0-9]{1,3})?$|^[[0-9]{0,10}(\.[0-9]{1,2})?$|^[[0-9]{0,11}(\.[0-9]{1})?$|^[0-9]{0,12}

Flutter TextFieldCode:

```<code>TextFormField(
   controller: _textEditingController,
   keyboardType:TextInputType.numberWithOptions(decimal: true),
   inputFormatters: <TextInputFormatter>[
          WhitelistingTextInputFormatter(RegExp(r'^[[0-9]{0,8}(\.[0-9]{1,4})?$|^[[0-9]{0,9}(\.[0-9]{1,3})?$|^[[0-9]{0,10}(\.[0-9]{1,2})?$|^[[0-9]{0,11}(\.[0-9]{1})?$|^[0-9]{0,12}')),
   ],
),
</code>```

Using the above code I am not able to type dot(.) inside the TextFormField.

Note: Users should not be able to enter the number more than one decimal point in the TextFormField.

答:
Note that if you want to validate the whole input sequence you need to define a validator: validateMyInput and then implement the function:

```<code>String validateMyInput(String value) {
    RegExp regex = new RegExp(r'^(?=\D*(?:\d\D*){1,12}$)\d+(?:\.\d{1,4})?$');
    if (!regex.hasMatch(value))
      return 'Enter Valid Number';
    else
      return null;
  }
</code>```

See more details at Form Validation in Flutter.

The regex is

```<code>^(?=\D*(?:\d\D*){1,12}$)\d+(?:\.\d{1,4})?$
</code>```

See its demo. Details

^ - start of string

(?=\D*(?:\d\D*){1,12}$) - one to twelve digits required in the string

\d+ - 1 or more digits

(?:\.\d{1,4})? - an optional sequence of a . and then 1, 2, 3 or 4 digits

$ - end of string.

Body:
The requirement for Regex:

Max length of the number is 12 character

If there is a decimal point in number then the user can add a maximum of 4 digits after the decimal point and minimum 1 digit.

Valid Inputs: - 222244445555, 22223333.3333, 5555.33, 1.2, 0.33, 11112222333.3

InValid Inputs: 22., .11, 2222333344443,444445555544.,333344445.1234

I have tried to generate regex for the same on RegExr and it satisfied my requirements but when I applied the same for the flutter form TextFormField it not working.

Regex: ^[[0-9]{0,8}(\.[0-9]{1,4})?$|^[[0-9]{0,9}(\.[0-9]{1,3})?$|^[[0-9]{0,10}(\.[0-9]{1,2})?$|^[[0-9]{0,11}(\.[0-9]{1})?$|^[0-9]{0,12}

Flutter TextFieldCode:

TextFormField(
   controller: _textEditingController,
   keyboardType:TextInputType.numberWithOptions(decimal: true),
   inputFormatters: <TextInputFormatter>[
          WhitelistingTextInputFormatter(RegExp(r'^[[0-9]{0,8}(\.[0-9]{1,4})?$|^[[0-9]{0,9}(\.[0-9]{1,3})?$|^[[0-9]{0,10}(\.[0-9]{1,2})?$|^[[0-9]{0,11}(\.[0-9]{1})?$|^[0-9]{0,12}')),
   ],
),

Using the above code I am not able to type dot(.) inside the TextFormField.

Note: Users should not be able to enter the number more than one decimal point in the TextFormField.

Body:
Note that if you want to validate the whole input sequence you need to define a validator: validateMyInput and then implement the function:

String validateMyInput(String value) {
    RegExp regex = new RegExp(r'^(?=\D*(?:\d\D*){1,12}$)\d+(?:\.\d{1,4})?$');
    if (!regex.hasMatch(value))
      return 'Enter Valid Number';
    else
      return null;
  }

See more details at Form Validation in Flutter.

The regex is

^(?=\D*(?:\d\D*){1,12}$)\d+(?:\.\d{1,4})?$

See its demo. Details

^ - start of string

(?=\D*(?:\d\D*){1,12}$) - one to twelve digits required in the string

\d+ - 1 or more digits

(?:\.\d{1,4})? - an optional sequence of a . and then 1, 2, 3 or 4 digits

$ - end of string.


问:
Copying array in C v/s copying structure in C
Arrays and structures in C store data in memory which is contiguous. Then why is that C does not allow direct copying of arrays using "=" where as it is allowed for structure.
Example:</p>

```<code>int a[3] = {1,2,3};
int b[3];
b = a; // why is this not allowed.

struct book b1, b2;
b1.page = 100;
b1.price = 10.0;

b2 = b1; // Why is this allowed
</code>```

答:
Assignment requires that the type and therefore size of whatever is being assigned is known to the compiler.   So an assignment of form

```<code> a = b;
</code>```

requires that the types of a and b are both known to the compiler.   If the types are the same (e.g. both a and b are of type int) then the compiler can simply copy b into a by whatever instructions it deems are most efficient.     If the types are different, but an implicit promotion or type conversion is allowed, then the assignment is also possible after doing a promotion.    For example, if a is of type long and b is of type short, then b will be implicitly promoted to long and the result of that promotion stored in a.

This doesn't work for arrays, because the size of an array (calculated as the size of its elements multiplied by number of elements) is not necessarily known. One compilation unit (aka source file) may have a declaration (possibly by including a header file)

```<code> extern int a[];
 extern int b[];

 void some_func()
 {
      a = b;
 }
</code>```

which tells the compiler that a and b are arrays of int, but that they will be defined (which includes giving them a size) by another compilation unit.   Another compilation unit may then do;

```<code> extern int a[];

 int a[] = {3,1,4,2,3};    /*  definition of a */
</code>```

and a third compilation unit may similarly define b as an array of 27 elements.

Once the object files are linked into a single executable, the usages of a and b in all compilation units are associated, and all operations on them refer to the same definitions.

The problem with this comes about because the separate compilation model is a core feature of C.  So the compiler, when chewing on the first compilation unit above, has no information about the size of the arrays since it has no visibility of other compilation units, and is required to succeed or diagnose errors without referring to them.   Since there is no information about the number of elements in either array available to the first compilation unit, there is no way to work out how many elements to copy from one array to another.   The handling of this in C is that the assignment a = b is a diagnosable error in the function some_func().

There are alternative approaches (and some other programming languages handle such cases differently) but they are generally associated with other trade-offs.

The considerations doesn't generally affect struct types, since their size is known at compile time.   So, if a and b are of the same struct type, the assignment a = b is possible - and can be implemented by (say) a call of memcpy().

Note:  I am making some deliberate over-simplification in the explanation above, such as not considering the case of structs with flexible array members (from C99). Discussing  such cases would make the discussion above more complicated, without changing the core considerations.

Body:
Arrays and structures in C store data in memory which is contiguous. Then why is that C does not allow direct copying of arrays using "=" where as it is allowed for structure.
Example:

int a[3] = {1,2,3};
int b[3];
b = a; // why is this not allowed.

struct book b1, b2;
b1.page = 100;
b1.price = 10.0;

b2 = b1; // Why is this allowed

Body:
Assignment requires that the type and therefore size of whatever is being assigned is known to the compiler.   So an assignment of form

 a = b;

requires that the types of a and b are both known to the compiler.   If the types are the same (e.g. both a and b are of type int) then the compiler can simply copy b into a by whatever instructions it deems are most efficient.     If the types are different, but an implicit promotion or type conversion is allowed, then the assignment is also possible after doing a promotion.    For example, if a is of type long and b is of type short, then b will be implicitly promoted to long and the result of that promotion stored in a.

This doesn't work for arrays, because the size of an array (calculated as the size of its elements multiplied by number of elements) is not necessarily known. One compilation unit (aka source file) may have a declaration (possibly by including a header file)

 extern int a[];
 extern int b[];

 void some_func()
 {
      a = b;
 }

which tells the compiler that a and b are arrays of int, but that they will be defined (which includes giving them a size) by another compilation unit.   Another compilation unit may then do;

 extern int a[];

 int a[] = {3,1,4,2,3};    /*  definition of a */

and a third compilation unit may similarly define b as an array of 27 elements.

Once the object files are linked into a single executable, the usages of a and b in all compilation units are associated, and all operations on them refer to the same definitions.

The problem with this comes about because the separate compilation model is a core feature of C.  So the compiler, when chewing on the first compilation unit above, has no information about the size of the arrays since it has no visibility of other compilation units, and is required to succeed or diagnose errors without referring to them.   Since there is no information about the number of elements in either array available to the first compilation unit, there is no way to work out how many elements to copy from one array to another.   The handling of this in C is that the assignment a = b is a diagnosable error in the function some_func().

There are alternative approaches (and some other programming languages handle such cases differently) but they are generally associated with other trade-offs.

The considerations doesn't generally affect struct types, since their size is known at compile time.   So, if a and b are of the same struct type, the assignment a = b is possible - and can be implemented by (say) a call of memcpy().

Note:  I am making some deliberate over-simplification in the explanation above, such as not considering the case of structs with flexible array members (from C99). Discussing  such cases would make the discussion above more complicated, without changing the core considerations.


问:
ChartJs (ver: 2.8.0): Custom tooltip does not hide if clicked (or mouse pointer is moved) outside the chart canvas area
I am using ChartJs (ver: 2.8.0) to render line chart with custom tooltip that would be visible on click event of the points.

The issue is that the custom tooltip does not hide when mouse pointer is moved outside the chart canvas area.

To make the tooltip visible only on click event of the points, in the chart options I have made the chart to respond only on click events like this:

```<code>options: {
  events: ['click'],
.....
..
</code>```

Please let me know if above is the correct way to show tooltip on click event and not any other events.

With this, both the default chart js tooltip and custom tooltip does not get hide by itself when mouse is moved (or clicked) outside of the chart canvas area.

Can anyone please help me with the solution?

Here is the link to my JS Fiddle Example

Below is my full code:

JS:

```<code>var lineChartCustomTooltip = function (tooltip) {
  // Tooltip Element
  var tooltipEl = document.getElementById("chartjs-tooltip");

  if (!tooltipEl) {
    tooltipEl = document.createElement("div");
    tooltipEl.id = "chartjs-tooltip";
    tooltipEl.innerHTML = "<table></table>";
    this._chart.canvas.parentNode.appendChild(tooltipEl);
  }

  // Hide if no tooltip
  if (tooltip.opacity === 0) {
    tooltipEl.style.opacity = 0;
    return;
  }

  // Set caret Position
  tooltipEl.classList.remove("above", "below", "no-transform");
  if (tooltip.yAlign) {
    tooltipEl.classList.add(tooltip.yAlign);
  } else {
    tooltipEl.classList.add("no-transform");
  }

  function getBody(bodyItem) {
    return bodyItem.lines;
  }

  // Set Text
  if (tooltip.body) {
    var titleLines = tooltip.title || [];
    var bodyLines = tooltip.body.map(getBody);

    var innerHtml = "<thead>";

    titleLines.forEach(function (title) {
      innerHtml += "<tr><th>" + title + "</th></tr>";
    });
    innerHtml += "</thead><tbody>";

    bodyLines.forEach(function (body, i) {
      var colors = tooltip.labelColors[i];
      var style = "background:" + colors.backgroundColor;
      style += "; border-color:" + colors.borderColor;
      style += "; border-width: 2px";
      var span =
        '<span class="chartjs-tooltip-key" style="' + style + '"></span>';
      innerHtml += "<tr><td>" + span + body + "</td></tr>";
    });
    innerHtml += "</tbody>";

    var tableRoot = tooltipEl.querySelector("table");
    tableRoot.innerHTML = innerHtml;
  }

  var positionY = this._chart.canvas.offsetTop;
  var positionX = this._chart.canvas.offsetLeft;

  // Display, position, and set styles for font
  tooltipEl.style.opacity = 1;
  tooltipEl.style.left = positionX + tooltip.caretX + "px";
  tooltipEl.style.top = positionY + tooltip.caretY + "px";
  tooltipEl.style.fontFamily = tooltip._bodyFontFamily;
  tooltipEl.style.fontSize = tooltip.bodyFontSize + "px";
  tooltipEl.style.fontStyle = tooltip._bodyFontStyle;
  tooltipEl.style.padding = tooltip.yPadding + "px " + tooltip.xPadding + "px";
};

var options = {
  type: "line",
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [
      {
        label: "# of Votes",
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1,
        borderColor: "red",
        pointBackgroundColor: "red",
      },
      {
        label: "# of Points",
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1,
        borderColor: "blue",
        pointBackgroundColor: "blue",
      },
    ],
  },
  options: {
    events: ["click"],
    tooltips: {
      enabled: false, // disable the default tooltip
      custom: lineChartCustomTooltip, // use the custom tooltip
    },
    scales: {
      yAxes: [
        {
          ticks: {
            reverse: false,
          },
        },
      ],
    },
    title: {
      display: true,
      text: "Chart.js Line Chart - Custom Tooltips",
    },
  },
};

var ctx = document.getElementById("chartJSContainer").getContext("2d");
new Chart(ctx, options);
</code>```

HTML:

```<code><body>
    <canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>
</code>```

CSS:

```<code>canvas { background-color : #eee;
}

#chartJSContainer {
    border: 1px solid;
}

canvas {
      -moz-user-select: none;
      -webkit-user-select: none;
      -ms-user-select: none;
    }

    #chartjs-tooltip {
      opacity: 1;
      position: absolute;
      background: rgba(0, 0, 0, .7);
      color: white;
      border-radius: 3px;
      -webkit-transition: all .1s ease;
      transition: all .1s ease;
      pointer-events: none;
      -webkit-transform: translate(-50%, 0);
      transform: translate(-50%, 0);
    }

    .chartjs-tooltip-key {
      display: inline-block;
      width: 10px;
      height: 10px;
      margin-right: 10px;
    }
</code>```

答:
I found the solution!
Just by adding mouseout event to the chart events option, I got it resolved.

The custom added tooltip now hides when mouse is moved or clicked outside the chart area.

Code:

```<code>options: {
  events: ["click", "mouseout"],
....
...
</code>```

Here is the link to my updated JS Fiddel example.

Body:
I am using ChartJs (ver: 2.8.0) to render line chart with custom tooltip that would be visible on click event of the points.

The issue is that the custom tooltip does not hide when mouse pointer is moved outside the chart canvas area.

To make the tooltip visible only on click event of the points, in the chart options I have made the chart to respond only on click events like this:

options: {
  events: ['click'],
.....
..

Please let me know if above is the correct way to show tooltip on click event and not any other events.

With this, both the default chart js tooltip and custom tooltip does not get hide by itself when mouse is moved (or clicked) outside of the chart canvas area.

Can anyone please help me with the solution?

Here is the link to my JS Fiddle Example

Below is my full code:

JS:

var lineChartCustomTooltip = function (tooltip) {
  // Tooltip Element
  var tooltipEl = document.getElementById("chartjs-tooltip");

  if (!tooltipEl) {
    tooltipEl = document.createElement("div");
    tooltipEl.id = "chartjs-tooltip";
    tooltipEl.innerHTML = "

";
    this._chart.canvas.parentNode.appendChild(tooltipEl);
  }

  // Hide if no tooltip
  if (tooltip.opacity === 0) {
    tooltipEl.style.opacity = 0;
    return;
  }

  // Set caret Position
  tooltipEl.classList.remove("above", "below", "no-transform");
  if (tooltip.yAlign) {
    tooltipEl.classList.add(tooltip.yAlign);
  } else {
    tooltipEl.classList.add("no-transform");
  }

  function getBody(bodyItem) {
    return bodyItem.lines;
  }

  // Set Text
  if (tooltip.body) {
    var titleLines = tooltip.title || [];
    var bodyLines = tooltip.body.map(getBody);

    var innerHtml = "
";

    titleLines.forEach(function (title) {
      innerHtml += "
" + title + "
";
    });
    innerHtml += "

";

    bodyLines.forEach(function (body, i) {
      var colors = tooltip.labelColors[i];
      var style = "background:" + colors.backgroundColor;
      style += "; border-color:" + colors.borderColor;
      style += "; border-width: 2px";
      var span =
        '';
      innerHtml += "
" + span + body + "
";
    });
    innerHtml += "
";

    var tableRoot = tooltipEl.querySelector("table");
    tableRoot.innerHTML = innerHtml;
  }

  var positionY = this._chart.canvas.offsetTop;
  var positionX = this._chart.canvas.offsetLeft;

  // Display, position, and set styles for font
  tooltipEl.style.opacity = 1;
  tooltipEl.style.left = positionX + tooltip.caretX + "px";
  tooltipEl.style.top = positionY + tooltip.caretY + "px";
  tooltipEl.style.fontFamily = tooltip._bodyFontFamily;
  tooltipEl.style.fontSize = tooltip.bodyFontSize + "px";
  tooltipEl.style.fontStyle = tooltip._bodyFontStyle;
  tooltipEl.style.padding = tooltip.yPadding + "px " + tooltip.xPadding + "px";
};

var options = {
  type: "line",
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [
      {
        label: "# of Votes",
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1,
        borderColor: "red",
        pointBackgroundColor: "red",
      },
      {
        label: "# of Points",
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1,
        borderColor: "blue",
        pointBackgroundColor: "blue",
      },
    ],
  },
  options: {
    events: ["click"],
    tooltips: {
      enabled: false, // disable the default tooltip
      custom: lineChartCustomTooltip, // use the custom tooltip
    },
    scales: {
      yAxes: [
        {
          ticks: {
            reverse: false,
          },
        },
      ],
    },
    title: {
      display: true,
      text: "Chart.js Line Chart - Custom Tooltips",
    },
  },
};

var ctx = document.getElementById("chartJSContainer").getContext("2d");
new Chart(ctx, options);

HTML:

    <canvas id="chartJSContainer" width="600" height="400"></canvas>

CSS:

canvas { background-color : #eee;
}

#chartJSContainer {
    border: 1px solid;
}

canvas {
      -moz-user-select: none;
      -webkit-user-select: none;
      -ms-user-select: none;
    }

    #chartjs-tooltip {
      opacity: 1;
      position: absolute;
      background: rgba(0, 0, 0, .7);
      color: white;
      border-radius: 3px;
      -webkit-transition: all .1s ease;
      transition: all .1s ease;
      pointer-events: none;
      -webkit-transform: translate(-50%, 0);
      transform: translate(-50%, 0);
    }

    .chartjs-tooltip-key {
      display: inline-block;
      width: 10px;
      height: 10px;
      margin-right: 10px;
    }

Body:
I found the solution!
Just by adding mouseout event to the chart events option, I got it resolved.

The custom added tooltip now hides when mouse is moved or clicked outside the chart area.

Code:

options: {
  events: ["click", "mouseout"],
....
...

Here is the link to my updated JS Fiddel example.


问:
SwiftUI conditionally rendering one view or another
```<code>struct ContentView: View {
    @EnvironmentObject var demoModel: DemoModel

    var body: some View {
        //this works
        demoModel.isLoggedIn ? Text("logged in"):Text("logged out")

        //this doesnt work why
        //demoModel.loggedIn ?  StationListView(): LoginView()
    }
}
</code>```

答:
For opaque returns, as some View here, it should be returned one type, so use Group, as below

```<code>Group {
    if demoModel.loggedIn {
        StationListView()
    } else {
        LoginView()
    }
}
</code>```

Body:
For opaque returns, as some View here, it should be returned one type, so use Group, as below

Group {
    if demoModel.loggedIn {
        StationListView()
    } else {
        LoginView()
    }
}


问:
Cannot install pyodbc in docker and getting error command 'gcc' failed with exit status 1
I'm trying install pyodbc in docker running inside linux container
But I'm getting the following error

Click here to view the image

```<code> src/pyodbc.h:56:10: fatal error: sql.h: No such file or directory
   #include <sql.h>
            ^~~~~~~
  compilation terminated.
  error: command 'gcc' failed with exit status 1
  ----------------------------------------
  ERROR: Failed building wheel for pyodbc
</code>```

Here is my dockerfile

```<code>FROM mcr.microsoft.com/azure-functions/python:2.0
ENV AzureWebJobsScriptRoot=/home/site/wwwroot \
    AzureFunctionsJobHost__Logging__Console__IsEnabled=true
COPY . /home/site/wwwroot
FROM ubuntu
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update && \
    apt-get -y install gcc mono-mcs && \
    rm -rf /var/lib/apt/lists/*
FROM  python
RUN apt-get update && apt-get install -y python3-pip
# RUN /usr/bin/pip -r /home/site/wwwroot/requirements.txt
# WORKDIR /home/site/wwwroot
COPY --from=0 /home/site/wwwroot /home/site/wwwroot
RUN cd /home/site/wwwroot && pip install -r requirements.txt
</code>```

Note: I'm going push the code to the azure functionapp in linux machine

答:
I had the same issue, I added the below code in my docker file, and it started working. Microsoft docker image is missing unixodbc-dev, so you need to install separately using the below command.

```<code>RUN apt-get update && apt-get install -y --no-install-recommends \
    unixodbc-dev \
    unixodbc \
    libpq-dev
</code>```

Body:
I'm trying install pyodbc in docker running inside linux container
But I'm getting the following error

Click here to view the image

 src/pyodbc.h:56:10: fatal error: sql.h: No such file or directory
   #include <sql.h>
            ^~~~~~~
  compilation terminated.
  error: command 'gcc' failed with exit status 1
  ----------------------------------------
  ERROR: Failed building wheel for pyodbc

Here is my dockerfile

FROM mcr.microsoft.com/azure-functions/python:2.0
ENV AzureWebJobsScriptRoot=/home/site/wwwroot \
    AzureFunctionsJobHost__Logging__Console__IsEnabled=true
COPY . /home/site/wwwroot
FROM ubuntu
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update && \
    apt-get -y install gcc mono-mcs && \
    rm -rf /var/lib/apt/lists/*
FROM  python
RUN apt-get update && apt-get install -y python3-pip
# RUN /usr/bin/pip -r /home/site/wwwroot/requirements.txt
# WORKDIR /home/site/wwwroot
COPY --from=0 /home/site/wwwroot /home/site/wwwroot
RUN cd /home/site/wwwroot && pip install -r requirements.txt

Note: I'm going push the code to the azure functionapp in linux machine

Body:
I had the same issue, I added the below code in my docker file, and it started working. Microsoft docker image is missing unixodbc-dev, so you need to install separately using the below command.

RUN apt-get update && apt-get install -y --no-install-recommends \
    unixodbc-dev \
    unixodbc \
    libpq-dev


问:
Command line arguments to yarn start
I have created a react app with "start": "react-scripts start" in package.json. I run it using yarn start. However, I want to pass an argument from command line eg yarn start -- test=hello and access it it in index.js.

I tried to access it using process.argvs but it is not there. How should I pass command line arguments to yarn start ?

答:
I don't think that react-scripts take command line arguments. </p>

<p>If you want to pass arguments to node you will have to eject cra, then you will be able to pass arguments to node. </p>

Title: Command line arguments to yarn start

Body:
I don't think that react-scripts take command line arguments.

If you want to pass arguments to node you will have to eject cra, then you will be able to pass arguments to node.


问:
Physics OverlapSphere does not respond correctly
I can't quite understand how Physics.OverlapSphere works at this point. As shown below in the code, if the player enters the overlapsphere then it should return true, but I keep getting false when the player enters the sphere.
This is the script that call the method

```<code>void Update()
   {
       float distance = Vector3.Distance(target.position, transform.position);
       if (distance <= lookRadius)
       {
           agent.SetDestination(target.position);
           if (distance <= agent.stoppingDistance)
           {
               CharacterStats targetStats = target.GetComponent<CharacterStats>();
               Debug.Log(enemy.onPlayerEnter());
               if (targetStats != null && enemy.onPlayerEnter())
               {//if player exist and the player enters the attack area
                   Combat.Attack(targetStats);
               }

               FaceTarget();
           }
       }
       animator.SetFloat("speed", agent.velocity.magnitude);
</code>```

this is the script of the method:

```<code>public bool onPlayerEnter()
   {
       Collider[] hitColliders = Physics.OverlapSphere(interactionTransform.transform.localPosition, radius);
       //Debug.Log(interactionTransform.transform.localPosition);
       for(int i = 0; i < hitColliders.Length; i++)
       {
           if(LayerMask.LayerToName(hitColliders[i].gameObject.layer) == "Player")
           {
               Debug.Log("Player enter");
               return true;
           }
       }
       return false;
   }

//visualize the overlapsphere
private void OnDrawGizmosSelected()
   {
       if (interactionTransform == null) interactionTransform = transform;
       Gizmos.color = Color.cyan;
       Gizmos.DrawWireSphere(interactionTransform.position, radius);
   }
</code>```

collider with monster
[Collide with player[][1]][2]

https://i.stack.imgur.com/8Fgh0.png
    https://i.stack.imgur.com/jnubp.png

For unknown reason, I found that the overlapsphere works at certain position in the map, but the rest of the position does not work at all. I think this probably is a bug in Unity.

weird position

答:
Your sphere gizmo and actual sphere are different: for drawing gizmo you use transform.position, but for overlap sphere - transform.transform.localPosition (no need to double like transform.transform, and position and localPosition can be very different). I think, this is the answer.

Its easy to get mess with LayerMask, its a good approach, but for testing you better use tag, or gameObject.InstanceID, or even gameObject.name. But its minor, in general it looks like you deal with layers right.

Be sure that your agent.StoppingDistance not set too small

It`s a bad practice to use GetComponent every frame, as you do for get targetStats.

Body:
I can't quite understand how Physics.OverlapSphere works at this point. As shown below in the code, if the player enters the overlapsphere then it should return true, but I keep getting false when the player enters the sphere.
This is the script that call the method

void Update()
   {
       float distance = Vector3.Distance(target.position, transform.position);
       if (distance <= lookRadius)
       {
           agent.SetDestination(target.position);
           if (distance <= agent.stoppingDistance)
           {
               CharacterStats targetStats = target.GetComponent<CharacterStats>();
               Debug.Log(enemy.onPlayerEnter());
               if (targetStats != null && enemy.onPlayerEnter())
               {//if player exist and the player enters the attack area
                   Combat.Attack(targetStats);
               }

               FaceTarget();
           }
       }
       animator.SetFloat("speed", agent.velocity.magnitude);

this is the script of the method:

public bool onPlayerEnter()
   {
       Collider[] hitColliders = Physics.OverlapSphere(interactionTransform.transform.localPosition, radius);
       //Debug.Log(interactionTransform.transform.localPosition);
       for(int i = 0; i < hitColliders.Length; i++)
       {
           if(LayerMask.LayerToName(hitColliders[i].gameObject.layer) == "Player")
           {
               Debug.Log("Player enter");
               return true;
           }
       }
       return false;
   }

//visualize the overlapsphere
private void OnDrawGizmosSelected()
   {
       if (interactionTransform == null) interactionTransform = transform;
       Gizmos.color = Color.cyan;
       Gizmos.DrawWireSphere(interactionTransform.position, radius);
   }

collider with monster
[Collide with player[][1]][2]

https://i.stack.imgur.com/8Fgh0.png
    https://i.stack.imgur.com/jnubp.png

For unknown reason, I found that the overlapsphere works at certain position in the map, but the rest of the position does not work at all. I think this probably is a bug in Unity.

weird position


问:
Is it possible to implement include a script only where it is needed rather than in nuxt.config.js in nuxtjs
I am using Razorpay for my payment service. Other than the checkout page, no page is using it. I have included it in nuxt.config.js file. Is it possible in nuxtjs to use a script only where you might need it? not in all pages. (My lighthouse score is degrading due to this)</p>

答:
Yes, it is possible. You can use the Local Settings to include your resources in your .vue file inside the pages/ directory (here in the head function):

```<code><template>
  <h1>About page with jQuery and Roboto font</h1>
</template>

<script>
export default {
  head () {
    return {
      script: [
        { src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js' }
      ],
      link: [
        { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Roboto&display=swap' }
      ]
    }
  }
}
</script>

<style scoped>
h1 {
  font-family: Roboto, sans-serif;
}
</style>
</code>```

Here, this jQuery js file and Roboto font css will only be included in this page, instead of all the pages.

Body:
Yes, it is possible. You can use the Local Settings to include your resources in your .vue file inside the pages/ directory (here in the head function):

<template>
  <h1>About page with jQuery and Roboto font</h1>
</template>

<script>
export default {
  head () {
    return {
      script: [
        { src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js' }
      ],
      link: [
        { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Roboto&display=swap' }
      ]
    }
  }
}
</script>

<style scoped>
h1 {
  font-family: Roboto, sans-serif;
}
</style>

Here, this jQuery js file and Roboto font css will only be included in this page, instead of all the pages.


问:
Mounting a loop device on macOS in C
How do you mount a loop device (similar to hdiutil attach) on XNU / Darwin in C?

Specifically I'm looking for functionality that would be in linux/loop.h, but on XNU. ( I'm going to be doing this on iOS, don't ask ;) )

答:
There is no public API for disk images in macOS/Darwin. The disk image mechanism used by hdiutil is not implemented in core XNU itself, but the kext /System/Library/Extensions/IOHDIXController.kext. I have seen no documentation or source code on it, and I am not aware of a user space library for interfacing with it which is a public API. You will likely need to shell out to hdiutil on macOS.

Whether there's any chance of doing this on iOS is another question. (I assume you are talking about a jailbroken system) Judging by how OTA updates work in iOS, I can't think of anything else for which the OS itself might use disk images. So it seems likely that iOS has no disk image support at all. You could see what happens if you load an .iso or .dmg onto a USB storage device, connect that to your iDevice and try to open it in Files.app, but I'm not especially optimistic you'll be able to open them.

OwnerDisplayName: spv

Title: Mounting a loop device on macOS in C


问:
Collection add event fires on two independent Collections
Trying to understand the insides of backbone.js (Todos App) framework by adding some extra functionalities, my Todos App triggers an collection.add event on both collections, the original TodoList and my own UnsavedList

This is what I did:

Adding an 'Mark All Done' button to document trough _.template that checks all unchecked checkboxes without saving changes to the server.

Adding an 'Save ({unsaved collection length})' button to document trough _.template.

To accomplish this, I keep track of the 'savedState' of all models in TodoList

```<code>// inside TodoList
hasUnsaved: function() {
  return this.filter(function(todo) {
    var isEqual = _.isEqual(todo.savedAttributes, todo.attributes);
    return !isEqual;
  })
},
</code>```

Declaring and instantiating UnsavedList:

```<code>// inside window
window.UnsavedList = Backbone.Collection.extend({

  model: Todo,

  initialize: function() {
      this.bind('add', this.addHandler)
  },

  addHandler: function() {
      alert('added')
  }
});

window.UnsavedTodos = new UnsavedList;
</code>```

As in the original sample, the add event is bound to addOne Handler.

```<code>// inside AppView
...
initialize: function() {
  Todos.bind('add', this.addOne);
  ...
}
</code>```

Listens to 'Mark All Done' Button click to invoke markAllDone which in turn triggers 'change:allDone':

```<code>// inside AppView
markAllDone: function() {
    Todos.each(function(todo) {
        todo.set({ done: true });
    })
    Todos.trigger('change:allDone');

},
</code>```

... and 'change:allDone' invokes:

```<code>// inside AppView
checkSaved: function() {
    this.$('#todo-controls #button-saved').html(this.buttonSavedTemplate({
        saved: function() {
            var list = Todos.hasUnsaved();
            _.each(list, function(todo) {
                UnsavedTodos.add(todo);
            })
            return list.length;
        }
    }));
},
</code>```

If you look at the iterator of my template object, I'm adding all unsaved models to my UnsavedList. But strangely enough TodoList also listens to this exact 'add' event at what all unsaved models show up duplicated on the page.

Why is that, even tough I 'added' to UnsavedList only.

Thoughts ?

答:
Even though I could have lived with an { silent: true } option, I was too curious about this behavior and figured out myself looking in the source code:

Every time a model is added to an collection, the model itself triggers the add-event. And in my case both, the TodoList as well as UnsavedList are listening to 'add'

Here's the code snipped from backbone.js:

```<code>// inside _add
if (!options.silent) model.trigger('add', model, this, options);
</code>```

To walk around this (guess I want to keep my event flow), I just store a cloned copy of the model like this:

```<code>UnsavedTodos.add(_.clone(todo), { silent: false });
</code>```

I'm sure it's much easier to accomplish this using nested collections or whatever handling the same model instead of clones, I managed keeping track of my unsaved (cloned) models by means of events, triggered each time after a save, create or destroy.

This is my completed modified Todos App

Body:
Trying to understand the insides of backbone.js (Todos App) framework by adding some extra functionalities, my Todos App triggers an collection.add event on both collections, the original TodoList and my own UnsavedList

This is what I did:

Adding an 'Mark All Done' button to document trough _.template that checks all unchecked checkboxes without saving changes to the server.

Adding an 'Save ({unsaved collection length})' button to document trough _.template.

To accomplish this, I keep track of the 'savedState' of all models in TodoList

// inside TodoList
hasUnsaved: function() {
  return this.filter(function(todo) {
    var isEqual = _.isEqual(todo.savedAttributes, todo.attributes);
    return !isEqual;
  })
},

Declaring and instantiating UnsavedList:

// inside window
window.UnsavedList = Backbone.Collection.extend({

  model: Todo,

  initialize: function() {
      this.bind('add', this.addHandler)
  },

  addHandler: function() {
      alert('added')
  }
});

window.UnsavedTodos = new UnsavedList;

As in the original sample, the add event is bound to addOne Handler.

// inside AppView
...
initialize: function() {
  Todos.bind('add', this.addOne);
  ...
}

Listens to 'Mark All Done' Button click to invoke markAllDone which in turn triggers 'change:allDone':

// inside AppView
markAllDone: function() {
    Todos.each(function(todo) {
        todo.set({ done: true });
    })
    Todos.trigger('change:allDone');

},

... and 'change:allDone' invokes:

// inside AppView
checkSaved: function() {
    this.$('#todo-controls #button-saved').html(this.buttonSavedTemplate({
        saved: function() {
            var list = Todos.hasUnsaved();
            _.each(list, function(todo) {
                UnsavedTodos.add(todo);
            })
            return list.length;
        }
    }));
},

If you look at the iterator of my template object, I'm adding all unsaved models to my UnsavedList. But strangely enough TodoList also listens to this exact 'add' event at what all unsaved models show up duplicated on the page.

Why is that, even tough I 'added' to UnsavedList only.

Thoughts ?

Body:
Even though I could have lived with an { silent: true } option, I was too curious about this behavior and figured out myself looking in the source code:

Every time a model is added to an collection, the model itself triggers the add-event. And in my case both, the TodoList as well as UnsavedList are listening to 'add'

Here's the code snipped from backbone.js:

// inside _add
if (!options.silent) model.trigger('add', model, this, options);

To walk around this (guess I want to keep my event flow), I just store a cloned copy of the model like this:

UnsavedTodos.add(_.clone(todo), { silent: false });

I'm sure it's much easier to accomplish this using nested collections or whatever handling the same model instead of clones, I managed keeping track of my unsaved (cloned) models by means of events, triggered each time after a save, create or destroy.

This is my completed modified Todos App


问:
openapi 3 : how to specify that header parameters are JSON
I have a web service with JWT authentification.
Here is an example of using the web service

```<code>headers = {'content-type': 'application/json'}
    authentification={"username": "test", "password":"test"}
    r = requests.post("http://localhost:8888/login",headers=headers,json=authentification)
    dico= r.json()
    TOKEN=dico["access_token"]
    print("TOKEN",TOKEN)
</code>```

I try to document this in YAML in openapi 3. Here is my code

```<code>paths:
  /login:
    post:
      summary: authentification
      parameters:
        - in: header
          name: username
          schema:
            type: string
          required: true
          description: username
        - in: header
          name: password
          schema:
            type: string
          required: true
          description: mot de passe
      responses:
        '200':
          description: OK
</code>```

What is missing is that I don't know how to specify that the header parameters must be in json.
How can I do it?

Yours sincerely
Loïc

答:
In your example, username and password are not header parameters, they are sent in the JSON request body:

```<code>{"username": "...", "password": "..."}
</code>```

In OpenAPI 3.0, request body is defined using the requestBody keyword:

openapi: 3.0.0
...

paths:
  /login:
    post:
      summary: authentification
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/LoginRequest'
      responses:
        '200':
          description: OK

components:
  schemas:
    LoginRequest:
      type: object
      required:
        - username
        - password
      properties:
        username:
          type: string
        password:
          type: string
```

More info: Describing Request Body

Body:
I have a web service with JWT authentification.
Here is an example of using the web service

headers = {'content-type': 'application/json'}
    authentification={"username": "test", "password":"test"}
    r = requests.post("http://localhost:8888/login",headers=headers,json=authentification)
    dico= r.json()
    TOKEN=dico["access_token"]
    print("TOKEN",TOKEN)

I try to document this in YAML in openapi 3. Here is my code

paths:
  /login:
    post:
      summary: authentification
      parameters:
        - in: header
          name: username
          schema:
            type: string
          required: true
          description: username
        - in: header
          name: password
          schema:
            type: string
          required: true
          description: mot de passe
      responses:
        '200':
          description: OK

What is missing is that I don't know how to specify that the header parameters must be in json.
How can I do it?

Yours sincerely
Loïc

Body:
In your example, username and password are not header parameters, they are sent in the JSON request body:

{"username": "...", "password": "..."}

In OpenAPI 3.0, request body is defined using the requestBody keyword:

openapi: 3.0.0
...

paths:
  /login:
    post:
      summary: authentification
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/LoginRequest'
      responses:
        '200':
          description: OK

components:
  schemas:
    LoginRequest:
      type: object
      required:
        - username
        - password
      properties:
        username:
          type: string
        password:
          type: string

More info: Describing Request Body


问:
Error reading data from the old files, writing it into the new files and then deleting the old files in Python
I'm trying to use below code to read 5 files from source, write them in destination and then deleting the files in source. I get the following error: [Errno 13] Permission denied: 'c:\\data\\AM\\Desktop\\tester1. The file by the way look like this:

```<code>import os
import time

source = r'c:\data\AM\Desktop\tester'
destination = r'c:\data\AM\Desktop\tester1'

for file in os.listdir(source):
    file_path = os.path.join(source, file)
    if not os.path.isfile:
        continue
    print(file_path)

with open (file_path, 'r') as IN, open (destination, 'w') as OUT:
    data ={
            'Power': None,
            }
    for line in IN:
        splitter = (ID, Item, Content, Status) = line.strip().split()
        if Item in data == "Power":
            Content = str(int(Content) * 10)

os.remove(IN)
</code>```

答:
Sounds from your description like this line fails:

```<code>with open (file_path, 'r') as IN, open (destination, 'w') as OUT:
</code>```

Because of this operation:

```<code>open (destination, 'w')
</code>```

So, you might not have write-access to

```<code>c:\data\AM\Desktop\tester1
</code>```

Set file permission on Windows systems:
https://www.online-tech-tips.com/computer-tips/set-file-folder-permissions-windows/

Body:
I'm trying to use below code to read 5 files from source, write them in destination and then deleting the files in source. I get the following error: [Errno 13] Permission denied: 'c:\\data\\AM\\Desktop\\tester1. The file by the way look like this:

import os
import time

source = r'c:\data\AM\Desktop\tester'
destination = r'c:\data\AM\Desktop\tester1'

for file in os.listdir(source):
    file_path = os.path.join(source, file)
    if not os.path.isfile:
        continue
    print(file_path)

with open (file_path, 'r') as IN, open (destination, 'w') as OUT:
    data ={
            'Power': None,
            }
    for line in IN:
        splitter = (ID, Item, Content, Status) = line.strip().split()
        if Item in data == "Power":
            Content = str(int(Content) * 10)

os.remove(IN)

Body:
Sounds from your description like this line fails:

with open (file_path, 'r') as IN, open (destination, 'w') as OUT:

Because of this operation:

open (destination, 'w')

So, you might not have write-access to

c:\data\AM\Desktop\tester1

Set file permission on Windows systems:
https://www.online-tech-tips.com/computer-tips/set-file-folder-permissions-windows/


问:
Nuxt Compiled with warnings - extract-css-chunks-webpack-plugin
I'm working on a big project that contains multiple files and folders. Now, when I run npm run dev or change pages Nuxt is showing this these annoying warnings.

```<code> WARN  Compiled with 7 warnings                       friendly-errors 11:11:49

 WARN  Error                                          friendly-errors 11:11:49

chunk pages/add-new-property/index.pages/property/index.pages/room-management/add-new/index.pages/signup/index [extract-css-chunks-webpack-plugin]
Conflicting order. Following module has been added:
 * css ./node_modules/css-loader/dist/cjs.js??ref--7-oneOf-1-1!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--7-oneOf-1-2!./node_modules/sass-loader/dist/cjs.js??ref--7-oneOf-1-3!./node_modules/vuetify-loader/lib/loader.js??ref--16-0!./node_modules/vue-loader/lib??vue-loader-options!./components/property/policies/yes-no-box.vue?vue&type=style&index=0&id=67558805&lang=scss&scoped=true&
despite it was not able to fulfill desired ordering with these modules:
 * css ./node_modules/css-loader/dist/cjs.js??ref--7-oneOf-1-1!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--7-oneOf-1-2!./node_modules/sass-loader/dist/cjs.js??ref--7-oneOf-1-3!./node_modules/vuetify-loader/lib/loader.js??ref--16-0!./node_modules/vue-loader/lib??vue-loader-options!./components/UI/checkbox/checkbox.vue?vue&type=style&index=0&lang=scss&
   - couldn't fulfill desired order of chunk group(s) pages/property/index, pages/room-management/add-new/index
   - while fulfilling desired order of chunk group(s) pages/add-new-property/index, pages/signup/index
. . .
</code>```

That's just one of the 7 warnings.

Can anyone tell me how to fix or ,at least, ignore those warnings in Nuxtjs? Note that the warnings are from extract-css-chunks-webpack-plugin not from mini-css-extract-plugin.

Edit: This issue only occurs in the development and it's very annoying because when you first load a page the styles aren't loaded. So, you have to manually refresh the page. But after refreshing it, everything's fine if you revisit to that page again.

答:
pages/property/index, pages/room-management/add-new/index
and
pages/add-new-property/index, pages/signup/index

they both import some components, but the order of the import are different. So you have to check the import order in these files.

For example, file a.vue and b.vue have different import order:

a.vue:

```<code>import CompA from 'xxx'
import CompB from 'yyy'
</code>```

b.vue

```<code>import CompB from 'yyy'
import CompA from 'xxx'
</code>```

This will cause the error.

Body:
I'm working on a big project that contains multiple files and folders. Now, when I run npm run dev or change pages Nuxt is showing this these annoying warnings.

 WARN  Compiled with 7 warnings                       friendly-errors 11:11:49

 WARN  Error                                          friendly-errors 11:11:49

chunk pages/add-new-property/index.pages/property/index.pages/room-management/add-new/index.pages/signup/index [extract-css-chunks-webpack-plugin]
Conflicting order. Following module has been added:
 * css ./node_modules/css-loader/dist/cjs.js??ref--7-oneOf-1-1!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--7-oneOf-1-2!./node_modules/sass-loader/dist/cjs.js??ref--7-oneOf-1-3!./node_modules/vuetify-loader/lib/loader.js??ref--16-0!./node_modules/vue-loader/lib??vue-loader-options!./components/property/policies/yes-no-box.vue?vue&type=style&index=0&id=67558805&lang=scss&scoped=true&
despite it was not able to fulfill desired ordering with these modules:
 * css ./node_modules/css-loader/dist/cjs.js??ref--7-oneOf-1-1!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--7-oneOf-1-2!./node_modules/sass-loader/dist/cjs.js??ref--7-oneOf-1-3!./node_modules/vuetify-loader/lib/loader.js??ref--16-0!./node_modules/vue-loader/lib??vue-loader-options!./components/UI/checkbox/checkbox.vue?vue&type=style&index=0&lang=scss&
   - couldn't fulfill desired order of chunk group(s) pages/property/index, pages/room-management/add-new/index
   - while fulfilling desired order of chunk group(s) pages/add-new-property/index, pages/signup/index
. . .

That's just one of the 7 warnings.

Can anyone tell me how to fix or ,at least, ignore those warnings in Nuxtjs? Note that the warnings are from extract-css-chunks-webpack-plugin not from mini-css-extract-plugin.

Edit: This issue only occurs in the development and it's very annoying because when you first load a page the styles aren't loaded. So, you have to manually refresh the page. But after refreshing it, everything's fine if you revisit to that page again.

Body:
pages/property/index, pages/room-management/add-new/index
and
pages/add-new-property/index, pages/signup/index

they both import some components, but the order of the import are different. So you have to check the import order in these files.

For example, file a.vue and b.vue have different import order:

a.vue:

import CompA from 'xxx'
import CompB from 'yyy'

b.vue

import CompB from 'yyy'
import CompA from 'xxx'

This will cause the error.


问:
Getting source and destination must be different error while building project
I am getting this error while building project. Trying to add a new library in android-studio. Is there anybody who has an idea basically I am trying to create a new library here.

Options tried:

Manually deleted build

Invaildate cache/restart

Gradle clean build cache

Build->Clean Project

But build is failing.

Source C:\Users\abc\AndroidStudioProjects\Events\app\build\intermediates\cmake\debug\obj\armeabi-v7a\libnative-lib.so and destination C:\Users\abc\AndroidStudioProjects\Events\app\build\intermediates\cmake\debug\obj\armeabi-v7a\libnative-lib.so must be different

CMakeLists.txt I am using for the same:

```<code># For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.

cmake_minimum_required(VERSION 3.4.1)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.

add_library( # Sets the name of the library.
             native-lib

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             native-lib.cpp
        )

add_library (
        testLib
        SHARED
        TestClassesManager.cpp
)
# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

find_library( # Sets the name of the path variable.
              log-lib

              # Specifies the name of the NDK library that
              # you want CMake to locate.
              log )

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
                       native-lib

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib}

        )

target_link_libraries(
        testLib

        native-lib
)
</code>```

The error goes away if I am replacing

```<code>target_link_libraries(
        testLib

        native-lib
)
</code>```

by

```<code>target_link_libraries(
        testLib
    ${log-lib}

)
</code>```

But I want to link both libraries. But it is giving above error. Please help.

答:
What I understand and feel is your plugins is not the right version for your current sdk version or in-compactible.

Try to lower the plugin version or apply newer version might also help. Make sure to use the lastest Android Studion and try checking again. If the further error log is available, kindly paste here.

Body:
I am getting this error while building project. Trying to add a new library in android-studio. Is there anybody who has an idea basically I am trying to create a new library here.

Options tried:

Manually deleted build

Invaildate cache/restart

Gradle clean build cache

Build->Clean Project

But build is failing.

Source C:\Users\abc\AndroidStudioProjects\Events\app\build\intermediates\cmake\debug\obj\armeabi-v7a\libnative-lib.so and destination C:\Users\abc\AndroidStudioProjects\Events\app\build\intermediates\cmake\debug\obj\armeabi-v7a\libnative-lib.so must be different

CMakeLists.txt I am using for the same:

# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.

cmake_minimum_required(VERSION 3.4.1)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.

add_library( # Sets the name of the library.
             native-lib

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             native-lib.cpp
        )

add_library (
        testLib
        SHARED
        TestClassesManager.cpp
)
# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

find_library( # Sets the name of the path variable.
              log-lib

              # Specifies the name of the NDK library that
              # you want CMake to locate.
              log )

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
                       native-lib

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib}

        )

target_link_libraries(
        testLib

        native-lib
)

The error goes away if I am replacing

target_link_libraries(
        testLib

        native-lib
)

by

target_link_libraries(
        testLib
    ${log-lib}

)

But I want to link both libraries. But it is giving above error. Please help.


问:
Process same file in two threads using ifstream
I have an input file in my application that contains a vast amount of information. Reading over it sequentially, and at only a single file offset at a time is not sufficient for my application's usage. Ideally, I'd like to have two threads, that have separate and distinct ifstreams reading from two unique file offsets of the same file. I can't just start one ifstream up, and then make a copy of it using its copy constructor (since its uncopyable). So, how do I handle this?

Immediately I can think of two ways,

Construct a new ifstream for the second thread, open it on the same file.

Share a single instance of an open ifstream across both threads (using for instance boost::shared_ptr<>). Seek to the appropriate file offset that current thread is currently interested in, when the thread gets a time slice.

Is one of these two methods preferred?

Is there a third (or fourth) option that I have not yet thought of?

Obviously I am ultimately limited by the hard drive having to spin back and forth, but what I am interested in taking advantage of (if possible), is some OS level disk caching at both file offsets simultaneously.

Thanks.

答:
My vote would be a single reader, which hands the data to multiple worker threads.

If your file is on a single disk, then multiple readers will kill your read performance. Yes, your kernel may have some fantastic caching or queuing capabilities, but it is going to be spending more time seeking than reading data.


问:
"There was an error completing your request" when trying to make an Actions on Google project
Whenever I try to make an Actions on Google project, I always end up with the error:

There was an error completing your request

I don't have any extensions on my browser, and have made sure that I only have one account logged in when trying to make a project. It does end up making a project, but I can't choose what type of action I want to make (smart home action in my case). How would I fix this?

Image of how what I put in to add the project:

Image of the error I get:

Image of the project still showing up, but not having the option to turn it into a smart home action:

答:
As your project is created, you can change or set the category by these steps:

Click on the project

Go to the "develop" section and click on "Actions". Here you would get this page:
Actions-on-google console screenshot

Click on "Get started" and here you can choose the category of your action.

Click on "Home automation" in your case.


问:
Does selenium web driver supports Node.js and Vue.js?
Does selenium web driver support Node.js and Vue.js ? or Do we need to use any plugins to support them?if yes,please name the plugins?</p>

答:
Selenium is a free (open source) automated testing suite for web applications across different browsers and platforms. Primarily it is used for automating web applications for testing purposes, but is certainly not limited to just that.

Having said that, when using Selenium WebDriver you need not worry about the Application stack or the technologies involved as Selenium interacts with the elements within the DOM Tree.

So to conclude, irrespective of the AUT's underlying technology stack being built through Node.js or Vue.js, the main focus is how the WebElements are represented within the HTML DOM.


问:
Does c++ compiler protect const memory address from any change?
I wanted to prove that there is nothing known as (A protected memory address) and the whole story is just about the compiler, or the OS, or whatever application the hosted app is running on just make some checking on read and write requests the hosted app send to its superior process and this superior app or whatever you call it decide if this child process has the right to read or write to this specific memory location but this c++ code doesn't work in this essence so why :

```<code>#include <iostream>
int main()
{
    const int x = 10;
    std::cout << &x << std::endl; // So i can view address of x
    std::cout << "x Before is equal "<< x <<std::endl;

    int y ;
    std:: cin >> std::hex >>y;

    int *pinter = (int*)y ;
    *pinter = 20;
    std::cout << "x After is equal "<< x <<std::endl;
}
</code>```

This code is supposed to get around the concept of c++ compiler setting x variable type to const int so that neither pointer to the variable (unlike in C in which pointers to constants can change the value of constant ) nor references to the variable can change the variable so this code is supposed to get address of variable x (of course after it's printed out) and then a pointer do the rest of the work , so what i messed here , cause it seams like this memory location is hardware protected( I know it's not but I am very confused)

答:
This code is supposed to get around the concept of c++ compiler setting x variable type to const int so that [...]

You can break the rules of the language, but then your code is not valid C++. You shall not modify something that is qualified as const. If you do you have undefined behavior. As compilers are made to compile valid C++, they are not mandated to do anything meaningful to non-valid code and the result can be anything or nothing.

As already said in a comment:

const has nothing to do with hardware or memory. It is an agreement between you and your compiler and you broke that agreement. As a reward your compiler will do anything to your code, but not necessarily what you expect.

You tried to trick the compiler by making the modification at runtime such that at compile time the compiler cannot know that you will modify a const. However, you did declare x as const so the compiler will assume that its value will not change. If you still modify the value of x anything can happen.

PS: Rather frequently people come up with hacks to "proove" that private isn't really private, cosnt isn't really const and similar. The thing is: Those are facilities that are supposed to help you to make less mistakes and write cleaner code. If you try hard to cirumvent those facilites you will manage to do so (sometimes even without invoking UB). However, this "prooves" nothing except the possiblity to shoot yourself in the foot. C++ is not Java, it does not hold your hand and tries to prevent you from every possible mistake that you can make. In that regard C++ is closer to Pythons "we are all constenting adults here".

Body:
I wanted to prove that there is nothing known as (A protected memory address) and the whole story is just about the compiler, or the OS, or whatever application the hosted app is running on just make some checking on read and write requests the hosted app send to its superior process and this superior app or whatever you call it decide if this child process has the right to read or write to this specific memory location but this c++ code doesn't work in this essence so why :

#include <iostream>
int main()
{
    const int x = 10;
    std::cout << &x << std::endl; // So i can view address of x
    std::cout << "x Before is equal "<< x <<std::endl;

    int y ;
    std:: cin >> std::hex >>y;

    int *pinter = (int*)y ;
    *pinter = 20;
    std::cout << "x After is equal "<< x <<std::endl;
}

This code is supposed to get around the concept of c++ compiler setting x variable type to const int so that neither pointer to the variable (unlike in C in which pointers to constants can change the value of constant ) nor references to the variable can change the variable so this code is supposed to get address of variable x (of course after it's printed out) and then a pointer do the rest of the work , so what i messed here , cause it seams like this memory location is hardware protected( I know it's not but I am very confused)


问:
Not able to set default column value in JPA
i'm trying to set default value for column and i have tried with below code in entity

```<code>@Column(columnDefinition = "integer default 1")
private Integer views;
</code>```

now after running server still i could see views as null in sql. Any idea why not able to save default value.

Application.yml

```<code>hibernate:
  ddl-auto: create
</code>```

its always create as still its in development stage

答:
Please use the simple implementation in your code.

```<code>@Column("column name")
private Integer views = 1;
</code>```

set Default value while create that variable. if you want to change view value by using setter method.

if your not set the value in the model means it take 1 as the default value.

Or if your want to use columnDefinition  please use like follow

```<code>@Column(name="view",columnDefinition = "integer default '1'")
</code>```

Body:
i'm trying to set default value for column and i have tried with below code in entity

@Column(columnDefinition = "integer default 1")
private Integer views;

now after running server still i could see views as null in sql. Any idea why not able to save default value.

Application.yml

hibernate:
  ddl-auto: create

its always create as still its in development stage

Body:
Please use the simple implementation in your code.

@Column("column name")
private Integer views = 1;

set Default value while create that variable. if you want to change view value by using setter method.

if your not set the value in the model means it take 1 as the default value.

Or if your want to use columnDefinition  please use like follow

@Column(name="view",columnDefinition = "integer default '1'")


问:
For loop and Popup with liquid and jekyll
I want to create a list of modal popups with a for-loop, each of them displaying different text.
The site is created with Jekyll with the Liquid templating engine.

In particular, I want to create the list of my scientific publications, for each of them with 2 icons: one for the bibtex entry and one for the abstract. This information is stored in a yaml file.

I m following this simple tutorial for modal popups.

The popups work, but the text is the same for all the entries. How is possible to generate independent modal popups?

This is the html

{% for papers in papers %}
  {% for content in paper.papers %}

{{content.name}}

        <button data-close-button class="close-button">×</button>

{{content.text}}

  {% endfor %}
{% endfor %}
```

<p>and this is the Javascript code:</p>

<pre class="lang-js prettyprint-override"><code>const openModalIcons = document.querySelectorAll('[data-modal-target]')
const closeModalButtons = document.querySelectorAll('[data-close-button]')
const overlay = document.getElementById('overlay')

openModalIcons.forEach(icon => {
    icon.addEventListener('click', () => {
        const modal = document.querySelector(icon.dataset.modalTarget)
        openModal(modal)
    })
})

function openModal(modal) {
    if (modal == null) return
    modal.classList.add('active')
    overlay.classList.add('active')
}

closeModalButtons.forEach(button => {
    button.addEventListener('click', () => {
        const modal = button.closest('.modal')
        closeModal(modal)
    })
})

function closeModal(modal) {
    if (modal == null) return
    modal.classList.remove('active')
    overlay.classList.remove('active')
}

overlay.addEventListener('click', () => {
    const modals = document.querySelectorAll('.modal.active')
    modals.forEach(modal => {
        closeModal(modal)
    })
})
</code>```

答:
The problem is that all your modals have id="modal", so the selector #modal is probably always selecting the first one. The id attribute should be unique in the entire document.

Something like this should work:

```<code>{% for papers in papers %}
  {% for content in paper.papers %}
    <a title="{{content.name}}"><i class='{{content.icon}}' data-modal-target="#paperModal{{forloop.parentloop.counter}}_{{forloop.counter}}"></i></a>
    <div class="modal" id="paperModal{{forloop.parentloop.counter}}_{{forloop.counter}}">
      <div class="modal-header">
        <div class="title">{{content.name}}</div>
        <button data-close-button class="close-button">×</button>
      </div>

      <!-- text to display -->
      <div class="modal-body">{{content.text}}</div>
    </div>
  {% endfor %}
{% endfor %}
</code>```

Instead of the for loop counter, you could also use the paper name as the ID (as long as it's unique), e.g. id="paperModal_{{content.name | slugify}}".

Edit: Edited the snippet to use forloop.counter and account for the nested for loop.

Body:
I want to create a list of modal popups with a for-loop, each of them displaying different text.
The site is created with Jekyll with the Liquid templating engine.

In particular, I want to create the list of my scientific publications, for each of them with 2 icons: one for the bibtex entry and one for the abstract. This information is stored in a yaml file.

I m following this simple tutorial for modal popups.

The popups work, but the text is the same for all the entries. How is possible to generate independent modal popups?

This is the html

{% for papers in papers %}
  {% for content in paper.papers %}

{{content.name}}

        <button data-close-button class="close-button">×</button>

{{content.text}}

  {% endfor %}
{% endfor %}

and this is the Javascript code:

const openModalIcons = document.querySelectorAll('[data-modal-target]')
const closeModalButtons = document.querySelectorAll('[data-close-button]')
const overlay = document.getElementById('overlay')

openModalIcons.forEach(icon => {
    icon.addEventListener('click', () => {
        const modal = document.querySelector(icon.dataset.modalTarget)
        openModal(modal)
    })
})

function openModal(modal) {
    if (modal == null) return
    modal.classList.add('active')
    overlay.classList.add('active')
}

closeModalButtons.forEach(button => {
    button.addEventListener('click', () => {
        const modal = button.closest('.modal')
        closeModal(modal)
    })
})

function closeModal(modal) {
    if (modal == null) return
    modal.classList.remove('active')
    overlay.classList.remove('active')
}

overlay.addEventListener('click', () => {
    const modals = document.querySelectorAll('.modal.active')
    modals.forEach(modal => {
        closeModal(modal)
    })
})

Body:
The problem is that all your modals have id="modal", so the selector #modal is probably always selecting the first one. The id attribute should be unique in the entire document.

Something like this should work:

{% for papers in papers %}
  {% for content in paper.papers %}
    <a title="{{content.name}}"><i class='{{content.icon}}' data-modal-target="#paperModal{{forloop.parentloop.counter}}_{{forloop.counter}}"></i></a>
    <div class="modal" id="paperModal{{forloop.parentloop.counter}}_{{forloop.counter}}">
      <div class="modal-header">
        <div class="title">{{content.name}}</div>
        <button data-close-button class="close-button">&times;</button>
      </div>

      <!-- text to display -->
      <div class="modal-body">{{content.text}}</div>
    </div>
  {% endfor %}
{% endfor %}

Instead of the for loop counter, you could also use the paper name as the ID (as long as it's unique), e.g. id="paperModal_{{content.name | slugify}}".

Edit: Edited the snippet to use forloop.counter and account for the nested for loop.