问:
Wagtail-ModelTranslation Template Fragment Caching
I've implemented a multilingual site using wagtail and wagtail-modeltranslation but I'm having a problem with template fragment caching. The cache works but is not respecting the separate languages. Whichever language is accessed first after a save, is the one that will be served for all languages. I've tried two ways of setting the cache key to no avail. First from the django docs, second trying to explicitly include the language code in the template

First:

```<code>{% cache 604800 about_copy LANGUAGE_CODE %}
... HTML ...
{% endcache %}
</code>```

Second: Using a simple template tag

```<code>from django.utils.translation import get_language

@register.simple_tag(takes_context=True)
def get_lang(context, *args, **kwargs):
    return get_language()
</code>```

```<code>{% cache 604800 about_copy get_lang %}
... HTML ...
{% endcache %}
</code>```

My save method is as follows:

```<code>    def save(self, *args, **kwargs):
        """Create a template fragment key.
        Then delete the key."""

        key = make_template_fragment_key("about_copy")
        cache.delete(key)

        return super().save(*args, **kwargs)
</code>```

This does clear the correct fragment regardless of not including any language related arguments

Any help would be greatly appreciated. Thanks!

答:
Your first approach should work provided LANGUAGE_CODE is actually defined in the context. This doesn't happen automatically, so you probably just need to set it first:

```<code>{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}

{% cache 604800 about_copy LANGUAGE_CODE %}
... HTML ...
{% endcache %}
</code>```

A side note here is that you need to be careful with template fragment caching in Wagtail, because previewed, non-published content will get cached.

Body:
I've implemented a multilingual site using wagtail and wagtail-modeltranslation but I'm having a problem with template fragment caching. The cache works but is not respecting the separate languages. Whichever language is accessed first after a save, is the one that will be served for all languages. I've tried two ways of setting the cache key to no avail. First from the django docs, second trying to explicitly include the language code in the template

First:

{% cache 604800 about_copy LANGUAGE_CODE %}
... HTML ...
{% endcache %}

Second: Using a simple template tag

from django.utils.translation import get_language

@register.simple_tag(takes_context=True)
def get_lang(context, *args, **kwargs):
    return get_language()

{% cache 604800 about_copy get_lang %}
... HTML ...
{% endcache %}

My save method is as follows:

    def save(self, *args, **kwargs):
        """Create a template fragment key.
        Then delete the key."""

        key = make_template_fragment_key("about_copy")
        cache.delete(key)

        return super().save(*args, **kwargs)

This does clear the correct fragment regardless of not including any language related arguments

Any help would be greatly appreciated. Thanks!

Body:
Your first approach should work provided LANGUAGE_CODE is actually defined in the context. This doesn't happen automatically, so you probably just need to set it first:

{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}

{% cache 604800 about_copy LANGUAGE_CODE %}
... HTML ...
{% endcache %}

A side note here is that you need to be careful with template fragment caching in Wagtail, because previewed, non-published content will get cached.


来源: stackexchange

问:
Image won't show up after passing ImageSource instance from one ViewModel to another
I'm trying to make a simple jigsaw puzzle. First the user imports a photo from his library, then the image is displayed letting the user confirm, that this is the one, that he wants to use. Then he presses a "Play" button, which opens up a new content page, which should ALSO display the exact same image.

I'm using MVVM in this project.

The first ContentPage has an Image which is bound to a ImageSource property in the ViewModel.

When the ImageSource is set, it is also copied to a SharedData class.

When the user presses the "Play" button a new ContentPage is loaded, and the same Image should appear loading the ImageSource from the SharedData class.

However this does not happen!

Can anyone figure out what I'm doing wrong?

To put it simple, I just want to share the image between ViewModels (classes) in a very simple way. The task is not to set up some complicated architecture. I just want this little thing to work.

StartViewModel:

```<code>        // Image
    private ImageSource _imageSource = "";
    public ImageSource ImgSource
    {
        get { return _imageSource; }
        set
        {
            _imageSource = value;
            SharedData.ImageSource = value;
            OnPropertyChanged();

        }
    }
</code>```

XAML:

```<code>            <Image Margin="0,100,0,0" Source="{Binding ImgSource}" BackgroundColor="Black"></Image>
</code>```

This works fine, however when passing the ImageSource to the SharedData class or as a parameter in the MainViewModel it goes wrong

MainViewModel (The second view):

```<code>        // Image
    private ImageSource _imageSource = "mouse.jpg";
    public ImageSource ImgSource
    {
        get { return _imageSource; }
        set
        {
            _imageSource = value;
            OnPropertyChanged();

        }
    }

    public MainViewModel()
    {
        SwapCMD = new CommandDelegate(action: x => { Console.WriteLine("Ignore this line"); }, executable: x => { return true; });

        ImgSource = SharedData.ImageSource;

    }
</code>```

And as you can see I have bound the ImageSource the same way as in the previous view:

XAML:

```<code>        <Image Margin="0,100,0,0" Source="{Binding ImgSource}" BackgroundColor="Black"></Image>
</code>```

What am I doing wrong? Why can't I just pass the source to another view like that?

答:
You could try the code below. I am not sure why you use a SharedData class to store the imagesource at first time. But, when you pass the imagesource from one viewmodel to another, you could pass it directly.

StartPage.xaml

```<code> <StackLayout>
        <Image
            Margin="0,100,0,0"
            BackgroundColor="Black"
            Source="{Binding ImgSource}" />
        <Button
            x:Name="btnPlay"
            Clicked="btnPlay_Clicked"
            Text="Play" />
    </StackLayout>
</code>```

StartViewModel.cs

```<code>public class StartViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private ImageSource _imageSource = "";
    public ImageSource ImgSource
    {
        get { return _imageSource; }
        set
        {
            _imageSource = value;
            OnPropertyChanged("ImgSource");
        }
    }

    public StartViewModel()
    {
        ImgSource = "pink.jpg";
    }
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

StartPage.xaml.cs

```<code>  public StartPage()
    {
        InitializeComponent();

        this.BindingContext = new StartViewModel();
    }

    private async void btnPlay_Clicked(object sender, EventArgs e)
    {
        await Navigation.PushAsync(new MainPage());
    }
</code>```

MainPage.xaml

```<code>  <StackLayout>
    <!--  Place new controls here  -->
    <Image
        Margin="0,100,0,0"
        BackgroundColor="Black"
        Source="{Binding ImgSource}" />

</StackLayout>
</code>```

MainViewModel.cs

```<code> public class MainViewModel : INotifyPropertyChanged
{
    // Image
    private ImageSource _imageSource = "";

    public event PropertyChangedEventHandler PropertyChanged;

    public ImageSource ImgSource
    {
        get { return _imageSource; }
        set
        {
            _imageSource = value;
            OnPropertyChanged("ImgSource");

        }
    }
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public MainViewModel()
    {
        //SwapCMD = new CommandDelegate(action: x => { Console.WriteLine("Ignore this line"); }, executable: x => { return true; });

        ImgSource = new StartViewModel().ImgSource;

    }
}
</code>```

MainPage.xaml.cs

```<code> public MainPage()
    {
        InitializeComponent();
        this.BindingContext = new MainViewModel();
    }
</code>```

App.xaml.cs

```<code>   MainPage = new NavigationPage(new StartPage());
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make a simple jigsaw puzzle. First the user imports a photo from his library, then the image is displayed letting the user confirm, that this is the one, that he wants to use. Then he presses a "Play" button, which opens up a new content page, which should ALSO display the exact same image.

I'm using MVVM in this project.

The first ContentPage has an Image which is bound to a ImageSource property in the ViewModel.

When the ImageSource is set, it is also copied to a SharedData class.

When the user presses the "Play" button a new ContentPage is loaded, and the same Image should appear loading the ImageSource from the SharedData class.

However this does not happen!

Can anyone figure out what I'm doing wrong?

To put it simple, I just want to share the image between ViewModels (classes) in a very simple way. The task is not to set up some complicated architecture. I just want this little thing to work.

StartViewModel:

        // Image
    private ImageSource _imageSource = "";
    public ImageSource ImgSource
    {
        get { return _imageSource; }
        set
        {
            _imageSource = value;
            SharedData.ImageSource = value;
            OnPropertyChanged();

        }
    }

XAML:

            <Image Margin="0,100,0,0" Source="{Binding ImgSource}" BackgroundColor="Black"></Image>

This works fine, however when passing the ImageSource to the SharedData class or as a parameter in the MainViewModel it goes wrong

MainViewModel (The second view):

        // Image
    private ImageSource _imageSource = "mouse.jpg";
    public ImageSource ImgSource
    {
        get { return _imageSource; }
        set
        {
            _imageSource = value;
            OnPropertyChanged();

        }
    }

    public MainViewModel()
    {
        SwapCMD = new CommandDelegate(action: x => { Console.WriteLine("Ignore this line"); }, executable: x => { return true; });

        ImgSource = SharedData.ImageSource;

    }

And as you can see I have bound the ImageSource the same way as in the previous view:

XAML:

        <Image Margin="0,100,0,0" Source="{Binding ImgSource}" BackgroundColor="Black"></Image>

What am I doing wrong? Why can't I just pass the source to another view like that?

Body:
You could try the code below. I am not sure why you use a SharedData class to store the imagesource at first time. But, when you pass the imagesource from one viewmodel to another, you could pass it directly.

StartPage.xaml

 <StackLayout>
        <Image
            Margin="0,100,0,0"
            BackgroundColor="Black"
            Source="{Binding ImgSource}" />
        <Button
            x:Name="btnPlay"
            Clicked="btnPlay_Clicked"
            Text="Play" />
    </StackLayout>

StartViewModel.cs

public class StartViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private ImageSource _imageSource = "";
    public ImageSource ImgSource
    {
        get { return _imageSource; }
        set
        {
            _imageSource = value;
            OnPropertyChanged("ImgSource");
        }
    }

    public StartViewModel()
    {
        ImgSource = "pink.jpg";
    }
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

StartPage.xaml.cs

  public StartPage()
    {
        InitializeComponent();

        this.BindingContext = new StartViewModel();
    }

    private async void btnPlay_Clicked(object sender, EventArgs e)
    {
        await Navigation.PushAsync(new MainPage());
    }

MainPage.xaml

  <StackLayout>
    <!--  Place new controls here  -->
    <Image
        Margin="0,100,0,0"
        BackgroundColor="Black"
        Source="{Binding ImgSource}" />

</StackLayout>

MainViewModel.cs

 public class MainViewModel : INotifyPropertyChanged
{
    // Image
    private ImageSource _imageSource = "";

    public event PropertyChangedEventHandler PropertyChanged;

    public ImageSource ImgSource
    {
        get { return _imageSource; }
        set
        {
            _imageSource = value;
            OnPropertyChanged("ImgSource");

        }
    }
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public MainViewModel()
    {
        //SwapCMD = new CommandDelegate(action: x => { Console.WriteLine("Ignore this line"); }, executable: x => { return true; });

        ImgSource = new StartViewModel().ImgSource;

    }
}

MainPage.xaml.cs

 public MainPage()
    {
        InitializeComponent();
        this.BindingContext = new MainViewModel();
    }

App.xaml.cs

   MainPage = new NavigationPage(new StartPage());


问:
SQL Select where values in List<string>
Is there a way that I can create query against a data source (could be sql, oracle or access) that has a where clause that points to an ArrayList or List?

example:

```<code>Select * from Table where RecordID in (RecordIDList)
</code>```

I've seen some ways to do it with Linq, but I'd rather not resort to it if it's avoidable.

答:
I've only done what your trying to do with a comma separated list

```<code>Select * from Table where RecordID in (1,2,34,45,76,34,457,34)
</code>```

or where the results come from a separate select

```<code>Select * from Table where RecordID in (select recordId from otherTable where afieldtype=1)
</code>```

I'm pretty sure you can't achieve what you're after....

OwnerDisplayName: JoelHess

ContentLicense: CC BY-SA 2.5

Title: SQL Select where values in List<string>

Body:
Is there a way that I can create query against a data source (could be sql, oracle or access) that has a where clause that points to an ArrayList or List?

example:

Select * from Table where RecordID in (RecordIDList)

I've seen some ways to do it with Linq, but I'd rather not resort to it if it's avoidable.

LastEditorDisplayName: Andrew Hare

Body:
I've only done what your trying to do with a comma separated list

Select * from Table where RecordID in (1,2,34,45,76,34,457,34)

or where the results come from a separate select

Select * from Table where RecordID in (select recordId from otherTable where afieldtype=1)

I'm pretty sure you can't achieve what you're after....

OwnerDisplayName: GordonB


问:
Reset functions after ajax
I have this javascript file: http://pastebin.com/m2keHsTM

A big part of it is a toggle switch that works by sliding your finger or mouse on it. As you see at the end of the document

```<code>var togglebox = "<div class='toggle_box'></div>";
    $('input[type=checkbox]').css('display','none');
    $('fieldset[data-input-type=checkbox]').append(togglebox);
    var mouseDown = false;
    var beginTouchDown = 0;
    create_elements();
    set_listeners();
</code>```

replaces the checkboxes on the page by div's that are "slideable" This works great, only when I load another page trough ajax, other new checkboxes do not get replaced.
Is there a way to reset those functions and make them check again after an ajax call?

Thanks a lot for your help :)

答: I just added the original functions to hijacklinks() to initiate them each time the page changes :)

ContentLicense: CC BY-SA 3.0

Title: Reset functions after ajax

Body:
I have this javascript file: http://pastebin.com/m2keHsTM

A big part of it is a toggle switch that works by sliding your finger or mouse on it. As you see at the end of the document

var togglebox = "

";
    $('input[type=checkbox]').css('display','none');
    $('fieldset[data-input-type=checkbox]').append(togglebox);
    var mouseDown = false;
    var beginTouchDown = 0;
    create_elements();
    set_listeners();

replaces the checkboxes on the page by div's that are "slideable" This works great, only when I load another page trough ajax, other new checkboxes do not get replaced.
Is there a way to reset those functions and make them check again after an ajax call?

Thanks a lot for your help :)


问:
How to setup Lambda/Step Functions such that I'm not billed while idling for API responses?
Say I have a top level AWS Lambda function, called order_for_all_clients, and another Lambda function called order_for_single_client.

order_for_all_clients gathers up 1,000 clients, and makes a Step Function call to order_for_single_client for each one of them.

order_for_single_client has a workflow along these lines:

Place external API call, wait for response.

Based on #1, make another external API call, wait for response.

Based on #2, make another external API call, wait for response.

Within this function, 90% of the time is spent waiting for API calls to return a response. The other 10% is spent performing the actual processing/computation.

Is there a way to architect Lambda/Step Functions in such a way that it can fire off an API call, shut down the current Lambda function, and then re-initiate a Lambda function once the API call returns? In doing so, I will only be billed for actual computation time, and not be billed for time spent idling around waiting for API calls to return.

答:
No, this is not possible. There would be nothing to "receive" the API response.

A cleaner "async" solution would be to request the external service to send a response to an Amazon SQS queue, which could then trigger an AWS Lambda function. However, this would need a change to the way that the external service processes API requests.

Or, the external service might provide separate API calls to 'submit' a request and then 'retrieve' the result of a request. The Lambda function could 'submit' the request. Another process would then poll the service to retrieve the results for any jobs that have completed.

If you have many requests per second to the external service, it might be worth moving to Amazon EC2 and make requests in parallel. This would make greater use of the resources while waiting for a response.


问:
How to pass function of one class as argument of another function of another class
I have created a class Base which has a function addSuccessor() that takes address of function as argument and stores it in successor. How do I pass a function of another object in addSuccessor().
Here is my program. I think my main() has some mistake.

```<code>#include <iostream>
#include<vector>
using namespace std;
class Base{
public:
    void (*successor)()=NULL;
    void addSuccessor ( void (*f)() )
    {
        successor=f;
    }
    void start()
    {
        cout<<"In Class"<<endl;
        if(!successor==NULL)
            successor();
        else
            cout<<"No Successor"<<endl;
    }
};
class Second{
    public:
    void foo()
    {
        cout<<"Successor";
    }
};

int main()
{
    Base obj;
    Second obj2;

    obj.addSuccessor(&obj2.foo());
    obj.start();

}
</code>```

答:
Function pointers are very limited.  Use a std::function (defined in header <functional>) instead, which can store any invocable object in a type-erased manner, and provide a template member function to set the functor in which perfect forwarding is used to forward the provided functor to successor: (std::forward is defined in header <utility>)

```<code>class Base {
    std::function<void()> successor;
public:
    template <typename F>
    void add_successor(F&& f)
    {
        successor = std::forward<F>(f);
    }
    void start()
    {
        if (successor) {
            successor();
        } else {
            std::cout << "No Successor\n";
        }
    }
};
</code>```

Then, you can pass a lambda expression to add_successor:

```<code>obj.add_successor([&]{ obj2.foo(); });
</code>```

(live demo)

Body:
I have created a class Base which has a function addSuccessor() that takes address of function as argument and stores it in successor. How do I pass a function of another object in addSuccessor().
Here is my program. I think my main() has some mistake.

#include <iostream>
#include<vector>
using namespace std;
class Base{
public:
    void (*successor)()=NULL;
    void addSuccessor ( void (*f)() )
    {
        successor=f;
    }
    void start()
    {
        cout<<"In Class"<<endl;
        if(!successor==NULL)
            successor();
        else
            cout<<"No Successor"<<endl;
    }
};
class Second{
    public:
    void foo()
    {
        cout<<"Successor";
    }
};

int main()
{
    Base obj;
    Second obj2;

    obj.addSuccessor(&obj2.foo());
    obj.start();

}

Body:
Function pointers are very limited.  Use a std::function (defined in header <functional>) instead, which can store any invocable object in a type-erased manner, and provide a template member function to set the functor in which perfect forwarding is used to forward the provided functor to successor: (std::forward is defined in header <utility>)

class Base {
    std::function<void()> successor;
public:
    template <typename F>
    void add_successor(F&& f)
    {
        successor = std::forward<F>(f);
    }
    void start()
    {
        if (successor) {
            successor();
        } else {
            std::cout << "No Successor\n";
        }
    }
};

Then, you can pass a lambda expression to add_successor:

obj.add_successor([&]{ obj2.foo(); });

(live demo)


问:
Error when run ios project, main.dart not changes and keep default code
Error when run ios project, main.dart not changes and keep default code, but after i do hot restart, the app run perfectly and compile the code that i already edit at main.dart.

this is my main.dart

```<code>void _enablePlatformOverrideForDesktop() {
  if (!kIsWeb && (Platform.isMacOS || Platform.isWindows || Platform.isLinux)) {
    debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia;
  }
}

void main() {
  // ignore: invalid_use_of_visible_for_testing_member
  SharedPreferences.setMockInitialValues({});
  _enablePlatformOverrideForDesktop();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SplashScreen(),
      debugShowCheckedModeBanner: false,
    );
  }
}
</code>```

This only happen when i run the project, what is the problem i really dont know, do anyone know how to solve this, thanks.

答:
I was also facing the same Issue I am using VS Code on MacOs and I was experiencing same for Android

Whenever you fresh run the project just type this command

```<code>flutter clean
</code>```

Then

```<code>flutter run
</code>```

Body:
Error when run ios project, main.dart not changes and keep default code, but after i do hot restart, the app run perfectly and compile the code that i already edit at main.dart.

this is my main.dart

void _enablePlatformOverrideForDesktop() {
  if (!kIsWeb && (Platform.isMacOS || Platform.isWindows || Platform.isLinux)) {
    debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia;
  }
}

void main() {
  // ignore: invalid_use_of_visible_for_testing_member
  SharedPreferences.setMockInitialValues({});
  _enablePlatformOverrideForDesktop();
  runApp(MyApp());
}

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

This only happen when i run the project, what is the problem i really dont know, do anyone know how to solve this, thanks.

Body:
I was also facing the same Issue I am using VS Code on MacOs and I was experiencing same for Android

Whenever you fresh run the project just type this command

flutter clean

Then

flutter run


问:
Make the hover work even after a jquery bind('click')?
Basically, I wanted to make the hover work even after a bind click, but I set the .image26 and 27 to it's default background. The hover works at first, but when clicked, since I reset it back to default, does not work again.

Is there a better approach on this? If I did not put the rest of the image to it's default position, then all of them will be marked as clicked.

Working sample:
http://jsfiddle.net/louiemiranda/RkM3t/

The jquery code:

```<code>$(".image22").bind("click", function(event){
    $(this).css("background-position", "0 100%");
    $('#package22').attr("checked", "checked");
    $('.image26').css("background-position", "0 0");
    $('.image27').css("background-position", "0 0");
    var cashcredit = $('#package22').val();
    $('#fyi').html(cashcredit);
});

$(".image22").bind("mouseenter mouseleave", function(event){
    $(this).toggleClass("image22-selected");
});
</code>```

Any help is appreciated. Thanks!

答:
Once you call css to set background-position (a property that you are expecting to change by toggling image22-selected class), that css property is applied as inline style and, consequently, gains priority over a class rule.

You could remove the background-position css property before toggling the class. This way, no inline style would gain priority.

However, I think the more sensible way of achieving this is to use another css class name, like image22-hover and defining the rules in this order:

```<code>image22 {
    background-image: url(your-image-22);
    background-position: 0 0;
}

image22-hover {
    background-position: move to a grey version of the image.
}

image22-selected {
    background-position: move to a selected version of the image.
}

image22-selected.image22-hover {
    background-position: move to a grey-selected version of the image.
}
</code>```

Note that chained CSS classes selectors (the last selector) don't work in IE6:
http://www.ryanbrill.com/archives/multiple-classes-in-ie/

Body:
Basically, I wanted to make the hover work even after a bind click, but I set the .image26 and 27 to it's default background. The hover works at first, but when clicked, since I reset it back to default, does not work again.

Is there a better approach on this? If I did not put the rest of the image to it's default position, then all of them will be marked as clicked.

Working sample:
http://jsfiddle.net/louiemiranda/RkM3t/

The jquery code:

$(".image22").bind("click", function(event){
    $(this).css("background-position", "0 100%");
    $('#package22').attr("checked", "checked");
    $('.image26').css("background-position", "0 0");
    $('.image27').css("background-position", "0 0");
    var cashcredit = $('#package22').val();
    $('#fyi').html(cashcredit);
});

$(".image22").bind("mouseenter mouseleave", function(event){
    $(this).toggleClass("image22-selected");
});

Any help is appreciated. Thanks!

Body:
Once you call css to set background-position (a property that you are expecting to change by toggling image22-selected class), that css property is applied as inline style and, consequently, gains priority over a class rule.

You could remove the background-position css property before toggling the class. This way, no inline style would gain priority.

However, I think the more sensible way of achieving this is to use another css class name, like image22-hover and defining the rules in this order:

image22 {
    background-image: url(your-image-22);
    background-position: 0 0;
}

image22-hover {
    background-position: move to a grey version of the image.
}

image22-selected {
    background-position: move to a selected version of the image.
}

image22-selected.image22-hover {
    background-position: move to a grey-selected version of the image.
}

Note that chained CSS classes selectors (the last selector) don't work in IE6:
http://www.ryanbrill.com/archives/multiple-classes-in-ie/


问:
Can't locate element on Microsoft Sign In page for Microsoft Forms
I'm currently trying to locate Microsoft Sign In page's email input box by using xpath (others as well) but after many tries I still can't locate the correct element for it.

After copying the element from the page, this is the element given:

```<code><input type="email" class="form-control" placeholder="Email, phone, or Skype" aria-required="true" spellcheck="false" autocomplete="off" data-bind="
                                    hasFocus: focus,
                                    textInput: email,
                                    attr: {'placeholder': config.text.emailPlaceHolder, 'aria-invalid': !error}">
</code>```

And this is currently my python code:

```<code>login = browser.find_element_by_xpath("//input[@class='form-control']")
login.send_keys(config.username)
login.send_keys(Keys.RETURN)
</code>```

I had tried multiple times but I still can't get the proper element to proceed. After entering https://forms.office.com/ I had successfully captured the sign in element but stuck at the next page.

Please NOTE that this is similar to this question but is not the same as the page element is quite different. Any help would be greatly appreciated!

答:
Your target element is present in an iframe with id as hrdIframe. So you have to switch to the frame before interacting with the element.

```<code>driver.switch_to.frame('hrdIframe')
driver.find_element_by_xpath("//input[@type='email']").send_keys(config.username)
</code>```

Always make sure you switch back to default frame once you are done with the actions in iframe.

Body:
I'm currently trying to locate Microsoft Sign In page's email input box by using xpath (others as well) but after many tries I still can't locate the correct element for it.

After copying the element from the page, this is the element given:

<input type="email" class="form-control" placeholder="Email, phone, or Skype" aria-required="true" spellcheck="false" autocomplete="off" data-bind="
                                    hasFocus: focus,
                                    textInput: email,
                                    attr: {'placeholder': config.text.emailPlaceHolder, 'aria-invalid': !error}">

And this is currently my python code:

login = browser.find_element_by_xpath("//input[@class='form-control']")
login.send_keys(config.username)
login.send_keys(Keys.RETURN)

I had tried multiple times but I still can't get the proper element to proceed. After entering https://forms.office.com/ I had successfully captured the sign in element but stuck at the next page.

Please NOTE that this is similar to this question but is not the same as the page element is quite different. Any help would be greatly appreciated!

Body:
Your target element is present in an iframe with id as hrdIframe. So you have to switch to the frame before interacting with the element.

driver.switch_to.frame('hrdIframe')
driver.find_element_by_xpath("//input[@type='email']").send_keys(config.username)

Always make sure you switch back to default frame once you are done with the actions in iframe.


问:
Python how to get a value from a complex dictionary?
In dict1 below, how do I assign from_port to the value of 'FromPort' if I am unsure what index it will be in the 'IpPermissions'?

For the example below, I can use an index, but it is not always index 0.

from_port = dict1['IpPermissions'][0]['FromPort']

dict1 = {'Description': 'Some AWS security group', 'IpPermissions': [{'Cidr': '0.0.0.0/0', 'FromPort': '80', 'IpProtocol': 'TCP'}]}

答:
You can check if each element in the list has the attribute FromPort.

dict1 = {'Description': 'Some AWS security group', 'IpPermissions': [{'Cidr': '0.0.0.0/0', 'FromPort': '80', 'IpProtocol': 'TCP'}]}

ip_permissions = dict1['IpPermissions']
for perm in ip_permissions:
    if 'FromPort' in perm:
        from_port = perm['FromPort']
```

Note: this doesn't handle the case if there is more than one dict with a 'FromPort' in it.

Body:
You can check if each element in the list has the attribute FromPort.

dict1 = {'Description': 'Some AWS security group', 'IpPermissions': [{'Cidr': '0.0.0.0/0', 'FromPort': '80', 'IpProtocol': 'TCP'}]}

ip_permissions = dict1['IpPermissions']
for perm in ip_permissions:
    if 'FromPort' in perm:
        from_port = perm['FromPort']

Note: this doesn't handle the case if there is more than one dict with a 'FromPort' in it.


问:
Flask - how to develop and debug Azure Web App using provider-specific headers?
I'm working on a small site using Flask/Azure web apps and would like to use Azure AD authentication, which is provided through the Azure portal web app settings.  I also need to access to Microsoft Graph using the same credentials once a user is logged in.  This seems easy enough when the app is actually set up on Azure:

request these headers as needed and make the requests.

X-MS-TOKEN-AAD-ID-TOKEN
X-MS-TOKEN-AAD-ACCESS-TOKEN
X-MS-TOKEN-AAD-EXPIRES-ON
X-MS-TOKEN-AAD-REFRESH-TOKEN

I can't figure out how to do this part while I'm developing, however.  I don't want to have to write a bit, upload to Azure, catch a bug, then start all over again.  Is there a way to emulate the login/headers while developing?

答:
In local, you could register an AD App in azure ad, give the Delegated permissions for Microsoft Graph, e.g. if you want to call this API - List users, you give the User.Read.All delegated permission, then use the auth code flow to get the access token to call the API, for details see this link. Once call the API successfully, it means the user could be able to call the API.

I also need to access to Microsoft Graph using the same credentials once a user is logged in.

To call Microsoft Graph once the user logged in the web app, you need to configure the https://microsoft.graph.com in the authsettings -> additionaloginparams of your web app in the resource explorer, follow this link.


问:
Rails replay to a message to moderator or admin - depends on created_at date
My app currently just displays a message which a client received after applying for a product. I want to give to the client the ability to reply to the original message from the moderator and saved it in his inbox (moderator inbox). However if the original message from moderator is older than 3 days, message should be routed to an admin and saved it in his inbox (admin inbox).

The app has 4 models:

user.rb

```<code>class User < ApplicationRecord
  has_one :inbox
  has_one :outbox
  has_many :messages

  scope :client, -> { where(is_client: true) }
  scope :admin, -> { where(is_admin: true) }
  scope :moderator, -> { where(is_moderator: true) }
end
</code>```

message.rb

```<code>class Message < ApplicationRecord
  belongs_to :inbox
  belongs_to :outbox
end
</code>```

When a user sends a message, it goes into their outbox and into the inbox of the recipient:

inbox.rb

```<code>class Inbox < ApplicationRecord
  belongs_to :user
  has_many :messages
end
</code>```

outbox.rb

```<code>class Outbox < ApplicationRecord
  belongs_to :user
  has_many :messages
end
</code>```

I'm trying to something like this:

MessagesController.rb

```<code>def show
  @message = Message.find(params[:id])
end

def new
  @message = Message.new
end

def create

  @message = Message.create(
  if current_user.message.created_at > 3.days.ago
    outbox: moderator.outbox
  else
    outbox: admin.outbox
  end
)
end
</code>```

If I assume that I've only one moderator and one client should I have to create another controller to catch this message which I want to reply?

答:
assuming in user inbox theres a link to reply to original message

```<code>= link_to 'Reply', new_message_path(message_id: orignal_message_id_goes_here)
</code>```

message_id will be passed as a query string

```<code>= form_for @message do |f|
  = hidden_field_tag :original_message_id, params[:message_id]
  ...
</code>```

this will submit original_message_id with form data

```<code>def create
  orignal_message = current_user.inbox.messages.find_by(id: params[:original_message_id])

  inbox = if orignal_message.created_at > 3.days.ago
             orignal_message.moderator.inbox
          else
             # find admin and get inbox
          end

  @message = Message.create(
    inbox: inbox
    body: params[:message][:body]
  )
end
</code>```

Body:
My app currently just displays a message which a client received after applying for a product. I want to give to the client the ability to reply to the original message from the moderator and saved it in his inbox (moderator inbox). However if the original message from moderator is older than 3 days, message should be routed to an admin and saved it in his inbox (admin inbox).

The app has 4 models:

user.rb

class User < ApplicationRecord
  has_one :inbox
  has_one :outbox
  has_many :messages

  scope :client, -> { where(is_client: true) }
  scope :admin, -> { where(is_admin: true) }
  scope :moderator, -> { where(is_moderator: true) }
end

message.rb

class Message < ApplicationRecord
  belongs_to :inbox
  belongs_to :outbox
end

When a user sends a message, it goes into their outbox and into the inbox of the recipient:

inbox.rb

class Inbox < ApplicationRecord
  belongs_to :user
  has_many :messages
end

outbox.rb

class Outbox < ApplicationRecord
  belongs_to :user
  has_many :messages
end

I'm trying to something like this:

MessagesController.rb

def show
  @message = Message.find(params[:id])
end

def new
  @message = Message.new
end

def create

  @message = Message.create(
  if current_user.message.created_at > 3.days.ago
    outbox: moderator.outbox
  else
    outbox: admin.outbox
  end
)
end

If I assume that I've only one moderator and one client should I have to create another controller to catch this message which I want to reply?

Body:
assuming in user inbox theres a link to reply to original message

= link_to 'Reply', new_message_path(message_id: orignal_message_id_goes_here)

message_id will be passed as a query string

= form_for @message do |f|
  = hidden_field_tag :original_message_id, params[:message_id]
  ...

this will submit original_message_id with form data

def create
  orignal_message = current_user.inbox.messages.find_by(id: params[:original_message_id])

  inbox = if orignal_message.created_at > 3.days.ago
             orignal_message.moderator.inbox
          else
             # find admin and get inbox
          end

  @message = Message.create(
    inbox: inbox
    body: params[:message][:body]
  )
end


问:
How to Get Child Product Ids from a Configurable product
I am trying to fetch all child product Ids from configurable product Ids.

```<code>$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $product = $objectManager->create('\Magento\Catalog\Model\Product');

        $storeManager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface');
        $currentStore = $storeManager->getStore();
        $mediaUrl = $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
        $productURL = $mediaUrl.'catalog/product';
        $collection = $this->_productCollectionFactory->create();
        $productCollection = $collection->addAttributeToSelect('*')->addAttributeToFilter('type_id','configurable');
        $vendor_product = array();

        $productData = $product->getData();
        foreach($productCollection as $prodObj){
            $productData = array();
            $product = $product->load($prodObj->getId());

                     $productTypeInstance = $product->getTypeInstance();
            $usedProducts = $productTypeInstance->getUsedProducts($product);

 foreach ($usedProducts  as $child) {
$productData['childrenIds'][] = $child->getId();
}
</code>```

I get Ids of my first configurable product in all the cases

答:
You can use the below code for getting Child ID.

```<code>$product = $block->getProduct();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$configurable_product_id = $product->getId();
$configurableProduct = $objectManager->get('Magento\Catalog\Model\ProductRepository')->getById($configurable_product_id);

$children = $configurableProduct->getTypeInstance()->getUsedProducts($configurableProduct);       $childIds = array();
foreach ($children as $child){
  $childIds[] = $child->getId();
}
sort($childIds);
print_r($childIds);
</code>```

This is for sample code but I suggest do not use $objectManager directly, you can use Block on Plugin Method to get Product Object.

Body:
I am trying to fetch all child product Ids from configurable product Ids.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $product = $objectManager->create('\Magento\Catalog\Model\Product');

        $storeManager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface');
        $currentStore = $storeManager->getStore();
        $mediaUrl = $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
        $productURL = $mediaUrl.'catalog/product';
        $collection = $this->_productCollectionFactory->create();
        $productCollection = $collection->addAttributeToSelect('*')->addAttributeToFilter('type_id','configurable');
        $vendor_product = array();

        $productData = $product->getData();
        foreach($productCollection as $prodObj){
            $productData = array();
            $product = $product->load($prodObj->getId());

                     $productTypeInstance = $product->getTypeInstance();
            $usedProducts = $productTypeInstance->getUsedProducts($product);

 foreach ($usedProducts  as $child) {
$productData['childrenIds'][] = $child->getId();
}

I get Ids of my first configurable product in all the cases

Body:
You can use the below code for getting Child ID.

$product = $block->getProduct();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$configurable_product_id = $product->getId();
$configurableProduct = $objectManager->get('Magento\Catalog\Model\ProductRepository')->getById($configurable_product_id);

$children = $configurableProduct->getTypeInstance()->getUsedProducts($configurableProduct);       $childIds = array();
foreach ($children as $child){
  $childIds[] = $child->getId();
}
sort($childIds);
print_r($childIds);

This is for sample code but I suggest do not use $objectManager directly, you can use Block on Plugin Method to get Product Object.


问:
Unable to install java8 with homebrew
Installing java8 with Homebrew seems to no longer be working. After running:

```<code>brew install caskroom/cask/java8
</code>```

I get the following error:

```<code>Error: Cask 'java8' is unavailable: '/usr/local/Homebrew/Library/Taps/caskroom/homebrew-cask/Casks/java8.rb' does not exist.
</code>```

Simply doing:

```<code>brew cask install java8
</code>```

Errors out with:

```<code>Error: Cask 'java8' is unavailable: No Cask with this name exists.
</code>```

This seems like a recent development because I remember installing it this way a few months ago. Any suggestions on how to properly install java8 on MacOS nowadays?

答: Ask the user to install Oracle JDK 8 instead of java8</p>

Title: Unable to install java8 with homebrew

Body:
Installing java8 with Homebrew seems to no longer be working. After running:

brew install caskroom/cask/java8

I get the following error:

Error: Cask 'java8' is unavailable: '/usr/local/Homebrew/Library/Taps/caskroom/homebrew-cask/Casks/java8.rb' does not exist.

Simply doing:

brew cask install java8

Errors out with:

Error: Cask 'java8' is unavailable: No Cask with this name exists.

This seems like a recent development because I remember installing it this way a few months ago. Any suggestions on how to properly install java8 on MacOS nowadays?


问:
In Azure DevOps release pipeline is it possible to request approval conditionally?
We use Azure DevOps Server 2019 (on-prem). I.e. no unified pipelines, no YAML release pipeline.

The scenario is this:

Stage A invokes terraform plan to produce a plan file

Stage B takes the plan file (somehow, see In Azure DevOps Server 2019 (on-prem) release pipeline how can one stage pass a file to another stage?) and runs terraform apply.

There is post-deployment approval on Stage A (and/or pre-deployment on Stage B) to let human inspect the plan before applying it.

Now, it does not make sense to request human approval always. We can inspect the plan automatically and request approval only if the plan contains destruction of stateful resources. The scripting code is not a problem, but how to request approval conditionally?

答:
As noted in the other answer there is not a first class way to do this, but I can suggest a way to get it done using the Rest API and powerShell. It involves a conditional set on an Agentless Job with a manual intervention step.

So release variables can't flow across Agent Jobs or Stages but what you can do is update a release variable, by updating the instance of the release itself via a Rest API call. Then you could use that variable in subsequent Jobs or stages.

In the job where you are getting the Terraform plan output, assuming you are capturing when there is an Add, Change, or Destroy operation you could then marshal that output back into the release, and use it further down the line.

So the example borrows from this post by Stefan Stranger. See also this post by Donavan Brown.

Assuming the below powerShell script runs in the first Agent phase and has access to your plan result.
I have predefined a variable in the Release Definition named TerraformPlanResult.

```<code>$releaseurl = ('{0}{1}/_apis/release/releases/{2}?api-version=5.0' -f $($env:SYSTEM_TEAMFOUNDATIONSERVERURI), $($env:SYSTEM_TEAMPROJECTID), $($env:RELEASE_RELEASEID)  )

Write-Host "URL: $releaseurl"
$Release = Invoke-RestMethod -Uri $releaseurl -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}

#update the predefined $TerraformPlanResult variable
$Release.variables.TerraformPlanResult.value = $YourPlanResult

Write-Output ('Updating Release Definition Instance')
$json = @($Release) | ConvertTo-Json -Depth 99
Invoke-RestMethod -Uri $releaseurl -Method Put -Body $json -ContentType "application/json" -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN" }
</code>```

Now that the $TerraformPlanResult variable is available at the release level, you define a Agentless Job with this conditional.

and(succeeded(), in(variables['TerraformPlanResult'], 'Add', 'Change','Destroy'))

Now the manual intervention step will only run if the condition is met.

A couple of other notes:

You also want to make sure your Project Collection Build Service has rights to update release definitions.

You want to make sure that the first Agent Job has the ability access the OAuth token so you can make the rest calls.

Body:
As noted in the other answer there is not a first class way to do this, but I can suggest a way to get it done using the Rest API and powerShell. It involves a conditional set on an Agentless Job with a manual intervention step.

So release variables can't flow across Agent Jobs or Stages but what you can do is update a release variable, by updating the instance of the release itself via a Rest API call. Then you could use that variable in subsequent Jobs or stages.

In the job where you are getting the Terraform plan output, assuming you are capturing when there is an Add, Change, or Destroy operation you could then marshal that output back into the release, and use it further down the line.

So the example borrows from this post by Stefan Stranger. See also this post by Donavan Brown.

Assuming the below powerShell script runs in the first Agent phase and has access to your plan result.
I have predefined a variable in the Release Definition named TerraformPlanResult.

$releaseurl = ('{0}{1}/_apis/release/releases/{2}?api-version=5.0' -f $($env:SYSTEM_TEAMFOUNDATIONSERVERURI), $($env:SYSTEM_TEAMPROJECTID), $($env:RELEASE_RELEASEID)  )

Write-Host "URL: $releaseurl"
$Release = Invoke-RestMethod -Uri $releaseurl -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}

#update the predefined $TerraformPlanResult variable
$Release.variables.TerraformPlanResult.value = $YourPlanResult

Write-Output ('Updating Release Definition Instance')
$json = @($Release) | ConvertTo-Json -Depth 99
Invoke-RestMethod -Uri $releaseurl -Method Put -Body $json -ContentType "application/json" -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN" }

Now that the $TerraformPlanResult variable is available at the release level, you define a Agentless Job with this conditional.

and(succeeded(), in(variables['TerraformPlanResult'], 'Add', 'Change','Destroy'))

Now the manual intervention step will only run if the condition is met.

A couple of other notes:

You also want to make sure your Project Collection Build Service has rights to update release definitions.

You want to make sure that the first Agent Job has the ability access the OAuth token so you can make the rest calls.


问:
Swift - splash screen / Launch Screen
This might be a silly question. I am trying to add launch screen to my app. In Xcode (11.3),I added the imageview in "LaunchScreen.storyboard" and added the image, when i run it in simulator, i notice the top and bottom of screen has default white color. Attached is the screen shot, can any one let me know, how i can add the entire image on screen.

Launch Screen

Launch Screen

答:
Try setting ContentMode of the UIImageView to scaleAspectFill

After doing that you still got the problem so all you need to do set your top and bottom constraints to superview so the white area will not appear.

after that step you should double click on top space and another thing will open which is also you can see in below image.
set the top and button constraints like this and you white space will gone.

Title: Swift - splash screen / Launch Screen


问:
Compare date in Oracle when some value is null?
I want to get records that have an expired_date less than "31/12/2015", but some value of expired_date field is null in the database. This is my SQL:

```<code>"AND TO_DATE(EXPIRED_DATE,'DD/MM/YYYY') < TO_DATE('31/12/2015','DD/MM/YYYY')"
</code>```

so I have got an error

```<code>"day of the month must between 1 and the last day of the month"
</code>```

How can I get just records that have an expired_date < '31/12/2015'?

EDIT: The problem is not the null value, but my format in my DB. I store "22-APR-15" and mistake is trying to assign it to 'DD/MM/YYYY' by to_date function

答:
If your column EXPIRED_DATE is of date type then, you don't need to convert it to date again using TO_DATE.

I think you need the following:

```<code>AND EXPIRED_DATE < TO_DATE('31/12/2015','DD/MM/YYYY')
</code>```

This will return false for any EXPIRED_DATE which is null and that record will not be included in the result.

If you want Null EXPIRED_DATE to be included in the result then you can use OR as following:

```<code>AND (EXPIRED_DATE IS NULL OR EXPIRED_DATE < TO_DATE('31/12/2015','DD/MM/YYYY'))
</code>```

Body:
I want to get records that have an expired_date less than "31/12/2015", but some value of expired_date field is null in the database. This is my SQL:

"AND TO_DATE(EXPIRED_DATE,'DD/MM/YYYY') < TO_DATE('31/12/2015','DD/MM/YYYY')"

so I have got an error

"day of the month must between 1 and the last day of the month"

How can I get just records that have an expired_date < '31/12/2015'?

EDIT: The problem is not the null value, but my format in my DB. I store "22-APR-15" and mistake is trying to assign it to 'DD/MM/YYYY' by to_date function

Body:
If your column EXPIRED_DATE is of date type then, you don't need to convert it to date again using TO_DATE.

I think you need the following:

AND EXPIRED_DATE < TO_DATE('31/12/2015','DD/MM/YYYY')

This will return false for any EXPIRED_DATE which is null and that record will not be included in the result.

If you want Null EXPIRED_DATE to be included in the result then you can use OR as following:

AND (EXPIRED_DATE IS NULL OR EXPIRED_DATE < TO_DATE('31/12/2015','DD/MM/YYYY'))


问:
Best practice for instantiating a new Android Fragment
I have seen two general practices to instantiate a new Fragment in an application:

```<code>Fragment newFragment = new MyFragment();
</code>```

and

```<code>Fragment newFragment = MyFragment.newInstance();
</code>```

The second option makes use of a static method newInstance() and generally contains the following method.

```<code>public static Fragment newInstance()
{
    MyFragment myFragment = new MyFragment();
    return myFragment;
}
</code>```

At first, I thought the main benefit was the fact that I could overload the newInstance() method to give flexibility when creating new instances of a Fragment - but I could also do this by creating an overloaded constructor for the Fragment.

Did I miss something?

What are the benefits of one approach over the other? Or is it just good practice?

答:
I'm lately here. But somethings I just known that might help you a bit.

If you are using Java, there is nothing much to change. But for Kotlin developers, here is some following snippet I think that can make you a basement to run on:

Parent fragment:

```<code>inline fun <reified T : SampleFragment> newInstance(text: String): T {
    return T::class.java.newInstance().apply {
        arguments = Bundle().also { it.putString("key_text_arg", text) }
    }
}
</code>```

Normal call

```<code>val f: SampleFragment = SampleFragment.newInstance("ABC")
// or val f = SampleFragment.newInstance<SampleFragment>("ABC")
</code>```

You can extend the parent init operation in child fragment class by:

```<code>fun newInstance(): ChildSampleFragment {
    val child = UserProfileFragment.newInstance<ChildSampleFragment>("XYZ")
    // Do anything with the current initialized args bundle here
    // with child.arguments = ....
    return child
}

</code>```

Happy coding.

Body:
I have seen two general practices to instantiate a new Fragment in an application:

Fragment newFragment = new MyFragment();

and

Fragment newFragment = MyFragment.newInstance();

The second option makes use of a static method newInstance() and generally contains the following method.

public static Fragment newInstance()
{
    MyFragment myFragment = new MyFragment();
    return myFragment;
}

At first, I thought the main benefit was the fact that I could overload the newInstance() method to give flexibility when creating new instances of a Fragment - but I could also do this by creating an overloaded constructor for the Fragment.

Did I miss something?

What are the benefits of one approach over the other? Or is it just good practice?

Body:
I'm lately here. But somethings I just known that might help you a bit.

If you are using Java, there is nothing much to change. But for Kotlin developers, here is some following snippet I think that can make you a basement to run on:

Parent fragment:

inline fun <reified T : SampleFragment> newInstance(text: String): T {
    return T::class.java.newInstance().apply {
        arguments = Bundle().also { it.putString("key_text_arg", text) }
    }
}

Normal call

val f: SampleFragment = SampleFragment.newInstance("ABC")
// or val f = SampleFragment.newInstance<SampleFragment>("ABC")

You can extend the parent init operation in child fragment class by:

fun newInstance(): ChildSampleFragment {
    val child = UserProfileFragment.newInstance<ChildSampleFragment>("XYZ")
    // Do anything with the current initialized args bundle here
    // with child.arguments = ....
    return child
}

Happy coding.


问:
How to iterate/foreach array in SwiftUI
I have this array of dictionaries.

```<code>let deckColors = [
    ["name": "blue", "desc": "desc1"],
    ["name": "yellow", "desc": "desc2"],
]
</code>```

And my view:

```<code>struct ContentView: View {
    var body: some View {
        ForEach(0 ..< deckColors.count) {value in
            Text(deckColors[value]["name"])
        }
    }
}
</code>```

How can I make it work? Currently getting this error: Protocol type Any cannot conform to StringProtocol because only concrete types can conform to protocols

答:
This works for me</p>

```<code>struct ContentView: View {
    let deckColors = [
        ["name": "blue", "desc": "desc1"],
        ["name": "yellow", "desc": "desc2"],
    ]

    var body: some View {
        ForEach(0 ..< deckColors.count, id: \.self) {value in
            Text(String(self.deckColors[value]["name"]!))
        }
    }
}
</code>```

Title: How to iterate/foreach array in SwiftUI

Body:
I have this array of dictionaries.

let deckColors = [
    ["name": "blue", "desc": "desc1"],
    ["name": "yellow", "desc": "desc2"],
]

And my view:

struct ContentView: View {
    var body: some View {
        ForEach(0 ..< deckColors.count) {value in
            Text(deckColors[value]["name"])
        }
    }
}

How can I make it work? Currently getting this error: Protocol type Any cannot conform to StringProtocol because only concrete types can conform to protocols

Body:
This works for me

struct ContentView: View {
    let deckColors = [
        ["name": "blue", "desc": "desc1"],
        ["name": "yellow", "desc": "desc2"],
    ]

    var body: some View {
        ForEach(0 ..< deckColors.count, id: \.self) {value in
            Text(String(self.deckColors[value]["name"]!))
        }
    }
}


问:
append string to each element in string array in typescript
How can I append a string to each element from a string array in typescript
I have an array like const original = ['a', 'b', 'c'] I want to make it as const original_string = ['i am key a', 'i am key b', 'i am key c'] how can I do that? maybe something like const original_string = original.map(() => ${'i am key'})?
I have following but it does not work

```<code>const original_string = original.forEach((item)=> (`i am key ${item}`));
</code>```

答:
```<code>const original = ['a', 'b', 'c'];
const original_string : any = [];

original.map((a) => {
  original_string.push("Key " + a);
});

console.log(original_string);
</code>```

Body:
How can I append a string to each element from a string array in typescript
I have an array like const original = ['a', 'b', 'c'] I want to make it as const original_string = ['i am key a', 'i am key b', 'i am key c'] how can I do that? maybe something like const original_string = original.map(() => ${'i am key'})?
I have following but it does not work

const original_string = original.forEach((item)=> (`i am key ${item}`));


问:
Check whether a string contains Japanese/Chinese characters
I need a way to check whether a string contains Japanese or Chinese text.

Currently I'm using this:

```<code>string.match(/[\u3400-\u9FBF]/);
</code>```

but it does not work with this for example: ディアボリックラヴァーズ or バッテリー.

Could you help me with that?

Thanks

答:
You can use this code and it's works for me.</p>

```<code>let str = "渣打銀行提供一系列迎合你生活需要嘅信用卡";
//let str = "SGGRAND DING HOUSE 4GRAND DING HOUSE";
const REGEX_CHINESE = /[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/;
const hasChinese = str.match(REGEX_CHINESE);
if(hasChinese){
  alert("Found");
}
else{
  alert("Not Found");
}
</code>```

Body:
I need a way to check whether a string contains Japanese or Chinese text.

Currently I'm using this:

string.match(/[\u3400-\u9FBF]/);

but it does not work with this for example: ディアボリックラヴァーズ or バッテリー.

Could you help me with that?

Thanks

Body:
You can use this code and it's works for me.

let str = "渣打銀行提供一系列迎合你生活需要嘅信用卡";
//let str = "SGGRAND DING HOUSE 4GRAND DING HOUSE";
const REGEX_CHINESE = /[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/;
const hasChinese = str.match(REGEX_CHINESE);
if(hasChinese){
  alert("Found");
}
else{
  alert("Not Found");
}


问:
IntelliJ Run Configuration Broken by an Incompatible Plugin I Can't Uninstall?
I had been developing an application on a trial version of IntelliJ 2016 Ultimate. Since the trial version ran out, I resumed work using the Community Edition. However, trying to launch my application yielded the following error:

```<code>Unknown run configuration type  #com.intellij.j2ee.web.tomcat.TomcatRunConfigurationFactory
</code>```

"No problem" I thought, just an incompatible plugin that was installed with Ultimate that I don't really need anyway. I opened the Plugins section of the Preferences menu, but I can't find the plugin in question. Below is a partial screenshot of the plugin list where I would expect to see the plugin listed in the error message.

The configuration can also not be edited from the Run/Debug Configurations menu, but lists the Run Configuration error as: "Broken configuration due to unavailable plugin or invalid configuration data."

Am I really unable to uninstall the Ultimate plugin preventing my run configuration from working from the Community Edition? What can I do to fix this if so?

答:
Simple upgrade Dart plugin..
Go to Settings/Plugins/Browse Repositories and search dart (Language) and upgrade

this will work.

Body:
I had been developing an application on a trial version of IntelliJ 2016 Ultimate. Since the trial version ran out, I resumed work using the Community Edition. However, trying to launch my application yielded the following error:

Unknown run configuration type  #com.intellij.j2ee.web.tomcat.TomcatRunConfigurationFactory

"No problem" I thought, just an incompatible plugin that was installed with Ultimate that I don't really need anyway. I opened the Plugins section of the Preferences menu, but I can't find the plugin in question. Below is a partial screenshot of the plugin list where I would expect to see the plugin listed in the error message.

The configuration can also not be edited from the Run/Debug Configurations menu, but lists the Run Configuration error as: "Broken configuration due to unavailable plugin or invalid configuration data."

Am I really unable to uninstall the Ultimate plugin preventing my run configuration from working from the Community Edition? What can I do to fix this if so?


问:
Why does this mongodb controller pass undefined back to route?
The app is using basic Node.js, Express, and MongoDB to return some data at different routes.

Route:

router.get('/api/v1/:collection', (req, res, next) => {
    try {
        const data = ApiController.getAllRecipes(req, res, next);
        console.log(data);
        res.send(data);
    } catch(error) {
        res.send(error);
    }
});
```

<p>The methods that query the database are contained within a simple controller:</p>

<pre class="lang-js prettyprint-override"><code>module.exports = {
    getAllRecipes: async (req, res, next) => {
        try {
            req.app.db.collection(req.params.collection).find({}).toArray((error, result) => {
                if (result.length > 0) {
                    console.log(result);
                    return result;
                } else {
                    let error = new Error();
                    error.statusCode = 404;
                    error.message = 'No API results found.';
                    next(error);
                }
            });
        } catch (error) {
            next(error);
        }
    }
};
</code>```

Inside the controller, the console.log(result); returns the correct data that I would like to be handled within the route file. However, the console.log(data); in the Route file returns undefined, even within the try/catch block.

Am I missing something in passing the data from the controller back to the route? Thank you :)

答:
Found a solution! Since the controller is asynchronous, it doesn't need to return data, but rather save it to res.locals and execute Express' next() method to continue with the route.

Updated Route:

router.get('/api/v:versionNumber/:collection', ApiController.getAllRecipes, (req, res, next) => {
    res.send(res.locals.results);
});

```

<p>Updated controller:</p>

<pre class="lang-js prettyprint-override"><code>getAllRecipes: async (req, res, next) => {
        try {
            req.app.db.collection(req.params.collection).find({}).toArray((error, result) => {
                if (result.length > 0) {
                    res.locals.results = result;
                    next();
                } else {
                    let error = new Error();
                    error.statusCode = 404;
                    error.message = 'No API results found.';
                    next(error);
                }
            });
        } catch (error) {
            next(error);
        }
    }
</code>```

Body:
The app is using basic Node.js, Express, and MongoDB to return some data at different routes.

Route:

router.get('/api/v1/:collection', (req, res, next) => {
    try {
        const data = ApiController.getAllRecipes(req, res, next);
        console.log(data);
        res.send(data);
    } catch(error) {
        res.send(error);
    }
});

The methods that query the database are contained within a simple controller:

module.exports = {
    getAllRecipes: async (req, res, next) => {
        try {
            req.app.db.collection(req.params.collection).find({}).toArray((error, result) => {
                if (result.length > 0) {
                    console.log(result);
                    return result;
                } else {
                    let error = new Error();
                    error.statusCode = 404;
                    error.message = 'No API results found.';
                    next(error);
                }
            });
        } catch (error) {
            next(error);
        }
    }
};

Inside the controller, the console.log(result); returns the correct data that I would like to be handled within the route file. However, the console.log(data); in the Route file returns undefined, even within the try/catch block.

Am I missing something in passing the data from the controller back to the route? Thank you :)

Body:
Found a solution! Since the controller is asynchronous, it doesn't need to return data, but rather save it to res.locals and execute Express' next() method to continue with the route.

Updated Route:

router.get('/api/v:versionNumber/:collection', ApiController.getAllRecipes, (req, res, next) => {
    res.send(res.locals.results);
});

Updated controller:

getAllRecipes: async (req, res, next) => {
        try {
            req.app.db.collection(req.params.collection).find({}).toArray((error, result) => {
                if (result.length > 0) {
                    res.locals.results = result;
                    next();
                } else {
                    let error = new Error();
                    error.statusCode = 404;
                    error.message = 'No API results found.';
                    next(error);
                }
            });
        } catch (error) {
            next(error);
        }
    }


问:
Devops deployment to D1 Shared Infrastructure app being ignored
I have a PHP Azure web app and I am deploying to it with a Dev Ops release. If is a D1 Shared Infrastructure app service plan.

I have done a build and a release that appear to work fine and everything looks successful. But the old site is still present and if I look at the files on the web app they are all dated for the previous release. So it's as though the release never happened and it disappeared into the void. I have restarted the site several times, to no avail. I have deployed the same build to other web apps and it works fine. All the app settings look the same as the sites where it does work.

I'm tempted to try scaling up at least temporarily to an S1. Not tried that yet, but is there another way?

答:
Firstly, please make sure you have really deployed the app to D1, just enable the variable system.debug (set the value to true), then trigger a new release to capture and check the complete logs.

Generally, it will update the changed files to the site. However you can also try to delete all the destination files before deploying. Just try the following things:

If you are using Azure App Service Deploy task to deploy it, then
you can enable the additional option to Remove Additional Files at Destination.

Besides, you can also try the extenion Azure WebApp Virtual File
System Tasks, it can delete files from Azure Web Apps through
KUDU Virtual File System Rest API (Put & Get coming soon)

If that still not work, then you can write a script to delete the
specific folder. But you need to make sure that the service account
has the correct permission to access and delete the folder on Azure.

Alternately you can Remove-Item with Specific Credential, below script for example:

```<code>Param(
  [string]$computerName = "computername",
  [string]$path ="E:\test\specific-folder"
)
$Username = "domain\user"
$Password = ConvertTo-SecureString "PasswordHere" -AsPlainText -Force

$cred = New-Object System.Management.Automation.PSCredential($Username,$password)

Invoke-Command -computername $computerName {Remove-Item -path $args[0] -Recurse} -cred $cred
</code>```

Body:
Firstly, please make sure you have really deployed the app to D1, just enable the variable system.debug (set the value to true), then trigger a new release to capture and check the complete logs.

Generally, it will update the changed files to the site. However you can also try to delete all the destination files before deploying. Just try the following things:

If you are using Azure App Service Deploy task to deploy it, then
you can enable the additional option to Remove Additional Files at Destination.

Besides, you can also try the extenion Azure WebApp Virtual File
System Tasks, it can delete files from Azure Web Apps through
KUDU Virtual File System Rest API (Put & Get coming soon)

If that still not work, then you can write a script to delete the
specific folder. But you need to make sure that the service account
has the correct permission to access and delete the folder on Azure.

Alternately you can Remove-Item with Specific Credential, below script for example:

Param(
  [string]$computerName = "computername",
  [string]$path ="E:\test\specific-folder"
)
$Username = "domain\user"
$Password = ConvertTo-SecureString "PasswordHere" -AsPlainText -Force

$cred = New-Object System.Management.Automation.PSCredential($Username,$password)

Invoke-Command -computername $computerName {Remove-Item -path $args[0] -Recurse} -cred $cred


问:
How to handle state using Redux with periodical updates and React Hooks?

My Use Case

I am just starting with React (Native) with Hooks and Redux and have some issues understanding some parts of the state update concept for my use case. I am currently working on a React Native App that should update data every full minute. So if the user enters the app at say 11h:31m:27s,

the initial state should be shown, then

a setTimeout handles the first update with the offset to reach the full minute (in this case 33s to reach 11h:32m:00s)

a setInterval handles the minutely update of the data from now on.

My Issue

Currently, with the below code the console.log("Reducer Fires!") inside the reducers.js file is fired increasingly more with every new minute (e.g. only once in the first minute, then two times in the second minute and so on). So I feel that I am still doing something wrong with how I handle the state of my data together with the setInterval() and setTimeout() logic. Could somebody review my code below and point me to the errors I am doing?

My Code (so far)

some dummy data:

```<code>export const DATA = [
    {"id": 1, "myAttr": 0},
    {"id": 2, "myAttr": 4},
    {"id": 3, "myAttr": 8},
    {"id": 4, "myAttr": 12},
]
</code>```

the App.js file with the redux store:

```<code>import React from 'react';
import { createStore, combineReducers } from "redux";
import { Provider } from "react-redux";
import { View } from 'react-native';

// Components
import MyComponent from "./components/MyComponent";
import dataReducer from "./store/reducers";

//Create Redux store
const rootReducer = combineReducers({
  mydata: dataReducer
});

const store = createStore(rootReducer);

export default function App() {

  return (
    <Provider store={store} >
      <View>
        <MyComponent />
      </View>
    </Provider>
  );
}
</code>```

the actions.js file storing my Redux action:

```<code>//Action to update the data
export const UPDATE_DATA = "UPDATE_DATA";

export const updateData = () => {
    return { type: UPDATE_DATA }
}
</code>```

the reducers.js file to store the reducers:

```<code>import { DATA } from "../data/data";
import { UPDATE_DATA } from "./actions";

// Initial state when app launches
const initState = {
    data: DATA
}

const dataReducer = (state = initState, action) => {
    switch (action.type) {
        case UPDATE_DATA:
            //Update an attribute in each object of the data array

            const updatedData = state.data.map((i) => {
                const newMyAttr = i.myAttr + 1;
                return { ...i, myAttr: newMyAttr }
            }
            )

            console.log("Reducer Fires!");
            return { ...state, data: updatedData }

        default:
            return state;
    }
};

export default dataReducer;
</code>```

the component where I am trying to update the state:

```<code>import React, { useEffect, useCallback } from "react";
import { useSelector, useDispatch } from "react-redux";
import { Text, View } from 'react-native';

const MyComponent = (props) => {
    const myData = useSelector(state => state.mydata.data);

    let start = new Date();
    const fullMinuteOffset = (60 - start.getSeconds()) * 1000;

    const dispatch = useDispatch();

    const saveData = useCallback(() => {
        dispatch(updateData())
    }, [dispatch]);

    useEffect(() => {
        const timer = setTimeout(() => {
            saveData()
            const interval = setInterval(() => {
                saveData()
            }, 60000)

            return () => clearInterval(interval);
        }, fullMinuteOffset);

        return () => clearTimeout(timer);
    }, [saveData, fullMinuteOffset]);

    return(
        <View>
            <Text>{myData[0].myAttr}</Text>
        </View>
    );
};

export default MyComponent;

</code>```

答:
Every time the component renders it will have a new value of fullOffserMinute and it's a dependency of useEffect thus registering a new interval call.

Here's a simplified working example of your code:

https://codesandbox.io/s/jolly-panini-k35s1?fontsize=14&hidenavigation=1&theme=dark

  // the relevant part of it
  let start = new Date();
  let [counter, setCounter] = useState(0);
  const fullMinuteOffset = (60 - start.getSeconds()) * 1000;

  function timerAction() {
    setCounter(counter => counter + 1);
  };

  useEffect(() => {
    console.log("-- use effect --");
    const timer = setTimeout(() => {
      console.log("save data timeout");
      timerAction();
      const interval = setInterval(() => {
        console.log("save data interval");
        timerAction();
      }, 5000);

      return () => clearInterval(interval);
    }, fullMinuteOffset);

    return () => clearTimeout(timer);
  }, []);
```

You should also read the answers here if you're going to update local state in intervals:
State not updating when using React state hook within setInterval

Body:
My Use Case

I am just starting with React (Native) with Hooks and Redux and have some issues understanding some parts of the state update concept for my use case. I am currently working on a React Native App that should update data every full minute. So if the user enters the app at say 11h:31m:27s,

the initial state should be shown, then

a setTimeout handles the first update with the offset to reach the full minute (in this case 33s to reach 11h:32m:00s)

a setInterval handles the minutely update of the data from now on.

My Issue

Currently, with the below code the console.log("Reducer Fires!") inside the reducers.js file is fired increasingly more with every new minute (e.g. only once in the first minute, then two times in the second minute and so on). So I feel that I am still doing something wrong with how I handle the state of my data together with the setInterval() and setTimeout() logic. Could somebody review my code below and point me to the errors I am doing?

My Code (so far)

some dummy data:

export const DATA = [
    {"id": 1, "myAttr": 0},
    {"id": 2, "myAttr": 4},
    {"id": 3, "myAttr": 8},
    {"id": 4, "myAttr": 12},
]

the App.js file with the redux store:

import React from 'react';
import { createStore, combineReducers } from "redux";
import { Provider } from "react-redux";
import { View } from 'react-native';

// Components
import MyComponent from "./components/MyComponent";
import dataReducer from "./store/reducers";

//Create Redux store
const rootReducer = combineReducers({
  mydata: dataReducer
});

const store = createStore(rootReducer);

export default function App() {

  return (
    <Provider store={store} >
      <View>
        <MyComponent />
      </View>
    </Provider>
  );
}

the actions.js file storing my Redux action:

//Action to update the data
export const UPDATE_DATA = "UPDATE_DATA";

export const updateData = () => {
    return { type: UPDATE_DATA }
}

the reducers.js file to store the reducers:

import { DATA } from "../data/data";
import { UPDATE_DATA } from "./actions";

// Initial state when app launches
const initState = {
    data: DATA
}

const dataReducer = (state = initState, action) => {
    switch (action.type) {
        case UPDATE_DATA:
            //Update an attribute in each object of the data array

            const updatedData = state.data.map((i) => {
                const newMyAttr = i.myAttr + 1;
                return { ...i, myAttr: newMyAttr }
            }
            )

            console.log("Reducer Fires!");
            return { ...state, data: updatedData }

        default:
            return state;
    }
};

export default dataReducer;

the component where I am trying to update the state:

import React, { useEffect, useCallback } from "react";
import { useSelector, useDispatch } from "react-redux";
import { Text, View } from 'react-native';

const MyComponent = (props) => {
    const myData = useSelector(state => state.mydata.data);

    let start = new Date();
    const fullMinuteOffset = (60 - start.getSeconds()) * 1000;

    const dispatch = useDispatch();

    const saveData = useCallback(() => {
        dispatch(updateData())
    }, [dispatch]);

    useEffect(() => {
        const timer = setTimeout(() => {
            saveData()
            const interval = setInterval(() => {
                saveData()
            }, 60000)

            return () => clearInterval(interval);
        }, fullMinuteOffset);

        return () => clearTimeout(timer);
    }, [saveData, fullMinuteOffset]);

    return(
        <View>
            <Text>{myData[0].myAttr}</Text>
        </View>
    );
};

export default MyComponent;

Body:
Every time the component renders it will have a new value of fullOffserMinute and it's a dependency of useEffect thus registering a new interval call.

Here's a simplified working example of your code:

https://codesandbox.io/s/jolly-panini-k35s1?fontsize=14&hidenavigation=1&theme=dark

  // the relevant part of it
  let start = new Date();
  let [counter, setCounter] = useState(0);
  const fullMinuteOffset = (60 - start.getSeconds()) * 1000;

  function timerAction() {
    setCounter(counter => counter + 1);
  };

  useEffect(() => {
    console.log("-- use effect --");
    const timer = setTimeout(() => {
      console.log("save data timeout");
      timerAction();
      const interval = setInterval(() => {
        console.log("save data interval");
        timerAction();
      }, 5000);

      return () => clearInterval(interval);
    }, fullMinuteOffset);

    return () => clearTimeout(timer);
  }, []);

You should also read the answers here if you're going to update local state in intervals:
State not updating when using React state hook within setInterval


问:
Get order ID from wc_get_order_item_meta
I am generating a QR code on woocmmerce my downloads page, By getting the Voucher code value stored and generate a token by calling the voucher value. At the end QR should represent URL+vouchercode+orderID. But i am unable to get the order id for that specific download. Any possible way to achieve that. Below my code</p>

```<code><?php
// include 'phpqrcode/qrlib.php';
$prefix = WOO_VOU_META_PREFIX;
$forc = 0;
         foreach ( $downloads as $download ) :

         $d=explode('&', $download['download_url']);

 $codes_item_meta = '';
  $querurl = '';

         $val =  str_replace('item_id=', '', $d[4]);
         $ks =   $d[3];
         $item = new WC_Order_Item_Product($val);

         $ib = 0;
         $cn  = substr($ks, -1)-1;
         $codes_item_meta = [];
         $cnn = [];
        for($i=0; $i<15; $i++){

            $codes_item_meta2    =  wc_get_order_item_meta($val , 'Voucher Code_'.$i , true);
            if($codes_item_meta2 != ""){
                $codes_item_meta[]   =  wc_get_order_item_meta($val , 'Voucher Code_'.$i , true);

                $cnn[]   =  $i;
            }

        }

    /*--------------------------------------Generate QR token END------------------------*/
        $tktest=wc_get_order_item_meta($val , 'Voucher Code_'.$forc , true);

        $order123 = new WC_Order( $order_id );

        $tk= getqrtoken($tktest) ;

        if($cnn[$cn]){
            $download['download_url'] .= '&df='.$cnn[$cn];

            $querurl = $url.wc_get_order_item_meta($val , 'Voucher Code_'.$cnn[$cn] , true);
        }else{
            $url2='www.example.com';
            $vouchercode=wc_get_order_item_meta($val , 'Voucher Code_'.$cnn[$cn] , true);
            $download['download_url'] .= '&df='.$forc;
            $querurl = $url2.$tk.{order_id};

        }
</code>```

答:
```<code>$order_id = wc_get_order_id_by_order_item_id($val);
</code>```

<p>above code worked inn my case, </p>

Body:
I am generating a QR code on woocmmerce my downloads page, By getting the Voucher code value stored and generate a token by calling the voucher value. At the end QR should represent URL+vouchercode+orderID. But i am unable to get the order id for that specific download. Any possible way to achieve that. Below my code

<?php
// include 'phpqrcode/qrlib.php';
$prefix = WOO_VOU_META_PREFIX;
$forc = 0;
         foreach ( $downloads as $download ) :

         $d=explode('&', $download['download_url']);

 $codes_item_meta = '';
  $querurl = '';

         $val =  str_replace('item_id=', '', $d[4]);
         $ks =   $d[3];
         $item = new WC_Order_Item_Product($val);

         $ib = 0;
         $cn  = substr($ks, -1)-1;
         $codes_item_meta = [];
         $cnn = [];
        for($i=0; $i<15; $i++){

            $codes_item_meta2    =  wc_get_order_item_meta($val , 'Voucher Code_'.$i , true);
            if($codes_item_meta2 != ""){
                $codes_item_meta[]   =  wc_get_order_item_meta($val , 'Voucher Code_'.$i , true);

                $cnn[]   =  $i;
            }

        }

    /*--------------------------------------Generate QR token END------------------------*/
        $tktest=wc_get_order_item_meta($val , 'Voucher Code_'.$forc , true);

        $order123 = new WC_Order( $order_id );

        $tk= getqrtoken($tktest) ;

        if($cnn[$cn]){
            $download['download_url'] .= '&df='.$cnn[$cn];

            $querurl = $url.wc_get_order_item_meta($val , 'Voucher Code_'.$cnn[$cn] , true);
        }else{
            $url2='www.example.com';
            $vouchercode=wc_get_order_item_meta($val , 'Voucher Code_'.$cnn[$cn] , true);
            $download['download_url'] .= '&df='.$forc;
            $querurl = $url2.$tk.{order_id};

        }

Body:
$order_id = wc_get_order_id_by_order_item_id($val);

above code worked inn my case,


问:
Reset AD user account password and email credentials to user
Task: I use the following code to import one column csv with user "samaccountname" and I use this one liner code -join (33..126|%{[char]$_}|Get-Random -Count 14) to generate a random password which is stored in the variable $newpwd followed by resetting the user password and outputting the password to host.

This works just find. However, I would like to send this new password to the AD Account email address. I have a working local smtp, and have written a simple Send-Mailmessage script for this purpose, however I just don't know how to add the "displayname, samaccountname, and new password" in the body of the message. Any help will be appreciated.

```<code>Import-Module ActiveDirectory
# Set the new password
$newpwd = -join (33..126|%{[char]$_}|Get-Random -Count 14)
$newPassword = ConvertTo-SecureString -AsPlainText "$newpwd" -Force
# Import users from CSV
Import-Csv "C:\Userlist.csv" | ForEach-Object {
$samAccountName = $_."samAccountName"

# Reset user password.
Set-ADAccountPassword -Identity $samAccountName -NewPassword $newPassword -Reset

# Force user to reset password at next logon.
Set-AdUser -Identity $samAccountName -ChangePasswordAtLogon $true
Write-Host "Your user account $samAccountName password has been update to: $newpwd"

}
# Output

Your user account jdoe password has been updated to: 9-5R_*&{/x%#Oh
</code>```

答:
Note / Warning: If you reset the password of a domain user, the user will no longer be able to sign in with the new password. Even if you send that password to the user after reset, the last known password that user is aware of will no longer function and prevent them from accessing their mailbox (even mobile).

When you run the command, Get-ADUser, it only gives you the basic information about the account without all the properties. Get-Member will give you basic properties that the Get-ADUser will return.

```<code>Get-ADUser <identity> | get-member
</code>```

Now, in order to get the properties that are not available by default, you can ask for these properties by using their names or using * to get ALL properties. For larger searches, this might take longer than expected. I would recommend only defining fields you need to retrieve. <Identity> is your sameaccountname

```<code>$user = Get-ADUser <identity> -Properties DisplayName, SamAccountName, Mail

# OR following command that will load up "every" property into $user.
$user = Get-ADUser <identity> -Properties *

$user | Set-ADAccountPassword -NewPassword $newPassword
$user | Set-ADUser -ChangePasswordAtLogon $True

Write-Output $user.DisplayName
Write-Output $user.SamAccountName
Write-Output $newpwd
</code>```

and to send an email,

```<code>Send-MailMessage -From administrator@company.com -To $user.Mail -Subject "Password was Reset" -Body "Your password was reset during routine updates. It was set to $newpwd" -SmtpServer xyz.company.com
</code>```

See Send-MailMessage

See Set-ADUser

See Get-ADUser

Body:
Task: I use the following code to import one column csv with user "samaccountname" and I use this one liner code -join (33..126|%{[char]$_}|Get-Random -Count 14) to generate a random password which is stored in the variable $newpwd followed by resetting the user password and outputting the password to host.

This works just find. However, I would like to send this new password to the AD Account email address. I have a working local smtp, and have written a simple Send-Mailmessage script for this purpose, however I just don't know how to add the "displayname, samaccountname, and new password" in the body of the message. Any help will be appreciated.

Import-Module ActiveDirectory
# Set the new password
$newpwd = -join (33..126|%{[char]$_}|Get-Random -Count 14)
$newPassword = ConvertTo-SecureString -AsPlainText "$newpwd" -Force
# Import users from CSV
Import-Csv "C:\Userlist.csv" | ForEach-Object {
$samAccountName = $_."samAccountName"

# Reset user password.
Set-ADAccountPassword -Identity $samAccountName -NewPassword $newPassword -Reset

# Force user to reset password at next logon.
Set-AdUser -Identity $samAccountName -ChangePasswordAtLogon $true
Write-Host "Your user account $samAccountName password has been update to: $newpwd"

}
# Output

Your user account jdoe password has been updated to: 9-5R_*&{/x%#Oh

Body:
Note / Warning: If you reset the password of a domain user, the user will no longer be able to sign in with the new password. Even if you send that password to the user after reset, the last known password that user is aware of will no longer function and prevent them from accessing their mailbox (even mobile).

When you run the command, Get-ADUser, it only gives you the basic information about the account without all the properties. Get-Member will give you basic properties that the Get-ADUser will return.

Get-ADUser <identity> | get-member

Now, in order to get the properties that are not available by default, you can ask for these properties by using their names or using * to get ALL properties. For larger searches, this might take longer than expected. I would recommend only defining fields you need to retrieve. <Identity> is your sameaccountname

$user = Get-ADUser <identity> -Properties DisplayName, SamAccountName, Mail

# OR following command that will load up "every" property into $user.
$user = Get-ADUser <identity> -Properties *

$user | Set-ADAccountPassword -NewPassword $newPassword
$user | Set-ADUser -ChangePasswordAtLogon $True

Write-Output $user.DisplayName
Write-Output $user.SamAccountName
Write-Output $newpwd

and to send an email,

Send-MailMessage -From administrator@company.com -To $user.Mail -Subject "Password was Reset" -Body "Your password was reset during routine updates. It was set to $newpwd" -SmtpServer xyz.company.com

See Send-MailMessage

See Set-ADUser

See Get-ADUser


问:
What is the output of the array / pointer in this c code
```<code>    #include <stdio.h>

    int main()
     {

     char*str="↔⬆12345";
     printf("%d",*str );
     return 0;
   }
</code>```

please help me to find the output of the given code

答:
Assuming the file is encoded using UTF-8, the string consists of these bytes in hex:

E2 86 94 E2 AC 86 F0 9F 99 82 31 32 33 34 35
```

On a system where char means unsigned char, the first char is 226.

On a two's-complement system where char means signed char, the first char is -30.

On a one's-complement system where char means signed char, the first char is -29.

This value will be promoted to an equivalent int, passed to printf, and printed.

Body:
    #include <stdio.h>

    int main()
     {

     char*str="↔⬆12345";
     printf("%d",*str );
     return 0;
   }

please help me to find the output of the given code

Body:
Assuming the file is encoded using UTF-8, the string consists of these bytes in hex:

E2 86 94 E2 AC 86 F0 9F 99 82 31 32 33 34 35

On a system where char means unsigned char, the first char is 226.

On a two's-complement system where char means signed char, the first char is -30.

On a one's-complement system where char means signed char, the first char is -29.

This value will be promoted to an equivalent int, passed to printf, and printed.


问:
Is anybody else getting errors when upgrading to com.google.android.material:material:1.1.0?
I was upgrading my material library in my Gradle file and suddenly I get this error.

```<code>\material-1.2.0-alpha04\res\values\values.xml:3360:5-3382:23: AAPT: error: duplicate value for resource 'attr/animationMode' with config ''.
</code>```

I have already changed all libraries to androidX. Is there somebody who faces the same problem?

答: Remove <attr>  of animationMode from attrs.xml then after rebuild project

Body:
I was upgrading my material library in my Gradle file and suddenly I get this error.

\material-1.2.0-alpha04\res\values\values.xml:3360:5-3382:23: AAPT: error: duplicate value for resource 'attr/animationMode' with config ''.

I have already changed all libraries to androidX. Is there somebody who faces the same problem?


问:
How to access ActiveStorage tempfile in Rails model?
I am trying to resize my images before uploading them with Rails' ActiveStorage. The following controller action works like a charm:

```<code>class CatsController < ApplicationController

  require 'mini_magick'

  def create
    @cat = current_user.cats.new(cat_params)

    params[:cat][:images].each do |image|
      mini_image = MiniMagick::Image.new(image.tempfile.path)
      mini_image.resize '1200x1200'
    end

    if @cat.save
      ...
    end
  end

end
</code>```

But I would like to keep my controllers skinny and move this functionality to the model. But when I do so, Rails can't find tempfile in the model.

Is there no way at all to access tempfile in the model?

Thanks for any help.

答:
Alternatively you can create a service

```<code># app/services/image_resizer.rb

class ImageResizer
  def self.call(images, size)
    Array(images).each do |image|
      i = MiniMagick::Image.new(image.tempfile.path)
      i.resize size
    end
  end
end
</code>```

```<code>def create
  @cat = current_user.cats.new(cat_params)
  ImageResizer.call(params[:cat][:images], '1200x1200')

  if @cat.save
    ...
  end
end
</code>```

Body:
I am trying to resize my images before uploading them with Rails' ActiveStorage. The following controller action works like a charm:

class CatsController < ApplicationController

  require 'mini_magick'

  def create
    @cat = current_user.cats.new(cat_params)

    params[:cat][:images].each do |image|
      mini_image = MiniMagick::Image.new(image.tempfile.path)
      mini_image.resize '1200x1200'
    end

    if @cat.save
      ...
    end
  end

end

But I would like to keep my controllers skinny and move this functionality to the model. But when I do so, Rails can't find tempfile in the model.

Is there no way at all to access tempfile in the model?

Thanks for any help.

Body:
Alternatively you can create a service

# app/services/image_resizer.rb

class ImageResizer
  def self.call(images, size)
    Array(images).each do |image|
      i = MiniMagick::Image.new(image.tempfile.path)
      i.resize size
    end
  end
end

def create
  @cat = current_user.cats.new(cat_params)
  ImageResizer.call(params[:cat][:images], '1200x1200')

  if @cat.save
    ...
  end
end


问:
Could not get any response azure storage table using API
I want to get data from azure storage table, I tried using below request:

```<code>https://<xxxx>.table.core.windows.net/testTable()
</code>```

But it returns below message:

```<code><error
xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<code>ResourceNotFound</code>
<message xml:lang="en-US">
The specified resource does not exist. RequestId:21b27073-d002-009d-3c4b-
e5d267000000 Time:2020-02-17T04:34:09.2754288Z
</message>
</error>
</code>```

答:
This is expected behavior. You're making an anonymous request to Azure Table Storage which is not allowed. All requests to Azure Tables must be authorized.

You can learn more about this here: https://learn.microsoft.com/en-us/rest/api/storageservices/authorize-requests-to-azure-storage.

Body:
I want to get data from azure storage table, I tried using below request:

https://<xxxx>.table.core.windows.net/testTable()

But it returns below message:

<error
xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
ResourceNotFound
<message xml:lang="en-US">
The specified resource does not exist. RequestId:21b27073-d002-009d-3c4b-
e5d267000000 Time:2020-02-17T04:34:09.2754288Z
</message>
</error>


问:
How to convert column into row with header sql

Note : i need the record like this

```<code>Scode value
BR     10
DL      7
</code>```

答:
```<code>You could also use CROSS APPLY with UNION ALL to convert the columns:

 select id, br,
 dl,
  ap
from yourtable
cross apply
(
  select 'br', Indicator1 union all
  select 'dl', Indicator2 union all
  select 'ap', Indicator3
) c (indicatorname, indicatorvalue);
</code>```

Body:
Note : i need the record like this

Scode value
BR     10
DL      7