问:
What's the proper way to set CachingStrategy to RecycleElement in Xamarin Forms?
I've been getting an error (but my code still runs with it so I've been ignoring it until now) saying that my BindableListView is not usable as an object element because it is not public or does not define a public parameterless constructor or a type converter.

I'm guessing this is the cause of another crash I'm getting: System.ObjectDisposedException: Cannot access a disposed object. Object name: 'Xamarin.Forms.Platform.Android.FormsTextView'
because I've seen suggestions online saying that most of the time, this issue is related to the ListView, and that I should set the CachingStrategy to RecycleElement.

So I decided to finally take a look at the BindableListView and add in the CachingStrategy = "RecycleElement"

Now there was already some code implemented that seemed to try and add the CachingStrategy already:

BindableListView.cs:

```<code>namespace MyApp.Core.Controls
{
    [PropertyChanged.DoNotNotify]
    public class BindableListView : ListView
    {
        public static BindableProperty ItemClickedProperty = BindableProperty.Create(nameof(ItemClicked), typeof(ICommand), typeof(BindableListView));
        public static BindableProperty ItemAppearsProperty = BindableProperty.Create(nameof(ItemAppears), typeof(ICommand), typeof(BindableListView));
        public static BindableProperty AnimateScrollToSelectedItemProperty = BindableProperty.Create(nameof(AnimateScrollToSelectedItem), typeof(bool), typeof(BindableListView), true);

        /// <summary>
        /// Constructs a <see cref="BindableListView"/>
        /// </summary>
        /// <param name="cachingStrategy">Sets the caching strategy for the <see cref="ListView"/>.</param>
        /// <example><![CDATA[
        /// <controls:BindableListView>
        ///  <x:Arguments>
        ///    <ListViewCachingStrategy>RecycleElement</ListViewCachingStrategy>
        ///  </x:Arguments>
        /// </controls:BindableListView>
        /// ]]></example>
        public BindableListView(ListViewCachingStrategy cachingStrategy)
            : base(cachingStrategy)
        {
            ItemTapped += OnItemTapped;
            ItemAppearing += OnItemAppearing;
            ItemSelected += OnItemSelected;
    ...
</code>```

Then in all the .xaml files that use this ListView:

```<code><controls:BindableListView
      ...>
      <x:Arguments>
        <ListViewCachingStrategy>RecycleElement</ListViewCachingStrategy>
      </x:Arguments>
</code>```

Would this be the correct way to set CachingStrategy to Recycle Element? If so then how would I go about fixing my error(s)?

Or should I remove the parameter from the constructor in BindableListView.cs to make it parameterless, and then just add the one line CachingStrategy = "RecycleElement" ? I tried this and the error went away at least.. (app won't run now though, "missing default ctor") but I don't know if it's the right thing to do. If this is what I'm supposed to do, will this fix my second error as well?

Thanks!

答:
The part of the error message that applies to your situation is:

... does not define a public parameterless constructor ...

Change this:

```<code>public BindableListView(ListViewCachingStrategy cachingStrategy)
            : base(cachingStrategy)
{
    ItemTapped += OnItemTapped;
    ItemAppearing += OnItemAppearing;
    ItemSelected += OnItemSelected;
    ...
}
</code>```

To this:

```<code>public BindableListView(ListViewCachingStrategy cachingStrategy)
        : base(cachingStrategy)
{
    Init();
}

public BindableListView()
        : base()
{
    Init();
}

private void Init()
{
    ItemTapped += OnItemTapped;
    ItemAppearing += OnItemAppearing;
    ItemSelected += OnItemSelected;
    ...
}
</code>```

Note that you do want to keep your parameterized constructor (XAML needs that); so the solution is to add a second (parameterless) constructor.

Thus you will have both forms of constructor that are needed, and each of them will perform your initialization logic.

Body:
I've been getting an error (but my code still runs with it so I've been ignoring it until now) saying that my BindableListView is not usable as an object element because it is not public or does not define a public parameterless constructor or a type converter.

I'm guessing this is the cause of another crash I'm getting: System.ObjectDisposedException: Cannot access a disposed object. Object name: 'Xamarin.Forms.Platform.Android.FormsTextView'
because I've seen suggestions online saying that most of the time, this issue is related to the ListView, and that I should set the CachingStrategy to RecycleElement.

So I decided to finally take a look at the BindableListView and add in the CachingStrategy = "RecycleElement"

Now there was already some code implemented that seemed to try and add the CachingStrategy already:

BindableListView.cs:

namespace MyApp.Core.Controls
{
    [PropertyChanged.DoNotNotify]
    public class BindableListView : ListView
    {
        public static BindableProperty ItemClickedProperty = BindableProperty.Create(nameof(ItemClicked), typeof(ICommand), typeof(BindableListView));
        public static BindableProperty ItemAppearsProperty = BindableProperty.Create(nameof(ItemAppears), typeof(ICommand), typeof(BindableListView));
        public static BindableProperty AnimateScrollToSelectedItemProperty = BindableProperty.Create(nameof(AnimateScrollToSelectedItem), typeof(bool), typeof(BindableListView), true);

        ///
        /// Constructs a <see cref="BindableListView"/>
        ///
        /// <param name="cachingStrategy">Sets the caching strategy for the <see cref="ListView"/>.</param>
        /// <example><![CDATA[
        /// <controls:BindableListView>
        ///  <x:Arguments>
        ///    <ListViewCachingStrategy>RecycleElement</ListViewCachingStrategy>
        ///  </x:Arguments>
        /// </controls:BindableListView>
        /// ]]></example>
        public BindableListView(ListViewCachingStrategy cachingStrategy)
            : base(cachingStrategy)
        {
            ItemTapped += OnItemTapped;
            ItemAppearing += OnItemAppearing;
            ItemSelected += OnItemSelected;
    ...

Then in all the .xaml files that use this ListView:

<controls:BindableListView
      ...>
      <x:Arguments>
        <ListViewCachingStrategy>RecycleElement</ListViewCachingStrategy>
      </x:Arguments>

Would this be the correct way to set CachingStrategy to Recycle Element? If so then how would I go about fixing my error(s)?

Or should I remove the parameter from the constructor in BindableListView.cs to make it parameterless, and then just add the one line CachingStrategy = "RecycleElement" ? I tried this and the error went away at least.. (app won't run now though, "missing default ctor") but I don't know if it's the right thing to do. If this is what I'm supposed to do, will this fix my second error as well?

Thanks!

Body:
The part of the error message that applies to your situation is:

... does not define a public parameterless constructor ...

Change this:

public BindableListView(ListViewCachingStrategy cachingStrategy)
            : base(cachingStrategy)
{
    ItemTapped += OnItemTapped;
    ItemAppearing += OnItemAppearing;
    ItemSelected += OnItemSelected;
    ...
}

To this:

public BindableListView(ListViewCachingStrategy cachingStrategy)
        : base(cachingStrategy)
{
    Init();
}

public BindableListView()
        : base()
{
    Init();
}

private void Init()
{
    ItemTapped += OnItemTapped;
    ItemAppearing += OnItemAppearing;
    ItemSelected += OnItemSelected;
    ...
}

Note that you do want to keep your parameterized constructor (XAML needs that); so the solution is to add a second (parameterless) constructor.

Thus you will have both forms of constructor that are needed, and each of them will perform your initialization logic.


来源: stackexchange

问:
Passing an array initializer as a method argument is not allowed
When I try to pass an array initializer as a method argument I get an error with the message 'Array initializer is not allowed here'.

methodTakingArrayArgument({0,0,0})

However, the construct works when the type is mentioned explicitly.

methodTakingArrayArgument(new int[]{0,0,0})

Is there a reason that this construct is not supported? There seems to be no documentation on the oracle website mentioning the same.

Edit:
I understand that there are a fixed number of ways to create an array in Java. The array initializer construct felt natural to be supported as a first class citizen in Java, like in languages like typescript.

As one of the answers has pointed out, the array initializer is not a valid expression, which is why it cannot be passed on to a method.

答:
The Java Language Specification is the final authority on such questions: Chapter 15 Expressions in general,  §15.12 Method Invocation Expressions and §15.10.1. Array Creation Expressions and 10.6. Array Initializers in particular.
In a nutshell, what you'll discover is:

The argument list of a method invocation consists of a series of comma-separated expression;

new int[]{0,0,0} is an arrayCreationExpression, which, in turn, is a type of expression and thus allowable as an argument in a method invocation;

{0,0,0} is an arrayInitializer which, by itself, is not an expression and thus not legal to use as an argument in a method invocation.

ContentLicense: CC BY-SA 4.0


问:
Cascade update on association
I have a class Yojana and another class Kabuliyat, where Kabuliyat belongs to Yojana, and a Yojana has one kabuliyat.

```<code>class Yojana < ApplicationRecord
  has_one :kabuliyat, dependent: :destroy
end
</code>```

```<code>class Kabuliyat < ApplicationRecord
  belongs_to :yojana
end
</code>```

Some of the fields/attributes of a kabuliat instance are dependent on the attributes of the yojana instance.

For example in partial form for a new kabuliyat.

```<code>- @yojana = Yojana.find_by_id(params[:yojana_id])

= form_for kabuliyat do |f|
tr
    td = f.label :yojana_name
    td = f.text_field :yojana_name, {value: @yojana.yojana_name,class: "hide-input",:readonly => true}

tr
    td = f.label :mukhya_samiti
    td = f.text_field :mukhya_samiti, {value: @yojana.mukhya_samiti,class: "hide-input",:readonly => true}

</code>```

As you can see, the attributes such as :yojana_name and :mukhya_samitit for a kabuliyat instance are extracted from it's parent yojana instances attribute.

Problem:

I wanted to know, if I had an instance of kabuliyat saved, and then I edited the Yojana's instance on whom the Kabuliyat's attributes are dependent on, how would I be able to also reflect the changes on the kabuliyat's instance.

For example: If I change the name of a Yojana instance from "A" to "B", can this change be automatically reflected on the child instance kabuliyat's attribute(for example: yojana_name) automatically.

What I have tried:

I used the before_update callback in the Yojana.rb model class, and manually made changed to all the other depended classes on Yojana. I wanted to know if there was any other efficient method.

答:
Create a service, UpdateYojana, you can do something like this,

```<code>class UpdateYojana
  attr_reader :yojana, :kabuliyat

  def initialize(yojana)
    @yojana = yojana
    @kabuliyat = yojana.kabuliyat
  end

  def self.update(yojana_id, params)
    yojana = Yojana.find(yojana_id)
    new(yojana).update(params)
  end

  def update(params)
    return false unless valid?

    ApplicationRecord.transaction do
      if yojana.yojana_name_changed? or yojana.mukhya_samiti_changed?
        kabuliyat.update!(yojana_name: yojana.yojana_name, mukhya_samiti: yojana.mukhya_samiti)
      end
      yojana.save!
    end
  end

  private

  def valid?(params)
    params.each do |attr, value|
      yojana.public_send("#{attr}=", value)
    end
    yojana.valid?
  end
end
</code>```

Ofcourse, you can make a lot of improvement to the code, but this is just to give an idea about how you can approach to this problem.

Title: Cascade update on association

Body:
I have a class Yojana and another class Kabuliyat, where Kabuliyat belongs to Yojana, and a Yojana has one kabuliyat.

class Yojana < ApplicationRecord
  has_one :kabuliyat, dependent: :destroy
end

class Kabuliyat < ApplicationRecord
  belongs_to :yojana
end

Some of the fields/attributes of a kabuliat instance are dependent on the attributes of the yojana instance.

For example in partial form for a new kabuliyat.

- @yojana = Yojana.find_by_id(params[:yojana_id])

= form_for kabuliyat do |f|
tr
    td = f.label :yojana_name
    td = f.text_field :yojana_name, {value: @yojana.yojana_name,class: "hide-input",:readonly => true}

tr
    td = f.label :mukhya_samiti
    td = f.text_field :mukhya_samiti, {value: @yojana.mukhya_samiti,class: "hide-input",:readonly => true}

As you can see, the attributes such as :yojana_name and :mukhya_samitit for a kabuliyat instance are extracted from it's parent yojana instances attribute.

Problem:

I wanted to know, if I had an instance of kabuliyat saved, and then I edited the Yojana's instance on whom the Kabuliyat's attributes are dependent on, how would I be able to also reflect the changes on the kabuliyat's instance.

For example: If I change the name of a Yojana instance from "A" to "B", can this change be automatically reflected on the child instance kabuliyat's attribute(for example: yojana_name) automatically.

What I have tried:

I used the before_update callback in the Yojana.rb model class, and manually made changed to all the other depended classes on Yojana. I wanted to know if there was any other efficient method.

Body:
Create a service, UpdateYojana, you can do something like this,

class UpdateYojana
  attr_reader :yojana, :kabuliyat

  def initialize(yojana)
    @yojana = yojana
    @kabuliyat = yojana.kabuliyat
  end

  def self.update(yojana_id, params)
    yojana = Yojana.find(yojana_id)
    new(yojana).update(params)
  end

  def update(params)
    return false unless valid?

    ApplicationRecord.transaction do
      if yojana.yojana_name_changed? or yojana.mukhya_samiti_changed?
        kabuliyat.update!(yojana_name: yojana.yojana_name, mukhya_samiti: yojana.mukhya_samiti)
      end
      yojana.save!
    end
  end

  private

  def valid?(params)
    params.each do |attr, value|
      yojana.public_send("#{attr}=", value)
    end
    yojana.valid?
  end
end

Ofcourse, you can make a lot of improvement to the code, but this is just to give an idea about how you can approach to this problem.


问:
Number Of ACE of a File - There is only 9 Members in Security Tab of File Property but it returns 13 ACE from ACL
void main() {

```<code>PSID UserSID = NULL;
PSID GroupSID = NULL;
//PSECURITY_DESCRIPTOR *SD = new PSECURITY_DESCRIPTOR;
PSECURITY_DESCRIPTOR SD = (PSECURITY_DESCRIPTOR)GlobalAlloc(GMEM_FIXED, sizeof(PSECURITY_DESCRIPTOR));
PACL pDACL ;
ULONG Count = NULL;
PEXPLICIT_ACCESS_W* pExplicitEntries = new PEXPLICIT_ACCESS_W;

string input, ext = "";
wcout << "Enter the location : " << endl;
std::getline(cin, input);
LPCSTR file = input.c_str();

HANDLE hFile = CreateFileA(file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);

if (hFile == INVALID_HANDLE_VALUE)
{
    if (GetLastError() == ERROR_ACCESS_DENIED)
    {
        cout << "Access Denied : System Files" << endl;
        return;
    }
    else if (GetLastError() == ERROR_PATH_NOT_FOUND)
    {
        cout << "Path Name Not Found" << endl;
        return;
    }
    else if (GetLastError() == ERROR_FILE_NOT_FOUND)
    {
        cout << "File Not Found" << endl;
        return;
    }
    else
    {
        cout << GetLastError() << endl;
        return;
    }
}
cout << GetLastError() << endl;

if ((GetSecurityInfo(hFile,SE_FILE_OBJECT,DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, &SD)) == ERROR_SUCCESS)
{
    cout << "Number of ACE : " << pDACL->AceCount << endl;
    cout << GetLastError() << endl;
}

for (int i = 0; i < pDACL->AceCount; i++)
{
    PACCESS_ALLOWED_ACE AceItem;
    ACE_HEADER* AceHdr = NULL;
    if (GetAce(pDACL, i, (LPVOID*)&AceItem) && GetAce(pDACL, i, (LPVOID*)&AceHdr))
    {
        TCHAR AccountBuff[80];
        TCHAR DomainBuff[80];
        DWORD AccountBufflength = 40;
        DWORD DomainBufflength = 40;
        PSID_NAME_USE peUse = new SID_NAME_USE;
        PSID Sid = &AceItem->SidStart;

        LookupAccountSidW(NULL, Sid, AccountBuff, &AccountBufflength, DomainBuff, &DomainBufflength,peUse);

        wcout << "\n----- " << AccountBuff << " @ " << DomainBuff << " -----\n" << endl;

        wcout << "AceType : " << AceHdr->AceType << " " << "Ace Flag : " << AceHdr->AceFlags << "\n" << endl;

        DisplayAccessMask(AceItem->Mask);

    }
    else
    {
        cout << GetLastError() << endl;
    }
}
</code>```

}`

How to get the correct number of ACE in the security tab of a file property ?
There is only 9 Members in Security Tab of File Property but the Access Control List consist of 13 ACE.
Can anyone tell me how can i get the users listed in the security tab ->advanced and their file permission...

答:
An ACE contains a set of access rights and a security identifier (SID)
that identifies a trustee for whom the rights are allowed, denied, or
audited.

ACE is access control entry, it not one-to-one correspondent to users and groups.

Each ACE in an access control list (ACL) applies to one trustee. But for one trustee, there may be multiple ACEs, like below, the same Administrators group has two ACEs, one is type of deny and another is type of allow:

Can anyone tell me how can i get the users listed in the security tab
->advanced and their file permission...

GetSecurityInfo does give me consistent number to permission entries at file properties -> secutiry -> advanced.

Update:

Number Of ACE of a File - There is only 9 Members in Security Tab of
File Property but it returns 13 ACE from ACL

It may happen that you find there is a difference between ACEs entries number (returned returned by GetSecurityInfo() and GetAce()) and the permission entries number (in the advanced security tab for folders).

Take folder C:/program files as an example. There are 9 permissions entries show in the advanced security tab for this folder as below.

However you may get 13 ACE entries using GetSecurityInfo() and GetAce().

It is expected because there is no 1:1 mapping between the ACE entry and the permission entry in the dialog.

File explorer applies some rules in order for displaying permission entries friendly to users. For example, there are two ACE entries, one is the full control for this folder and another is full control for subfolders, both of them for same user: TrustedInstaller. These two ACEs are merged into one displayed.

Body:
void main() {

PSID UserSID = NULL;
PSID GroupSID = NULL;
//PSECURITY_DESCRIPTOR *SD = new PSECURITY_DESCRIPTOR;
PSECURITY_DESCRIPTOR SD = (PSECURITY_DESCRIPTOR)GlobalAlloc(GMEM_FIXED, sizeof(PSECURITY_DESCRIPTOR));
PACL pDACL ;
ULONG Count = NULL;
PEXPLICIT_ACCESS_W* pExplicitEntries = new PEXPLICIT_ACCESS_W;

string input, ext = "";
wcout << "Enter the location : " << endl;
std::getline(cin, input);
LPCSTR file = input.c_str();

HANDLE hFile = CreateFileA(file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);

if (hFile == INVALID_HANDLE_VALUE)
{
    if (GetLastError() == ERROR_ACCESS_DENIED)
    {
        cout << "Access Denied : System Files" << endl;
        return;
    }
    else if (GetLastError() == ERROR_PATH_NOT_FOUND)
    {
        cout << "Path Name Not Found" << endl;
        return;
    }
    else if (GetLastError() == ERROR_FILE_NOT_FOUND)
    {
        cout << "File Not Found" << endl;
        return;
    }
    else
    {
        cout << GetLastError() << endl;
        return;
    }
}
cout << GetLastError() << endl;

if ((GetSecurityInfo(hFile,SE_FILE_OBJECT,DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, &SD)) == ERROR_SUCCESS)
{
    cout << "Number of ACE : " << pDACL->AceCount << endl;
    cout << GetLastError() << endl;
}

for (int i = 0; i < pDACL->AceCount; i++)
{
    PACCESS_ALLOWED_ACE AceItem;
    ACE_HEADER* AceHdr = NULL;
    if (GetAce(pDACL, i, (LPVOID*)&AceItem) && GetAce(pDACL, i, (LPVOID*)&AceHdr))
    {
        TCHAR AccountBuff[80];
        TCHAR DomainBuff[80];
        DWORD AccountBufflength = 40;
        DWORD DomainBufflength = 40;
        PSID_NAME_USE peUse = new SID_NAME_USE;
        PSID Sid = &AceItem->SidStart;

        LookupAccountSidW(NULL, Sid, AccountBuff, &AccountBufflength, DomainBuff, &DomainBufflength,peUse);

        wcout << "\n----- " << AccountBuff << " @ " << DomainBuff << " -----\n" << endl;

        wcout << "AceType : " << AceHdr->AceType << " " << "Ace Flag : " << AceHdr->AceFlags << "\n" << endl;

        DisplayAccessMask(AceItem->Mask);

    }
    else
    {
        cout << GetLastError() << endl;
    }
}

}`

How to get the correct number of ACE in the security tab of a file property ?
There is only 9 Members in Security Tab of File Property but the Access Control List consist of 13 ACE.
Can anyone tell me how can i get the users listed in the security tab ->advanced and their file permission...


问:
How to Download File Using DownloadManager in API 28 or Android Pie?
Writing exception to parcel java.lang.IllegalStateException: Not one of standard directories: /storage/emulated/0/Android/data...............

```<code> DownloadManager dm = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
                    Uri uri = Uri.parse(s);
                    DownloadManager.Request req = new DownloadManager.Request(uri);
                    req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    String filename = VideoTitle;
                    filename += ".mp4";

                    req.setDestinationInExternalPublicDir(context.getResources().getString(R.string.video_dir_path), filename);
                    req.setDestinationInExternalFilesDir(context,dir_path,filename);
                    StyleableToast.makeText(context,context.getResources().getString(R.string.download_started), Toast.LENGTH_SHORT, R.style.mytoast).show();

                    Long ref = dm.enqueue(req);
</code>```

How to resolve this error??

答:
I believe the problem is in the line you mentioned. The concatenation you're setting up is changing the directory of the file to one that is not standard.

For Eg:

```<code>request.setDestinationInExternalPublicDir(getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/NewFile","abc.jpg")
</code>```

The error shows that. See that the line tells you which directory it is trying to save to

Something like this

```<code>/storage/emulated/0/Android/data/com.a.b.downloadmanager/files/Pictures/NewFile
</code>```

So when you do that, it will try to save as

```<code>/storage/emulated/0/Android/data/com.a.b.downloadmanager/files/Pictures/NewFile/abc.jpg
</code>```

A solution to this would be to save the file to the standard directory. To do so you would only need to remove the concatenation.

Eg:

```<code>request.setDestinationInExternalPublicDir(getExternalFilesDir(Environment.DIRECTORY_PICTURES),"abc.jpg")
</code>```

Then it will try to save to the standard directory

```<code>/storage/emulated/0/Android/data/com.a.b.downloadmanager/files/Pictures/abc.jpg
</code>```

and Make sure you have

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

Make sure you have

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

in your manifest.xml

Also if you are using an emulator, make sure you created it with SD card storage. It's NOT created by default.

Body:
Writing exception to parcel java.lang.IllegalStateException: Not one of standard directories: /storage/emulated/0/Android/data...............

 DownloadManager dm = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
                    Uri uri = Uri.parse(s);
                    DownloadManager.Request req = new DownloadManager.Request(uri);
                    req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    String filename = VideoTitle;
                    filename += ".mp4";

                    req.setDestinationInExternalPublicDir(context.getResources().getString(R.string.video_dir_path), filename);
                    req.setDestinationInExternalFilesDir(context,dir_path,filename);
                    StyleableToast.makeText(context,context.getResources().getString(R.string.download_started), Toast.LENGTH_SHORT, R.style.mytoast).show();

                    Long ref = dm.enqueue(req);

How to resolve this error??

Body:
I believe the problem is in the line you mentioned. The concatenation you're setting up is changing the directory of the file to one that is not standard.

For Eg:

request.setDestinationInExternalPublicDir(getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/NewFile","abc.jpg")

The error shows that. See that the line tells you which directory it is trying to save to

Something like this

/storage/emulated/0/Android/data/com.a.b.downloadmanager/files/Pictures/NewFile

So when you do that, it will try to save as

/storage/emulated/0/Android/data/com.a.b.downloadmanager/files/Pictures/NewFile/abc.jpg

A solution to this would be to save the file to the standard directory. To do so you would only need to remove the concatenation.

Eg:

request.setDestinationInExternalPublicDir(getExternalFilesDir(Environment.DIRECTORY_PICTURES),"abc.jpg")

Then it will try to save to the standard directory

/storage/emulated/0/Android/data/com.a.b.downloadmanager/files/Pictures/abc.jpg

and Make sure you have

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Make sure you have

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

in your manifest.xml

Also if you are using an emulator, make sure you created it with SD card storage. It's NOT created by default.


问:
Get total [checkbox] value
HTML:

```<code><input type="checkbox" name="product[book]" value="10" /> book
<input type="checkbox" name="product[plane]" value="20" /> plane
</code>```

PHP:

```
<code>
foreach ($_POST['product'] as $name => $value) {
    echo $value;
}
</code>
```

How to get the total (sum) value if the user select two fields (book & plane)

答:
In your form you have an array of product. If you foreach that, create a $total = 0; at the start, add the value to it, at the end you have a total.

You can check that would work by  print_r($_POST) and you'll see any selected values show as part of an array within the array of $_POST.

ContentLicense: CC BY-SA 3.0

Title: Get total [checkbox] value

Body:
HTML:

<input type="checkbox" name="product[book]" value="10" /> book
<input type="checkbox" name="product[plane]" value="20" /> plane

PHP:

foreach ($_POST['product'] as $name => $value) {
    echo $value;
}

How to get the total (sum) value if the user select two fields (book & plane)


问:
Figure out a way to convert a var implementation to val
I'm using the following interface from a Java library:

```<code>// This is a Java class from a library I'm using
public interface Listener {
  void receiveConfigInfo(final String configInfo);
}
</code>```

And I'm extending it as follows, in Scala:

```<code>//MyClass needs to extends the Listener interface
final class MyClass extends Listener {
  private var config = Option.empty

  // Implement the the Listener interface
  override def receiveConfigInfo(configInfo: String): Unit = {
    try {
      config  = decode[Map[String, String]](configInfo) match {
        case Right(config) => Some(config)
        case Left(_) => None
      }
    } catch {
      case _: Throwable => nacosConfig = None
    }
  }

  override def getConfig():Option[Map[String, String]] = nacosConfig
}
</code>```

receiveConfigInfo will be called in automatically whenever relevant.

getConfig returns the latest value of configuration.

Is there a way to make config into a val, rather than a mutable var? I cannot change the signature of receiveConfigInfo, as it needs to respect the signature of parent class.

The objective is whenever I call getConfig, I should get latest config value. However my current implementation has a var which is not good, is there any way to change this code to make it val or another way if possible?

答:
Given that the Java interface you're implementing seems to require an implementation to accept arbitrarily many new configInfos, I'd suggest that the most honest thing is to leave the var but encapsulated such that it can only be changed via receiveConfigInfo.

So perhaps something like

```<code>object MyClass {
  private[MyClass] Config {
    private var underlying: Map[String, String] = Map.empty

    override def get(key: String): Option[String] =
      synchronized { underlying.get(key) }

    override def toMap: Map[String, String] =
      synchronized { underlying }

    override def update(configInfo: String): Unit =
      synchronized {
        // I'm assuming that decode is somewhere statically accessible
        // I'm also assuming that a function returning an `Either` won't throw non-fatal exceptions... if it can return a Left, a Right, or throw, then:
        //   Try { decode[...](configInfo) }.flatMap(_.left.map(msg => new RuntimeException(msg)).toTry)
        val decoded =
          decode[Map[String, String]](configInfo)
            .left
            .map(_ => new RuntimeException("decode failed")
            .toTry
        decoded.foreach { newConfig => underlying = newConfig }
        decoded.recoverWith { _ =>
          underlying = Map.empty
          decoded
        }
      }
  }
}

class MyClass extends Listener {
  private val config = new MyClass.Config

  override def receiveConfigInfo(configInfo: String): Unit = config.update(configInfo)
}
</code>```

With a solution along these lines, the configuration is immutable to anything in MyClass that doesn't call update (which is hopefully apparent enough vs. assigning to a var.

I'm preserving the behavior of unsetting the config if a bad configInfo comes along; it may make more sense to leave configInfo unchanged in that case, which would make it even more difficult in practice to inadvertently change the config except by a client of MyClass calling receiveConfigInfo with a valid config.

Body:
I'm using the following interface from a Java library:

// This is a Java class from a library I'm using
public interface Listener {
  void receiveConfigInfo(final String configInfo);
}

And I'm extending it as follows, in Scala:

//MyClass needs to extends the Listener interface
final class MyClass extends Listener {
  private var config = Option.empty

  // Implement the the Listener interface
  override def receiveConfigInfo(configInfo: String): Unit = {
    try {
      config  = decode[Map[String, String]](configInfo) match {
        case Right(config) => Some(config)
        case Left(_) => None
      }
    } catch {
      case _: Throwable => nacosConfig = None
    }
  }

  override def getConfig():Option[Map[String, String]] = nacosConfig
}

receiveConfigInfo will be called in automatically whenever relevant.

getConfig returns the latest value of configuration.

Is there a way to make config into a val, rather than a mutable var? I cannot change the signature of receiveConfigInfo, as it needs to respect the signature of parent class.

The objective is whenever I call getConfig, I should get latest config value. However my current implementation has a var which is not good, is there any way to change this code to make it val or another way if possible?

Body:
Given that the Java interface you're implementing seems to require an implementation to accept arbitrarily many new configInfos, I'd suggest that the most honest thing is to leave the var but encapsulated such that it can only be changed via receiveConfigInfo.

So perhaps something like

object MyClass {
  private[MyClass] Config {
    private var underlying: Map[String, String] = Map.empty

    override def get(key: String): Option[String] =
      synchronized { underlying.get(key) }

    override def toMap: Map[String, String] =
      synchronized { underlying }

    override def update(configInfo: String): Unit =
      synchronized {
        // I'm assuming that decode is somewhere statically accessible
        // I'm also assuming that a function returning an `Either` won't throw non-fatal exceptions... if it can return a Left, a Right, or throw, then:
        //   Try { decode[...](configInfo) }.flatMap(_.left.map(msg => new RuntimeException(msg)).toTry)
        val decoded =
          decode[Map[String, String]](configInfo)
            .left
            .map(_ => new RuntimeException("decode failed")
            .toTry
        decoded.foreach { newConfig => underlying = newConfig }
        decoded.recoverWith { _ =>
          underlying = Map.empty
          decoded
        }
      }
  }
}

class MyClass extends Listener {
  private val config = new MyClass.Config

  override def receiveConfigInfo(configInfo: String): Unit = config.update(configInfo)
}

With a solution along these lines, the configuration is immutable to anything in MyClass that doesn't call update (which is hopefully apparent enough vs. assigning to a var.

I'm preserving the behavior of unsetting the config if a bad configInfo comes along; it may make more sense to leave configInfo unchanged in that case, which would make it even more difficult in practice to inadvertently change the config except by a client of MyClass calling receiveConfigInfo with a valid config.


问:
How to get Flutter ScrollController to save position of ListView.builder() when changing tabs?
I have made a simple example with 2 tabs, each containing a ListView builder.  My goal is to be able to scroll in the first list view, switch to the 2nd tab, and then switch back to the first and see the same scroll position from before.

I have tried adding Keys to each of the list views, but that was only a guess as I don't fully understand keys.  That didn't help.

Why don't the ScrollControllers save the scroll position?

Here is the example main.dart:

```<code>import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  ScrollController controllerA = ScrollController(keepScrollOffset: true);
  ScrollController controllerB = ScrollController(keepScrollOffset: true);
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        appBar: AppBar(
          bottom: TabBar(
            tabs: <Widget>[
              Text('controllerA'),
              Text('controllerB'),
            ],
          ),
        ),
        body: TabBarView(
          children: <Widget>[
            ListView.builder(
                controller: controllerA,
                itemCount: 2000,
                itemBuilder: (context, i) {
                  return ListTile(
                      title: Text(
                    i.toString(),
                    textScaleFactor: 1.5,
                    style: TextStyle(color: Colors.blue),
                  ));
                }),
            ListView.builder(
                controller: controllerB,
                itemCount: 2000,
                itemBuilder: (context, i) {
                  return Card(
                    child: ListTile(
                      title: Text(i.toString()),
                    ),
                  );
                }),
          ],
        ),
      ),
    );
  }
}
</code>```

Here is a hacky but working example of what I want.  This doesn't feel like the correct way to do this though, as its rebuilding both controllers every frame.

```<code>import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  double offsetA = 0.0;
  double offsetB = 0.0;

  @override
  Widget build(BuildContext context) {
    ScrollController statelessControllerA =
        ScrollController(initialScrollOffset: offsetA);
    statelessControllerA.addListener(() {
      setState(() {
        offsetA = statelessControllerA.offset;
      });
    });

    ScrollController statelessControllerB =
        ScrollController(initialScrollOffset: offsetB);
    statelessControllerB.addListener(() {
      setState(() {
        offsetB = statelessControllerB.offset;
      });
    });

    return DefaultTabController(
      length: 2,
      child: Scaffold(
        appBar: AppBar(
          bottom: TabBar(
            tabs: <Widget>[
              Text('controllerA'),
              Text('controllerB'),
            ],
          ),
        ),
        body: TabBarView(
          children: <Widget>[
            ListView.builder(
                controller: statelessControllerA,
                itemCount: 2000,
                itemBuilder: (context, i) {
                  return ListTile(
                      title: Text(
                    i.toString(),
                    textScaleFactor: 1.5,
                    style: TextStyle(color: Colors.blue),
                  ));
                }),
            ListView.builder(
                controller: statelessControllerB,
                itemCount: 2000,
                itemBuilder: (context, i) {
                  return Card(
                    child: ListTile(
                      title: Text(i.toString()),
                    ),
                  );
                }),
          ],
        ),
      ),
    );
  }
}
</code>```

答:
You can use AutomaticKeepAliveClientMixin to persist the states in Tab View.

For Example

```<code>class GetListView extends StatefulWidget{
  @override
  State<StatefulWidget> createState() =>_GetListViewState();

}

class _GetListViewState extends State<GetListView> with AutomaticKeepAliveClientMixin<GetListView>{

  @override
  Widget build(BuildContext context){
    return ListView.builder(

                itemCount: 2000,
                itemBuilder: (context, i) {
                  return ListTile(
                      title: Text(
                    i.toString(),
                    textScaleFactor: 1.5,
                    style: TextStyle(color: Colors.blue),
                  ));
                });
  }

  @override
  bool get wantKeepAlive => true;

}
</code>```

Instead of using  ListView.builder in childern of TabBarView use GetListView.

For Example

```<code>TabBarView(
          children: <Widget>[
            GetListView(),
            ListView.builder(
                controller: controllerB,
                itemCount: 2000,
                itemBuilder: (context, i) {
                  return Card(
                    child: ListTile(
                      title: Text(i.toString()),
                    ),
                  );
                }),
          ],
        ),
      )
</code>```

The second way to achieve this is by using PageStorageKey. PageStorageKey is used by Scrollables to save the scroll offset. Each time a scroll completes, the scrollable's page storage is updated.

For Example

```<code> ListView.builder(
                key: PageStorageKey<String>('controllerA'),
                controller: statelessControllerA,
                itemCount: 2000,
                itemBuilder: (context, i) {
                  print("Rebuilded 1");
                  return ListTile(
                      title: Text(
                    i.toString(),
                    textScaleFactor: 1.5,
                    style: TextStyle(color: Colors.blue),
                  ));
                }),
</code>```

Note: In the second example the widgets will be rebuilded everytime with a specific scroll offset. It's recommended to use the first solution.

Body:
I have made a simple example with 2 tabs, each containing a ListView builder.  My goal is to be able to scroll in the first list view, switch to the 2nd tab, and then switch back to the first and see the same scroll position from before.

I have tried adding Keys to each of the list views, but that was only a guess as I don't fully understand keys.  That didn't help.

Why don't the ScrollControllers save the scroll position?

Here is the example main.dart:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  ScrollController controllerA = ScrollController(keepScrollOffset: true);
  ScrollController controllerB = ScrollController(keepScrollOffset: true);
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        appBar: AppBar(
          bottom: TabBar(
            tabs: <Widget>[
              Text('controllerA'),
              Text('controllerB'),
            ],
          ),
        ),
        body: TabBarView(
          children: <Widget>[
            ListView.builder(
                controller: controllerA,
                itemCount: 2000,
                itemBuilder: (context, i) {
                  return ListTile(
                      title: Text(
                    i.toString(),
                    textScaleFactor: 1.5,
                    style: TextStyle(color: Colors.blue),
                  ));
                }),
            ListView.builder(
                controller: controllerB,
                itemCount: 2000,
                itemBuilder: (context, i) {
                  return Card(
                    child: ListTile(
                      title: Text(i.toString()),
                    ),
                  );
                }),
          ],
        ),
      ),
    );
  }
}

Here is a hacky but working example of what I want.  This doesn't feel like the correct way to do this though, as its rebuilding both controllers every frame.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  double offsetA = 0.0;
  double offsetB = 0.0;

  @override
  Widget build(BuildContext context) {
    ScrollController statelessControllerA =
        ScrollController(initialScrollOffset: offsetA);
    statelessControllerA.addListener(() {
      setState(() {
        offsetA = statelessControllerA.offset;
      });
    });

    ScrollController statelessControllerB =
        ScrollController(initialScrollOffset: offsetB);
    statelessControllerB.addListener(() {
      setState(() {
        offsetB = statelessControllerB.offset;
      });
    });

    return DefaultTabController(
      length: 2,
      child: Scaffold(
        appBar: AppBar(
          bottom: TabBar(
            tabs: <Widget>[
              Text('controllerA'),
              Text('controllerB'),
            ],
          ),
        ),
        body: TabBarView(
          children: <Widget>[
            ListView.builder(
                controller: statelessControllerA,
                itemCount: 2000,
                itemBuilder: (context, i) {
                  return ListTile(
                      title: Text(
                    i.toString(),
                    textScaleFactor: 1.5,
                    style: TextStyle(color: Colors.blue),
                  ));
                }),
            ListView.builder(
                controller: statelessControllerB,
                itemCount: 2000,
                itemBuilder: (context, i) {
                  return Card(
                    child: ListTile(
                      title: Text(i.toString()),
                    ),
                  );
                }),
          ],
        ),
      ),
    );
  }
}

Body:
You can use AutomaticKeepAliveClientMixin to persist the states in Tab View.

For Example

class GetListView extends StatefulWidget{
  @override
  State<StatefulWidget> createState() =>_GetListViewState();

}

class _GetListViewState extends State<GetListView> with AutomaticKeepAliveClientMixin<GetListView>{

  @override
  Widget build(BuildContext context){
    return ListView.builder(

                itemCount: 2000,
                itemBuilder: (context, i) {
                  return ListTile(
                      title: Text(
                    i.toString(),
                    textScaleFactor: 1.5,
                    style: TextStyle(color: Colors.blue),
                  ));
                });
  }

  @override
  bool get wantKeepAlive => true;

}

Instead of using  ListView.builder in childern of TabBarView use GetListView.

For Example

TabBarView(
          children: <Widget>[
            GetListView(),
            ListView.builder(
                controller: controllerB,
                itemCount: 2000,
                itemBuilder: (context, i) {
                  return Card(
                    child: ListTile(
                      title: Text(i.toString()),
                    ),
                  );
                }),
          ],
        ),
      )

The second way to achieve this is by using PageStorageKey. PageStorageKey is used by Scrollables to save the scroll offset. Each time a scroll completes, the scrollable's page storage is updated.

For Example

 ListView.builder(
                key: PageStorageKey<String>('controllerA'),
                controller: statelessControllerA,
                itemCount: 2000,
                itemBuilder: (context, i) {
                  print("Rebuilded 1");
                  return ListTile(
                      title: Text(
                    i.toString(),
                    textScaleFactor: 1.5,
                    style: TextStyle(color: Colors.blue),
                  ));
                }),

Note: In the second example the widgets will be rebuilded everytime with a specific scroll offset. It's recommended to use the first solution.


问:
Generate random probability based on the data size in Numpy
I want to generate a non-uniform random sample using a range and specific size using Numpy as follows:

np.random.choice(m=5, n, p=[0.1, 0, 0.3, 0.6, 0]),

However, I want to obtain p randomly based on the size of m automatically without manually writing p=[0.1, 0, 0.3, 0.6, 0]) as above. How to do that in Numpy?

答:
A way to get a list of random float values, of length m, that sums to 1:

```<code>m = 5
values = [np.random.rand() for _ in range(m)]
p = [v/sum(values) for v in values]
</code>```

However, since values are all in the range 0-1, the weighting is more even than you may be after. You'd have to specify more about what type of distribution you're looking for, to get a more specific answer.

Body:
A way to get a list of random float values, of length m, that sums to 1:

m = 5
values = [np.random.rand() for _ in range(m)]
p = [v/sum(values) for v in values]

However, since values are all in the range 0-1, the weighting is more even than you may be after. You'd have to specify more about what type of distribution you're looking for, to get a more specific answer.


问:
SKWarpGeometry on SKLabelNode as child of SKEffectNode flips label upside-down
I'm trying to warp an SKLabelNode as a child of SKEffectNode (documentation says you can do that), but it flips the label node upside-down before it applies the warp.  This may be a bug, but before I file it, I thought I'd ask on here...

Here's my code:

```<code>func warpNode(_ node: SKEffectNode)
{
    if #available(iOS 10.0, *)
    {
        let sourcePositions: [vector_float2] =
            [
                vector_float2(0, 0),   vector_float2(0.5, 0),   vector_float2(1, 0),  //bottom row of object
                vector_float2(0, 0.5), vector_float2(0.5, 0.5), vector_float2(1, 0.5),  //middle row of object
                vector_float2(0, 1),   vector_float2(0.5, 1),   vector_float2(1, 1)  //top row of object
            ]

        let destinationPositions: [vector_float2] =
            [
                vector_float2(0, 0),   vector_float2(0.5, 0),   vector_float2(1, 0),  //bottom row of object
                vector_float2(0, 0.5), vector_float2(0.5, 0.5), vector_float2(1, 0.5),  //middle row of object
                vector_float2(0, 0.8), vector_float2(0.5, 0.8), vector_float2(1, 0.8)  //top row of object
            ]

        let warpGeometryGrid = SKWarpGeometryGrid(columns: 2, rows: 2, sourcePositions: sourcePositions, destinationPositions: destinationPositions)

        let warpGeometryGridNoWarp = SKWarpGeometryGrid(columns: 2, rows: 2)

        node.warpGeometry = warpGeometryGridNoWarp

        let warpAction = SKAction.animate(withWarps: [warpGeometryGridNoWarp, warpGeometryGrid, warpGeometryGridNoWarp], times: [0.25, 0.5, 0.75], restore: true)

        node.run(warpAction!)
    }
    else
    {
        print("Need iOS >= iOS 10 to warp!!!")
    }
}

let effectNode = SKEffectNode()
effectNode.shouldEnableEffects = true
addChild(effectNode)

let labelNode = SKLabelNode(fontNamed: "Chalkduster")
labelNode.text = "Label"
effectNode.addChild(labelNode)

warpNode(effectNode)
</code>```

This code should squish the top of the label down and then return it to its original position (as if you pushed on a ball or something), however, it flips it upside-down, then squishes the top (which is now the bottom of the word), and then returns it to its original size and position (rightside-up).

EDIT: Based on 0x141E's comment, I converted the SKLabelnode to SKTexture and added a new SKSpriteNode with that texture.  If I used the warpNode function on the effectNode, it had the same effect of flipping the word upside-down and then applying the squish.  However, if I used the warpNode function directly on the new SKSpriteNode, it worked properly.

New code below:

```<code>func warpNode(_ node: SKSpriteNode)
{
    if #available(iOS 10.0, *)
    {
        let sourcePositions: [vector_float2] =
            [
                vector_float2(0, 0),   vector_float2(0.5, 0),   vector_float2(1, 0),  //bottom row of object
                vector_float2(0, 0.5), vector_float2(0.5, 0.5), vector_float2(1, 0.5),  //middle row of object
                vector_float2(0, 1),   vector_float2(0.5, 1),   vector_float2(1, 1)  //top row of object
            ]

        let destinationPositions: [vector_float2] =
            [
                vector_float2(0, 0),   vector_float2(0.5, 0),   vector_float2(1, 0),  //bottom row of object
                vector_float2(0, 0.5), vector_float2(0.5, 0.5), vector_float2(1, 0.5),  //middle row of object
                vector_float2(0, 0.8), vector_float2(0.5, 0.8), vector_float2(1, 0.8)  //top row of object
            ]

        let warpGeometryGrid = SKWarpGeometryGrid(columns: 2, rows: 2, sourcePositions: sourcePositions, destinationPositions: destinationPositions)

        let warpGeometryGridNoWarp = SKWarpGeometryGrid(columns: 2, rows: 2)

        node.warpGeometry = warpGeometryGridNoWarp

        let warpAction = SKAction.animate(withWarps: [warpGeometryGridNoWarp, warpGeometryGrid, warpGeometryGridNoWarp], times: [0.25, 0.5, 0.75], restore: true)

        node.run(warpAction!)
    }
    else
    {
        print("Need iOS >= iOS 10 to warp!!!")
    }
}

let labelNode = SKLabelNode(fontNamed: "Chalkduster")
labelNode.text = "Label"

let labelNodeTexture = SKView().texture(from: labelNode)!
let labelNodeSprite = SKSpriteNode(texture: labelNodeTexture)

addChild(labelNodeSprite)

warpNode(labelNodeSprite)
</code>```

I just eliminated the whole effectNode part of the code and added the new sprite and did the warp on that.

答: If you're always warping your label node (either animating it continuously or applying the warp initially) you can pre-emptively flip your label node by using labelNode.yScale = -1. Then when you warp, it'll be right side up. A little silly, but it works for my purposes.

Body:
I'm trying to warp an SKLabelNode as a child of SKEffectNode (documentation says you can do that), but it flips the label node upside-down before it applies the warp.  This may be a bug, but before I file it, I thought I'd ask on here...

Here's my code:

func warpNode(_ node: SKEffectNode)
{
    if #available(iOS 10.0, *)
    {
        let sourcePositions: [vector_float2] =
            [
                vector_float2(0, 0),   vector_float2(0.5, 0),   vector_float2(1, 0),  //bottom row of object
                vector_float2(0, 0.5), vector_float2(0.5, 0.5), vector_float2(1, 0.5),  //middle row of object
                vector_float2(0, 1),   vector_float2(0.5, 1),   vector_float2(1, 1)  //top row of object
            ]

        let destinationPositions: [vector_float2] =
            [
                vector_float2(0, 0),   vector_float2(0.5, 0),   vector_float2(1, 0),  //bottom row of object
                vector_float2(0, 0.5), vector_float2(0.5, 0.5), vector_float2(1, 0.5),  //middle row of object
                vector_float2(0, 0.8), vector_float2(0.5, 0.8), vector_float2(1, 0.8)  //top row of object
            ]

        let warpGeometryGrid = SKWarpGeometryGrid(columns: 2, rows: 2, sourcePositions: sourcePositions, destinationPositions: destinationPositions)

        let warpGeometryGridNoWarp = SKWarpGeometryGrid(columns: 2, rows: 2)

        node.warpGeometry = warpGeometryGridNoWarp

        let warpAction = SKAction.animate(withWarps: [warpGeometryGridNoWarp, warpGeometryGrid, warpGeometryGridNoWarp], times: [0.25, 0.5, 0.75], restore: true)

        node.run(warpAction!)
    }
    else
    {
        print("Need iOS >= iOS 10 to warp!!!")
    }
}

let effectNode = SKEffectNode()
effectNode.shouldEnableEffects = true
addChild(effectNode)

let labelNode = SKLabelNode(fontNamed: "Chalkduster")
labelNode.text = "Label"
effectNode.addChild(labelNode)

warpNode(effectNode)

This code should squish the top of the label down and then return it to its original position (as if you pushed on a ball or something), however, it flips it upside-down, then squishes the top (which is now the bottom of the word), and then returns it to its original size and position (rightside-up).

EDIT: Based on 0x141E's comment, I converted the SKLabelnode to SKTexture and added a new SKSpriteNode with that texture.  If I used the warpNode function on the effectNode, it had the same effect of flipping the word upside-down and then applying the squish.  However, if I used the warpNode function directly on the new SKSpriteNode, it worked properly.

New code below:

func warpNode(_ node: SKSpriteNode)
{
    if #available(iOS 10.0, *)
    {
        let sourcePositions: [vector_float2] =
            [
                vector_float2(0, 0),   vector_float2(0.5, 0),   vector_float2(1, 0),  //bottom row of object
                vector_float2(0, 0.5), vector_float2(0.5, 0.5), vector_float2(1, 0.5),  //middle row of object
                vector_float2(0, 1),   vector_float2(0.5, 1),   vector_float2(1, 1)  //top row of object
            ]

        let destinationPositions: [vector_float2] =
            [
                vector_float2(0, 0),   vector_float2(0.5, 0),   vector_float2(1, 0),  //bottom row of object
                vector_float2(0, 0.5), vector_float2(0.5, 0.5), vector_float2(1, 0.5),  //middle row of object
                vector_float2(0, 0.8), vector_float2(0.5, 0.8), vector_float2(1, 0.8)  //top row of object
            ]

        let warpGeometryGrid = SKWarpGeometryGrid(columns: 2, rows: 2, sourcePositions: sourcePositions, destinationPositions: destinationPositions)

        let warpGeometryGridNoWarp = SKWarpGeometryGrid(columns: 2, rows: 2)

        node.warpGeometry = warpGeometryGridNoWarp

        let warpAction = SKAction.animate(withWarps: [warpGeometryGridNoWarp, warpGeometryGrid, warpGeometryGridNoWarp], times: [0.25, 0.5, 0.75], restore: true)

        node.run(warpAction!)
    }
    else
    {
        print("Need iOS >= iOS 10 to warp!!!")
    }
}

let labelNode = SKLabelNode(fontNamed: "Chalkduster")
labelNode.text = "Label"

let labelNodeTexture = SKView().texture(from: labelNode)!
let labelNodeSprite = SKSpriteNode(texture: labelNodeTexture)

addChild(labelNodeSprite)

warpNode(labelNodeSprite)

I just eliminated the whole effectNode part of the code and added the new sprite and did the warp on that.


问:
How to simply get a bearer token to send requests to Azure DevOps API?
I need to create an organizational feed to host nuget packages shared among projects on our Azure DevOps environment.

After several unsuccesful attempts and research, I discovered that the only way to create an organizational feed is, by design from Microsoft mouth, the Azure DevOps API.

Source for the claim : This question on VS dev community
and The MS docs on project-scoped feeds

Basically, I just need to be able to perform a POST here :
https://feeds.dev.azure.com/{organization}/_apis/packaging/feeds?api-version=5.1-preview.1

with the body :

```<code>{
    "name": "{myfeedname}",
    "hideDeletedPackageVersions": true,
    "upstreamEnabled": true
}
</code>```

And of course, a Bearer token to authenticate myself. That's the point where I'm confused.

What is the simplest way to obtain one ? I'm logged in through my company Microsoft AD account on my computer browser on Azure DevOps. I don't see any Bearer token that I can "steal" to use in PostMan in my browser dev tools.

The API docs described some relevant info, but I'm confused on how to use it in Postman :

Security oauth2

Type: oauth2

Flow: accessCode

Authorization URL: https://app.vssps.visualstudio.com/oauth2/authorize&response_type=Assertion

Token URL: https://app.vssps.visualstudio.com/oauth2/token?client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer

Scopes Name   Description

vso.packaging_write   Grants the ability to
  create and read feeds and packages.

Here is the interface in Postman for OAuth2:

Ican see how the info in the docs relates to the fields 1 - 2 - 3 - 4, but then, what callback url should I use ? What credentials ? my Microsoft email + password from AD ?

I tried this, and all I seem to get is this from Postman :

```<code>{"$id":"1","innerException":null,"message":"A potentially dangerous Request.Path value was detected from the client (&).","typeName":"System.Web.HttpException, System.Web","typeKey":"HttpException","errorCode":0,"eventId":0}
</code>```

TLDR

How do I properly proceed to get a token with Postman, or other tool to manually execute my one-time request to Azure DevOps REST API ?

notes :

Following info here : Unable to get Authorization code for Devops using Postman oAuth2.0
, leading here : https://github.com/Microsoft/azure-devops-auth-samples/tree/master/OAuthWebSample , I understand that I have to register and run a whole web application. Am I understanding this correctly ? I there a simpler way ?

答:
I understand that I have to register and run a whole web application. Am I understanding this correctly ? I there a simpler way ?

Yes, you are right. You have to register whole web application.

As the interface in Postman for OAuth2, we need provide the CallbackUrl, ClientID, ClientSecret and so on. Then, we check the document Requesting an OAuth 2.0 token, we could to know the Callback URL is:

The client application callback URL redirected to after auth, and that
  should be registered with the API provider.

So, we have to register an OAuth client app in Azure DevOps (https://app.vsaex.visualstudio.com/app/register), then we could get the following information, like:

You could check the document Authorize access to VSTS REST APIs with OAuth 2.0 for some more details.

AFAIK, there is currently no simpler way to get a bearer token to send requests to the Azure DevOps API.

Hope this helps.

Body:
I need to create an organizational feed to host nuget packages shared among projects on our Azure DevOps environment.

After several unsuccesful attempts and research, I discovered that the only way to create an organizational feed is, by design from Microsoft mouth, the Azure DevOps API.

Source for the claim : This question on VS dev community
and The MS docs on project-scoped feeds

Basically, I just need to be able to perform a POST here :
https://feeds.dev.azure.com/{organization}/_apis/packaging/feeds?api-version=5.1-preview.1

with the body :

{
    "name": "{myfeedname}",
    "hideDeletedPackageVersions": true,
    "upstreamEnabled": true
}

And of course, a Bearer token to authenticate myself. That's the point where I'm confused.

What is the simplest way to obtain one ? I'm logged in through my company Microsoft AD account on my computer browser on Azure DevOps. I don't see any Bearer token that I can "steal" to use in PostMan in my browser dev tools.

The API docs described some relevant info, but I'm confused on how to use it in Postman :

Security oauth2

Type: oauth2

Flow: accessCode

Authorization URL: https://app.vssps.visualstudio.com/oauth2/authorize&response_type=Assertion

Token URL: https://app.vssps.visualstudio.com/oauth2/token?client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer

Scopes Name   Description

vso.packaging_write   Grants the ability to
  create and read feeds and packages.

Here is the interface in Postman for OAuth2:

Ican see how the info in the docs relates to the fields 1 - 2 - 3 - 4, but then, what callback url should I use ? What credentials ? my Microsoft email + password from AD ?

I tried this, and all I seem to get is this from Postman :

{"$id":"1","innerException":null,"message":"A potentially dangerous Request.Path value was detected from the client (&).","typeName":"System.Web.HttpException, System.Web","typeKey":"HttpException","errorCode":0,"eventId":0}

TLDR

How do I properly proceed to get a token with Postman, or other tool to manually execute my one-time request to Azure DevOps REST API ?

notes :

Following info here : Unable to get Authorization code for Devops using Postman oAuth2.0
, leading here : https://github.com/Microsoft/azure-devops-auth-samples/tree/master/OAuthWebSample , I understand that I have to register and run a whole web application. Am I understanding this correctly ? I there a simpler way ?


问:
How to use dynamic SQL for updating the query with multiple conditions?
I am trying to execute below procedure:

```<code>ALTER PROCEDURE UFP_PROCEDURE
    (@table_name1 varchar(100))
AS
BEGIN
    DECLARE @sql varchar(200);

    SET @sql = 'UPDATE' + @table_name1 +
               'SET' + QUOTENAME(operation) +  '=' + 'U' + 'where' + QUOTENAME(last_updated_time) + 'IS NOT NULL' + 'AND' + QUOTENAME(last_created_date) + 'IS NOT NULL' + 'AND'  + QUOTENAME(delete_flag) + 'IS NULL'

    EXEC(@SQL)
END
</code>```

I am not getting how to use dynamic SQL with all the single quotes and the columns which are in QUOTENAME is giving as invalid columns.

Here @table_name1 is the table name which I am passing from Azure pipeline.

If anyone can give solution..... it would be very helpful.

答:
There are issues in your dynamic query due to incorrect spaces and incorrect QUOTENAME, change your query like following.

```<code>ALTER PROCEDURE UFP_PROCEDURE(@table_name1 varchar(100))
AS
BEGIN
    DECLARE @sql varchar(200);

   set @sql = 'UPDATE ' + quotename(@table_name1) +
    ' SET  operation = ''U'' where last_updated_time IS NOT NULL AND last_created_date IS NOT NULL AND delete_flag IS NULL'

    EXEC(@SQL)
END
</code>```

Note: Instead of EXEC, you can always check your query using print(@SQL)

Body:
I am trying to execute below procedure:

ALTER PROCEDURE UFP_PROCEDURE
    (@table_name1 varchar(100))
AS
BEGIN
    DECLARE @sql varchar(200);

    SET @sql = 'UPDATE' + @table_name1 +
               'SET' + QUOTENAME(operation) +  '=' + 'U' + 'where' + QUOTENAME(last_updated_time) + 'IS NOT NULL' + 'AND' + QUOTENAME(last_created_date) + 'IS NOT NULL' + 'AND'  + QUOTENAME(delete_flag) + 'IS NULL'

    EXEC(@SQL)
END

I am not getting how to use dynamic SQL with all the single quotes and the columns which are in QUOTENAME is giving as invalid columns.

Here @table_name1 is the table name which I am passing from Azure pipeline.

If anyone can give solution..... it would be very helpful.

Body:
There are issues in your dynamic query due to incorrect spaces and incorrect QUOTENAME, change your query like following.

ALTER PROCEDURE UFP_PROCEDURE(@table_name1 varchar(100))
AS
BEGIN
    DECLARE @sql varchar(200);

   set @sql = 'UPDATE ' + quotename(@table_name1) +
    ' SET  operation = ''U'' where last_updated_time IS NOT NULL AND last_created_date IS NOT NULL AND delete_flag IS NULL'

    EXEC(@SQL)
END

Note: Instead of EXEC, you can always check your query using print(@SQL)


问:
Rethinkdb: "Connection closed"
I'm using rethinkdb with flask (python 3) that is hosted locally on a Windows machine.
The problem is that connection is being closed very frequently.

The error looks like this:

```<code>rethinkdb.errors.ReqlDriverError: Connection is closed.
</code>```

In python i defined connection like this:

```<code>conn = r.connect("localhost", 28015).repl()
</code>```

Example of my query:

```<code>  r.db('izmjene').table("users").get_all(
         email, index="email").count().run(conn)
</code>```

答:
The repl command is a convenience method that sets a default connection in your shell so you don’t have to pass it to the run command to run your queries. Avoid using repl in application code. RethinkDB connection objects are not thread-safe, and calls to connect from multiple threads may change the global connection object used by repl. Applications should specify connections explicitly.

There is a very good example that demonstrates connecting and closing the connection here

Title: Rethinkdb: "Connection closed"

Body:
I'm using rethinkdb with flask (python 3) that is hosted locally on a Windows machine.
The problem is that connection is being closed very frequently.

The error looks like this:

rethinkdb.errors.ReqlDriverError: Connection is closed.

In python i defined connection like this:

conn = r.connect("localhost", 28015).repl()

Example of my query:

  r.db('izmjene').table("users").get_all(
         email, index="email").count().run(conn)


问:
What unix command can we use to append some text to a specific line in a file?
Does anyone know of a series of unix commands that allows someone to append some text to the end of a specific line in a file?

eg

Line 1

Line 2

Line 3

Line 4

I wish to append the text ", extra information" to Line 3 so that the File will now look like this:

Line 1

Line 2

Line 3, extra information

Line 4

答:
Here is a version with portable sed (without -i option):

```<code>sed '3s/$/Hello World/' myfile
</code>```

Note that myfile is not modified, so you can recover from possible mistakes.

OwnerDisplayName: Alex Wong

ContentLicense: CC BY-SA 2.5

Body:
Here is a version with portable sed (without -i option):

sed '3s/$/Hello World/' myfile

Note that myfile is not modified, so you can recover from possible mistakes.

OwnerDisplayName: mouviciel


问:
get the parent element of the final child or grandchild?
I am working with angularjs and I have this response from my service and Its coming as tree and I am representing that data to the angular tree. this object have 4 main children, name and id. but these children and their children also have children, name and id. What I want is no matter which child I click, I always want to access the value of main root parent name thats "node1" "node2" "node3" as name so i know what is my main parent and whats parent under im clicking.

$scope.loadOrganizationTree = function () {
     userManagementFactory.getOrganizationTree()
     .success(function(data, status) {
        if (JSON.stringify(data.statusType).indexOf("success") > -1) {
            $scope.dataForTheTree = data.statusMsg;
                }
        } else {
            $scope.setResponseMsgs(data, status);
        }
    }).error(function(data, status) {
        $scope.userErrorMsg = data.statusMsg;
        $scope.showErrorMSg = true ;
    });
```

<pre class="lang-html prettyprint-override"><code><div treecontrol class="tree-light accordion-org-tree"
     style="height: 609px !important;" tree-model="dataForTheTree"
     order-by="name"  reverse-order="false"  options="treeOptions"
     on-selection="showSelected(node, selected, $parentNode, $index, $first, $middle, $last, $odd, $even)"
     selected-node="node1" filter-expression="userProfileOrgSearch">

    {{node.name}}
</div>
</code>```

[
  {
    "id": 1,
    "name": "node1",
    "children": [
      {
        "id": 11,
        "name": "node1.1",
        "children": [
          {
            "id": 111,
            "name": "node1.1.1",
            "children": []
          }
        ]
      },
      {
        "id": 12,
        "name": "node1.2",
        "children": []
      }
    ]
  },
  {
    "id": 2,
    "name": "node2",
    "children": [
      {
        "id": 21,
        "name": "node2.1",
        "nodes": []
      },
      {
        "id": 22,
        "name": "node2.2",
        "nodes": []
      }
    ]
  },
  {
    "id": 3,
    "name": "node3",
    "children": [
      {
        "id": 31,
        "name": "node3.1",
        "children": []
      }
    ]
  }
]
```

So far I have tried accessing with $parentnode but its not working out for me. Please let me know the solution.
Thanks in advance.

答:
After loading the data you fill $scope.dataForTheTree. Then you can walk through the tree and set the root of each node.
I coded this for you using a var dataForTheTree with your example data.
After running the below, each node has a root property set with it's root node.

```<code>var setRoot = function(elementWithChildren, root) {
    elementWithChildren.root = root;
    if (elementWithChildren.children != null) {
        angular.forEach(elementWithChildren.children, function(child) { setRoot(child, root); });
    }
};
angular.forEach(dataForTheTree, function(rootNode) { setRoot(rootNode, rootNode); });
</code>```

we take each node of the tree and call the setRoot() function. which then calls the setRoot function for each of it's children.
Recursive.

Body:
I am working with angularjs and I have this response from my service and Its coming as tree and I am representing that data to the angular tree. this object have 4 main children, name and id. but these children and their children also have children, name and id. What I want is no matter which child I click, I always want to access the value of main root parent name thats "node1" "node2" "node3" as name so i know what is my main parent and whats parent under im clicking.

$scope.loadOrganizationTree = function () {
     userManagementFactory.getOrganizationTree()
     .success(function(data, status) {
        if (JSON.stringify(data.statusType).indexOf("success") > -1) {
            $scope.dataForTheTree = data.statusMsg;
                }
        } else {
            $scope.setResponseMsgs(data, status);
        }
    }).error(function(data, status) {
        $scope.userErrorMsg = data.statusMsg;
        $scope.showErrorMSg = true ;
    });

    {{node.name}}

[
  {
    "id": 1,
    "name": "node1",
    "children": [
      {
        "id": 11,
        "name": "node1.1",
        "children": [
          {
            "id": 111,
            "name": "node1.1.1",
            "children": []
          }
        ]
      },
      {
        "id": 12,
        "name": "node1.2",
        "children": []
      }
    ]
  },
  {
    "id": 2,
    "name": "node2",
    "children": [
      {
        "id": 21,
        "name": "node2.1",
        "nodes": []
      },
      {
        "id": 22,
        "name": "node2.2",
        "nodes": []
      }
    ]
  },
  {
    "id": 3,
    "name": "node3",
    "children": [
      {
        "id": 31,
        "name": "node3.1",
        "children": []
      }
    ]
  }
]

So far I have tried accessing with $parentnode but its not working out for me. Please let me know the solution.
Thanks in advance.

Body:
After loading the data you fill $scope.dataForTheTree. Then you can walk through the tree and set the root of each node.
I coded this for you using a var dataForTheTree with your example data.
After running the below, each node has a root property set with it's root node.

var setRoot = function(elementWithChildren, root) {
    elementWithChildren.root = root;
    if (elementWithChildren.children != null) {
        angular.forEach(elementWithChildren.children, function(child) { setRoot(child, root); });
    }
};
angular.forEach(dataForTheTree, function(rootNode) { setRoot(rootNode, rootNode); });

we take each node of the tree and call the setRoot() function. which then calls the setRoot function for each of it's children.
Recursive.


问:
Friendly URL for RazorPage with query string
I would like to create friendly routes that map to different query string values of a single Razor Page and it's base GET handler. I'd be fine with switching the query string to being a part of the route as well. The idea is we have a single page that loads a file list and can filter. I'd prefer it if the URL was more straight forward. If it's not possible I could just go with /Files/In or /Files/Out

Example

```<code>/Files?direction=In  -> /In
/Files?direction=Out -> /Out
</code>```

Is there any way to do something like this?

答:
You can use route data parameters which  are defined in a Route Template as part of the @page directive in the .cshtml file :

```<code>@page "{direction?}"
</code>```

Then you can access the route parameter value in OnGet method of your file page :

```<code>public void OnGet(string direction)
{
     if (!string.IsNullOrEmpty(direction))
     {
           //filter files based on direction

     }
}
</code>```

You can pass direction value as /Files/In or /Files/Out , without filter directly use /Files .

Body:
I would like to create friendly routes that map to different query string values of a single Razor Page and it's base GET handler. I'd be fine with switching the query string to being a part of the route as well. The idea is we have a single page that loads a file list and can filter. I'd prefer it if the URL was more straight forward. If it's not possible I could just go with /Files/In or /Files/Out

Example

/Files?direction=In  -> /In
/Files?direction=Out -> /Out

Is there any way to do something like this?

Body:
You can use route data parameters which  are defined in a Route Template as part of the @page directive in the .cshtml file :

@page "{direction?}"

Then you can access the route parameter value in OnGet method of your file page :

public void OnGet(string direction)
{
     if (!string.IsNullOrEmpty(direction))
     {
           //filter files based on direction

     }
}

You can pass direction value as /Files/In or /Files/Out , without filter directly use /Files .


问:
How do I get at the contents of a private reflect.Value in go?
I'm trying to make a general purpose debug printer for complex data types because %v has a tendency to just print pointer values rather than what they point at. I've got it working with everything up until I have to deal with structs containing reflect.Value fields.

The following demo code runs without error: (https://play.golang.org/p/qvdRKc40R8k)

package main

import (
    "fmt"
    "reflect"
)

type MyStruct struct {
    i int
    R reflect.Value
}

func printContents(value interface{}) {
    // Omitted: check if value is actually a struct
    rv := reflect.ValueOf(value)
    for i := 0; i < rv.NumField(); i++ {
        fmt.Printf("%v: ", rv.Type().Field(i).Name)
        field := rv.Field(i)
        switch field.Kind() {
        case reflect.Int:
            fmt.Printf("%v", field.Int())
        case reflect.Struct:
            // Omitted: check if field is actually a reflect.Value to an int
            fmt.Printf("reflect.Value(%v)", field.Interface().(reflect.Value).Int())
        }
        fmt.Printf("\n")
    }
}

func main() {
    printContents(MyStruct{123, reflect.ValueOf(456)})
}
```

<p>This prints:</p>

```i: 123
R: reflect.Value(456)
```

<p>However, if I change MyStruct's <code>R</code> field name to <code>r</code>, it fails:</p>

```panic: reflect.Value.Interface: cannot return value obtained from unexported field or method
```

Of course, it's rightly failing because this would otherwise be a way to get an unexported field into proper goland, which is a no-no.

But this leaves me in a quandry: How can I gain access to whatever the unexported reflect.Value refers to without using Interface() so that I can walk its contents and print? I've looked through the reflect documentation and haven't found anything that looks helpful...

答:
After some digging, I've found a solution:

The only way to get at the inner reflect.Value is to call Interface() and type assert it, but this will panic if called on an unexported field. The only way around this is to use the unsafe package to clear the read-only flag so that the Interface() method will think it's exported when it's not (basically, we subvert the type system):

type flag uintptr // reflect/value.go:flag

type flagROTester struct {
    A   int
    a   int // reflect/value.go:flagStickyRO
    int     // reflect/value.go:flagEmbedRO
    // Note: flagRO = flagStickyRO | flagEmbedRO
}

var flagOffset uintptr
var maskFlagRO flag
var hasExpectedReflectStruct bool

func initUnsafe() {
    if field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag"); ok {
        flagOffset = field.Offset
    } else {
        log.Println("go-describe: exposeInterface() is disabled because the " +
            "reflect.Value struct no longer has a flag field. Please open an " +
            "issue at https://github.com/kstenerud/go-describe/issues")
        hasExpectedReflectStruct = false
        return
    }

    rv := reflect.ValueOf(flagROTester{})
    getFlag := func(v reflect.Value, name string) flag {
        return flag(reflect.ValueOf(v.FieldByName(name)).FieldByName("flag").Uint())
    }
    flagRO := (getFlag(rv, "a") | getFlag(rv, "int")) ^ getFlag(rv, "A")
    maskFlagRO = ^flagRO

    if flagRO == 0 {
        log.Println("go-describe: exposeInterface() is disabled because the " +
            "reflect flag type no longer has a flagEmbedRO or flagStickyRO bit. " +
            "Please open an issue at https://github.com/kstenerud/go-describe/issues")
        hasExpectedReflectStruct = false
        return
    }

    hasExpectedReflectStruct = true
}

func canExposeInterface() bool {
    return hasExpectedReflectStruct
}

func exposeInterface(v reflect.Value) interface{} {
    pFlag := (*flag)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + flagOffset))
    *pFlag &= maskFlagRO
    return v.Interface()
}
```

There are caveats, in that unsafe isn't allowed or desirable in all environments, not to mention that subverting the type system is rarely the right thing to do. It's recommended that you make such code conditional on build tags, and include a safe alternative.

Body:
I'm trying to make a general purpose debug printer for complex data types because %v has a tendency to just print pointer values rather than what they point at. I've got it working with everything up until I have to deal with structs containing reflect.Value fields.

The following demo code runs without error: (https://play.golang.org/p/qvdRKc40R8k)

package main

import (
    "fmt"
    "reflect"
)

type MyStruct struct {
    i int
    R reflect.Value
}

func printContents(value interface{}) {
    // Omitted: check if value is actually a struct
    rv := reflect.ValueOf(value)
    for i := 0; i < rv.NumField(); i++ {
        fmt.Printf("%v: ", rv.Type().Field(i).Name)
        field := rv.Field(i)
        switch field.Kind() {
        case reflect.Int:
            fmt.Printf("%v", field.Int())
        case reflect.Struct:
            // Omitted: check if field is actually a reflect.Value to an int
            fmt.Printf("reflect.Value(%v)", field.Interface().(reflect.Value).Int())
        }
        fmt.Printf("\n")
    }
}

func main() {
    printContents(MyStruct{123, reflect.ValueOf(456)})
}

This prints:

i: 123
R: reflect.Value(456)

However, if I change MyStruct's R field name to r, it fails:

panic: reflect.Value.Interface: cannot return value obtained from unexported field or method

Of course, it's rightly failing because this would otherwise be a way to get an unexported field into proper goland, which is a no-no.

But this leaves me in a quandry: How can I gain access to whatever the unexported reflect.Value refers to without using Interface() so that I can walk its contents and print? I've looked through the reflect documentation and haven't found anything that looks helpful...

Body:
After some digging, I've found a solution:

The only way to get at the inner reflect.Value is to call Interface() and type assert it, but this will panic if called on an unexported field. The only way around this is to use the unsafe package to clear the read-only flag so that the Interface() method will think it's exported when it's not (basically, we subvert the type system):

type flag uintptr // reflect/value.go:flag

type flagROTester struct {
    A   int
    a   int // reflect/value.go:flagStickyRO
    int     // reflect/value.go:flagEmbedRO
    // Note: flagRO = flagStickyRO | flagEmbedRO
}

var flagOffset uintptr
var maskFlagRO flag
var hasExpectedReflectStruct bool

func initUnsafe() {
    if field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag"); ok {
        flagOffset = field.Offset
    } else {
        log.Println("go-describe: exposeInterface() is disabled because the " +
            "reflect.Value struct no longer has a flag field. Please open an " +
            "issue at https://github.com/kstenerud/go-describe/issues")
        hasExpectedReflectStruct = false
        return
    }

    rv := reflect.ValueOf(flagROTester{})
    getFlag := func(v reflect.Value, name string) flag {
        return flag(reflect.ValueOf(v.FieldByName(name)).FieldByName("flag").Uint())
    }
    flagRO := (getFlag(rv, "a") | getFlag(rv, "int")) ^ getFlag(rv, "A")
    maskFlagRO = ^flagRO

    if flagRO == 0 {
        log.Println("go-describe: exposeInterface() is disabled because the " +
            "reflect flag type no longer has a flagEmbedRO or flagStickyRO bit. " +
            "Please open an issue at https://github.com/kstenerud/go-describe/issues")
        hasExpectedReflectStruct = false
        return
    }

    hasExpectedReflectStruct = true
}

func canExposeInterface() bool {
    return hasExpectedReflectStruct
}

func exposeInterface(v reflect.Value) interface{} {
    pFlag := (*flag)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + flagOffset))
    *pFlag &= maskFlagRO
    return v.Interface()
}

There are caveats, in that unsafe isn't allowed or desirable in all environments, not to mention that subverting the type system is rarely the right thing to do. It's recommended that you make such code conditional on build tags, and include a safe alternative.


问:
which is faster to load? svg as image or svg code
I have a lengthy web page that shows lots of typography designs. Will it be faster to simply load them in images or to use the svg code?

Other than the speed concern, I will choose svg in code simply because I can use css transition and animation to spice up the design.

What other things I need to consider in choosing between the two?

答:
It is better to use SVG element to display typographic designs if your design is not complex.

Quality of SVG element does not depend on resolution of your screen.It looks pretty sharp on any device whereas in image, it's sharpness is dependent on its size.

since simple SVG files is defined by the colors, layers, gradients, effects, and masks that it contains, the size of SVG code is small when compared to size of the image which is defined by the number of pixels that it consists of.

SVG code is loaded faster because there is no need for an HTTP request to load in an image file. The time taken for SVG code is only rendering time.

There can be numerous editing and animating opportunities for SVG code like you said.

Say if you use the same design throughout the website but in different colours and in different sizes, you can use a single SVG code and change its parameters accordingly.You do not have to create multiple copies of it as in the case of image.

However it is difficult to display the design in SVG code if your design has complex details.At this time, there is no other option but to go for image.


问:
How do I disable the chrome pop-up notifications using selenium in python?
```<code>from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys

username = 'loremipsum'
password = 'loremipsum'

url = 'https://www.facebook.com/'

driver = webdriver.Chrome(r"C:\Users\kevin\Downloads\chromedriver")
driver.get(url)

driver.find_element_by_id('email').send_keys(username)
driver.find_element_by_id('pass').send_keys(password)

time.sleep(2)

driver.find_element_by_id('loginbutton').click()

time.sleep(10)
</code>```

What do I have to do to disable a chrome notification I get "Facebook wants to show notifications, allow or block" when I sign in?

答:
You need to add an option to your chrome driver before starting it.</p>

```<code>options= webdriver.ChromeOptions()
options.add_argument('--disable-notifications')
#options.add_argument("disable-notifications");
driver = webdriver.Chrome(r"C:\Users\kevin\Downloads\chromedriver", chrome_options=options)
</code>```

Body:
from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys

username = 'loremipsum'
password = 'loremipsum'

url = 'https://www.facebook.com/'

driver = webdriver.Chrome(r"C:\Users\kevin\Downloads\chromedriver")
driver.get(url)

driver.find_element_by_id('email').send_keys(username)
driver.find_element_by_id('pass').send_keys(password)

time.sleep(2)

driver.find_element_by_id('loginbutton').click()

time.sleep(10)

What do I have to do to disable a chrome notification I get "Facebook wants to show notifications, allow or block" when I sign in?

Body:
You need to add an option to your chrome driver before starting it.

options= webdriver.ChromeOptions()
options.add_argument('--disable-notifications')
#options.add_argument("disable-notifications");
driver = webdriver.Chrome(r"C:\Users\kevin\Downloads\chromedriver", chrome_options=options)


问:
Remember the time left when browser refresh using jquery
This code below pops up with an interval of 5 seconds, 10 seconds & 15 seconds and inside this box is a contact form 7 form

So when I refresh the page it goes back to 5 seconds all the time.

```<code>var iteration = 0;
var times = [5,10,15]
var showPopUp = function(time) {
    setTimeout(function() {
        jQuery('.pop_timer_box').css('display','flex');
        Cookies.set('popup_box', time);
    }, time)

}

showPopUp(times[iteration]);

jQuery('body').on('click', '.cclose_pop', function() {
    jQuery('.pop_timer_box').hide();
    iteration +=1;
    if (iteration < 3) {
      showPopUp(times[iteration])
    }
});
</code>```

How can I make it so that when I refresh the page will will remember what it has left

and also make it all stop when contact form 7 is successfully submitted (popup will not show anymore maybe until browser exit)

Thank in advance for the help

答:
You should take a look at the localstorage function.

You can set / update Information like this:

```<code>localStorage.setItem("seconds", time);
</code>```

After the page has been loaded simply use

```<code>localStorage.getItem("seconds");
</code>```

Body:
This code below pops up with an interval of 5 seconds, 10 seconds & 15 seconds and inside this box is a contact form 7 form

So when I refresh the page it goes back to 5 seconds all the time.

var iteration = 0;
var times = [5,10,15]
var showPopUp = function(time) {
    setTimeout(function() {
        jQuery('.pop_timer_box').css('display','flex');
        Cookies.set('popup_box', time);
    }, time)

}

showPopUp(times[iteration]);

jQuery('body').on('click', '.cclose_pop', function() {
    jQuery('.pop_timer_box').hide();
    iteration +=1;
    if (iteration < 3) {
      showPopUp(times[iteration])
    }
});

How can I make it so that when I refresh the page will will remember what it has left

and also make it all stop when contact form 7 is successfully submitted (popup will not show anymore maybe until browser exit)

Thank in advance for the help

Body:
You should take a look at the localstorage function.

You can set / update Information like this:

localStorage.setItem("seconds", time);

After the page has been loaded simply use

localStorage.getItem("seconds");


问:
Pageview display grey screen when in release mode
He everyone,

I have an issue with the following code:

```<code>import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Expanded(
          child: PageView(
            children: <Widget>[
              Container(
                color: Colors.red,
              ),
              Container(
                color: Colors.yellow,
              ),
              Container(
                color: Colors.green,
              ),
              Container(
                color: Colors.blue,
              ),
            ],
          ),
        ),
      ],
    );
  }
}
</code>```

When I run it using "flutter run" it displays exactly what I need but when I use the "--release" parameter it completely stops working and displays a grey screen. Any help is appreciated!

答:
You're using Expanded inside a Widget (Stack) who has its own fit. In order to fix it, remove Expanded and apply the fit parameter to your Stack

```<code>class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<ThisApp> {
  @override
  Widget build(BuildContext context) {
    return Stack(
      fit: StackFit.expand, // StackFit.expand fixes the issue
      children: <Widget>[
        PageView(
          children: <Widget>[
            Container(
              color: Colors.red,
            ),
            Container(
              color: Colors.yellow,
            ),
            Container(
              color: Colors.green,
            ),
            Container(
              color: Colors.blue,
            ),
          ],
        )
      ],
    );
  }
}
</code>```

Using debug mode, you'd notice the stack trace telling your about that error. Because --release always try to avoid issues/crashes, will disable that part of the UI, aka = grey screen.

Body:
He everyone,

I have an issue with the following code:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Expanded(
          child: PageView(
            children: <Widget>[
              Container(
                color: Colors.red,
              ),
              Container(
                color: Colors.yellow,
              ),
              Container(
                color: Colors.green,
              ),
              Container(
                color: Colors.blue,
              ),
            ],
          ),
        ),
      ],
    );
  }
}

When I run it using "flutter run" it displays exactly what I need but when I use the "--release" parameter it completely stops working and displays a grey screen. Any help is appreciated!

Body:
You're using Expanded inside a Widget (Stack) who has its own fit. In order to fix it, remove Expanded and apply the fit parameter to your Stack

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<ThisApp> {
  @override
  Widget build(BuildContext context) {
    return Stack(
      fit: StackFit.expand, // StackFit.expand fixes the issue
      children: <Widget>[
        PageView(
          children: <Widget>[
            Container(
              color: Colors.red,
            ),
            Container(
              color: Colors.yellow,
            ),
            Container(
              color: Colors.green,
            ),
            Container(
              color: Colors.blue,
            ),
          ],
        )
      ],
    );
  }
}

Using debug mode, you'd notice the stack trace telling your about that error. Because --release always try to avoid issues/crashes, will disable that part of the UI, aka = grey screen.


问:
Looking to identify shopify/ecommerce website
Hi I am making a webscraping tool to parse website and determine if they are ecommerce website (contain signs of shopify, magento, etc.) I am feeding in URLs from a csv file. I want to look at the header to find the word this piece of html or something similar.

example from https://www.thecriticalslidesociety.com/

Right now I can solo of the head information but when I try to find that string of html, I don't get anything.

Can someone guide me to what I should do next.

```<code>import csv
from bs4 import BeautifulSoup as soup
import requests
import csv
from urllib.request import urlopen as uReq
import re

with open('URL.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)

    with open('Approval.csv', 'w') as Approval_file:
        csv_writer = csv.writer(Approval_file, delimiter='_')

    next(csv_reader)
    for line in csv_reader:
        my_URL = line[0]
        Uclient = uReq(my_URL)

        page_html = Uclient.read()

        web_header={'User-Agent':'Mozilla/5.0(Macintosh;IntelMacOSX10_13_2)AppleWebKit/537.36(KHTML,likeGecko)Chrome/63.0.3239.132Safari/537.36'}

        Uclient.close()

        page_soup = soup(page_html, "html.parser")

        search = page_soup.find("head")
</code>```

答:
from bs4 import BeautifulSoup
import requests

url = "http://example.com/"
html = requests.get(url).text

soup = BeautifulSoup(html, "html.parser")
search = soup.find("head")

print(search)
```

<p>Outputs the <code><head></code> tag:</p>

<pre class="lang-html prettyprint-override"><code><head>
<title>Example Domain</title>
<meta charset="utf-8"/>
<meta content="text/html; charset=utf-8" http-equiv="Content-type"/>
<meta content="width=device-width, initial-scale=1" name="viewport"/>
<style type="text/css">
    body {
        background-color: #f0f0f2;
        margin: 0;
        padding: 0;
        font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;

    }
    div {
        width: 600px;
        margin: 5em auto;
        padding: 2em;
        background-color: #fdfdff;
        border-radius: 0.5em;
        box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);
    }
    a:link, a:visited {
        color: #38488f;
        text-decoration: none;
    }
    @media (max-width: 700px) {
        div {
            margin: 0 auto;
            width: auto;
        }
    }
    </style>
</head>
</code>```

Body:
Hi I am making a webscraping tool to parse website and determine if they are ecommerce website (contain signs of shopify, magento, etc.) I am feeding in URLs from a csv file. I want to look at the header to find the word this piece of html or something similar.

example from https://www.thecriticalslidesociety.com/

Right now I can solo of the head information but when I try to find that string of html, I don't get anything.

Can someone guide me to what I should do next.

import csv
from bs4 import BeautifulSoup as soup
import requests
import csv
from urllib.request import urlopen as uReq
import re

with open('URL.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)

    with open('Approval.csv', 'w') as Approval_file:
        csv_writer = csv.writer(Approval_file, delimiter='_')

    next(csv_reader)
    for line in csv_reader:
        my_URL = line[0]
        Uclient = uReq(my_URL)

        page_html = Uclient.read()

        web_header={'User-Agent':'Mozilla/5.0(Macintosh;IntelMacOSX10_13_2)AppleWebKit/537.36(KHTML,likeGecko)Chrome/63.0.3239.132Safari/537.36'}

        Uclient.close()

        page_soup = soup(page_html, "html.parser")

        search = page_soup.find("head")

Body:
from bs4 import BeautifulSoup
import requests

url = "http://example.com/"
html = requests.get(url).text

soup = BeautifulSoup(html, "html.parser")
search = soup.find("head")

print(search)

Outputs the <head> tag:

<head>
<title>Example Domain</title>
<meta charset="utf-8"/>
<meta content="text/html; charset=utf-8" http-equiv="Content-type"/>
<meta content="width=device-width, initial-scale=1" name="viewport"/>
<style type="text/css">
    body {
        background-color: #f0f0f2;
        margin: 0;
        padding: 0;
        font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;

    }
    div {
        width: 600px;
        margin: 5em auto;
        padding: 2em;
        background-color: #fdfdff;
        border-radius: 0.5em;
        box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);
    }
    a:link, a:visited {
        color: #38488f;
        text-decoration: none;
    }
    @media (max-width: 700px) {
        div {
            margin: 0 auto;
            width: auto;
        }
    }
    </style>
</head>