问:
access c multidemensional array with only one argument?
I am reading this C code, and I find it difficult to understand what's going on.

Here is the array:

```<code>static const char   gradient[32][4] =
{
{ 1,  1,  1,  0}, { 1,  1,  0,  1}, { 1,  0,  1,  1}, { 0,  1,  1,  1},
{ 1,  1, -1,  0}, { 1,  1,  0, -1}, { 1,  0,  1, -1}, { 0,  1,  1, -1},
{ 1, -1,  1,  0}, { 1, -1,  0,  1}, { 1,  0, -1,  1}, { 0,  1, -1,  1},
{ 1, -1, -1,  0}, { 1, -1,  0, -1}, { 1,  0, -1, -1}, { 0,  1, -1, -1},
{-1,  1,  1,  0}, {-1,  1,  0,  1}, {-1,  0,  1,  1}, { 0, -1,  1,  1},
{-1,  1, -1,  0}, {-1,  1,  0, -1}, {-1,  0,  1, -1}, { 0, -1,  1, -1},
{-1, -1,  1,  0}, {-1, -1,  0,  1}, {-1,  0, -1,  1}, { 0, -1, -1,  1},
{-1, -1, -1,  0}, {-1, -1,  0, -1}, {-1,  0, -1, -1}, { 0, -1, -1, -1},
};
</code>```

and it's 32*4, this is another part of the code that trying to access this array:

```<code>const char * g0000 = gradient[Indice (x1, y1, z1, t1)];
</code>```

Indice is a function that returns an int. So what is this g0000 (I know it's a pointer), say Indice returns 1, what is the value g0000 holds? I mostly code in C# to my understanding if you want to access multidimensional array you would need several arguments, but here is only one, I am really confused...

答:
That wouldn't be unreasonable to assume Indice() returns the index of the row in gradient that holds the 4 values x1, y1, z1 and t1.

gradient being const char[32][4], say Indice returns an index i used in gradient

```<code>gradient[i]
</code>```

is an address that points to a char ; the calculated address of gradient[i]

```<code>g0000 = gradient[i]
</code>```

is

```<code>gradient + ( i*4*sizeof(gradient[0][0]) )
</code>```

that is, it points to the first element of gradient at address &gradient[i][0]

In C there is no automatic control of array out of bounds indexes, and in that array, accessing [R][C] is like accessing [R*4+C], meaning while g0000 points to a [4] char area, you might try to access beyond that 4-limit, (e.g. [i][5]) and would access the next row (since it's [i*4+5] or [i+1][1]).

However accessing the array out of bounds leads to undefined behavior (if i+1 > 31 in that case, since an array [X] goes from [0] to [X-1]).

Body:
I am reading this C code, and I find it difficult to understand what's going on.

Here is the array:

static const char   gradient[32][4] =
{
{ 1,  1,  1,  0}, { 1,  1,  0,  1}, { 1,  0,  1,  1}, { 0,  1,  1,  1},
{ 1,  1, -1,  0}, { 1,  1,  0, -1}, { 1,  0,  1, -1}, { 0,  1,  1, -1},
{ 1, -1,  1,  0}, { 1, -1,  0,  1}, { 1,  0, -1,  1}, { 0,  1, -1,  1},
{ 1, -1, -1,  0}, { 1, -1,  0, -1}, { 1,  0, -1, -1}, { 0,  1, -1, -1},
{-1,  1,  1,  0}, {-1,  1,  0,  1}, {-1,  0,  1,  1}, { 0, -1,  1,  1},
{-1,  1, -1,  0}, {-1,  1,  0, -1}, {-1,  0,  1, -1}, { 0, -1,  1, -1},
{-1, -1,  1,  0}, {-1, -1,  0,  1}, {-1,  0, -1,  1}, { 0, -1, -1,  1},
{-1, -1, -1,  0}, {-1, -1,  0, -1}, {-1,  0, -1, -1}, { 0, -1, -1, -1},
};

and it's 32*4, this is another part of the code that trying to access this array:

const char * g0000 = gradient[Indice (x1, y1, z1, t1)];

Indice is a function that returns an int. So what is this g0000 (I know it's a pointer), say Indice returns 1, what is the value g0000 holds? I mostly code in C# to my understanding if you want to access multidimensional array you would need several arguments, but here is only one, I am really confused...

Body:
That wouldn't be unreasonable to assume Indice() returns the index of the row in gradient that holds the 4 values x1, y1, z1 and t1.

gradient being const char[32][4], say Indice returns an index i used in gradient

gradient[i]

is an address that points to a char ; the calculated address of gradient[i]

g0000 = gradient[i]

is

gradient + ( i*4*sizeof(gradient[0][0]) )

that is, it points to the first element of gradient at address &gradient[i][0]

In C there is no automatic control of array out of bounds indexes, and in that array, accessing [R][C] is like accessing [R*4+C], meaning while g0000 points to a [4] char area, you might try to access beyond that 4-limit, (e.g. [i][5]) and would access the next row (since it's [i*4+5] or [i+1][1]).

However accessing the array out of bounds leads to undefined behavior (if i+1 > 31 in that case, since an array [X] goes from [0] to [X-1]).


来源: stackexchange

问:
Find a number where it appears exactly N/2 times
Here is one of my interview question. Given an array of N elements and where an element appears exactly N/2 times and the rest N/2 elements are unique. How would you find the element with a better run time?

Remember the elements are not sorted and you can assume N is even. For example,

```<code>input array [] = { 10, 2, 3, 10, 1, 4, 10, 5, 10, 10 }
</code>```

So here 10 appears extactly 5 times which is N/2.

I know a solution with O(n) run time. But still looking forward to know a better solution with O(log n).

答:
The answer is straightforward.. and can be achieved in worst case (n/2 + 1) comparisons

Compare pairwise first (n-2) numbers, that is, compare nos. at 0 and 1, then 2 and 3 and so on... total n/2 -1 comparisons.
If we find identical numbers in any of the above comparisons.. we have the repeated number... else:

Take any one of the last two remaining numbers (say second last one I took)  and compare it with the numbers in the second last pair.. if match occurs..second last no. is the repated one, else last one is the repeated one... in all 2 comparisons.

Total comparisons = n/2 - 1 + 2 =n/2 + 1 (worst case)
I dont think there is any O(log n) method to achieve this

ContentLicense: CC BY-SA 2.5

Body:
Here is one of my interview question. Given an array of N elements and where an element appears exactly N/2 times and the rest N/2 elements are unique. How would you find the element with a better run time?

Remember the elements are not sorted and you can assume N is even. For example,

input array [] = { 10, 2, 3, 10, 1, 4, 10, 5, 10, 10 }

So here 10 appears extactly 5 times which is N/2.

I know a solution with O(n) run time. But still looking forward to know a better solution with O(log n).


问:
Dagger2 annotation processor is not working
I try to use Dagger2 in my Android project;
When I use apt, every things is right.But apt is not supported in AndroidStudio 3.0, so I use annotation processor.But no Dagger2 code created after I click "Make Project";
And I'm sure the annotetion processing is enable in AndroidStudio,because the Butterknife annotation processor is all right.
the follow is the build.gradle:</p>

```<code>dependencies {
    annotationProcessor 'com.google.dagger:dagger-android-processor:2.13'
    compile 'com.google.dagger:dagger-android:2.13'
    compile 'com.google.dagger:dagger-android-support:2.13'
    compile 'com.jakewharton:butterknife:8.6.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'
}
</code>```

答:
use this in android studio 3.0 version</p>

```<code>implementation 'com.google.dagger:dagger:2.9'
annotationProcessor 'com.google.dagger:dagger-compiler:2.9'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I try to use Dagger2 in my Android project;
When I use apt, every things is right.But apt is not supported in AndroidStudio 3.0, so I use annotation processor.But no Dagger2 code created after I click "Make Project";
And I'm sure the annotetion processing is enable in AndroidStudio,because the Butterknife annotation processor is all right.
the follow is the build.gradle:

dependencies {
    annotationProcessor 'com.google.dagger:dagger-android-processor:2.13'
    compile 'com.google.dagger:dagger-android:2.13'
    compile 'com.google.dagger:dagger-android-support:2.13'
    compile 'com.jakewharton:butterknife:8.6.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'
}

Body:
use this in android studio 3.0 version

implementation 'com.google.dagger:dagger:2.9'
annotationProcessor 'com.google.dagger:dagger-compiler:2.9'

ContentLicense: CC BY-SA 3.0


问:
How do I get Android client side callback to fire after Firebase Cloud Function onWrite finishes?
So I'm on a user page and I'd like to let users create a post but fanout on the server side.

```<code>exports.fanoutUpdatePost = functions.database.ref('/post/{postKey}').onWrite(event => {
        var post = event.data.val();

        var fanoutObject = {};

        fanoutObject['/user-post/'+post.userKey+'/post/'+event.params.postKey] = post;
        fanoutObject['/blog-post/'+post.blogKey+'/post/'+event.params.postKey] = post;

       return event.data.adminRef.root.update(fanoutObject);
});
</code>```

I'm doing this so you can just post on /post/ and the server will automatically fanout.
The problem is that I want the client side to show progress bar until it gets saved in /user-post/.

But my client side callback fires immediately after post gets created on /post/.

```<code>public void addPost(final PostDao post, ProgressBar progressBar) {
    progressBar.setVisibility(View.VISIBLE);

    String key = mDatabase.child(“post”).push().getKey();

    Map<String, Object> postUpdateMap = new HashMap<>();
    postUpdateMap.put(“/post/” +key, post.toMap());

    mDatabase.updateChildren(postUpdateMap, new DatabaseReference.CompletionListener() {
                @Override
                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                    if(databaseError == null){
                        Log.e(TAG, databaseError);
                    }else{
                        // @@@@@ This executes before server side
                        // @@@@@ cloud function fanoutUpdatePost
                        // @@@@@ finishes. Can I make this happen
                        // @@@@@ after it?
                    }
                }
            });
}
</code>```

Is there a way to wait until my onWrite cloud function finishes?

答:
It's not possible for a database write to wait for the completion of some Cloud Function.  Writes don't know anything about Cloud Functions - the write just becomes an event for the function to consume some time later.

If you need to wait for the completion of a Cloud Function, it'll be much easier if you write it as an HTTPS trigger and invoke it directly from the client, sending a response back only when it's done.  Send the data to post in the request, and have the function be responsible for doing all the actual database writes.

Body:
So I'm on a user page and I'd like to let users create a post but fanout on the server side.

exports.fanoutUpdatePost = functions.database.ref('/post/{postKey}').onWrite(event => {
        var post = event.data.val();

        var fanoutObject = {};

        fanoutObject['/user-post/'+post.userKey+'/post/'+event.params.postKey] = post;
        fanoutObject['/blog-post/'+post.blogKey+'/post/'+event.params.postKey] = post;

       return event.data.adminRef.root.update(fanoutObject);
});

I'm doing this so you can just post on /post/ and the server will automatically fanout.
The problem is that I want the client side to show progress bar until it gets saved in /user-post/.

But my client side callback fires immediately after post gets created on /post/.

public void addPost(final PostDao post, ProgressBar progressBar) {
    progressBar.setVisibility(View.VISIBLE);

    String key = mDatabase.child(“post”).push().getKey();

    Map<String, Object> postUpdateMap = new HashMap<>();
    postUpdateMap.put(“/post/” +key, post.toMap());

    mDatabase.updateChildren(postUpdateMap, new DatabaseReference.CompletionListener() {
                @Override
                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                    if(databaseError == null){
                        Log.e(TAG, databaseError);
                    }else{
                        // @@@@@ This executes before server side
                        // @@@@@ cloud function fanoutUpdatePost
                        // @@@@@ finishes. Can I make this happen
                        // @@@@@ after it?
                    }
                }
            });
}

Is there a way to wait until my onWrite cloud function finishes?


问:
Linq To Sql Many-Many Join Table
I am a somewhat experienced Rails developer and I thought I would try out ASP.NET's version of MVC. In doing so I also decided to try Linq->Sql...

I am a bit confused about the way Linq->Sql handles joins.

A trivial example of my schema is :

books:

id

title

categories:

id

name

books_categories:

book_id

category_id

Simply dragging these tables to the .dbml file doesn't seem to do it. I get a property on my Book class books_categories, what I expect is a property that I can iterate over and get Category classes directly.

Right now I have to do something that feels very wrong

```<code>        foreach (books_categories bc in book.books_categories)
        {
            category_names.Add(bc.Category.category.Trim());
        }
</code>```

[In Response to Accepted answer]

I grudgingly accepted the answer of "write your own glue code". After continuing my research of Linq->Sql I discovered that it is apparently slowly being let go in favor of the (more powereful, IMO) Entity Framework. EF still allows one to use LINQ for queries and does a decent job of figuring out relationships like Ruby's ActiveRecord.

答:
I don't think your expected result is supported in Linq to Sql.

What you're doing may feel wrong, but I think that's one way  to work around that limitation of L2S.

Man, i've really got to get into Rails...

OwnerDisplayName: Bill

Title: Linq To Sql Many-Many Join Table

Body:
I am a somewhat experienced Rails developer and I thought I would try out ASP.NET's version of MVC. In doing so I also decided to try Linq->Sql...

I am a bit confused about the way Linq->Sql handles joins.

A trivial example of my schema is :

books:

id

title

categories:

id

name

books_categories:

book_id

category_id

Simply dragging these tables to the .dbml file doesn't seem to do it. I get a property on my Book class books_categories, what I expect is a property that I can iterate over and get Category classes directly.

Right now I have to do something that feels very wrong

        foreach (books_categories bc in book.books_categories)
        {
            category_names.Add(bc.Category.category.Trim());
        }

[In Response to Accepted answer]

I grudgingly accepted the answer of "write your own glue code". After continuing my research of Linq->Sql I discovered that it is apparently slowly being let go in favor of the (more powereful, IMO) Entity Framework. EF still allows one to use LINQ for queries and does a decent job of figuring out relationships like Ruby's ActiveRecord.

LastEditorDisplayName: Bill

OwnerDisplayName: Bramha Ghosh


问:
Alternate of rename() and remove() in C++
I am trying to implement same functionality for File rename() and remove() for my winCE device.
but i guess the these function are not there in wince. as its there in cstdio header for C++.

Please suggest me the alternate for this.

答:
Rename

MoveFile

http://msdn.microsoft.com/en-us/library/aa365239(v=VS.85).aspx

Remove

DeleteFile

http://msdn.microsoft.com/en-us/library/aa363915(v=VS.85).aspx


问:
Can I clone a paused Docker container?
I can suspend the processes running inside a container with the PAUSE command. Is it possible to clone the Docker container whilst paused, so that it can be resumed (i.e. via the UNPAUSE command) several times in parallel?

The use case for this is a process which takes long time to start (i.e. ~20 seconds). Given that I want to have a pool of short-living Docker containers running that process in parallel, I would reduce start-up time for each container a lot if this was somehow possible.

答:
Yes, you can, using docker checkpoint (criu). This does not have anything to do with pause though, it is a seperate docker command.

Also see here.

Title: Can I clone a paused Docker container?


问:
How to use RevoScaleR to read SAS data chunk-by-chunk and output into a format other than xdf?
I am trying to develop some code using RevoScaleR and noticed that it has options like rowsPerRead and can output xdf files in chunks using the rxImport method.
However my use cases I want to apply some custom transformation (to the entire chunk; not just columns)  and output the results in fst format instead of xdf (as I find it to be faster).

Is there a way to apply customer transforms of each chunk being read it using RevoScaleR?

答:
Following the example it's like the below except it doesn't seem to work and just eats up lots of RAM (at least on Windows)</p>

```<code>library(RevoScaleR)
a = RxSasData("file.sas7bdat")
rxOpen(a)
rxNext(a)
rxClose(a)
</code>```

Body:
Following the example it's like the below except it doesn't seem to work and just eats up lots of RAM (at least on Windows)

library(RevoScaleR)
a = RxSasData("file.sas7bdat")
rxOpen(a)
rxNext(a)
rxClose(a)


问:
Trying to pass URL into Iframe Src Angular 2 getting an error
I'm trying to dynamically add a URL into an iframe src on a click event but I'm getting this error

Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'SafeValue%20must%20use%20%5Bproperty%5D'

Ive used domSanitizer to make the URL safe to insert it in the iframe

HTML

```<code> <div class="cards-wrapper">
                <div class="prepackaged__card" *ngFor="let video of videos">

                    <img class="prepackaged__card-header" src="{{video.thumbnail}}">
                    <div class="prepackaged__card-body">
                        <div class="category">{{video.subname}}</div>
                        <h2 class="title">{{video.name}}
                        </h2>

                        <button (click)="sendUrl(video.videoData)">PLAY VIDEO</button>
                    </div>
                </div>
            </div>
<div class="video-player-modal">
     <div class="video-player-modal_header">

     </div>
     <div class="video-player-modal_video">
         <iframe class="video-player-modal_video_player" src="" frameborder="0" allowfullscreen=""></iframe>
     </div>
</div>
</code>```

app.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { DashboardServiceProxy, UserVideoDto } from '@shared/service-proxies/service-proxies';
import { DomSanitizer, SafeResourceUrl, SafeUrl } from '@angular/platform-browser';

declare var jQuery: any;
const $ = jQuery;

@Component({
  selector: 'app-video',
  templateUrl: './video.component.html',
  styleUrls: ['./video.component.scss'],
  providers: [
    DashboardServiceProxy
  ]
})
export class VideoComponent implements OnInit {
  videos: UserVideoDto[] = [];
  trustedDashboardUrl: SafeUrl;

  constructor(
    private _dashboardService: DashboardServiceProxy,
    private sanitizer: DomSanitizer
  ) {

    }

  ngOnInit() {
    this.getVideos();
  }

  getVideos() {
    this._dashboardService.getAllUserVideos().subscribe((result) => {
    this.videos = result;
    console.log(this.videos);
 });
}

  sendUrl(playerUrl) {
    this.trustedDashboardUrl = this.sanitizer.bypassSecurityTrustResourceUrl(playerUrl);
    $('.video-player-modal_video_player').attr('src', this.trustedDashboardUrl);
  }

}
</code>```

any ideas on what is happening?

答:
What I would recommend is using property binding instead of using jQuery for dynamically populating the attributes. It goes as follows:

Set the src attribute to a component member variable which is initialised to empty string:

```<code>[src]="iframeURL"
</code>```

In your component file set iframeURL:

```<code>iframeURL = '';
</code>```

Modify your click event handler as follows:

```<code>sendUrl(playerUrl) {
    // this.iframeURL = playerUrl // try it first, if it doesn't work use the sanitized URL
    this.trustedDashboardUrl = this.sanitizer.bypassSecurityTrustResourceUrl(playerUrl);
    this.iframeURL = this.trustedDashboardUrl;
}
</code>```

Hope it works! Kindly share in case it doesn't.

Body:
I'm trying to dynamically add a URL into an iframe src on a click event but I'm getting this error

Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'SafeValue%20must%20use%20%5Bproperty%5D'

Ive used domSanitizer to make the URL safe to insert it in the iframe

HTML

{{video.subname}}

{{video.name}}

                        <button (click)="sendUrl(video.videoData)">PLAY VIDEO</button>

app.component.ts

import { Component, OnInit } from '@angular/core';
import { DashboardServiceProxy, UserVideoDto } from '@shared/service-proxies/service-proxies';
import { DomSanitizer, SafeResourceUrl, SafeUrl } from '@angular/platform-browser';

declare var jQuery: any;
const $ = jQuery;

@Component({
  selector: 'app-video',
  templateUrl: './video.component.html',
  styleUrls: ['./video.component.scss'],
  providers: [
    DashboardServiceProxy
  ]
})
export class VideoComponent implements OnInit {
  videos: UserVideoDto[] = [];
  trustedDashboardUrl: SafeUrl;

  constructor(
    private _dashboardService: DashboardServiceProxy,
    private sanitizer: DomSanitizer
  ) {

    }

  ngOnInit() {
    this.getVideos();
  }

  getVideos() {
    this._dashboardService.getAllUserVideos().subscribe((result) => {
    this.videos = result;
    console.log(this.videos);
 });
}

  sendUrl(playerUrl) {
    this.trustedDashboardUrl = this.sanitizer.bypassSecurityTrustResourceUrl(playerUrl);
    $('.video-player-modal_video_player').attr('src', this.trustedDashboardUrl);
  }

}

any ideas on what is happening?

Body:
What I would recommend is using property binding instead of using jQuery for dynamically populating the attributes. It goes as follows:

Set the src attribute to a component member variable which is initialised to empty string:

[src]="iframeURL"

In your component file set iframeURL:

iframeURL = '';

Modify your click event handler as follows:

sendUrl(playerUrl) {
    // this.iframeURL = playerUrl // try it first, if it doesn't work use the sanitized URL
    this.trustedDashboardUrl = this.sanitizer.bypassSecurityTrustResourceUrl(playerUrl);
    this.iframeURL = this.trustedDashboardUrl;
}

Hope it works! Kindly share in case it doesn't.


问:
WPF is there a way to copy a MediaElement in c# (clone)
is there a way to copy a MediaElement in c# (clone) ?

Thank you

Wally

答:
The only 2 ways I can think of are:

Make a custom Clone method. That is a lot of work and might not be possible because of the private data that you can't reach.

Serialize the MediaElement using a (Xaml)serializer and then deserialize.

Disclaimer: I haven't tried either of them.

Question: why would you want to Clone a MediaElement?

EDIT A better way of duplicating the same video might be by using the VisualBrush. Simply apply a VisualBrush that points to the MediaElement to a Rectangle. No need to copy the video or clone the MediaElement.


问:
SoapUI handshake_failure on https endpoint service
When the project endpoint moves to https from http, I got handsshake_failure error for the request. By checking some topics, I modified SoapUI-5.2.1.vmoptions file by adding this

-Dsoapui.https.protocols=TLSv1.2

or with SSL. And restart SoapUI.

But I still get the error.

答: moved to soap ui 5.4 solved this problem for me</p>


问:
(C++) Is creating a class/object specifically for handling all other custom objects a proper way to handle a project?
I asked a question yesterday, but it seems I did ask it incorrectly, so here I go again. I quickly mocked up this code, and I'm wondering if this is a proper way to handle the objects (outside of just putting everything in main(). This would be my first time trying to complete a larger project, so I've never had a need to question how to contain and handle the objects.

skill.h

```<code>#pragma once

#include <string>
#include <vector>
#include <memory>
#include <unordered_map>

class Skill;

typedef std::vector<std::shared_ptr<Skill>> SkillVector;
typedef std::unordered_map<std::string, std::shared_ptr<Skill>> SkillMap;

class Skill {
private:
    std::string _skill_name;
    std::string _skill_description;
    friend std::ostream& operator<< (std::ostream& stream, const Skill& skill);
    void print(std::ostream& stream) const;

public:
    Skill(const std::string& skill_name, const std::string& skill_description);
    const std::string& getSkillName() const;
    const std::string& getSkillDescription() const;
    bool isMatch(const std::string& substring) const;
};
</code>```

application.h

```<code>#pragma once

#include "skill.h"

extern std::string SKILL_FILE;

class Application {
private:
    std::unique_ptr<SkillMap> _skill_map;
    void loadData();
    void loadSkills();
    void printSkillMap();
    void printSkillVector(const SkillVector& skills);
    std::unique_ptr<SkillVector> skillSearch(const std::string& input) const;
public:
    Application();
    void run();
};
</code>```

main.cpp

```<code>#include "application.h"

int main() {
    std::unique_ptr<Application> application(new Application);
    application->run();

    return 0;
}
</code>```

This is going to be a command-line application, so other than this I can't think of doing anything else except putting all the methods from the application class straight into main as regular functions. That doesn't seem like the correct approach though. I've tried researching this pretty extensively, but haven't really found anything that answers this.

What are the other options for containing all the objects in an orderly fashion? What are the advantages of doing it certain ways? And is what I'm doing here acceptable?

NOTE: This isn't an exact representation of my project, and I'm just using it as an example to understand my question at hand.

答:
TL;DR There isn't a single answer on how to move forward. It depends on:

What your goal is.

What subsystems the project will have, and how they integrate with one another.

The type and quantity of data that the project will require.

That said, it's almost always a good idea to apply separation of concerns, segregating data & functionality between types that correspond to each of your project's concerns. Here's an example using a finite state machine to get you started:

```<code>// Note that this example uses C++11 features.
// Note that the stubs are intentional, to keep this example as terse as possible.

// For consistency with your naming style.
typedef std::string String;
template<typename T>
using Vector = std::vector<T>;
template<typename T>
using UniquePtr = std::unique_ptr<T>;

// Skill.hpp: Represents a single skill.
class Skill {
private:
    String _name;
    String _description;

public:
    Skill(String name, String description);

    const String& getName() const { return _name; }
    const String& getDescription() const { return _description; }
};

// Player.hpp: Represents a single player.
class Player {
private:
    Vector<Skill*> _skills;
    bool _isVirtual; // Is this player from another computer? (networked multiplayer)

public:
    Player(bool isVirtual = false) :
        _skills(),
        _isVirtual(isVirtual) {}
    Player(const Player& other) = delete; // Non-copyable.

    bool hasSkill(Skill* skill) const;
    void addSkill(Skill* skill);
    bool removeSkill(Skill* skill); // Returns true if removed, false otherwise.
    bool isVirtual() const { return _isVirtual; }
};

// Level.hpp: Represents a single level of the game.
class Level {
private:
    // Per-level data...

public:
    Level();
    Level(const Level& other) = delete; // Non-copyable.
};

// GameState.hpp: Represents the state of the game.
enum class GameState {
    MainMenu,   // The user is in the main menu.
    World,      // The user is navigating the world.
    Combat,     // The user is in combat.
};

// Game.hpp: Represents a single game instance.
class Game {
private:
    Application* _app;
    Vector<UniquePtr<Player>> _players;
    Vector<UniquePtr<Level>> _levels;
    Level* _level; // Current level the player(s) are on.
    GameState _state; // Current state of the game.
    bool _isRunning; // Is the game running?

    void mainMenuLoop() {
        while (_isRunning) {
            // Implement your main menu here.
            // Update the menu display after user input.

            // When a selection is confirmed, execute it and return.
        }
    }
    void combatLoop() {
        while (_isRunning) {
            // Implement your combat system here.

            // When combat is over, update _state and return.
        }
    }

public:
    Game(Application* app) :
        _app(app),
        _players(),
        _levels(),
        _level(),
        _state(GameState::MainMenu),
        _isRunning(true) {
        // Finish initializing and:
        // If loading is fast enough, do so here.
        // If loading is slow, spin up a thread and load asynchronously.
    }
    Game(const Game& other) = delete; // Non-copyable.

    void run() {
        // If loading is slow, wait on the loading thread to complete.

        // Possibly show an introduction banner.
        while (_isRunning) {
            switch (_state) {
                case GameState::MainMenu:
                    mainMenuLoop();
                    break;
                case GameState::Combat:
                    combatLoop();
                    break;
            }
        }
    }
    void quit() { _isRunning = false; }
    const Player* getPlayer(int index) const;
    Player* getPlayer(int index);
    void addPlayer(Player* player);
    bool removePlayer(Player* player); // Returns true if removed, false otherwise.
    const Level* getLevel(int index) const;
    Level* getLevel(int index);
    void addLevel(Level* level);
    bool removeLevel(Level* level); // Returns true if removed, false otherwise.
};

// Options.hpp: Represents command line options.
struct Options {
    // Add your command line options here.

    Options();
    Options(const Options& other);
};

// Application.hpp: Represents a single application instance.
class Application {
private:
    Options _options;
    Game _game;

public:
    // For compatibility with your code.
    Application() :
        _options(),
        _game(this) {}
    // For later, when you add command line options.
    Application(const Options& options) :
        _options(options),
        _game(this) {}
    Application(const Application& other) = delete; // Non-copyable.

    const Options& getOptions() const { return _options; }
    const Game* getGame() const { return &_game; }
    Game* getGame() { return &_game; }
    // For compatibility with your code. You could
    // remove this and directly use getGame()->run()
    void run() { _game.run(); }
};
</code>```

In main using unique_ptr for the Application object is unnecessary. Use the stack instead:

```<code>// Added arguments because you'll probably want command-line options later.
int main(int argc, char** argv) {
    Application app; // Better locality, no dynamic allocation.
    app.run();
    return 0;
}
</code>```

Body:
I asked a question yesterday, but it seems I did ask it incorrectly, so here I go again. I quickly mocked up this code, and I'm wondering if this is a proper way to handle the objects (outside of just putting everything in main(). This would be my first time trying to complete a larger project, so I've never had a need to question how to contain and handle the objects.

skill.h

#pragma once

#include <string>
#include <vector>
#include <memory>
#include <unordered_map>

class Skill;

typedef std::vector<std::shared_ptr<Skill>> SkillVector;
typedef std::unordered_map<std::string, std::shared_ptr<Skill>> SkillMap;

class Skill {
private:
    std::string _skill_name;
    std::string _skill_description;
    friend std::ostream& operator<< (std::ostream& stream, const Skill& skill);
    void print(std::ostream& stream) const;

public:
    Skill(const std::string& skill_name, const std::string& skill_description);
    const std::string& getSkillName() const;
    const std::string& getSkillDescription() const;
    bool isMatch(const std::string& substring) const;
};

application.h

#pragma once

#include "skill.h"

extern std::string SKILL_FILE;

class Application {
private:
    std::unique_ptr<SkillMap> _skill_map;
    void loadData();
    void loadSkills();
    void printSkillMap();
    void printSkillVector(const SkillVector& skills);
    std::unique_ptr<SkillVector> skillSearch(const std::string& input) const;
public:
    Application();
    void run();
};

main.cpp

#include "application.h"

int main() {
    std::unique_ptr<Application> application(new Application);
    application->run();

    return 0;
}

This is going to be a command-line application, so other than this I can't think of doing anything else except putting all the methods from the application class straight into main as regular functions. That doesn't seem like the correct approach though. I've tried researching this pretty extensively, but haven't really found anything that answers this.

What are the other options for containing all the objects in an orderly fashion? What are the advantages of doing it certain ways? And is what I'm doing here acceptable?

NOTE: This isn't an exact representation of my project, and I'm just using it as an example to understand my question at hand.

Body:
TL;DR There isn't a single answer on how to move forward. It depends on:

What your goal is.

What subsystems the project will have, and how they integrate with one another.

The type and quantity of data that the project will require.

That said, it's almost always a good idea to apply separation of concerns, segregating data & functionality between types that correspond to each of your project's concerns. Here's an example using a finite state machine to get you started:

// Note that this example uses C++11 features.
// Note that the stubs are intentional, to keep this example as terse as possible.

// For consistency with your naming style.
typedef std::string String;
template<typename T>
using Vector = std::vector<T>;
template<typename T>
using UniquePtr = std::unique_ptr<T>;

// Skill.hpp: Represents a single skill.
class Skill {
private:
    String _name;
    String _description;

public:
    Skill(String name, String description);

    const String& getName() const { return _name; }
    const String& getDescription() const { return _description; }
};

// Player.hpp: Represents a single player.
class Player {
private:
    Vector<Skill*> _skills;
    bool _isVirtual; // Is this player from another computer? (networked multiplayer)

public:
    Player(bool isVirtual = false) :
        _skills(),
        _isVirtual(isVirtual) {}
    Player(const Player& other) = delete; // Non-copyable.

    bool hasSkill(Skill* skill) const;
    void addSkill(Skill* skill);
    bool removeSkill(Skill* skill); // Returns true if removed, false otherwise.
    bool isVirtual() const { return _isVirtual; }
};

// Level.hpp: Represents a single level of the game.
class Level {
private:
    // Per-level data...

public:
    Level();
    Level(const Level& other) = delete; // Non-copyable.
};

// GameState.hpp: Represents the state of the game.
enum class GameState {
    MainMenu,   // The user is in the main menu.
    World,      // The user is navigating the world.
    Combat,     // The user is in combat.
};

// Game.hpp: Represents a single game instance.
class Game {
private:
    Application* _app;
    Vector<UniquePtr<Player>> _players;
    Vector<UniquePtr<Level>> _levels;
    Level* _level; // Current level the player(s) are on.
    GameState _state; // Current state of the game.
    bool _isRunning; // Is the game running?

    void mainMenuLoop() {
        while (_isRunning) {
            // Implement your main menu here.
            // Update the menu display after user input.

            // When a selection is confirmed, execute it and return.
        }
    }
    void combatLoop() {
        while (_isRunning) {
            // Implement your combat system here.

            // When combat is over, update _state and return.
        }
    }

public:
    Game(Application* app) :
        _app(app),
        _players(),
        _levels(),
        _level(),
        _state(GameState::MainMenu),
        _isRunning(true) {
        // Finish initializing and:
        // If loading is fast enough, do so here.
        // If loading is slow, spin up a thread and load asynchronously.
    }
    Game(const Game& other) = delete; // Non-copyable.

    void run() {
        // If loading is slow, wait on the loading thread to complete.

        // Possibly show an introduction banner.
        while (_isRunning) {
            switch (_state) {
                case GameState::MainMenu:
                    mainMenuLoop();
                    break;
                case GameState::Combat:
                    combatLoop();
                    break;
            }
        }
    }
    void quit() { _isRunning = false; }
    const Player* getPlayer(int index) const;
    Player* getPlayer(int index);
    void addPlayer(Player* player);
    bool removePlayer(Player* player); // Returns true if removed, false otherwise.
    const Level* getLevel(int index) const;
    Level* getLevel(int index);
    void addLevel(Level* level);
    bool removeLevel(Level* level); // Returns true if removed, false otherwise.
};

// Options.hpp: Represents command line options.
struct Options {
    // Add your command line options here.

    Options();
    Options(const Options& other);
};

// Application.hpp: Represents a single application instance.
class Application {
private:
    Options _options;
    Game _game;

public:
    // For compatibility with your code.
    Application() :
        _options(),
        _game(this) {}
    // For later, when you add command line options.
    Application(const Options& options) :
        _options(options),
        _game(this) {}
    Application(const Application& other) = delete; // Non-copyable.

    const Options& getOptions() const { return _options; }
    const Game* getGame() const { return &_game; }
    Game* getGame() { return &_game; }
    // For compatibility with your code. You could
    // remove this and directly use getGame()->run()
    void run() { _game.run(); }
};

In main using unique_ptr for the Application object is unnecessary. Use the stack instead:

// Added arguments because you'll probably want command-line options later.
int main(int argc, char** argv) {
    Application app; // Better locality, no dynamic allocation.
    app.run();
    return 0;
}


问:
Reversing words in shell
Task is to reverse all letters (a-zA-Z) in words that have 5 or less characters.

EDIT: Let's assume word is a not interrupted sequence of letters from english alphabet.

( letter: ASCII range A-Z && a-z)

Example:

Input: "One ring to rule them all, one ring to find them, One ring to bring them all and in the darkness bind them."

Output: "enO gnir ot elur meht lla, eno gnir ot dnif meht, enO gnir ot gnirb meht lla dna ni eht darkness dnib meht."

I have been able to write this script, but it sruggles with words with special chracters such as {,.} that are not supposed to be reversed.

```<code>#!/bin/bash

    word_length=0
    touch tmp

    for word in $(cat ./TEXT)
    do
            word_length=$(echo -n $word | wc -c )
            if [ $word_length -le 5 ]
            then
                    echo -n $word | rev >> tmp
                    echo -n " " >> tmp
            else
                    echo -n $word >> tmp
                    echo -n " " >> tmp
            fi
    done

    cat tmp > TEXT
    echo " " >> TEXT
    rm -rf tmp
</code>```

Output of this script:
"enO gnir ot elur meht ,lla eno gnir ot dnif ,meht enO gnir ot gnirb meht lla dna ni eht darkness dnib .meht"

You can see that {,.} are in the wrong place.

答:
With perl

```<code>$ cat ip.txt
"One ring to rule them all,
one ring to find them,
One ring to bring them all and in the darkness bind them."
O'Donnell 1234 there's pre-existing

$ perl -F'/([^a-z])/i' -ane '
          print map {$_ = length()<6 && /[a-z]/i ? reverse : $_} @F' ip.txt
"enO gnir ot elur meht lla,
eno gnir ot dnif meht,
enO gnir ot gnirb meht lla dna ni eht darkness dnib meht."
O'Donnell 1234 ereht's erp-existing
</code>```

-F'/([^a-z])/i' use non alphabets as field separator, use of () means the field separators would be also be saved in @F array along with word fields

see https://perldoc.perl.org/perlrun.html#Command-Switches for explanation of command line options

map is used to transform each element of array

length()<6 && /[a-z]/i condition to select words less than length 6 and to ignore field separators

reverse will reverse the string in scalar context

finally the changed array is printed

Title: Reversing words in shell

Body:
Task is to reverse all letters (a-zA-Z) in words that have 5 or less characters.

EDIT: Let's assume word is a not interrupted sequence of letters from english alphabet.

( letter: ASCII range A-Z && a-z)

Example:

Input: "One ring to rule them all, one ring to find them, One ring to bring them all and in the darkness bind them."

Output: "enO gnir ot elur meht lla, eno gnir ot dnif meht, enO gnir ot gnirb meht lla dna ni eht darkness dnib meht."

I have been able to write this script, but it sruggles with words with special chracters such as {,.} that are not supposed to be reversed.

#!/bin/bash

    word_length=0
    touch tmp

    for word in $(cat ./TEXT)
    do
            word_length=$(echo -n $word | wc -c )
            if [ $word_length -le 5 ]
            then
                    echo -n $word | rev >> tmp
                    echo -n " " >> tmp
            else
                    echo -n $word >> tmp
                    echo -n " " >> tmp
            fi
    done

    cat tmp > TEXT
    echo " " >> TEXT
    rm -rf tmp

Output of this script:
"enO gnir ot elur meht ,lla eno gnir ot dnif ,meht enO gnir ot gnirb meht lla dna ni eht darkness dnib .meht"

You can see that {,.} are in the wrong place.

Body:
With perl

$ cat ip.txt
"One ring to rule them all,
one ring to find them,
One ring to bring them all and in the darkness bind them."
O'Donnell 1234 there's pre-existing

$ perl -F'/([^a-z])/i' -ane '
          print map {$_ = length()<6 && /[a-z]/i ? reverse : $_} @F' ip.txt
"enO gnir ot elur meht lla,
eno gnir ot dnif meht,
enO gnir ot gnirb meht lla dna ni eht darkness dnib meht."
O'Donnell 1234 ereht's erp-existing

-F'/([^a-z])/i' use non alphabets as field separator, use of () means the field separators would be also be saved in @F array along with word fields

see https://perldoc.perl.org/perlrun.html#Command-Switches for explanation of command line options

map is used to transform each element of array

length()<6 && /[a-z]/i condition to select words less than length 6 and to ignore field separators

reverse will reverse the string in scalar context

finally the changed array is printed


问:
Formatting the messages in JSF
HI,

I have the following code in my JSP file:

```<code><h:inputText id="name" value="#{jsfBean.name }" required="true"/>
<h:message for="name"/>
</code>```

The error messages displayed is something like this:

```<code>j_id_jsp_1916142437_1:name: Validation Error: Value is required.
</code>```

How can I format the output error message like giving the color,font,etc.

答:
Simply By  applying CSS.

```<code><h:message for="age" style="errorMessage" /></p>
</code>```

You can also override default messages by providing Messages.properties file

```<code>javax.faces.component.UIInput.REQUIRED=Please enter a value for this field.
    javax.faces.converter.DateTimeConverter.DATE=Please enter a valid date.
javax.faces.converter.DateTimeConverter.DATE_detail=Please enter a valid date. Example: {1}
</code>```

Also See

Nice Article on Customizing error message

Title: Formatting the messages in JSF

Body:
HI,

I have the following code in my JSP file:

<h:inputText id="name" value="#{jsfBean.name }" required="true"/>
<h:message for="name"/>

The error messages displayed is something like this:

j_id_jsp_1916142437_1:name: Validation Error: Value is required.

How can I format the output error message like giving the color,font,etc.

Body:
Simply By  applying CSS.

<h:message for="age" style="errorMessage" /></p>

You can also override default messages by providing Messages.properties file

javax.faces.component.UIInput.REQUIRED=Please enter a value for this field.
    javax.faces.converter.DateTimeConverter.DATE=Please enter a valid date.
javax.faces.converter.DateTimeConverter.DATE_detail=Please enter a valid date. Example: {1}

Also See

Nice Article on Customizing error message


问:
Python-Saving txt information to dictionary containing lists
I’m new to python and I know you can save information to a dictionary in the format:

```<code>dictionary ={'Albany' : [ 201, 16.9, etc] }
</code>```

But I am trying to get information from a text file to go into that format. Does anyone know how I would do this? Sorry if I am being vague I can try to clarify for anyone if necessary.
Here is part of the text file:

36   1    39857    35436    44278 13.7 12.2 15.2     9271     7566    10976 16.1 13.1 19.1     6123     4832     7414 14.5 11.4 17.6  55778  53673  57883

Albany County                                 NY est13_NY.txt 05NOV2014

36   3     7296     5941     8651 16.7 13.6 19.8     2526     2043     3009 25.6 20.7 30.5     1707     1331     2083 23.5 18.3 28.7  41849  39467  44231

Allegany County                               NY est13_NY.txt 05NOV2014

The first two lines are one line in the text file and what I have to do is compare certain statistics from the top line(child poverty data) and have my program state which county has the highest percent of poverty based on one of the pieces of data and other things based on other pieces of data in the txt file.

For each county this is the data that I need:
The data we care about for each county are:
Position Variable

50- 57 Estimate of people age 0-17 in poverty

77- 80 Estimated percent of people age 0-17 in poverty

134-139 Estimate of median household income

194-238 State or county name

county name includes ' County'. To get rid of it use
replace(' County','') after stripping trailing white space.

Also I cannot use any modules.
So far I opened the txt file and then did a for loop reading each line in the file and putting that into a dictionary, but i am not sure how to put it in the format I said above.

答:
You have not provided much information so here is just a demo code help for letting you know how you can achieve that thing :

Generally, people use collections.defaultdict for that kind of thing but since you said you don't want any module to import then here is algorithm pattern for this kind of problem :

Let's first understand the actual problem :

Example Hint :

For these types of list problems there is a pattern :

So suppose you have a list :

```<code>a=[(2006,1),(2007,4),(2008,9),(2006,5)]
</code>```

And you want to convert this to a dict as the first element of the tuple as key and second element of the tuple. something like :

```<code>{2008: [9], 2006: [5], 2007: [4]}
</code>```

But there is a catch you also want that those keys which have different values but keys are same like (2006,1) and (2006,5) keys are same but values are different. you want that those values append with only one key so expected output :

```<code>{2008: [9], 2006: [1, 5], 2007: [4]}
</code>```

for this type of problem we do something like this:

first create a new dict then we follow this pattern:

```<code>if item[0] not in new_dict:
    new_dict[item[0]]=[item[1]]
else:
    new_dict[item[0]].append(item[1])
</code>```

So we first check if key is in new dict and if it already then add the value of duplicate key to its value:

full code:

```<code>a=[(2006,1),(2007,4),(2008,9),(2006,5)]

new_dict={}

for item in a:
    if item[0] not in new_dict:
        new_dict[item[0]]=[item[1]]
    else:
        new_dict[item[0]].append(item[1])

print(new_dict)
</code>```

Body:
I’m new to python and I know you can save information to a dictionary in the format:

dictionary ={'Albany' : [ 201, 16.9, etc] }

But I am trying to get information from a text file to go into that format. Does anyone know how I would do this? Sorry if I am being vague I can try to clarify for anyone if necessary.
Here is part of the text file:

36   1    39857    35436    44278 13.7 12.2 15.2     9271     7566    10976 16.1 13.1 19.1     6123     4832     7414 14.5 11.4 17.6  55778  53673  57883

Albany County                                 NY est13_NY.txt 05NOV2014

36   3     7296     5941     8651 16.7 13.6 19.8     2526     2043     3009 25.6 20.7 30.5     1707     1331     2083 23.5 18.3 28.7  41849  39467  44231

Allegany County                               NY est13_NY.txt 05NOV2014

The first two lines are one line in the text file and what I have to do is compare certain statistics from the top line(child poverty data) and have my program state which county has the highest percent of poverty based on one of the pieces of data and other things based on other pieces of data in the txt file.

For each county this is the data that I need:
The data we care about for each county are:
Position Variable

50- 57 Estimate of people age 0-17 in poverty

77- 80 Estimated percent of people age 0-17 in poverty

134-139 Estimate of median household income

194-238 State or county name

county name includes ' County'. To get rid of it use
replace(' County','') after stripping trailing white space.

Also I cannot use any modules.
So far I opened the txt file and then did a for loop reading each line in the file and putting that into a dictionary, but i am not sure how to put it in the format I said above.

Body:
You have not provided much information so here is just a demo code help for letting you know how you can achieve that thing :

Generally, people use collections.defaultdict for that kind of thing but since you said you don't want any module to import then here is algorithm pattern for this kind of problem :

Let's first understand the actual problem :

Example Hint :

For these types of list problems there is a pattern :

So suppose you have a list :

a=[(2006,1),(2007,4),(2008,9),(2006,5)]

And you want to convert this to a dict as the first element of the tuple as key and second element of the tuple. something like :

{2008: [9], 2006: [5], 2007: [4]}

But there is a catch you also want that those keys which have different values but keys are same like (2006,1) and (2006,5) keys are same but values are different. you want that those values append with only one key so expected output :

{2008: [9], 2006: [1, 5], 2007: [4]}

for this type of problem we do something like this:

first create a new dict then we follow this pattern:

if item[0] not in new_dict:
    new_dict[item[0]]=[item[1]]
else:
    new_dict[item[0]].append(item[1])

So we first check if key is in new dict and if it already then add the value of duplicate key to its value:

full code:

a=[(2006,1),(2007,4),(2008,9),(2006,5)]

new_dict={}

for item in a:
    if item[0] not in new_dict:
        new_dict[item[0]]=[item[1]]
    else:
        new_dict[item[0]].append(item[1])

print(new_dict)


问:
How to check if string1 is the reverse of string2 using recursion (python)
I know how to reverse a string using recursion

```<code>def reverse(s):
    if len(s) == 0:
        return s
    return s[-1] + reverse(s[0 : -1])

def main() :
    r = reverse("Hello!")
    print(r)
    print("Expected: !olleH")
main()
</code>```

However I'm having trouble figuring out how to check if one string is the reverse of a second given two strings. I want the output to be true if it is the reverse, false if it isn't the reverse. Capitals and lowercases ignored. This is what I have so far:

```<code>def isReversed(str1, str2):
    if len(str1) != len(str2):
        return False
</code>```

I'm not sure how to call the function within itself using two arguments.

答:
Since your reverse() function is good, you could compare string str1 to see if it's the reverse of str2 by:

```<code>def isReversed(str1, str2):
    return str1 == reverse(str2)
</code>```

Because, if str1 and str2 are really the reverse of one another, reversing one of them should make them match.

If you really want to ignore case, then:

```<code>def isReversed(str1, str2):
    return str1.lower() == reverse(str2).lower()
</code>```

You can also do an easy string reversal with str1[::-1] so you could check if str1 == str2[::-1]

Body:
I know how to reverse a string using recursion

def reverse(s):
    if len(s) == 0:
        return s
    return s[-1] + reverse(s[0 : -1])

def main() :
    r = reverse("Hello!")
    print(r)
    print("Expected: !olleH")
main()

However I'm having trouble figuring out how to check if one string is the reverse of a second given two strings. I want the output to be true if it is the reverse, false if it isn't the reverse. Capitals and lowercases ignored. This is what I have so far:

def isReversed(str1, str2):
    if len(str1) != len(str2):
        return False

I'm not sure how to call the function within itself using two arguments.

Body:
Since your reverse() function is good, you could compare string str1 to see if it's the reverse of str2 by:

def isReversed(str1, str2):
    return str1 == reverse(str2)

Because, if str1 and str2 are really the reverse of one another, reversing one of them should make them match.

If you really want to ignore case, then:

def isReversed(str1, str2):
    return str1.lower() == reverse(str2).lower()

You can also do an easy string reversal with str1[::-1] so you could check if str1 == str2[::-1]


问:
Android gradle sync issue
This app was running perfectly OK without any issue. Suddenly i saw this gradle sync problems.I'm really stuck and need help. What to do now? I've uninstalled and reinstalled android support repository from SDK manager.

```<code>C:\Users\DELL\AndroidStudioProjects\Prokriti\app\build.gradle
    Error:Error:Failed to resolve: com.android.support:support-annotations:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:appcompat-v7:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:customtabs:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:cardview-v7:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:support-v4:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:support-core-utils:27.0.1
Install Repository and sync project
</code>```

build.gradle  (app)

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.avtro.prokriti.prokriti"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-core-utils:25.3.1'
    compile 'com.android.support:support-annotations:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-auth:11.0.4'
    compile 'com.google.firebase:firebase-core:11.0.2'
    compile 'com.google.firebase:firebase-messaging:11.0.2'
    compile 'com.google.firebase:firebase-database:11.0.2'
    compile 'com.google.firebase:firebase-auth:11.0.2'
    compile 'com.google.firebase:firebase-ads:11.0.2'
    compile 'com.afollestad.material-dialogs:core:0.9.4.5'
    compile 'com.wang.avi:library:2.1.3'
    compile 'com.google.android.gms:play-services-ads:11.0.4'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.survivingwithandroid:weatherlib:1.6.0'
    compile 'com.amitshekhar.android:android-networking:1.0.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.squareup.okhttp:okhttp:2.0.0'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.google.firebase:firebase-storage:11.0.2'
    androidTestCompile 'junit:junit:4.12'
    compile 'javax.inject:javax.inject:1'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'com.github.bumptech.glide:glide:3.8.0'
}
apply plugin: 'com.google.gms.google-services'
</code>```

build.gradle  (project)

```<code>buildscript {
    repositories {
        jcenter()
    }
dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

i didnt update android studio or gradle. Android support repository is installed.

答:
Add google() in buildscript.repositories and allprojects.repositories :

```<code>buildscript {
    repositories {
        google()
        jcenter()
    }
dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

This should solve your problem.

Title: Android gradle sync issue

Body:
This app was running perfectly OK without any issue. Suddenly i saw this gradle sync problems.I'm really stuck and need help. What to do now? I've uninstalled and reinstalled android support repository from SDK manager.

C:\Users\DELL\AndroidStudioProjects\Prokriti\app\build.gradle
    Error:Error:Failed to resolve: com.android.support:support-annotations:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:appcompat-v7:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:customtabs:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:cardview-v7:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:support-v4:27.0.1
Install Repository and sync project
    Error:Error:Failed to resolve: com.android.support:support-core-utils:27.0.1
Install Repository and sync project

build.gradle  (app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.avtro.prokriti.prokriti"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-core-utils:25.3.1'
    compile 'com.android.support:support-annotations:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-auth:11.0.4'
    compile 'com.google.firebase:firebase-core:11.0.2'
    compile 'com.google.firebase:firebase-messaging:11.0.2'
    compile 'com.google.firebase:firebase-database:11.0.2'
    compile 'com.google.firebase:firebase-auth:11.0.2'
    compile 'com.google.firebase:firebase-ads:11.0.2'
    compile 'com.afollestad.material-dialogs:core:0.9.4.5'
    compile 'com.wang.avi:library:2.1.3'
    compile 'com.google.android.gms:play-services-ads:11.0.4'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.survivingwithandroid:weatherlib:1.6.0'
    compile 'com.amitshekhar.android:android-networking:1.0.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.squareup.okhttp:okhttp:2.0.0'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.google.firebase:firebase-storage:11.0.2'
    androidTestCompile 'junit:junit:4.12'
    compile 'javax.inject:javax.inject:1'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'com.github.bumptech.glide:glide:3.8.0'
}
apply plugin: 'com.google.gms.google-services'

build.gradle  (project)

buildscript {
    repositories {
        jcenter()
    }
dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

i didnt update android studio or gradle. Android support repository is installed.

Body:
Add google() in buildscript.repositories and allprojects.repositories :

buildscript {
    repositories {
        google()
        jcenter()
    }
dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

This should solve your problem.


问:
What is the Jersey 2.0 equivalent of GZIPContentEncodingFilter
I am in the progress to migrate a Jerset 1.x client project to Jersey 2.0.

I found that GZIPContentEncodingFilter does not exist any longer. Is there something similar?

I stumbled over GZIPEncoder but am not sure how to plug it in.

In Jersey 1.17 I use:

```<code>WebResource r = ...
r.register(new GZIPContentEncodingFilter());
</code>```

In Jersey 2.0 I search for somethink like:

```<code>WebTarget r = ...
r.register(new GZIPContentEncodingFilter());
</code>```

答:
In Jersey 2.x (I use 2.26):

```<code>WebTarget target = ...
target.register(GZipEncoder.class);
</code>```

I did not have to include EncodingFilter/DeflateEncoder.

Body:
I am in the progress to migrate a Jerset 1.x client project to Jersey 2.0.

I found that GZIPContentEncodingFilter does not exist any longer. Is there something similar?

I stumbled over GZIPEncoder but am not sure how to plug it in.

In Jersey 1.17 I use:

WebResource r = ...
r.register(new GZIPContentEncodingFilter());

In Jersey 2.0 I search for somethink like:

WebTarget r = ...
r.register(new GZIPContentEncodingFilter());

Body:
In Jersey 2.x (I use 2.26):

WebTarget target = ...
target.register(GZipEncoder.class);

I did not have to include EncodingFilter/DeflateEncoder.


问:
libclang python how to get number of arguments for function with default values
I'm using libclang with it's python binding and I'm trying to get the number of arguments for CallExpr, I found that if a member function has default value and being called with this argument missing, libclang returns the number of arguments in the function declaration and not as in the call expression.

For example :

```<code>class SomeClass
{
public:
    int sum(int x, int y)
    {
        return x + y;
    }

    int sum_def(int x, int y = 0)
    {
        return x + y;
    }
};

int main()
{
    SomeClass x;
    x.sum(10, 100);
    x.sum_def(20);
    return 0;
}
</code>```

traverse ast using liblcang :

```<code>def traverse(node):
    if node.kind == clang.cindex.CursorKind.CALL_EXPR:
        print('%-35s %-20s %-10s [%-6s:%s - %-6s:%s] %s %s ' % (
        node.kind, node.spelling, node.type.spelling, node.extent.start.line, node.extent.start.column,
        node.extent.end.line, node.extent.end.column, node.location.file, node.mangled_name))
        print("%d  " % node.get_num_arguments())
        for arg in node.get_arguments():
            print("ARG=%s %s" % (arg.kind, arg.spelling))

    for child in node.get_children():
        traverse(child)
</code>```

The output :

```<code>CursorKind.CALL_EXPR                sum                  int        [20    :5 - 20    :19] main.cpp
2
ARG=CursorKind.INTEGER_LITERAL
ARG=CursorKind.INTEGER_LITERAL
CursorKind.CALL_EXPR                sum_def              int        [21    :5 - 21    :18] main.cpp
2
ARG=CursorKind.INTEGER_LITERAL
ARG=CursorKind.UNEXPOSED_EXPR
</code>```

I would expect to get 1 as number of arguments in the CALL_EXPR for sum_def, it is possible to get it or should I parse the code myself, something I don't really want to do.
Thank you.

答:
I changed a bit the traverse function to print more details

```<code>def traverse(node, level):
    print('%s %-35s %-20s %-10s [%-6s:%s - %-6s:%s] %s %s ' % (' ' * level,
    node.kind, node.spelling, node.type.spelling, node.extent.start.line, node.extent.start.column,
    node.extent.end.line, node.extent.end.column, node.location.file, node.mangled_name))
    if node.kind == clang.cindex.CursorKind.CALL_EXPR:
        for arg in node.get_arguments():
            print("ARG=%s %s" % (arg.kind, arg.spelling))

    for child in node.get_children():
        traverse(child, level+1)
</code>```

The output :

```<code>  CursorKind.CLASS_DECL               SomeClass            SomeClass  [2     :1 - 14    :2] main.cpp
   CursorKind.CXX_ACCESS_SPEC_DECL                                     [4     :1 - 4     :8] main.cpp
   CursorKind.CXX_METHOD               sum                  int (int, int) [5     :5 - 8     :6] main.cpp _ZN9SomeClass3sumEii
    CursorKind.PARM_DECL                x                    int        [5     :13 - 5     :18] main.cpp _ZZN9SomeClass3sumEiiE1x
    CursorKind.PARM_DECL                y                    int        [5     :20 - 5     :25] main.cpp _ZZN9SomeClass3sumEiiE1y
    CursorKind.COMPOUND_STMT                                            [6     :5 - 8     :6] main.cpp
     CursorKind.RETURN_STMT                                              [7     :9 - 7     :21] main.cpp
      CursorKind.BINARY_OPERATOR                               int        [7     :16 - 7     :21] main.cpp
       CursorKind.UNEXPOSED_EXPR           x                    int        [7     :16 - 7     :17] main.cpp
        CursorKind.DECL_REF_EXPR            x                    int        [7     :16 - 7     :17] main.cpp
       CursorKind.UNEXPOSED_EXPR           y                    int        [7     :20 - 7     :21] main.cpp
        CursorKind.DECL_REF_EXPR            y                    int        [7     :20 - 7     :21] main.cpp
   CursorKind.CXX_METHOD               sum_def              int (int, int) [10    :5 - 13    :6] main.cpp _ZN9SomeClass7sum_defEii
    CursorKind.PARM_DECL                x                    int        [10    :17 - 10    :22] main.cpp _ZZN9SomeClass7sum_defEiiE1x
    CursorKind.PARM_DECL                y                    int        [10    :24 - 10    :33] main.cpp _ZZN9SomeClass7sum_defEiiE1y
     CursorKind.INTEGER_LITERAL                               int        [10    :32 - 10    :33] main.cpp
    CursorKind.COMPOUND_STMT                                            [11    :5 - 13    :6] main.cpp
     CursorKind.RETURN_STMT                                              [12    :9 - 12    :21] main.cpp
      CursorKind.BINARY_OPERATOR                               int        [12    :16 - 12    :21] main.cpp
       CursorKind.UNEXPOSED_EXPR           x                    int        [12    :16 - 12    :17] main.cpp
        CursorKind.DECL_REF_EXPR            x                    int        [12    :16 - 12    :17] main.cpp
       CursorKind.UNEXPOSED_EXPR           y                    int        [12    :20 - 12    :21] main.cpp
        CursorKind.DECL_REF_EXPR            y                    int        [12    :20 - 12    :21] main.cpp
  CursorKind.FUNCTION_DECL            main                 int ()     [17    :1 - 26    :2] main.cpp main
   CursorKind.COMPOUND_STMT                                            [18    :1 - 26    :2] main.cpp
    CursorKind.DECL_STMT                                                [19    :5 - 19    :22] main.cpp
     CursorKind.VAR_DECL                 i                    int        [19    :5 - 19    :14] main.cpp _ZZ4mainE1i
      CursorKind.INTEGER_LITERAL                               int        [19    :13 - 19    :14] main.cpp
     CursorKind.VAR_DECL                 j                    int        [19    :16 - 19    :21] main.cpp _ZZ4mainE1j
      CursorKind.INTEGER_LITERAL                               int        [19    :20 - 19    :21] main.cpp
    CursorKind.DECL_STMT                                                [20    :5 - 20    :17] main.cpp
     CursorKind.VAR_DECL                 x                    SomeClass  [20    :5 - 20    :16] main.cpp _ZZ4mainE1x
      CursorKind.TYPE_REF                 class SomeClass      SomeClass  [20    :5 - 20    :14] main.cpp
      CursorKind.CALL_EXPR                SomeClass            SomeClass  [20    :15 - 20    :16] main.cpp
    CursorKind.CALL_EXPR                sum                  int        [21    :5 - 21    :19] main.cpp
ARG=CursorKind.INTEGER_LITERAL
ARG=CursorKind.INTEGER_LITERAL
     CursorKind.MEMBER_REF_EXPR          sum                  <bound member function type> [21    :5 - 21    :10] main.cpp
      CursorKind.DECL_REF_EXPR            x                    SomeClass  [21    :5 - 21    :6] main.cpp
     CursorKind.INTEGER_LITERAL                               int        [21    :11 - 21    :13] main.cpp
     CursorKind.INTEGER_LITERAL                               int        [21    :15 - 21    :18] main.cpp
    CursorKind.CALL_EXPR                sum_def              int        [22    :5 - 22    :18] main.cpp
ARG=CursorKind.INTEGER_LITERAL
ARG=CursorKind.UNEXPOSED_EXPR
     CursorKind.MEMBER_REF_EXPR          sum_def              <bound member function type> [22    :5 - 22    :14] main.cpp
      CursorKind.DECL_REF_EXPR            x                    SomeClass  [22    :5 - 22    :6] main.cpp
     CursorKind.INTEGER_LITERAL                               int        [22    :15 - 22    :17] main.cpp
     CursorKind.UNEXPOSED_EXPR                                int        [0     :0 - 0     :0] None
    CursorKind.CALL_EXPR                sum_def              int        [23    :5 - 23    :23] main.cpp
ARG=CursorKind.INTEGER_LITERAL
ARG=CursorKind.INTEGER_LITERAL
     CursorKind.MEMBER_REF_EXPR          sum_def              <bound member function type> [23    :5 - 23    :14] main.cpp
      CursorKind.DECL_REF_EXPR            x                    SomeClass  [23    :5 - 23    :6] main.cpp
     CursorKind.INTEGER_LITERAL                               int        [23    :15 - 23    :17] main.cpp
     CursorKind.INTEGER_LITERAL                               int        [23    :19 - 23    :22] main.cpp
    CursorKind.CALL_EXPR                sum                  int        [24    :5 - 24    :16] main.cpp
ARG=CursorKind.UNEXPOSED_EXPR i
ARG=CursorKind.UNEXPOSED_EXPR j
     CursorKind.MEMBER_REF_EXPR          sum                  <bound member function type> [24    :5 - 24    :10] main.cpp
      CursorKind.DECL_REF_EXPR            x                    SomeClass  [24    :5 - 24    :6] main.cpp
     CursorKind.UNEXPOSED_EXPR           i                    int        [24    :11 - 24    :12] main.cpp
      CursorKind.DECL_REF_EXPR            i                    int        [24    :11 - 24    :12] main.cpp
     CursorKind.UNEXPOSED_EXPR           j                    int        [24    :14 - 24    :15] main.cpp
      CursorKind.DECL_REF_EXPR            j                    int        [24    :14 - 24    :15] main.cpp
    CursorKind.RETURN_STMT                                              [25    :5 - 25    :13] main.cpp
     CursorKind.INTEGER_LITERAL                               int        [25    :12 - 25    :13] main.cpp
</code>```

With this output, and some more testcases which I added to my source code, I understood that I should count as argument every argument that is not UNEXPOSED_EXPR, and if it is UNEXPOSED_EXRP I should check if it has children. If it does it means that I need to count it.

Body:
I'm using libclang with it's python binding and I'm trying to get the number of arguments for CallExpr, I found that if a member function has default value and being called with this argument missing, libclang returns the number of arguments in the function declaration and not as in the call expression.

For example :

class SomeClass
{
public:
    int sum(int x, int y)
    {
        return x + y;
    }

    int sum_def(int x, int y = 0)
    {
        return x + y;
    }
};

int main()
{
    SomeClass x;
    x.sum(10, 100);
    x.sum_def(20);
    return 0;
}

traverse ast using liblcang :

def traverse(node):
    if node.kind == clang.cindex.CursorKind.CALL_EXPR:
        print('%-35s %-20s %-10s [%-6s:%s - %-6s:%s] %s %s ' % (
        node.kind, node.spelling, node.type.spelling, node.extent.start.line, node.extent.start.column,
        node.extent.end.line, node.extent.end.column, node.location.file, node.mangled_name))
        print("%d  " % node.get_num_arguments())
        for arg in node.get_arguments():
            print("ARG=%s %s" % (arg.kind, arg.spelling))

    for child in node.get_children():
        traverse(child)

The output :

CursorKind.CALL_EXPR                sum                  int        [20    :5 - 20    :19] main.cpp
2
ARG=CursorKind.INTEGER_LITERAL
ARG=CursorKind.INTEGER_LITERAL
CursorKind.CALL_EXPR                sum_def              int        [21    :5 - 21    :18] main.cpp
2
ARG=CursorKind.INTEGER_LITERAL
ARG=CursorKind.UNEXPOSED_EXPR

I would expect to get 1 as number of arguments in the CALL_EXPR for sum_def, it is possible to get it or should I parse the code myself, something I don't really want to do.
Thank you.

Body:
I changed a bit the traverse function to print more details

def traverse(node, level):
    print('%s %-35s %-20s %-10s [%-6s:%s - %-6s:%s] %s %s ' % (' ' * level,
    node.kind, node.spelling, node.type.spelling, node.extent.start.line, node.extent.start.column,
    node.extent.end.line, node.extent.end.column, node.location.file, node.mangled_name))
    if node.kind == clang.cindex.CursorKind.CALL_EXPR:
        for arg in node.get_arguments():
            print("ARG=%s %s" % (arg.kind, arg.spelling))

    for child in node.get_children():
        traverse(child, level+1)

The output :

  CursorKind.CLASS_DECL               SomeClass            SomeClass  [2     :1 - 14    :2] main.cpp
   CursorKind.CXX_ACCESS_SPEC_DECL                                     [4     :1 - 4     :8] main.cpp
   CursorKind.CXX_METHOD               sum                  int (int, int) [5     :5 - 8     :6] main.cpp _ZN9SomeClass3sumEii
    CursorKind.PARM_DECL                x                    int        [5     :13 - 5     :18] main.cpp _ZZN9SomeClass3sumEiiE1x
    CursorKind.PARM_DECL                y                    int        [5     :20 - 5     :25] main.cpp _ZZN9SomeClass3sumEiiE1y
    CursorKind.COMPOUND_STMT                                            [6     :5 - 8     :6] main.cpp
     CursorKind.RETURN_STMT                                              [7     :9 - 7     :21] main.cpp
      CursorKind.BINARY_OPERATOR                               int        [7     :16 - 7     :21] main.cpp
       CursorKind.UNEXPOSED_EXPR           x                    int        [7     :16 - 7     :17] main.cpp
        CursorKind.DECL_REF_EXPR            x                    int        [7     :16 - 7     :17] main.cpp
       CursorKind.UNEXPOSED_EXPR           y                    int        [7     :20 - 7     :21] main.cpp
        CursorKind.DECL_REF_EXPR            y                    int        [7     :20 - 7     :21] main.cpp
   CursorKind.CXX_METHOD               sum_def              int (int, int) [10    :5 - 13    :6] main.cpp _ZN9SomeClass7sum_defEii
    CursorKind.PARM_DECL                x                    int        [10    :17 - 10    :22] main.cpp _ZZN9SomeClass7sum_defEiiE1x
    CursorKind.PARM_DECL                y                    int        [10    :24 - 10    :33] main.cpp _ZZN9SomeClass7sum_defEiiE1y
     CursorKind.INTEGER_LITERAL                               int        [10    :32 - 10    :33] main.cpp
    CursorKind.COMPOUND_STMT                                            [11    :5 - 13    :6] main.cpp
     CursorKind.RETURN_STMT                                              [12    :9 - 12    :21] main.cpp
      CursorKind.BINARY_OPERATOR                               int        [12    :16 - 12    :21] main.cpp
       CursorKind.UNEXPOSED_EXPR           x                    int        [12    :16 - 12    :17] main.cpp
        CursorKind.DECL_REF_EXPR            x                    int        [12    :16 - 12    :17] main.cpp
       CursorKind.UNEXPOSED_EXPR           y                    int        [12    :20 - 12    :21] main.cpp
        CursorKind.DECL_REF_EXPR            y                    int        [12    :20 - 12    :21] main.cpp
  CursorKind.FUNCTION_DECL            main                 int ()     [17    :1 - 26    :2] main.cpp main
   CursorKind.COMPOUND_STMT                                            [18    :1 - 26    :2] main.cpp
    CursorKind.DECL_STMT                                                [19    :5 - 19    :22] main.cpp
     CursorKind.VAR_DECL                 i                    int        [19    :5 - 19    :14] main.cpp _ZZ4mainE1i
      CursorKind.INTEGER_LITERAL                               int        [19    :13 - 19    :14] main.cpp
     CursorKind.VAR_DECL                 j                    int        [19    :16 - 19    :21] main.cpp _ZZ4mainE1j
      CursorKind.INTEGER_LITERAL                               int        [19    :20 - 19    :21] main.cpp
    CursorKind.DECL_STMT                                                [20    :5 - 20    :17] main.cpp
     CursorKind.VAR_DECL                 x                    SomeClass  [20    :5 - 20    :16] main.cpp _ZZ4mainE1x
      CursorKind.TYPE_REF                 class SomeClass      SomeClass  [20    :5 - 20    :14] main.cpp
      CursorKind.CALL_EXPR                SomeClass            SomeClass  [20    :15 - 20    :16] main.cpp
    CursorKind.CALL_EXPR                sum                  int        [21    :5 - 21    :19] main.cpp
ARG=CursorKind.INTEGER_LITERAL
ARG=CursorKind.INTEGER_LITERAL
     CursorKind.MEMBER_REF_EXPR          sum                  <bound member function type> [21    :5 - 21    :10] main.cpp
      CursorKind.DECL_REF_EXPR            x                    SomeClass  [21    :5 - 21    :6] main.cpp
     CursorKind.INTEGER_LITERAL                               int        [21    :11 - 21    :13] main.cpp
     CursorKind.INTEGER_LITERAL                               int        [21    :15 - 21    :18] main.cpp
    CursorKind.CALL_EXPR                sum_def              int        [22    :5 - 22    :18] main.cpp
ARG=CursorKind.INTEGER_LITERAL
ARG=CursorKind.UNEXPOSED_EXPR
     CursorKind.MEMBER_REF_EXPR          sum_def              <bound member function type> [22    :5 - 22    :14] main.cpp
      CursorKind.DECL_REF_EXPR            x                    SomeClass  [22    :5 - 22    :6] main.cpp
     CursorKind.INTEGER_LITERAL                               int        [22    :15 - 22    :17] main.cpp
     CursorKind.UNEXPOSED_EXPR                                int        [0     :0 - 0     :0] None
    CursorKind.CALL_EXPR                sum_def              int        [23    :5 - 23    :23] main.cpp
ARG=CursorKind.INTEGER_LITERAL
ARG=CursorKind.INTEGER_LITERAL
     CursorKind.MEMBER_REF_EXPR          sum_def              <bound member function type> [23    :5 - 23    :14] main.cpp
      CursorKind.DECL_REF_EXPR            x                    SomeClass  [23    :5 - 23    :6] main.cpp
     CursorKind.INTEGER_LITERAL                               int        [23    :15 - 23    :17] main.cpp
     CursorKind.INTEGER_LITERAL                               int        [23    :19 - 23    :22] main.cpp
    CursorKind.CALL_EXPR                sum                  int        [24    :5 - 24    :16] main.cpp
ARG=CursorKind.UNEXPOSED_EXPR i
ARG=CursorKind.UNEXPOSED_EXPR j
     CursorKind.MEMBER_REF_EXPR          sum                  <bound member function type> [24    :5 - 24    :10] main.cpp
      CursorKind.DECL_REF_EXPR            x                    SomeClass  [24    :5 - 24    :6] main.cpp
     CursorKind.UNEXPOSED_EXPR           i                    int        [24    :11 - 24    :12] main.cpp
      CursorKind.DECL_REF_EXPR            i                    int        [24    :11 - 24    :12] main.cpp
     CursorKind.UNEXPOSED_EXPR           j                    int        [24    :14 - 24    :15] main.cpp
      CursorKind.DECL_REF_EXPR            j                    int        [24    :14 - 24    :15] main.cpp
    CursorKind.RETURN_STMT                                              [25    :5 - 25    :13] main.cpp
     CursorKind.INTEGER_LITERAL                               int        [25    :12 - 25    :13] main.cpp

With this output, and some more testcases which I added to my source code, I understood that I should count as argument every argument that is not UNEXPOSED_EXPR, and if it is UNEXPOSED_EXRP I should check if it has children. If it does it means that I need to count it.


问:
Android: How to switch from Fragment to Main Activity?
My MainActivity is the Google Maps Activity and I have 2 fragments called "LoginForm" and "appSettings". I can switch from the MainActivity to the 2 fragments, but I can't switch back to MainActivity. I have tried fragment.addToBackStack() but it doesn't do anything. Any idea? Here is the code from the Navigation Drawer.</p>

```<code>public void selectedDrawerItem(MenuItem menuItem){

    Class fragmentClass = null;
    FrameLayout frameLayoutMap = (FrameLayout) findViewById(R.id.main_container_login);

    FragmentManager fragmentManager = getSupportFragmentManager();

    // For every new Fragment, add in Switch statement.
    switch(menuItem.getItemId()) {

        case R.id.nav_geomap:
            fragmentClass = MapsActivity.class;
            break;

        case R.id.nav_login:
            Log.d(TAG, "Accessed fragment: menuItem nav_login");
            //frameLayoutMap.removeAllViews();
            fragmentClass = LoginForm.class;
            break;

        case R.id.nav_settings:
            Log.d(TAG, "Accessed fragment: menuItem nav_settings");
            // frameLayoutMap.removeAllViews();
            fragmentClass = appSettings.class;
            break;

    }
    try
    {
        fragment = (Fragment) fragmentClass.newInstance();

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

    fragmentManager.beginTransaction().replace(R.id.map, fragment).commit();

    menuItem.setChecked(true);
    setTitle(menuItem.getTitle());
    mDrawerLayout.closeDrawers();

}
</code>```

答:
try this</p>

```<code>public void addPage(Fragment fragment) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.add(R.id.content_main, fragment);
            ft.addToBackStack(null);
            ft.commit();
        }

public void forwardPage(final Fragment fragment) {

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.content_main, fragment);
        ft.addToBackStack(null);
        ft.commit();
    }
</code>```

Body:
My MainActivity is the Google Maps Activity and I have 2 fragments called "LoginForm" and "appSettings". I can switch from the MainActivity to the 2 fragments, but I can't switch back to MainActivity. I have tried fragment.addToBackStack() but it doesn't do anything. Any idea? Here is the code from the Navigation Drawer.

public void selectedDrawerItem(MenuItem menuItem){

    Class fragmentClass = null;
    FrameLayout frameLayoutMap = (FrameLayout) findViewById(R.id.main_container_login);

    FragmentManager fragmentManager = getSupportFragmentManager();

    // For every new Fragment, add in Switch statement.
    switch(menuItem.getItemId()) {

        case R.id.nav_geomap:
            fragmentClass = MapsActivity.class;
            break;

        case R.id.nav_login:
            Log.d(TAG, "Accessed fragment: menuItem nav_login");
            //frameLayoutMap.removeAllViews();
            fragmentClass = LoginForm.class;
            break;

        case R.id.nav_settings:
            Log.d(TAG, "Accessed fragment: menuItem nav_settings");
            // frameLayoutMap.removeAllViews();
            fragmentClass = appSettings.class;
            break;

    }
    try
    {
        fragment = (Fragment) fragmentClass.newInstance();

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

    fragmentManager.beginTransaction().replace(R.id.map, fragment).commit();

    menuItem.setChecked(true);
    setTitle(menuItem.getTitle());
    mDrawerLayout.closeDrawers();

}

Body:
try this

public void addPage(Fragment fragment) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.add(R.id.content_main, fragment);
            ft.addToBackStack(null);
            ft.commit();
        }

public void forwardPage(final Fragment fragment) {

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.content_main, fragment);
        ft.addToBackStack(null);
        ft.commit();
    }


问:
What's the problem in my code? c# winforms
I have two forms Login and Main form. Initially, the Login form will be displayed and when the user is authenticated, the Main form will be displayed and the Login form will be closed.

It's kinda working, but I have to click the btnLogin (a Button in the Login form) twice to close the Login form and show the Main form.

Here's my code.

Program.cs (Login form)

```<code>namespace Login
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Login fLogin = new Login();
            if (fLogin.ShowDialog() == DialogResult.OK)
            {
                Application.Run(new Main());
            }
        }
    }
}
</code>```

Login form

```<code>namespace Login
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private void Login_Load(object sender, EventArgs e)
        {

        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            // initially btnLogin has a DialogResult property set to None
            Authenticate();
        }

        private void Authenticate()
        {
            SqlCeConnection conn = new SqlCeConnection(@"Data source=d:/BIMS.sdf");
            conn.Open();
            SqlCeCommand cmd = new SqlCeCommand(Properties.Resources.CheckIfUserExists, conn);
            cmd.Parameters.Add("username", txtUsername.Text.Trim());
            cmd.Parameters.Add("password", txtPassword.Text.Trim());

            SqlCeDataReader dr = cmd.ExecuteReader();
            bool hasRow = dr.Read();
            if (hasRow)
            {
                btnLogin.DialogResult = DialogResult.OK;
            }
        }
    }
}
</code>```

Where do you think I'm doing it wrong?
Thanks....

答:
just change </p>

```<code>if (hasRow)
{
  // btnLogin.DialogResult = DialogResult.OK;
     this.DialogResult = DialogResult.OK;
     this.close();
}
</code>```

Body:
I have two forms Login and Main form. Initially, the Login form will be displayed and when the user is authenticated, the Main form will be displayed and the Login form will be closed.

It's kinda working, but I have to click the btnLogin (a Button in the Login form) twice to close the Login form and show the Main form.

Here's my code.

Program.cs (Login form)

namespace Login
{
    static class Program
    {
        ///
        /// The main entry point for the application.
        ///
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Login fLogin = new Login();
            if (fLogin.ShowDialog() == DialogResult.OK)
            {
                Application.Run(new Main());
            }
        }
    }
}

Login form

namespace Login
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private void Login_Load(object sender, EventArgs e)
        {

        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            // initially btnLogin has a DialogResult property set to None
            Authenticate();
        }

        private void Authenticate()
        {
            SqlCeConnection conn = new SqlCeConnection(@"Data source=d:/BIMS.sdf");
            conn.Open();
            SqlCeCommand cmd = new SqlCeCommand(Properties.Resources.CheckIfUserExists, conn);
            cmd.Parameters.Add("username", txtUsername.Text.Trim());
            cmd.Parameters.Add("password", txtPassword.Text.Trim());

            SqlCeDataReader dr = cmd.ExecuteReader();
            bool hasRow = dr.Read();
            if (hasRow)
            {
                btnLogin.DialogResult = DialogResult.OK;
            }
        }
    }
}

Where do you think I'm doing it wrong?
Thanks....

Body:
just change

if (hasRow)
{
  // btnLogin.DialogResult = DialogResult.OK;
     this.DialogResult = DialogResult.OK;
     this.close();
}


问:
How to display Google Maps with different location in multiple pages?

Is there possible to display a Google Map for each page with different locations ?</p>

答:
the solution is simple you just have to create a js script inside your page and create two variables:

archivo js.js

function initMap() {
        var uluru = {lat: cordenax, lng: cordenay};
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 4,
          center: uluru
        });
        var marker = new google.maps.Marker({
          position: uluru,
          map: map
        });
}```
</div>
</div>
</p>

<p>archivo index.html</p>

<pre class="lang-html prettyprint-override"><code> <body>
    <h3>My Google Maps Demo</h3>
    <div id="map"></div>

 <script type="text/javascript">
    var cordenax = -25.363;

    var cordenay = 131.044;
  </script>

   <script src="js.js"></script>

    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCd71PV2l5xNnRiVat4sKNV56CJcBhyS5E&callback=initMap">
    </script>

  </body>
</code>```

the two variables indicate the coordinates, I hope you have understood

Body:
the solution is simple you just have to create a js script inside your page and create two variables:

archivo js.js

function initMap() {
        var uluru = {lat: cordenax, lng: cordenay};
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 4,
          center: uluru
        });
        var marker = new google.maps.Marker({
          position: uluru,
          map: map
        });
}

archivo index.html

 <body>
    <h3>My Google Maps Demo</h3>
    <div id="map"></div>

 <script type="text/javascript">
    var cordenax = -25.363;

    var cordenay = 131.044;
  </script>

   <script src="js.js"></script>

    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCd71PV2l5xNnRiVat4sKNV56CJcBhyS5E&callback=initMap">
    </script>

  </body>

the two variables indicate the coordinates, I hope you have understood


问:
php evaluating multidimensional array from inner array to outer araray
How do I solve the following problem using PHP RecursiveIteratorIterator?

```<code>$arr = array(
    "sum"=>array(2,4,6, "multiply" => array(1,3,5) ),
    "multiply"=>array(3,3,3, "sum" => array(2,4,6) ),
);
</code>```

I am expecting the following answers

```<code>(2 + 4 + 6 + ( 1 * 3 * 5) ) = 27;
(3 * 3 * 3 * (2 + 4 + 6)) = 324;
</code>```

Partial code so far..

```<code>   $calc = new ArrayObject($arr);
   $MRI = new RecursiveIteratorIterator(new      MyRecursiveIterator($calc), 1);
   foreach ($MRI as $key=>$value) {
   echo " Current Depth: ". $MRI->getDepth() . "\n";
   echo $key . " : " . $value . "\n";
   $currentDepth = $MRI->getDepth();
   for ($subDepth = $currentDepth; $subDepth >= 0; $subDepth--)
   { echo "sub Depth: ". $subDepth . "\n";
   $subIterator = $MRI->getSubIterator($subDepth);
   // var_dump($subIterator); } }
</code>```

答:
Simple and easy solution :-

```<code>$arr = array("sum"=>array(2,4,6, "multiply" => array(1,3,5) ),"multiply"=>array(3,3,3, "sum" => array(2,4,6)));
    foreach($arr as $key => $newarr){
        if($key =="sum"){
            $sum = array_sum($newarr);
            $product = array_product($newarr['multiply']);
            $finalarray[$key] = $sum+$product;
        }elseif($key =="multiply") {
            $product = array_product($newarr);
            $sum = array_sum($newarr['sum']);
            $finalarray[$key] = $sum*$product;
        }
    }
    echo "```"; print_r($finalarray);
```

Hope it helps!

Body:
How do I solve the following problem using PHP RecursiveIteratorIterator?

$arr = array(
    "sum"=>array(2,4,6, "multiply" => array(1,3,5) ),
    "multiply"=>array(3,3,3, "sum" => array(2,4,6) ),
);

I am expecting the following answers

(2 + 4 + 6 + ( 1 * 3 * 5) ) = 27;
(3 * 3 * 3 * (2 + 4 + 6)) = 324;

Partial code so far..

   $calc = new ArrayObject($arr);
   $MRI = new RecursiveIteratorIterator(new      MyRecursiveIterator($calc), 1);
   foreach ($MRI as $key=>$value) {
   echo " Current Depth: ". $MRI->getDepth() . "\n";
   echo $key . " : " . $value . "\n";
   $currentDepth = $MRI->getDepth();
   for ($subDepth = $currentDepth; $subDepth >= 0; $subDepth--)
   { echo "sub Depth: ". $subDepth . "\n";
   $subIterator = $MRI->getSubIterator($subDepth);
   // var_dump($subIterator); } }

Body:
Simple and easy solution :-

$arr = array("sum"=>array(2,4,6, "multiply" => array(1,3,5) ),"multiply"=>array(3,3,3, "sum" => array(2,4,6)));
    foreach($arr as $key => $newarr){
        if($key =="sum"){
            $sum = array_sum($newarr);
            $product = array_product($newarr['multiply']);
            $finalarray[$key] = $sum+$product;
        }elseif($key =="multiply") {
            $product = array_product($newarr);
            $sum = array_sum($newarr['sum']);
            $finalarray[$key] = $sum*$product;
        }
    }
    echo "<pre>"; print_r($finalarray);

Hope it helps!


问:
Use array of a component in another component in angular2
I have an array declared public like :

```<code>public arr: Array<any> = []
</code>```

in AddUserComponent which stores the name of users.

i need this array to be used in another component AddTopicComponent to display the user's names as a dropdown.

How do i use this array values in AddTopicComponent ? these two components are not parent-child component.

答:
You can use @Input for sharing data from container component to inner components. Check this for explanation: https://angular.io/guide/attribute-directives#pass-values-into-the-directive-with-an-input-data-binding

If the relationship between the components is not parent-child, you can use any of below approaches:

Using Services(Most Recommended).

Using Behavior Subjects from RxJS library.

Using browser storage(session/local) but least recommended as prone
to data security.

Body:
I have an array declared public like :

public arr: Array<any> = []

in AddUserComponent which stores the name of users.

i need this array to be used in another component AddTopicComponent to display the user's names as a dropdown.

How do i use this array values in AddTopicComponent ? these two components are not parent-child component.


问:
.net implementation of bcrypt
Does anyone know of a good implementation of bcrypt, I know this question has been asked before but it got very little response.   I'm a bit unsure of just picking an implementation that turns up in google and am thinking that I may be better off using sha256 in the System.Security.Cryptography namespace, at least then I know it's supported!  What are you thoughts?</p>

答:
I needed a BCrypt implementation when moving something from PostgreSQL (which has pg_crypto) to SQLite (which doesn't), so I wrote my own. Seeing from this message I'm not the only one needing this, I've decided to slap a license on it and release it. The URL is:

http://zer7.com/software.php?page=cryptsharp

The Blowfish implementation behind it is a port of Bruce Schneier's public domain C implementation, and succeeds on all the official test vectors.

The BCrypt code I wrote myself based on the spec. I also created a PHP script which generates random passwords of length 0 to 100 and salts, crypts them, and outputs them to a test file. The C# code matches these 100% of the time so far. You are welcome to use the script and test this yourself.

The library also includes PBKDF2 code which works for any HMAC as opposed to .Net's SHA-1-only implementation (added today -- I'm intending to do SCrypt in C# soon and that requires PBKDF2 with HMAC-SHA256). You could make yourself a scheme based on this too, if you wanted.

Title: .net implementation of bcrypt