问:
Django, browser display filename instead of the picture
I am missing some element to display picture  attatched with each post on a blog created with Django instead of picture file name.

Many solutions to this kind of a problem were:

```<code><img src="{{Object.picture.url}}"/>
</code>```

On template I have tried:

1

```<code><img src="{{ posts.title_picture.url }}"/>
</code>```

2

```<code><img src="{{title_picture.url}}"/>
</code>```

Which resulted respectively in displaying those on the browser:

1.

pictureforpost1.png

2.

img

model:

```<code>class Post(models.Model):
    title = models.CharField(max_length=255, blank=True, null=True)
    title_picture = models.FileField(blank=True,null=True)
</code>```

view:

```<code>class IndexView(ListView):
    model = Post
    context_object_name = 'posts'
</code>```

Seems like Django is finding the file. It is just not displaying the picture.

****Solution thanks to the below answers:****

changed

```<code>STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

to

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
</code>```

and added the following

```<code>urls.py

urlpatterns = [
   ...
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# when served with STATIC_URL and STATIC_ROOT instead it
# is not working so check difference in MEDIA and STATIC.

</code>```

In general I was lacking (and still do :) ) basic knowledge on uploads and displaying the static files.

Thanks.

答:
From the look of the code, you tried to get the image from a collection of Post rather than just one post.

Try to just display one of the post, if the syntax below doesn't work you can use the for loop to iterate through your collection.

```<code><img src="{{ posts.first.title_picture.url }}"/>
</code>```

Body:
I am missing some element to display picture  attatched with each post on a blog created with Django instead of picture file name.

Many solutions to this kind of a problem were:

On template I have tried:

1

2

Which resulted respectively in displaying those on the browser:

1.

pictureforpost1.png

2.

img

model:

class Post(models.Model):
    title = models.CharField(max_length=255, blank=True, null=True)
    title_picture = models.FileField(blank=True,null=True)

view:

class IndexView(ListView):
    model = Post
    context_object_name = 'posts'

Seems like Django is finding the file. It is just not displaying the picture.

****Solution thanks to the below answers:****

changed

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

to

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

and added the following

urls.py

urlpatterns = [
   ...
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# when served with STATIC_URL and STATIC_ROOT instead it
# is not working so check difference in MEDIA and STATIC.

In general I was lacking (and still do :) ) basic knowledge on uploads and displaying the static files.

Thanks.

Body:
From the look of the code, you tried to get the image from a collection of Post rather than just one post.

Try to just display one of the post, if the syntax below doesn't work you can use the for loop to iterate through your collection.

<img src="{{ posts.first.title_picture.url }}"/>


来源: stackexchange

问:
How to uninstall or remove configuration of a deployment pool or deployment agent
I am using Azure DevOps Server (TFS), and I register deployment pool agents in my test and production servers, now iIneed to uninstall or remove the configuration on my server and in my UI how can I do that there are a script to run or just delete the files or what could you please help me with that.</p>

答:
You need to do 2 things:

1) Go to the agent folder (where he installed) and run config.cmd with the flag remove. if you are in the agent folder run this in the command line:

```<code>./config remove
</code>```

2) Go to the Deployment Group (in the UI) and click on the ... near the group and then Delete (to delete all the group, if you want only the agents so go inside and do the same thing there).

ContentLicense: CC BY-SA 4.0

Body:
You need to do 2 things:

1) Go to the agent folder (where he installed) and run config.cmd with the flag remove. if you are in the agent folder run this in the command line:

./config remove

2) Go to the Deployment Group (in the UI) and click on the ... near the group and then Delete (to delete all the group, if you want only the agents so go inside and do the same thing there).


问:
Change an object passed by pointer to a function
I need:

Create reference to object.

Pass it to a function that calls the constructor of the object's class and make some calculation over the object.

Pass the object to another function that also make some stuff with it.

My object that goes to the second function is always empty.

I slightly know the difference between stack and heap memory and the use of new operator but can't handle with it. I don't understand why g doesn't change after the func1 is over.

```<code>#include <iostream>

class Grid
{
    public:
        int a;

        Grid()
        {
            a = 2;
        }
};

void func1(Grid * g);
void func2(Grid * g);

int
main ()
{
    Grid g;
    func1(&g);
    func2(&g);
}

void
func1 (Grid * g)
{
    g = new Grid();
    g->a = 5;
}

void
func2 (Grid * g)
{
    std::cout << g->a << std::endl;
}
</code>```

How make the output in the func2 5, cause now it's 2?

答:
In fact, when you use new, you change the value of the pointer.

But anyway, I think you can do it much more easier. For example:

```<code>void func(Grid & g)
{
    g.a = 5;
}
</code>```

EDIT:
Of course, you have to call func() like this:

```<code>Grid gr;
func(gr);
</code>```

I hope it can help;

Body:
I need:

Create reference to object.

Pass it to a function that calls the constructor of the object's class and make some calculation over the object.

Pass the object to another function that also make some stuff with it.

My object that goes to the second function is always empty.

I slightly know the difference between stack and heap memory and the use of new operator but can't handle with it. I don't understand why g doesn't change after the func1 is over.

#include <iostream>

class Grid
{
    public:
        int a;

        Grid()
        {
            a = 2;
        }
};

void func1(Grid * g);
void func2(Grid * g);

int
main ()
{
    Grid g;
    func1(&g);
    func2(&g);
}

void
func1 (Grid * g)
{
    g = new Grid();
    g->a = 5;
}

void
func2 (Grid * g)
{
    std::cout << g->a << std::endl;
}

How make the output in the func2 5, cause now it's 2?

Body:
In fact, when you use new, you change the value of the pointer.

But anyway, I think you can do it much more easier. For example:

void func(Grid & g)
{
    g.a = 5;
}

EDIT:
Of course, you have to call func() like this:

Grid gr;
func(gr);

I hope it can help;


问:
How to remove static string "DataSet" from Legends of Pie Chart for danielgindi/Charts ios?
I am using danielgindi/Charts for iOS/Swift. There is an extra Legend Entry with label "DataSet" displays in Pie Chart as seen in this image:

When I traced, I found there are two entries in the array of LegendEntry found in the PieChartView legend, i.e. PieChartView.legend.entries, where as I have only one object in my array.

Here is the code:

```<code>let dataSet = PieChartDataSet()
    dataSet.drawIconsEnabled = false
    dataSet.setColor(AppColors.selectedMenuItem)
    dataSet.sliceSpace = 3
    dataSet.iconsOffset = CGPoint(x: 0, y: 40)
    dataSet.selectionShift = 5

    var totalRevenuePer:Double = 0.0

    _ = arrRevenue.map({ (objRevenue) -> Void in
        if let percentage = Double(objRevenue.per ?? "0.0"), percentage != 0.0{
            dataSet.append(PieChartDataEntry(value: percentage, label: "\((objRevenue.rev_center_name ?? "") + " " + objRevenue.revenue.currencyString())"))
            totalRevenuePer += percentage
        }
    })

    var colors = AppColors.TenderColors
    if totalRevenuePer < 100{ colors.append(.clear) }
    dataSet.colors = colors

    let data = PieChartData(dataSet: dataSet)
    data.setValueFormatter(PercentageFormatter())
    data.setValueFont(NSUIFont.systemFont(ofSize: 11))
    data.setValueTextColor(.white)

    pieChart.data = data
    pieChart.highlightValue(nil)
    let legend = pieChart.legend
    legend.textColor = .white
    legend.entries.last?.label = ""

    pieChart.animate(yAxisDuration: 1.4, easingOption: .easeInOutQuad)

    // Refresh chart with new data
    pieChart.notifyDataSetChanged()
</code>```

Appreciate any help, thank you.

答:
It's a property of PieChartDataSet

The default value, if you don't set your own, is "DataSet"

```<code>let dataSet = PieChartDataSet()

// provide your own
dataSet.label = "My Label"

// or, no label
dataSet.label = ""
</code>```

Body:
I am using danielgindi/Charts for iOS/Swift. There is an extra Legend Entry with label "DataSet" displays in Pie Chart as seen in this image:

When I traced, I found there are two entries in the array of LegendEntry found in the PieChartView legend, i.e. PieChartView.legend.entries, where as I have only one object in my array.

Here is the code:

let dataSet = PieChartDataSet()
    dataSet.drawIconsEnabled = false
    dataSet.setColor(AppColors.selectedMenuItem)
    dataSet.sliceSpace = 3
    dataSet.iconsOffset = CGPoint(x: 0, y: 40)
    dataSet.selectionShift = 5

    var totalRevenuePer:Double = 0.0

    _ = arrRevenue.map({ (objRevenue) -> Void in
        if let percentage = Double(objRevenue.per ?? "0.0"), percentage != 0.0{
            dataSet.append(PieChartDataEntry(value: percentage, label: "\((objRevenue.rev_center_name ?? "") + " " + objRevenue.revenue.currencyString())"))
            totalRevenuePer += percentage
        }
    })

    var colors = AppColors.TenderColors
    if totalRevenuePer < 100{ colors.append(.clear) }
    dataSet.colors = colors

    let data = PieChartData(dataSet: dataSet)
    data.setValueFormatter(PercentageFormatter())
    data.setValueFont(NSUIFont.systemFont(ofSize: 11))
    data.setValueTextColor(.white)

    pieChart.data = data
    pieChart.highlightValue(nil)
    let legend = pieChart.legend
    legend.textColor = .white
    legend.entries.last?.label = ""

    pieChart.animate(yAxisDuration: 1.4, easingOption: .easeInOutQuad)

    // Refresh chart with new data
    pieChart.notifyDataSetChanged()

Appreciate any help, thank you.

Body:
It's a property of PieChartDataSet

The default value, if you don't set your own, is "DataSet"

let dataSet = PieChartDataSet()

// provide your own
dataSet.label = "My Label"

// or, no label
dataSet.label = ""


答:
To help you imagine this, I'm going to write it like this:

```<code>#include <iostream>

class Grid
{
    public:
        int a;

        Grid()
        {
            a = 2;
        }
};

void func1(uint64_t g);
void func2(uint64_t g);

int
main ()
{
    Grid g;
    func1((uint64_t)&g);
    func2((uint64_t)&g);
}

void
func1 (uint64_t g)
{
    g = (uint64_t)new Grid();
    ((Grid*)g)->a = 5;
}

void
func2 (uint64_t g)
{
    std::cout << ((Grid*)g)->a << std::endl;
}
</code>```

The code above will work exactly the same as the other code (on a 64-bit system). Obviously it is horrific and the code above should never be used, but writing it out like this might help you understand pointers.

Title: Change an object passed by pointer to a function

Body:
To help you imagine this, I'm going to write it like this:

#include <iostream>

class Grid
{
    public:
        int a;

        Grid()
        {
            a = 2;
        }
};

void func1(uint64_t g);
void func2(uint64_t g);

int
main ()
{
    Grid g;
    func1((uint64_t)&g);
    func2((uint64_t)&g);
}

void
func1 (uint64_t g)
{
    g = (uint64_t)new Grid();
    ((Grid*)g)->a = 5;
}

void
func2 (uint64_t g)
{
    std::cout << ((Grid*)g)->a << std::endl;
}

The code above will work exactly the same as the other code (on a 64-bit system). Obviously it is horrific and the code above should never be used, but writing it out like this might help you understand pointers.


问:
Stop audio loop (audioplayers package)
I'm new to flutter programming and I want to create an application, where I need an audio file to play/loop in the background. However it should stop, when double tapping on the screen.

The audio is saved in the assets folder. I am able to play it, but i don't know how to pause/stop it. I am using this package.

```<code>  @override
  Widget build(BuildContext context) {
    audioCache.play('rainsound.mp3', );
    return new Scaffold(
      child: new GestureDetector(
        onDoubleTap: () {
          //here I would like to stop the audio
          debugPrint('audio stopped');
        },
</code>```

答:
Update (audioplayers v1.0.1)

To Play:

```<code>final player = AudioPlayer();
</code>```

// Assuming you have the file in "assets/audio/my_audio.mp3"
player.play(AssetSource('audio/my_audio.mp3'));
```
<h4>To Stop:</h4>
<pre class="lang-dart prettyprint-override"><code>audioPlayer.stop();
</code>```

You will have to get the instance of AudioPlayer to stop the file, simply use await on play() to get the instance and using this, you can call stop(). This is the working code.

```<code>AudioCache cache; // you have this
AudioPlayer player; // create this

void _playFile() async{
  player = await cache.play('my_audio.mp3'); // assign player here
}

void _stopFile() {
  player?.stop(); // stop the file like this
}
</code>```

Title: Stop audio loop (audioplayers package)

Body:
I'm new to flutter programming and I want to create an application, where I need an audio file to play/loop in the background. However it should stop, when double tapping on the screen.

The audio is saved in the assets folder. I am able to play it, but i don't know how to pause/stop it. I am using this package.

  @override
  Widget build(BuildContext context) {
    audioCache.play('rainsound.mp3', );
    return new Scaffold(
      child: new GestureDetector(
        onDoubleTap: () {
          //here I would like to stop the audio
          debugPrint('audio stopped');
        },

Body:
Update (audioplayers v1.0.1)

To Play:

final player = AudioPlayer();

// Assuming you have the file in "assets/audio/my_audio.mp3"
player.play(AssetSource('audio/my_audio.mp3'));

To Stop:

audioPlayer.stop();

You will have to get the instance of AudioPlayer to stop the file, simply use await on play() to get the instance and using this, you can call stop(). This is the working code.

AudioCache cache; // you have this
AudioPlayer player; // create this

void _playFile() async{
  player = await cache.play('my_audio.mp3'); // assign player here
}

void _stopFile() {
  player?.stop(); // stop the file like this
}


问:
How to change top and bottom padding of text in MaterialDesign Overlined Textfield in iOS?
I'm trying to change padding top and padding bottom of text in material design text field.

I already try to apply shape and typography schemes but it had no effect.

This is my code:

// Outlet
@IBOutlet weak var nameTextField: MDCTextField!

// Implementation
nameTextField.placeholder = "Nome"
nameTextField.delegate = self
let nameTextFieldController = MDCTextInputControllerOutlined(textInput: nameTextField)
```

How can i change these spaces?

**** UPDATE ****

After change textRect by overiding MDCTextField i achieve following result. That is a a great advance. But how can i change the size of border to match text?

答:
If you can extend the MDCTextField class, then override this method:

```<code>        override func textRect(forBounds bounds: CGRect) -> CGRect {
         return bounds.inset(by: UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0))
        }
</code>```

Change top and bottom values as you wish.

If you cannot access/modify or extend the MDCTextField class, or if it already has its textRect(:forBounds) implementation, you can create your own UITextField class such as:

```<code>       class MyTextField: UITextField{
           ...
       }
</code>```

NOTE: You can even try to inherit MDCTextField class:

```<code>       class MyTextField: MDCTextField{
           ...
       }
</code>```

Body:
I'm trying to change padding top and padding bottom of text in material design text field.

I already try to apply shape and typography schemes but it had no effect.

This is my code:

// Outlet
@IBOutlet weak var nameTextField: MDCTextField!

// Implementation
nameTextField.placeholder = "Nome"
nameTextField.delegate = self
let nameTextFieldController = MDCTextInputControllerOutlined(textInput: nameTextField)

How can i change these spaces?

**** UPDATE ****

After change textRect by overiding MDCTextField i achieve following result. That is a a great advance. But how can i change the size of border to match text?

Body:
If you can extend the MDCTextField class, then override this method:

        override func textRect(forBounds bounds: CGRect) -> CGRect {
         return bounds.inset(by: UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0))
        }

Change top and bottom values as you wish.

If you cannot access/modify or extend the MDCTextField class, or if it already has its textRect(:forBounds) implementation, you can create your own UITextField class such as:

       class MyTextField: UITextField{
           ...
       }

NOTE: You can even try to inherit MDCTextField class:

       class MyTextField: MDCTextField{
           ...
       }


问:
SQLNative query returning empty results
I'm trying to execute a query which needs 4 tables :

```<code>    @Query(value="SELECT e.* FROM erreur e, synop sy, synop_decode sd, station st WHERE e.id_synop = sd.id_synop_decode "
            + "and sd.id_synop_decode = sy.id_synop" + " and DATE(sy.date)= :date and "
                    + "sy.id_station = st.id_station and st.id_station= :stationId", nativeQuery=true)
    public List<Erreur> recherche(@Param("date") Date date, @Param("stationId") Long stationId);
</code>```

This query works fine et native sql, i pass an existing stationId and  a date like the following :

```<code>SELECT e.* FROM erreur e, synop sy, synop_decode sd, station st WHERE e.id_synop = sd.id_synop_decode and sd.id_synop_decode = sy.id_synop
            and DATE(sy.date)= '2019-05-27' and sy.id_station = st.id_station and st.id_station= 60355;
</code>```

This query works fine in Mysql Workbench.

Here's the actual controller i'm using for testing purpose :

```<code>@GetMapping("/station/{stationId}/erreurs/today")
    public List<Erreur> getTodayErreurByStationId(@PathVariable Long stationId)
    {
        List<Erreur> erreurs = new ArrayList<Erreur>();
        Optional<Station> stationOptional = stationRepository.findById(stationId);
        if(stationOptional.isPresent())
        {
            return erreurRepository.recherche(new Date(), stationId);
        }
        return null;
    }
</code>```

The expected results are the actual "Ererur" objects in my array list, but RestClient just returns an empty array [], while the query works just fine in mysql like i described it above.

So my question is : How can i write this query into Hql language so that i can return the right entities. Or how can i map my sql results to my target custom calss "Erreur"?

```<code>@Entity
@Getter @Setter @NoArgsConstructor
@Table(name="erreur")
public class Erreur {

    public Erreur(int section, int groupe, String info) {
        this.section = section;
        this.groupe = groupe;
        this.info = info;
    }

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_erreur")
    private Long id;

    @ManyToOne(cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH},
    fetch=FetchType.LAZY)
    @JsonIgnore
    @JoinColumn(name="id_synop")
    private SynopDecode synopDecode;

    @OneToOne
    @JoinColumn(name="id_controle")
    private Controle controle;

    @ManyToOne(cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH},
            fetch=FetchType.LAZY)
    @JsonIgnore
    @JoinColumn(name="id_station")
    private Station station;

    @Column(name="section")
    private int section;

    @Column(name="groupe")
    private int groupe;

    @Column(name="info")
    private String info;
}
</code>```

答:
I figured a way to get the same results as my SQL Query using the @Query annotation and accessing object properties like this : </p>

```<code>    @Query("from Erreur e where e.synopDecode.synop.station.id = :stationId and "
            + "DATE(e.synopDecode.synop.date) = :date")
    public List<Erreur> recherche(@Param("date") Date date, @Param("stationId") Long stationId);
</code>```

<p>I think it solves my problem, thanks for the help </p>

Title: SQLNative query returning empty results

Body:
I'm trying to execute a query which needs 4 tables :

    @Query(value="SELECT e.* FROM erreur e, synop sy, synop_decode sd, station st WHERE e.id_synop = sd.id_synop_decode "
            + "and sd.id_synop_decode = sy.id_synop" + " and DATE(sy.date)= :date and "
                    + "sy.id_station = st.id_station and st.id_station= :stationId", nativeQuery=true)
    public List<Erreur> recherche(@Param("date") Date date, @Param("stationId") Long stationId);

This query works fine et native sql, i pass an existing stationId and  a date like the following :

SELECT e.* FROM erreur e, synop sy, synop_decode sd, station st WHERE e.id_synop = sd.id_synop_decode and sd.id_synop_decode = sy.id_synop
            and DATE(sy.date)= '2019-05-27' and sy.id_station = st.id_station and st.id_station= 60355;

This query works fine in Mysql Workbench.

Here's the actual controller i'm using for testing purpose :

@GetMapping("/station/{stationId}/erreurs/today")
    public List<Erreur> getTodayErreurByStationId(@PathVariable Long stationId)
    {
        List<Erreur> erreurs = new ArrayList<Erreur>();
        Optional<Station> stationOptional = stationRepository.findById(stationId);
        if(stationOptional.isPresent())
        {
            return erreurRepository.recherche(new Date(), stationId);
        }
        return null;
    }

The expected results are the actual "Ererur" objects in my array list, but RestClient just returns an empty array [], while the query works just fine in mysql like i described it above.

So my question is : How can i write this query into Hql language so that i can return the right entities. Or how can i map my sql results to my target custom calss "Erreur"?

@Entity
@Getter @Setter @NoArgsConstructor
@Table(name="erreur")
public class Erreur {

    public Erreur(int section, int groupe, String info) {
        this.section = section;
        this.groupe = groupe;
        this.info = info;
    }

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_erreur")
    private Long id;

    @ManyToOne(cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH},
    fetch=FetchType.LAZY)
    @JsonIgnore
    @JoinColumn(name="id_synop")
    private SynopDecode synopDecode;

    @OneToOne
    @JoinColumn(name="id_controle")
    private Controle controle;

    @ManyToOne(cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH},
            fetch=FetchType.LAZY)
    @JsonIgnore
    @JoinColumn(name="id_station")
    private Station station;

    @Column(name="section")
    private int section;

    @Column(name="groupe")
    private int groupe;

    @Column(name="info")
    private String info;
}

Body:
I figured a way to get the same results as my SQL Query using the @Query annotation and accessing object properties like this :

    @Query("from Erreur e where e.synopDecode.synop.station.id = :stationId and "
            + "DATE(e.synopDecode.synop.date) = :date")
    public List<Erreur> recherche(@Param("date") Date date, @Param("stationId") Long stationId);

I think it solves my problem, thanks for the help


问:
Permissions Error Exporting a table from Google BigQuery to Google Cloud Storage
Getting the following error as of 2017-07-08 when exporting a table to Cloud Storage.

Access Denied: BigQuery BigQuery: Permission denied while writing data

Working fine before that date, haven't changed anything in the project, big query or cloud storage.

JobId: alert-basis-89415:bquijob_6adfd86e_15d2de5ce1b

答:
Look up the service account's e-mail address, and add the account to the bucket ACL as a writer and file reader: </p>

```<code>gsutil acl ch -u blabla@project.iam.gserviceaccount.com:W gs://bucket
gsutil acl ch -u blabla@project.iam.gserviceaccount.com:R gs://bucket/1.csv
gsutil acl ch -u blabla@project.iam.gserviceaccount.com:R gs://bucket/2.csv
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Look up the service account's e-mail address, and add the account to the bucket ACL as a writer and file reader:

gsutil acl ch -u blabla@project.iam.gserviceaccount.com:W gs://bucket
gsutil acl ch -u blabla@project.iam.gserviceaccount.com:R gs://bucket/1.csv
gsutil acl ch -u blabla@project.iam.gserviceaccount.com:R gs://bucket/2.csv


问:
ModelMapper not ignoring null values
I want to do a partial update on one of my entities but if one propertie is null then the entity to be updated gets that value set to null too. I want that if a property from the source is null then to keep the one from the source.

I have tried this but no luck:

```<code>    @Bean
    public ModelMapper modelMapper() {
        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
        modelMapper.createTypeMap(String.class, Date.class);
        modelMapper.addConverter(new StringToDate());
        modelMapper.addConverter(new DateToString());
        return modelMapper;
    }
</code>```

Then I update my object like this:

```<code>    @Override
    public void editUser(final User user) {
        UserDocument userDocument = this.usersRepository.findByIdAndActivo(user.getId(), true)
                .orElseThrow(UserNotFoundException::new);

        userDocument = this.modelMapper.map(user, UserDocument.class);
        this.usersRepository.save(userDocument);
    }
</code>```

The user object has 1 property set at null while the object userDocument has it with a value, then when I save it in the database that value is gone (because it has transformed into null).

What can be wrong?

Thanks.

答:
Okay so that configuration isn't for the purpose I thought it was.

I've solved the issue by merging the updated object with the old one like this:

```<code>    @Override
    public void editUser(final User user) {
        UserDocument userDocument = this.usersRepository.findByIdAndActivo(user.getId(), true)
                .orElseThrow(UserNotFoundException::new);

        this.modelMapper.map(user, userDocument);
        this.usersRepository.save(userDocument);
    }
</code>```

Title: ModelMapper not ignoring null values

Body:
I want to do a partial update on one of my entities but if one propertie is null then the entity to be updated gets that value set to null too. I want that if a property from the source is null then to keep the one from the source.

I have tried this but no luck:

    @Bean
    public ModelMapper modelMapper() {
        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
        modelMapper.createTypeMap(String.class, Date.class);
        modelMapper.addConverter(new StringToDate());
        modelMapper.addConverter(new DateToString());
        return modelMapper;
    }

Then I update my object like this:

    @Override
    public void editUser(final User user) {
        UserDocument userDocument = this.usersRepository.findByIdAndActivo(user.getId(), true)
                .orElseThrow(UserNotFoundException::new);

        userDocument = this.modelMapper.map(user, UserDocument.class);
        this.usersRepository.save(userDocument);
    }

The user object has 1 property set at null while the object userDocument has it with a value, then when I save it in the database that value is gone (because it has transformed into null).

What can be wrong?

Thanks.

Body:
Okay so that configuration isn't for the purpose I thought it was.

I've solved the issue by merging the updated object with the old one like this:

    @Override
    public void editUser(final User user) {
        UserDocument userDocument = this.usersRepository.findByIdAndActivo(user.getId(), true)
                .orElseThrow(UserNotFoundException::new);

        this.modelMapper.map(user, userDocument);
        this.usersRepository.save(userDocument);
    }


问:
Protocol Buffers In C#: How Are Boxed Value Types Handled
In the following examples:

```<code>public class RowData
{
    public object[] Values;
}

public class FieldData
{
    public object Value;
}
</code>```

I am curious as how either protobuf-net or dotnet-protobufs would handle such classes.  I am more familiar with protobuf-net, so what I actually have is:

```<code>[ProtoContract]
public class RowData
{
    [ProtoMember(1)]
    public object[] Values;
}
[ProtoContract]
public class FieldData
{
    [ProtoMember(1)]
    public object Value;
}
</code>```

However I get an error saying "No suitable Default Object encoding found".  Is there an easy way to treat these classes, that I am just not aware of?

To elaborate more on the use case:

This is a scaled down version of a data class used in remoting.  So essentially it looks like this:

```<code>FieldData data = new FieldData();
data.Value = 8;

remoteObject.DoSomething(data);
</code>```

Note: I've omitted the ISerializable implementation for simplicity, but it is as you'd expect.

答:
Direct encapsulation seems to work fine with no additional overhead from all the properties, in the following manner:</p>

```<code>[ProtoContract, Serializable]
public class ObjectWrapper : ISerializable
{
    public ObjectWrapper()
    { }
    [ProtoIgnore]
    public object Value
    {
        get
        {
            if (Int32Value.HasValue)
                return Int32Value.Value;
            else if (BinaryValue != null)
                return BinaryValue;
            else
                return StringValue;
        }
        set
        {
            if (value is int)
                this.Int32Value = (int)value;
            else if (value is byte[])
                this.BinaryValue = (byte[])value;
            else if (value is string)
                this.StringValue = (string)value;
        }
    }
    [ProtoMember(1)]
    private int? Int32Value;
    [ProtoMember(2)]
    private string StringValue;
    [ProtoMember(3)]
    private byte[] BinaryValue;
            // etc

    #region ISerializable Members
    protected ObjectWrapper(SerializationInfo info, StreamingContext context)
    {
        Serializer.Merge<ObjectWrapper>(info, this);
    }
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        Serializer.Serialize<ObjectWrapper>(info, this);
    }

    #endregion
}
</code>```

OwnerDisplayName: Greg Dean

ContentLicense: CC BY-SA 2.5

Body:
In the following examples:

public class RowData
{
    public object[] Values;
}

public class FieldData
{
    public object Value;
}

I am curious as how either protobuf-net or dotnet-protobufs would handle such classes.  I am more familiar with protobuf-net, so what I actually have is:

[ProtoContract]
public class RowData
{
    [ProtoMember(1)]
    public object[] Values;
}
[ProtoContract]
public class FieldData
{
    [ProtoMember(1)]
    public object Value;
}

However I get an error saying "No suitable Default Object encoding found".  Is there an easy way to treat these classes, that I am just not aware of?

To elaborate more on the use case:

This is a scaled down version of a data class used in remoting.  So essentially it looks like this:

FieldData data = new FieldData();
data.Value = 8;

remoteObject.DoSomething(data);

Note: I've omitted the ISerializable implementation for simplicity, but it is as you'd expect.

LastEditorDisplayName: Greg Dean

Body:
Direct encapsulation seems to work fine with no additional overhead from all the properties, in the following manner:

[ProtoContract, Serializable]
public class ObjectWrapper : ISerializable
{
    public ObjectWrapper()
    { }
    [ProtoIgnore]
    public object Value
    {
        get
        {
            if (Int32Value.HasValue)
                return Int32Value.Value;
            else if (BinaryValue != null)
                return BinaryValue;
            else
                return StringValue;
        }
        set
        {
            if (value is int)
                this.Int32Value = (int)value;
            else if (value is byte[])
                this.BinaryValue = (byte[])value;
            else if (value is string)
                this.StringValue = (string)value;
        }
    }
    [ProtoMember(1)]
    private int? Int32Value;
    [ProtoMember(2)]
    private string StringValue;
    [ProtoMember(3)]
    private byte[] BinaryValue;
            // etc

    #region ISerializable Members
    protected ObjectWrapper(SerializationInfo info, StreamingContext context)
    {
        Serializer.Merge<ObjectWrapper>(info, this);
    }
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        Serializer.Serialize<ObjectWrapper>(info, this);
    }

    #endregion
}


问:
Haskell caught directory not exist but not empty value
With the LambdaCase I am able to filter out if a dir does not exist. However: if a user is prompted and hits enter (empty) I still get an exception.
I think Maybe or Either can help me here, but I have a hard time figuring out how to set this up.

```<code>    {-# LANGUAGE LambdaCase #-}

    import System.Directory
    import System.IO

    dirExist = do
      a <- prompt "Directory:> "
      doesDirectoryExist a >>= \case
        True -> getDirContent a
        _ -> putStrLn "Directory does not exist or invalid value specified."

getDirContent :: FilePath -> IO ()
getDirContent dir = do
  result <- getDirectoryContents dir
  mapM_ putStrLn $ result

    prompt :: String -> IO String
    prompt x = do
      putStr x
      a <- getLine
      return a
</code>```

答:
The problem is that doesDirectoryExist "" returns True, but whatever is in your getDirContent function (which you'll need to post if you want a more detailed answer) doesn't work when passed "".

There's no need for Maybe or Either to fix it. Just wrap the block in an if construct, and put something like putStrLn "You must enter a directory name" in the else.

Body:
With the LambdaCase I am able to filter out if a dir does not exist. However: if a user is prompted and hits enter (empty) I still get an exception.
I think Maybe or Either can help me here, but I have a hard time figuring out how to set this up.

    {-# LANGUAGE LambdaCase #-}

    import System.Directory
    import System.IO

    dirExist = do
      a <- prompt "Directory:> "
      doesDirectoryExist a >>= \case
        True -> getDirContent a
        _ -> putStrLn "Directory does not exist or invalid value specified."

getDirContent :: FilePath -> IO ()
getDirContent dir = do
  result <- getDirectoryContents dir
  mapM_ putStrLn $ result

    prompt :: String -> IO String
    prompt x = do
      putStr x
      a <- getLine
      return a


问:
Maven is ignoring Cucumber tests
I'm trying to run two cucumber feature files by Maven but nothing happens. I'm using the Dutch (NL) version of Gherkin. When I'm running the feature files directly in Eclipse or with Gradle they are running fine. I studied all earlier questions about this issue on Stackoverflow but still couldn't find a solution.

This is my project structure in Eclipse:
Eclipse project structure

The result of running the project with Maven using the command mvn Test is:

```<code>Running nl.werkwel.cucumber.RunTest
Configuring TestNG with: org.apache.maven.surefire.testng.conf.TestNG652Configurator@f5c0729
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.341 sec

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

[INFO] BUILD SUCCESS
</code>```

I also tried to run with:
"mvn test -Dcucumber.options="src/test/resources/registratiepage.feature"
but the result was the same

This is the POM

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

  <groupId>nl.werkwel</groupId>
  <artifactId>cucumber</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

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

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

  <dependencies>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>1.2.4</version>
    </dependency>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.8.8</version>

    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.53.0</version>
    </dependency>

    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.7</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>1.2.4</version>
    </dependency>

  </dependencies>

</project>
</code>```

And here is one of the feature files:

```<code># language: nl
Functionaliteit: Testen van de Registratiepagina

  Achtergrond:
      Gegeven Gebruiker is op de registratiepagina

  Scenario: Niet succesvolle registratie, emailadres niet gevuld
    Als Gebruiker geen emailadres invult
    En Klikt op de button nu registreren
    Dan wordt de melding "Voer een waarde in" getoond

    Scenario: Link Algeregistreerd
    Als Gebruiker op link algeregistreerd klikt
    Dan gaat gebruiker verder naar het inlogscherm

  Scenario: Link Annuleren
    Als Gebruiker op link annuleren klikt
    Dan gaat gebruiker verder naar het inlogscherm
</code>```

The Runner Class

```<code>package nl.werkwel.cucumber;

import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(

        plugin = {"pretty", "html:out"},
        features={"."}

        )

public class RunTest {

}
</code>```

答: Yup the runner or main class name should end with Test, </p>

Title: Maven is ignoring Cucumber tests

Body:
I'm trying to run two cucumber feature files by Maven but nothing happens. I'm using the Dutch (NL) version of Gherkin. When I'm running the feature files directly in Eclipse or with Gradle they are running fine. I studied all earlier questions about this issue on Stackoverflow but still couldn't find a solution.

This is my project structure in Eclipse:
Eclipse project structure

The result of running the project with Maven using the command mvn Test is:

Running nl.werkwel.cucumber.RunTest
Configuring TestNG with: org.apache.maven.surefire.testng.conf.TestNG652Configurator@f5c0729
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.341 sec

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

[INFO] BUILD SUCCESS

I also tried to run with:
"mvn test -Dcucumber.options="src/test/resources/registratiepage.feature"
but the result was the same

This is the POM

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

  <groupId>nl.werkwel</groupId>
  <artifactId>cucumber</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

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

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

  <dependencies>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>1.2.4</version>
    </dependency>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.8.8</version>

    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.53.0</version>
    </dependency>

    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.7</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>1.2.4</version>
    </dependency>

  </dependencies>

</project>

And here is one of the feature files:

# language: nl
Functionaliteit: Testen van de Registratiepagina

  Achtergrond:
      Gegeven Gebruiker is op de registratiepagina

  Scenario: Niet succesvolle registratie, emailadres niet gevuld
    Als Gebruiker geen emailadres invult
    En Klikt op de button nu registreren
    Dan wordt de melding "Voer een waarde in" getoond

    Scenario: Link Algeregistreerd
    Als Gebruiker op link algeregistreerd klikt
    Dan gaat gebruiker verder naar het inlogscherm

  Scenario: Link Annuleren
    Als Gebruiker op link annuleren klikt
    Dan gaat gebruiker verder naar het inlogscherm

The Runner Class

package nl.werkwel.cucumber;

import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(

        plugin = {"pretty", "html:out"},
        features={"."}

        )

public class RunTest {

}


问:
Unable to run angular application
I installed node and npm in my local and @angular cli v6.1.1. and created application name with ANGULAR6. then try to run the application but i'm getting error.</p>

```<code>PS C:\Users\762739\Desktop\Local _test_Files\Angular\ANGULAR6> ng serve
** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
       10% building modules 6/6 modules 0 activei ｢wds｣: Project is running at http://localhost:4200/
i ｢wds｣: webpack output is served from /
i ｢wds｣: Content not from webpack is served from C:\Users\762739\Desktop\Local _test_Files\Angular\ANGULAR6
i ｢wds｣: 404s will fallback to //index.html
Date: 2019-05-29T12:03:00.535Z
Hash: 39bd7e13701cafb5c814
Time: 2887ms
chunk {main} main.js, main.js.map (main) 344 kB [entry] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 344 kB [entry] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 5.22 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 359 kB [entry] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 10.2 kB [initial] [rendered]

ERROR in node_modules/rxjs/internal/types.d.ts(81,44): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(81,74): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(81,77): error TS1109: Expression expected.
node_modules/rxjs/internal/types.d.ts(82,52): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(82,88): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(82,92): error TS1109: Expression expected.
</code>```

答:
There are two solutions:

1- Update your TS version: TS ^2.8
You can update the Typescript by changing the version of Typescript in the package.json from your xx version to "typescript": "~2.8"

2- Use the following version:

```<code>npm install rxjs@6.0.0 --save
</code>```

Title: Unable to run angular application

Body:
I installed node and npm in my local and @angular cli v6.1.1. and created application name with ANGULAR6. then try to run the application but i'm getting error.

PS C:\Users\762739\Desktop\Local _test_Files\Angular\ANGULAR6> ng serve
** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
       10% building modules 6/6 modules 0 activei ｢wds｣: Project is running at http://localhost:4200/
i ｢wds｣: webpack output is served from /
i ｢wds｣: Content not from webpack is served from C:\Users\762739\Desktop\Local _test_Files\Angular\ANGULAR6
i ｢wds｣: 404s will fallback to //index.html
Date: 2019-05-29T12:03:00.535Z
Hash: 39bd7e13701cafb5c814
Time: 2887ms
chunk {main} main.js, main.js.map (main) 344 kB [entry] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 344 kB [entry] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 5.22 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 359 kB [entry] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 10.2 kB [initial] [rendered]

ERROR in node_modules/rxjs/internal/types.d.ts(81,44): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(81,74): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(81,77): error TS1109: Expression expected.
node_modules/rxjs/internal/types.d.ts(82,52): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(82,88): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(82,92): error TS1109: Expression expected.

Body:
There are two solutions:

1- Update your TS version: TS ^2.8
You can update the Typescript by changing the version of Typescript in the package.json from your xx version to "typescript": "~2.8"

2- Use the following version:

npm install rxjs@6.0.0 --save


问:
Values in one column based on condition in another column
I have a dataframe:

```<code>Data = {'group':  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
        'value1': [2, 0, 0, 5, 5, 5, 6, 31, 7, 5, 0, 99],
        'value2': [25, 12 ,15, 11, 36, 3, 65, 6, 89, 8, 74, 5]
        }

current_result = pd.DataFrame(Data, columns = ['group','value1', 'value2'])
</code>```

I want to set value2 to zero if corresponding value1 is equal to zero while keeping all other values the same. So my desired result would be:

```<code>Data = {'group':  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
        'value1': [2, 0, 0, 5, 5, 5, 6, 31, 7, 5, 0, 99],
        'value2': [25, 0 ,0, 11, 36, 3, 65, 6, 89, 8, 0, 5]
        }

current_result = pd.DataFrame(Data, columns = ['group','value1', 'value2'])
</code>```

How could I do this?

答:
```<code>def change_value(row):
    if row.value1 == 0:
        row.value2 = 0
    return row

current_result = current_result.apply(change_value, axis=1)
</code>```

Body:
I have a dataframe:

Data = {'group':  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
        'value1': [2, 0, 0, 5, 5, 5, 6, 31, 7, 5, 0, 99],
        'value2': [25, 12 ,15, 11, 36, 3, 65, 6, 89, 8, 74, 5]
        }

current_result = pd.DataFrame(Data, columns = ['group','value1', 'value2'])

I want to set value2 to zero if corresponding value1 is equal to zero while keeping all other values the same. So my desired result would be:

Data = {'group':  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
        'value1': [2, 0, 0, 5, 5, 5, 6, 31, 7, 5, 0, 99],
        'value2': [25, 0 ,0, 11, 36, 3, 65, 6, 89, 8, 0, 5]
        }

current_result = pd.DataFrame(Data, columns = ['group','value1', 'value2'])

How could I do this?


问:
iOS - forward all touches through a view
I have a view overlayed on top of many other views. I am only using the overaly to detect some number of touches on the screen, but other than that I don't want the view to stop the behavior of other views underneath, which are scrollviews, etc. How can I forward all the touches through this overlay view? It is a subclass of UIView.</p>

答:
In Swift 5</p>

```<code>class ThroughView: UIView {
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        guard let slideView = subviews.first else {
            return false
        }

        return slideView.hitTest(convert(point, to: slideView), with: event) != nil
    }
}
</code>```

Body:
In Swift 5

class ThroughView: UIView {
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        guard let slideView = subviews.first else {
            return false
        }

        return slideView.hitTest(convert(point, to: slideView), with: event) != nil
    }
}


问:
why my second image is not moving or animating
i am trying to animate 2 images:
1.from bottom left to top right.
other from bottom right to top left.
image 1 is moving while the other is not...

1 image is moving (the image from bottom left to top right), the other is still not moving
when i run the code of still image in saprate html filr it runs fine...

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html><body>
    <div class="move_to_right">
      <!--<img id="move" src="https://pngimage.net/wp-content/uploads/2018/05/f16-png-6.png" style="width:150px; height:150px;">-->
      <img id="move_to_right" src="f16.png" style="width:150px; height:150px;">
    </div>
<div class="move_to_left">
      <!--<img id="move" src="https://pngimage.net/wp-content/uploads/2018/05/f16-png-6.png" style="width:150px; height:150px;">-->
      <img id="move_to_left" src="f162.png" style="width:150px; height:150px;">
    </div>
</body></html></code>```

答:
Some issues:

you didn't close the @keyframes opening curly brace

both your keyframes had the same name examples

html {
  height: 100%
}

body {
  height: 100%;
  width: 100%;
  margin: 0;
  background-repeat: no-repeat;
  background-image: radial-gradient(black, white);
}

div.move_to_right {
  width: auto;
  height: auto;
  position: absolute;
  left: 200px;
}

.move_to_right {
  position: absolute;
  left: 200px;
}

#move_to_right {
  width: 150px;
  height: 150px;
  position: relative;
  -webkit-animation-name: move_to_right;
  -webkit-animation-duration: 10s;
  animation-name: move_to_right;
  animation-duration: 3s;
  animation-iteration-count: infinite;
}

@keyframes move_to_right {
  0% {
    opacity: 0.5;
    transform: translate(-200px, 150px);
  }
  100% {
    opacity: 1;
    transform: translate(0px, 0px);
  }
}

div.move_to_left {
  width: auto;
  height: auto;
  position: absolute;
  left: 200px;
}

.move_to_left {
  position: absolute;
  right: 200px;
}

#move_to_left {
  width: 150px;
  height: 150px;
  position: relative;
  -webkit-animation-name: move_to_left;
  -webkit-animation-duration: 10s;
  animation-name: move_to_left;
  animation-duration: 3s;
  animation-iteration-count: infinite;
}

@keyframes move_to_left {
  0% {
    opacity: 0.5;
    transform: translate(200px, 150px);
  }
  100% {
    opacity: 1;
    transform: translate(0px, 0px);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="move_to_right">
  <img id="move_to_right" src="https://pngimage.net/wp-content/uploads/2018/05/f16-png-6.png" style="width:150px; height:150px;">
</div>
<div class="move_to_left">
  <img id="move_to_left" src="https://pngimage.net/wp-content/uploads/2018/05/f16-png-6.png" style="width:150px; height:150px;">
</div></code>```

Body:
Some issues:

you didn't close the @keyframes opening curly brace

both your keyframes had the same name examples

html {
  height: 100%
}

body {
  height: 100%;
  width: 100%;
  margin: 0;
  background-repeat: no-repeat;
  background-image: radial-gradient(black, white);
}

div.move_to_right {
  width: auto;
  height: auto;
  position: absolute;
  left: 200px;
}

.move_to_right {
  position: absolute;
  left: 200px;
}

#move_to_right {
  width: 150px;
  height: 150px;
  position: relative;
  -webkit-animation-name: move_to_right;
  -webkit-animation-duration: 10s;
  animation-name: move_to_right;
  animation-duration: 3s;
  animation-iteration-count: infinite;
}

@keyframes move_to_right {
  0% {
    opacity: 0.5;
    transform: translate(-200px, 150px);
  }
  100% {
    opacity: 1;
    transform: translate(0px, 0px);
  }
}

div.move_to_left {
  width: auto;
  height: auto;
  position: absolute;
  left: 200px;
}

.move_to_left {
  position: absolute;
  right: 200px;
}

#move_to_left {
  width: 150px;
  height: 150px;
  position: relative;
  -webkit-animation-name: move_to_left;
  -webkit-animation-duration: 10s;
  animation-name: move_to_left;
  animation-duration: 3s;
  animation-iteration-count: infinite;
}

@keyframes move_to_left {
  0% {
    opacity: 0.5;
    transform: translate(200px, 150px);
  }
  100% {
    opacity: 1;
    transform: translate(0px, 0px);
  }
}

<div class="move_to_right">
  <img id="move_to_right" src="https://pngimage.net/wp-content/uploads/2018/05/f16-png-6.png" style="width:150px; height:150px;">
</div>
<div class="move_to_left">
  <img id="move_to_left" src="https://pngimage.net/wp-content/uploads/2018/05/f16-png-6.png" style="width:150px; height:150px;">
</div>


问:
Highchart loading animation not working when giving 'verticalAlign' for 'setTitle'
I am building a pie chart with highchart. I need to set custom title for my pie chart. And I need to align it to the center of the pie chart. Everything works fine except the initial circle loading animation of pie chart. If I remove

```<code>verticalAlign: 'middle',
</code>```

It will work. The problem is only in highchart v7.1.1 . This animation is working fine in Highchart v7.0.3.

This is my codepen link.

Can any one please help me to fix it?

答:
Reported issue: https://github.com/highcharts/highcharts/issues/10835

To workaround enable floating in title configuration object:

```<code>title: {
    floating: true
},
</code>```

Live demo: http://jsfiddle.net/BlackLabel/9nywd2mx/

API Reference: https://api.highcharts.com/highstock/title.floating

Body:
I am building a pie chart with highchart. I need to set custom title for my pie chart. And I need to align it to the center of the pie chart. Everything works fine except the initial circle loading animation of pie chart. If I remove

verticalAlign: 'middle',

It will work. The problem is only in highchart v7.1.1 . This animation is working fine in Highchart v7.0.3.

This is my codepen link.

Can any one please help me to fix it?

Body:
Reported issue: https://github.com/highcharts/highcharts/issues/10835

To workaround enable floating in title configuration object:

title: {
    floating: true
},

Live demo: http://jsfiddle.net/BlackLabel/9nywd2mx/

API Reference: https://api.highcharts.com/highstock/title.floating


问:
Android Keyevent injection requires system permissions
hi i am using key event injection using window manager
but when i tested this application it gives me error

```<code>  04-12 18:19:35.794: WARN/WindowManager(58): Permission denied: injecting key event
  from pid 6290 uid 10039 to window Window{45034880
   com.android.launcher/com.android.launcher2.Launcher paused=false} owned by uid 10020

   04-12 18:19:35.794: WARN/System.err(6290): java.lang.SecurityException: Injecting to
    another application requires INJECT_EVENTS permission

 04-12 18:19:35.854: DEBUG/PhoneData(6290):

  04-12 18:19:36.048: WARN/System.err(6290):     at
 android.os.Parcel.readException(Parcel.java:1247)

  04-12 18:19:36.048: WARN/System.err(6290):     at
  android.os.Parcel.readException(Parcel.java:1235)
</code>```

I also give the inject event permission
is there any way to give a application system permissions.

答:
Normally, you can't do this, for obvious security reasons. However, if this is for test purposes, you might find the Activity Testing documentation useful.

Hope this helps.

Body:
hi i am using key event injection using window manager
but when i tested this application it gives me error

  04-12 18:19:35.794: WARN/WindowManager(58): Permission denied: injecting key event
  from pid 6290 uid 10039 to window Window{45034880
   com.android.launcher/com.android.launcher2.Launcher paused=false} owned by uid 10020

   04-12 18:19:35.794: WARN/System.err(6290): java.lang.SecurityException: Injecting to
    another application requires INJECT_EVENTS permission

 04-12 18:19:35.854: DEBUG/PhoneData(6290):

  04-12 18:19:36.048: WARN/System.err(6290):     at
 android.os.Parcel.readException(Parcel.java:1247)

  04-12 18:19:36.048: WARN/System.err(6290):     at
  android.os.Parcel.readException(Parcel.java:1235)

I also give the inject event permission
is there any way to give a application system permissions.


问:
When does image.setImageResource() set the image resource inside a function?
Goal: To click on an image in an app and get it to fade out to make a different image appear.

My Method: To make the 1st image fade away after 2000ms and AFTER THAT change the image resource of the 1st image to the 2nd image to make the 2nd image appear

I have a correct solution which was provided by my instructor, so I dont want any correct solution for this. What i want to know is why is my solution not working, i.e why is setImageResource() setting the Image1 to Image 2 at the beginning despite calling it at the end

This is the fade function i have created which the image1 goes to when it is clicked

public void fade(View view){

```<code>    ImageView image1 = findViewById(R.id.image1);
    image1.animate().alpha(0f).setDuration(2000);

    image1.setImageResource(R.drawable.cat2);
}
</code>```

Actual Output: Image 1 changes to Image 2 as soon as I click it and then Image 2 fades away

Problem: Inspite of calling setImageResource() at the end of the code, it actually sets the image resource at the beginning

答:
The animation is asynchronous in your code - it doesn't block/wait, but starts the animation (or rather, queues the animation to be started) and then immediately executes the next line, which sets the image. If you want to update your image once the animation is complete, you can use withEndAction and supply a callback.

```<code>image1.animate()
    .alpha(0f)
    .setDuration(2000)
    .withEndAction(new Runnable() {
      @Override
      public void run() {
        image1.setImageResource(R.drawable.cat2);
      }
    })
    .start();
</code>```

Body:
Goal: To click on an image in an app and get it to fade out to make a different image appear.

My Method: To make the 1st image fade away after 2000ms and AFTER THAT change the image resource of the 1st image to the 2nd image to make the 2nd image appear

I have a correct solution which was provided by my instructor, so I dont want any correct solution for this. What i want to know is why is my solution not working, i.e why is setImageResource() setting the Image1 to Image 2 at the beginning despite calling it at the end

This is the fade function i have created which the image1 goes to when it is clicked

public void fade(View view){

    ImageView image1 = findViewById(R.id.image1);
    image1.animate().alpha(0f).setDuration(2000);

    image1.setImageResource(R.drawable.cat2);
}

Actual Output: Image 1 changes to Image 2 as soon as I click it and then Image 2 fades away

Problem: Inspite of calling setImageResource() at the end of the code, it actually sets the image resource at the beginning

Body:
The animation is asynchronous in your code - it doesn't block/wait, but starts the animation (or rather, queues the animation to be started) and then immediately executes the next line, which sets the image. If you want to update your image once the animation is complete, you can use withEndAction and supply a callback.

image1.animate()
    .alpha(0f)
    .setDuration(2000)
    .withEndAction(new Runnable() {
      @Override
      public void run() {
        image1.setImageResource(R.drawable.cat2);
      }
    })
    .start();


问:
How to use template literals queried from database or variable?
I have HTML e-mail templates stored in a MySQL database. Most of them include JavaScript variables. I tried to store them using template literals (i.e.: ${this.auth.user.name}) but this will not return the variable but the exact string. I assume my problem is because the string is encapsulated by double quotes or single quotes and not back-ticks.

So my JavaScript looks the following, where template is an array of objects queried from my MySQL show here.

var email_template: this.template[0].body;

The actual output is Hello ${this.auth.name}!

I expect the output of Hello Jack!

Do you have any ideas what could be the problem?

Thanks in advance,
Tibor

答:
Try making a new Function like so:

const name = "Jack";
const string = "Hello ${name}";
const actualString = new Function("return `" + string + "`").call(string);
console.log(actualString);```


问:
Undefined function with javascripts
I'm writing a small 'quote calculator'. I want to print the summary to the browser with innerHTML, but I'm still getting "undefined" instead of the price. But in my console.log everything works fine, I can console.log the variable price and get the expected result.

//Variables

const form = document.getElementById('request-quote');
const html = new HTMLUI();

//Event Listeners

eventListeners();

function eventListeners() {
  document.addEventListener('DOMContentLoaded', function() {
    //Create the <option> for the years
    html.displayYears();
  });
  //when the form is submitted

  form.addEventListener('submit', function(e) {
    e.preventDefault();

    //get values from the form
    const make = document.getElementById('make').value;
    const year = document.getElementById('year').value;

    //Read the radio buttons

    const level =
      document.querySelector('input[name="level"]:checked').value;

    // Validation
    if (make === '' || year === '' || level === '') {
      html.displayErrors('All fields are mendatory')
    } else {
      //Make the quotation
      const insurance = new Insurance(make, year, level);
      const price = insurance.calculateQuotation(insurance);
      //print
      html.showResults(price);
    }

  });
}
// Create another prototype with for the object HTMLUI. to print Errors

//Object
// Everything related to the calculation and quotation

function Insurance(make, year, level) {
  this.make = make;
  this.year = year;
  this.level = level;
}

//calculation

Insurance.prototype.calculateQuotation = function(insurance) {
  let price;
  const base = 2000;

  //get make
  const make = insurance.make;

  /**
   1. america: 15
   2. Asia : 5
   3. europia: 35
  */

  switch (make) {
    case '1':
      price = base * 1.15;
      break

    case '2':
      price = base * 1.05;
      break

    case '3':
      price = base * 1.35;
      break
  }

  //get level

  const level = insurance.level;

  price = this.calculateLevel(price, level);

  //get year

  const year = insurance.year;
  const difference = this.getYearDifference(year);
  price = price - ((difference * 3) * price) / 100;
  console.log(price);

}
//return difference between years

Insurance.prototype.getYearDifference = function(year) {
  return new Date().getFullYear() - year;
  // each year the cost must be 3% cheaper

}

//add value based on level

Insurance.prototype.calculateLevel = function(price, level) {
  //basic increase 30%

  //complete increases 50%
  if (level === 'basic') {
    price = price * 1.30;
  } else {
    price = price * 1.50;
  }
  return price;
}

function HTMLUI() {}
//display the latest 20 years in the select
HTMLUI.prototype.displayYears = function() {
  //Max & minimum years
  const max = new Date().getFullYear();
  min = max - 20;
  //Generate the list
  const selectYears = document.getElementById('year');

  //print the values

  for (let i = max; i >= min; i--) {
    const option = document.createElement('option')
    option.value = i;
    option.textContent = i;
    selectYears.appendChild(option);
  }
}

//Print Error, by creating a prototype

HTMLUI.prototype.displayErrors = function(message) {
  //create div
  const div = document.createElement('div');
  div.classList = 'error';

  //insert message
  div.innerText = `

${message}

    `;

  form.insertBefore(div, document.querySelector('.form-group'));

  //Remove the error

  setTimeout(function() {
    document.querySelector('.error').remove();
  }, 3000);
}

HTMLUI.prototype.showResults = function(price) {
  //print result
  const result = document.getElementById('result');

  //create a div with the result

  const div = document.createElement('div');
  //insert the result
  div.innerHTML = `

Total: $ ${price}

    `;
  //insert into html

  result.appendChild(div)
}
```

I am expecting to print the value of the variable price( which will actually be the price) but I'm getting "undefined" while trying to print the price

答:
You need to add in a return statement to the calculateQuotation function. Here's why, in case it helps.

The reason you're getting undefined is because the price variable is never being given a value.

On this line:

const price = insurance.calculateQuotation(insurance);

price is getting whatever the calculateQuotation function sends back with a return statement. However, in that function you're just filling a price variable which exists only in the context of that function. To make this work, I believe you need to add in a return statement at the end of the calculateQuotation function like so:

```<code>Insurance.prototype.calculateQuotation = function(insurance) {
  let price;
  const base = 2000;

  //get make
  const make = insurance.make;

  /**
   1. america: 15
   2. Asia : 5
   3. europia: 35
  */

  switch (make) {
    case '1':
      price = base * 1.15;
      break

    case '2':
      price = base * 1.05;
      break

    case '3':
      price = base * 1.35;
      break
  }

  //get level

  const level = insurance.level;

  price = this.calculateLevel(price, level);

  //get year

  const year = insurance.year;
  const difference = this.getYearDifference(year);
  price = price - ((difference * 3) * price) / 100;
  console.log(price);
  return price; // Added this in
}
</code>```

Title: Undefined function with javascripts

Body:
I'm writing a small 'quote calculator'. I want to print the summary to the browser with innerHTML, but I'm still getting "undefined" instead of the price. But in my console.log everything works fine, I can console.log the variable price and get the expected result.

//Variables

const form = document.getElementById('request-quote');
const html = new HTMLUI();

//Event Listeners

eventListeners();

function eventListeners() {
  document.addEventListener('DOMContentLoaded', function() {
    //Create the <option> for the years
    html.displayYears();
  });
  //when the form is submitted

  form.addEventListener('submit', function(e) {
    e.preventDefault();

    //get values from the form
    const make = document.getElementById('make').value;
    const year = document.getElementById('year').value;

    //Read the radio buttons

    const level =
      document.querySelector('input[name="level"]:checked').value;

    // Validation
    if (make === '' || year === '' || level === '') {
      html.displayErrors('All fields are mendatory')
    } else {
      //Make the quotation
      const insurance = new Insurance(make, year, level);
      const price = insurance.calculateQuotation(insurance);
      //print
      html.showResults(price);
    }

  });
}
// Create another prototype with for the object HTMLUI. to print Errors

//Object
// Everything related to the calculation and quotation

function Insurance(make, year, level) {
  this.make = make;
  this.year = year;
  this.level = level;
}

//calculation

Insurance.prototype.calculateQuotation = function(insurance) {
  let price;
  const base = 2000;

  //get make
  const make = insurance.make;

  /**
   1. america: 15
   2. Asia : 5
   3. europia: 35
  */

  switch (make) {
    case '1':
      price = base * 1.15;
      break

    case '2':
      price = base * 1.05;
      break

    case '3':
      price = base * 1.35;
      break
  }

  //get level

  const level = insurance.level;

  price = this.calculateLevel(price, level);

  //get year

  const year = insurance.year;
  const difference = this.getYearDifference(year);
  price = price - ((difference * 3) * price) / 100;
  console.log(price);

}
//return difference between years

Insurance.prototype.getYearDifference = function(year) {
  return new Date().getFullYear() - year;
  // each year the cost must be 3% cheaper

}

//add value based on level

Insurance.prototype.calculateLevel = function(price, level) {
  //basic increase 30%

  //complete increases 50%
  if (level === 'basic') {
    price = price * 1.30;
  } else {
    price = price * 1.50;
  }
  return price;
}

function HTMLUI() {}
//display the latest 20 years in the select
HTMLUI.prototype.displayYears = function() {
  //Max & minimum years
  const max = new Date().getFullYear();
  min = max - 20;
  //Generate the list
  const selectYears = document.getElementById('year');

  //print the values

  for (let i = max; i >= min; i--) {
    const option = document.createElement('option')
    option.value = i;
    option.textContent = i;
    selectYears.appendChild(option);
  }
}

//Print Error, by creating a prototype

HTMLUI.prototype.displayErrors = function(message) {
  //create div
  const div = document.createElement('div');
  div.classList = 'error';

  //insert message
  div.innerText = `

${message}

    `;

  form.insertBefore(div, document.querySelector('.form-group'));

  //Remove the error

  setTimeout(function() {
    document.querySelector('.error').remove();
  }, 3000);
}

HTMLUI.prototype.showResults = function(price) {
  //print result
  const result = document.getElementById('result');

  //create a div with the result

  const div = document.createElement('div');
  //insert the result
  div.innerHTML = `

Total: $ ${price}

    `;
  //insert into html

  result.appendChild(div)
}

I am expecting to print the value of the variable price( which will actually be the price) but I'm getting "undefined" while trying to print the price

Body:
You need to add in a return statement to the calculateQuotation function. Here's why, in case it helps.

The reason you're getting undefined is because the price variable is never being given a value.

On this line:

const price = insurance.calculateQuotation(insurance);

price is getting whatever the calculateQuotation function sends back with a return statement. However, in that function you're just filling a price variable which exists only in the context of that function. To make this work, I believe you need to add in a return statement at the end of the calculateQuotation function like so:

Insurance.prototype.calculateQuotation = function(insurance) {
  let price;
  const base = 2000;

  //get make
  const make = insurance.make;

  /**
   1. america: 15
   2. Asia : 5
   3. europia: 35
  */

  switch (make) {
    case '1':
      price = base * 1.15;
      break

    case '2':
      price = base * 1.05;
      break

    case '3':
      price = base * 1.35;
      break
  }

  //get level

  const level = insurance.level;

  price = this.calculateLevel(price, level);

  //get year

  const year = insurance.year;
  const difference = this.getYearDifference(year);
  price = price - ((difference * 3) * price) / 100;
  console.log(price);
  return price; // Added this in
}


问:
Short horizontal line in front of the text
I've ready many posts about creating a horizontal line before and after header, but all the examples are not totally what i want to have and I cannot change them to what I would like to have.

Basically I need a SHORT (25px) horizontal line in front of the Header.

See image:

Maybe it is not possible to do with css ... how to do it better then?

Any assistance would be welcome.

Thanks in advance

答:
You can easily do this via CSS, by creating a pseudo element.

I used vertical-align: middle here, and then some relative positioning with a bit of negative top to get it to move up - in my experience, that usually gives a bit better control over the position, than using vertical-align: text-top o.ä. on its own.

h1::before {
  content: "";
  display: inline-block;
  position: relative;
  top: -.35em;
  margin-right: .25em;
  width: 25px;
  height: 2px;
  background: #ccc;
  vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Foobar</h1></code>```

Body:
You can easily do this via CSS, by creating a pseudo element.

I used vertical-align: middle here, and then some relative positioning with a bit of negative top to get it to move up - in my experience, that usually gives a bit better control over the position, than using vertical-align: text-top o.ä. on its own.

h1::before {
  content: "";
  display: inline-block;
  position: relative;
  top: -.35em;
  margin-right: .25em;
  width: 25px;
  height: 2px;
  background: #ccc;
  vertical-align: middle;
}

<h1>Foobar</h1>


问:
How to assign a return value from a SQL Server Function to a Variable
I have function that returns a Date value. I need to assign that return value to a declared variable.

```<code>Declare @Duedate Date
Set @Duedate = SELECT dbo.TATDueDateCaluator('2019-05-10',2)
Select @Duedate
</code>```

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'SELECT'.

答:
You can assign directly in a SELECT:

```<code>Declare @Duedate Date;

SELECT @DueDate = dbo.TATDueDateCaluator('2019-05-10', 2);

Select @Duedate;
</code>```

Your code doesn't work because subqueries always need their own parentheses.

Body:
I have function that returns a Date value. I need to assign that return value to a declared variable.

Declare @Duedate Date
Set @Duedate = SELECT dbo.TATDueDateCaluator('2019-05-10',2)
Select @Duedate

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'SELECT'.

Body:
You can assign directly in a SELECT:

Declare @Duedate Date;

SELECT @DueDate = dbo.TATDueDateCaluator('2019-05-10', 2);

Select @Duedate;

Your code doesn't work because subqueries always need their own parentheses.


问:
How to set Accessibility focus to button programmatically in iOS
In iOS, how to set accessibility focus to a button through programmatically?</p>

答:
@ClemensL response works great.
Here is a Swift 5 version:</p>

```<code>func setAccessibilityFocus() {
    UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: self)
}
</code>```

Body:
@ClemensL response works great.
Here is a Swift 5 version:

func setAccessibilityFocus() {
    UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: self)
}


问:
Speed of NSArray#count
If I do

```<code>[myArray count]
</code>```

is it O(1) or O(n), where n is the number of elements in the array?

答: The source code of Core Foundation collections (upon which Foundation collections are built) is open source. If you inspect CFArray.c, you’ll see that __CFArrayGetCount() is O(1).

Title: Speed of NSArray#count

Body:
If I do

[myArray count]

is it O(1) or O(n), where n is the number of elements in the array?


问:
How to store an ES6 module in more than one file?
This declares an ES6 module:

```<code><script type="module" src="animals.js"></script>
</code>```

My problem is: this makes a 1-to-1 connection between a module and a source file.

I would like to split "animals.js" into "dogs.js" and "cats.js". Is this possible with ES6 modules?

I would like to define the module in this way:

```<code><script type="module" name="animals" src="dogs.js" src="cat.js"></script>
</code>```

答:
ES modules are constraint to a single exporting context which happens to correlate to a single automatically created exporting context per file. So you can’t. You can however introduce a new module and it will be its own file/script block.

Alternatively, you can use a bundler that will accept several input files and produce a single ES module output file. Webpack might be a great choice.

Alternatively, you can introduce a module that imports and exports the contents of the other modules, serving as a kind of a wrapper or facade if you will.

Also, keep in mind that 1-to-1 connection between a script file and an ES module is inherent to the whole design of the ES modules, as well as many other bundling and namespacing systems. This is legitimately a feature and the need to have more than one source file per module might designate a flawed architectural design in your software.

If you would like a Java-like module behavior, you should definitely check out Typescript namespaces. Although, you will eventually realize how many different type inference caveats and parallel module visibility issues are there and thus will stop using them altogether in favor of ES2015 modules, they might be useful for just getting used to the modern technology.

Body:
This declares an ES6 module:

My problem is: this makes a 1-to-1 connection between a module and a source file.

I would like to split "animals.js" into "dogs.js" and "cats.js". Is this possible with ES6 modules?

I would like to define the module in this way:


问:
get Google AdWords API all campaign stats for total impressions and clicks
How to get total impressions and clicks for all campaigns on Google AdWords API?
Right now I am doing this way

```<code>  // Get the service, which loads the required classes.
  $campaignService = $user->GetService('CampaignService', ADWORDS_VERSION);

  // Create selector.
  $selector = new Selector();
  $selector->fields =
      array('Id', 'Name', 'Impressions', 'Clicks', 'Cost', 'Ctr');
  $selector->predicates[] =
      new Predicate('Impressions', 'GREATER_THAN', array(0));

  // Set date range to request stats for.
  $dateRange = new DateRange();
  $dateRange->min = date('Ym01', time());
  $dateRange->max = date('Ymd', time());
  $selector->dateRange = $dateRange;

  // Make the get request.
  $page = $campaignService->get($selector);

  // get results.
  $impressions = 0;
  $clicks = 0;
  if (isset($page->entries)) {
    foreach ($page->entries as $campaign) {
        $impressions += $campaign->campaignStats->impressions;
        $clicks += $campaign->campaignStats->clicks;
    }
  } else {
    //print "No matching campaigns were found.\n";
  }

  return array('impressions'=>$impressions, 'clicks'=>$clicks);
</code>```

I am wondering if I can just get total without using foreach and loop through the  campaigns.

答:
```<code>$startDate = date('Ymd', strtotime('2018-10-12'));
$endDate = date('Ymd', strtotime('2018-11-13'));
$query = (new ReportQueryBuilder())
    ->select([
        'CampaignId',
        'AdGroupId',
        'Impressions',
        'Clicks',
        'Cost'
    ])
    ->from(ReportDefinitionReportType::CRITERIA_PERFORMANCE_REPORT)
    ->where('Status')->in(['ENABLED', 'PAUSED'])
    ->during($startDate, $endDate)
    ->build();
</code>```

Body:
How to get total impressions and clicks for all campaigns on Google AdWords API?
Right now I am doing this way

  // Get the service, which loads the required classes.
  $campaignService = $user->GetService('CampaignService', ADWORDS_VERSION);

  // Create selector.
  $selector = new Selector();
  $selector->fields =
      array('Id', 'Name', 'Impressions', 'Clicks', 'Cost', 'Ctr');
  $selector->predicates[] =
      new Predicate('Impressions', 'GREATER_THAN', array(0));

  // Set date range to request stats for.
  $dateRange = new DateRange();
  $dateRange->min = date('Ym01', time());
  $dateRange->max = date('Ymd', time());
  $selector->dateRange = $dateRange;

  // Make the get request.
  $page = $campaignService->get($selector);

  // get results.
  $impressions = 0;
  $clicks = 0;
  if (isset($page->entries)) {
    foreach ($page->entries as $campaign) {
        $impressions += $campaign->campaignStats->impressions;
        $clicks += $campaign->campaignStats->clicks;
    }
  } else {
    //print "No matching campaigns were found.\n";
  }

  return array('impressions'=>$impressions, 'clicks'=>$clicks);

I am wondering if I can just get total without using foreach and loop through the  campaigns.


问:
Center title in latex-rendered text for matplotlib figure
I would like to center a title for a Matplotlib figure which includes a newline return (\) when rendering it LaTeX style

inserting a simple return code for latex \\ in the middle of the title will work, but will not have it centered so that the newline is awkwardly shifted from the first line.

from matplotlib import pyplot as plt
plt.rc('text', usetex=True)
plt.title(r"\center{\textbf{Some title \\ with with a newline}}")
```

<p>or </p>

<pre class="lang-py prettyprint-override"><code>plt.title(r"\begin{centering}{\textbf{Some title \\ with a newline}\end{centering}")
</code>```

won't work

When I input the previously cited lines, I get no title output at all on the figure. I do not have a LaTeX error on the python command interpreter though.

答:
You can easily use \n to get newline within plt.title():

```<code>import numpy as np
import matplotlib.pyplot as plt

plt.rc('text', usetex=True)

t = np.arange(0., 5., 0.2)

plt.plot(t, t/5000,)
plt.title(r"$\textbf{Some title}$"
          "\n"
          r"$\textbf{with a formula}:$"
          "\n"
          r"$y=t/5000$")
plt.show()
</code>```

Body:
I would like to center a title for a Matplotlib figure which includes a newline return (\) when rendering it LaTeX style

inserting a simple return code for latex \\ in the middle of the title will work, but will not have it centered so that the newline is awkwardly shifted from the first line.

from matplotlib import pyplot as plt
plt.rc('text', usetex=True)
plt.title(r"\center{\textbf{Some title \\ with with a newline}}")

or

plt.title(r"\begin{centering}{\textbf{Some title \\ with a newline}\end{centering}")

won't work

When I input the previously cited lines, I get no title output at all on the figure. I do not have a LaTeX error on the python command interpreter though.

Body:
You can easily use \n to get newline within plt.title():

import numpy as np
import matplotlib.pyplot as plt

plt.rc('text', usetex=True)

t = np.arange(0., 5., 0.2)

plt.plot(t, t/5000,)
plt.title(r"$\textbf{Some title}$"
          "\n"
          r"$\textbf{with a formula}:$"
          "\n"
          r"$y=t/5000$")
plt.show()


问:
C standard regarding pointer arithmetic outside arrays
I read lot of things about pointer arithmetic and undefined behavior (link, link, link, link, link). It always ends up to the same conclusion: Pointer arithmetic is well defined only on array type and between array[0] and array[array_size+1] (one element past the end is valid with regard to the C standard).

My question is: Does it means that when the compiler sees a pointer arithmetic not related to any array (undefined behavior), it could emit what it want (even nothing) ? Or is it more a high level "undefined behavior" meaning you could reach unmapped memory, garbage data, etc and there is not guarantee about the address validity?

In this example:

```<code>char test[10];
char * ptr = &test[0];
printf("test[-1] : %d", *(ptr-1))
</code>```

By "undefined behavior", is it just that the value is not guarantee at all (could be garbage, unmapped memory, etc) but we can still say with certainty that we are accessing the memory address contiguous to the array 8 bytes before the start? Or is it "undefined behavior" in a way that the compiler can just not emit this code at all?

Another simple use case: You want to compute the in-memory size of one function. One naïve implementation could be the following code assuming that the functions are outputted in the binary in the same order, are contiguous and without any padding in between.

```<code>#include <stdint.h>
#include <stdio.h>

void func1()
{}

void func2()
{}

int main()
{
  uint8_t * ptr1 = (uint8_t*) &func1;
  uint8_t * ptr2 = (uint8_t*) &func2;

  printf("Func 1 size : %ld", ptr2-ptr1);

  return 0;
}

</code>```

Since ptr1 and ptr2 are not part of an array, it is considered as undefined behavior. Again, does it means the compiler could not emit those code? Or does "undefined behavior" means that the subtraction is meaningless depending on the system (functions not contiguous in memory, with padding, etc) but still occurs as expected? Is there any well defined way to compute the subtraction between two unrelated pointers?

答:
The C standard doesn't define degrees of undefinedness for undefined behavior. If it's undefined, it's always all bets are off.

Additionally, modern compilers mess with this pointer provenance thing where the compiler even watches if a possibly valid pointer is derived correctly and if it isn't, it can adjust program behavior.

If you want mathematical pointer arithmetic without the possibility of UB,
you can try and cast your pointer to uintptr_t prior to doing the math.

E.g.:

```<code>#include <stdio.h>
int main()
{
    char a,b;
    printf("&a=%p\n", &a);
    printf("&b=%p\n", &b);
    printf("&a+1=%p\n", &a+1);
    printf("&b+1=%p\n", &b+1);
    printf("%d\n", &a+1==&b || &b+1==&a);
}
</code>```

on my machine, compiled with gcc -O2, results in:

```<code>&a=0x7ffee4e36cae
&b=0x7ffee4e36caf
&a+1=0x7ffee4e36caf
&b+1=0x7ffee4e36cb0
0
</code>```

I.e., &a+1 has the same numerical address as &b but is treated as unequal to &b because the addresses are derived from different objects.

(This gcc optimization is somewhat controversial. It doesn't carry across function call / translation unit boundaries, clang doesn't do it, and it's not necessary as 6.5.9p6 does allow for accidental pointer equality. See dbush's to this Keith Thompson's answer for more details.)

Body:
I read lot of things about pointer arithmetic and undefined behavior (link, link, link, link, link). It always ends up to the same conclusion: Pointer arithmetic is well defined only on array type and between array[0] and array[array_size+1] (one element past the end is valid with regard to the C standard).

My question is: Does it means that when the compiler sees a pointer arithmetic not related to any array (undefined behavior), it could emit what it want (even nothing) ? Or is it more a high level "undefined behavior" meaning you could reach unmapped memory, garbage data, etc and there is not guarantee about the address validity?

In this example:

char test[10];
char * ptr = &test[0];
printf("test[-1] : %d", *(ptr-1))

By "undefined behavior", is it just that the value is not guarantee at all (could be garbage, unmapped memory, etc) but we can still say with certainty that we are accessing the memory address contiguous to the array 8 bytes before the start? Or is it "undefined behavior" in a way that the compiler can just not emit this code at all?

Another simple use case: You want to compute the in-memory size of one function. One naïve implementation could be the following code assuming that the functions are outputted in the binary in the same order, are contiguous and without any padding in between.

#include <stdint.h>
#include <stdio.h>

void func1()
{}

void func2()
{}

int main()
{
  uint8_t * ptr1 = (uint8_t*) &func1;
  uint8_t * ptr2 = (uint8_t*) &func2;

  printf("Func 1 size : %ld", ptr2-ptr1);

  return 0;
}

Since ptr1 and ptr2 are not part of an array, it is considered as undefined behavior. Again, does it means the compiler could not emit those code? Or does "undefined behavior" means that the subtraction is meaningless depending on the system (functions not contiguous in memory, with padding, etc) but still occurs as expected? Is there any well defined way to compute the subtraction between two unrelated pointers?

Body:
The C standard doesn't define degrees of undefinedness for undefined behavior. If it's undefined, it's always all bets are off.

Additionally, modern compilers mess with this pointer provenance thing where the compiler even watches if a possibly valid pointer is derived correctly and if it isn't, it can adjust program behavior.

If you want mathematical pointer arithmetic without the possibility of UB,
you can try and cast your pointer to uintptr_t prior to doing the math.

E.g.:

#include <stdio.h>
int main()
{
    char a,b;
    printf("&a=%p\n", &a);
    printf("&b=%p\n", &b);
    printf("&a+1=%p\n", &a+1);
    printf("&b+1=%p\n", &b+1);
    printf("%d\n", &a+1==&b || &b+1==&a);
}

on my machine, compiled with gcc -O2, results in:

&a=0x7ffee4e36cae
&b=0x7ffee4e36caf
&a+1=0x7ffee4e36caf
&b+1=0x7ffee4e36cb0
0

I.e., &a+1 has the same numerical address as &b but is treated as unequal to &b because the addresses are derived from different objects.

(This gcc optimization is somewhat controversial. It doesn't carry across function call / translation unit boundaries, clang doesn't do it, and it's not necessary as 6.5.9p6 does allow for accidental pointer equality. See dbush's to this Keith Thompson's answer for more details.)


问:
How to check if a key/value pair exists in a Dictionary?
How can one check if a key/value pair exists in a Dictionary<TKey,TValue>? I'm able to check if a key or value exist, using ContainsKey and ContainsValue, but I'm unsure of how to check if a key/value pair exist.

答:
```<code>var result= YourDictionaryName.TryGetValue(key, out string value) ? YourDictionaryName[key] : "";
</code>```

If the key is present in the dictionary, it returns the value of the key otherwise it returns a blank object.

Hope, this code helps you.

Body:
var result= YourDictionaryName.TryGetValue(key, out string value) ? YourDictionaryName[key] : "";

If the key is present in the dictionary, it returns the value of the key otherwise it returns a blank object.

Hope, this code helps you.


问:
Cannot pass params using navigate and multiple StackNavigators
```<code>  render() {
    const { icon, title, description, preview, video } = this.props;

    return (
  ....
            <Text
              onPress={() => {
                this.props.navigation("VideoPlayer", video);
              }}
              style={styles.text}
            >
              {title}
            </Text>
</code>```

Using seperate stackNavigators in a DrawerNavigator, in my component I use getParam, however, its empty, how can I pass props?

```<code>  render() {
    const { navigation } = this.props;
    const videoId = navigation.getParam("video", ''); // empty

    return (
</code>```

AppNavigator:

```<code>const config = {
    initialRouteName: "Home",
    contentOptions: {
        activeTintColor: "#e91e63",
        itemStyle: {
            flexDirection: "row-reverse"
        }
    },
    drawerWidth: 300,
    drawerPosition: "right"
};

const withHeader = (
    screen: Function,
    routeName: string,
    Header
): StackNavigator =>
    createStackNavigator(
        {
            [routeName]: {
                screen,
                navigationOptions: ({ navigation, routeName, props }) => ({
                    header: props => <Header {...props} />
                })
            }
        },
        {
            transparentCard: true
        }
    );

const routes = {
    Home: {
        screen: withHeader(HomeScreen, "Home", BasicHeader)
    },
    Links: {
        screen: withHeader(LinksScreen, "Links", DrawerHeader)
    },
    Settings: {
        screen: withHeader(SettingsScreen, "Settings", DrawerHeader)
    },
    VideoEpisodes: {
        screen: withHeader(VideoEpisodesScreen, "Video Episodes", DrawerHeader)
    },
    VideoPlayer: {
        screen: withHeader(VideoPlayerScreen, "Video Player", DrawerHeader)
    },
    TestYourself: {
        screen: withHeader(TestYourselfScreen, "Test Yourself", DrawerHeader)
    },
    MyResults: {
        screen: withHeader(MyResultsScreen, "My Results", DrawerHeader)
    },
    BookmarkedVideos: {
        screen: withHeader(
            BookmarkedVideosScreen,
            "Bookmarked Videos",
            DrawerHeader
        )
    },
    Search: {
        screen: withHeader(SearchScreen, "Search", DrawerHeader)
    },
    About: {
        screen: withHeader(AboutScreen, "About", DrawerHeader)
    }
};

const AppNavigator = createDrawerNavigator(routes, config);

export default createAppContainer(AppNavigator);
</code>```

VideoPlayer:

```<code>    export default class VideoPlayerScreen extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          video: this.props.navigation.state.params.video
        };
      }
      render() {
        console.log(this.state.video);

        return (
          <View style={styles.container}>
            <VideoPlayer {...this.props} />
          </View>
        );
      }

}
</code>```

Snack setup here

答:
The second parameter of navigate is an object called params, and your video object should be a property of that object, try like this:

this.props.c("VideoPlayer", { video });

Body:
  render() {
    const { icon, title, description, preview, video } = this.props;

    return (
  ....
            <Text
              onPress={() => {
                this.props.navigation("VideoPlayer", video);
              }}
              style={styles.text}
            >
              {title}
            </Text>

Using seperate stackNavigators in a DrawerNavigator, in my component I use getParam, however, its empty, how can I pass props?

  render() {
    const { navigation } = this.props;
    const videoId = navigation.getParam("video", ''); // empty

    return (

AppNavigator:

const config = {
    initialRouteName: "Home",
    contentOptions: {
        activeTintColor: "#e91e63",
        itemStyle: {
            flexDirection: "row-reverse"
        }
    },
    drawerWidth: 300,
    drawerPosition: "right"
};

const withHeader = (
    screen: Function,
    routeName: string,
    Header
): StackNavigator =>
    createStackNavigator(
        {
            [routeName]: {
                screen,
                navigationOptions: ({ navigation, routeName, props }) => ({
                    header: props =>
                })
            }
        },
        {
            transparentCard: true
        }
    );

const routes = {
    Home: {
        screen: withHeader(HomeScreen, "Home", BasicHeader)
    },
    Links: {
        screen: withHeader(LinksScreen, "Links", DrawerHeader)
    },
    Settings: {
        screen: withHeader(SettingsScreen, "Settings", DrawerHeader)
    },
    VideoEpisodes: {
        screen: withHeader(VideoEpisodesScreen, "Video Episodes", DrawerHeader)
    },
    VideoPlayer: {
        screen: withHeader(VideoPlayerScreen, "Video Player", DrawerHeader)
    },
    TestYourself: {
        screen: withHeader(TestYourselfScreen, "Test Yourself", DrawerHeader)
    },
    MyResults: {
        screen: withHeader(MyResultsScreen, "My Results", DrawerHeader)
    },
    BookmarkedVideos: {
        screen: withHeader(
            BookmarkedVideosScreen,
            "Bookmarked Videos",
            DrawerHeader
        )
    },
    Search: {
        screen: withHeader(SearchScreen, "Search", DrawerHeader)
    },
    About: {
        screen: withHeader(AboutScreen, "About", DrawerHeader)
    }
};

const AppNavigator = createDrawerNavigator(routes, config);

export default createAppContainer(AppNavigator);

VideoPlayer:

    export default class VideoPlayerScreen extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          video: this.props.navigation.state.params.video
        };
      }
      render() {
        console.log(this.state.video);

        return (
          <View style={styles.container}>
            <VideoPlayer {...this.props} />
          </View>
        );
      }

}

Snack setup here