问:
Empty response from CreateStoredProcedureAsync documentdb
So i am calling this method which was in the sample code provided by microsoft for documentdb but i get a null response when trying to create a new stored procedure.

```<code>private static async Task RunBulkImport(string collectionLink)
    {

        string Datafilepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Data");
        string inputDirectory = Datafilepath;
        string inputFileMask = "*.json";
        int maxFiles = 2000;
        int maxScriptSize = 50000;

        // 1. Get the files.
        string[] fileNames = Directory.GetFiles(inputDirectory, inputFileMask);
        DirectoryInfo di = new DirectoryInfo(inputDirectory);
        FileInfo[] fileInfos = di.GetFiles(inputFileMask);

        // 2. Prepare for import.
        int currentCount = 0;
        int fileCount = maxFiles != 0 ? Math.Min(maxFiles, fileNames.Length) : fileNames.Length;

        // 3. Create stored procedure for this script.
        string procedurepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"SP\BulkImport.js");
        string body = File.ReadAllText(procedurepath);
        StoredProcedure sproc = new StoredProcedure
        {
            Id = "BulkImport",
            Body = body
        };

        await TryDeleteStoredProcedure(collectionLink, sproc.Id);
        sproc = await client.CreateStoredProcedureAsync(collectionLink, sproc);

        while (currentCount < fileCount)
        {
            // 5. Create args for current batch.
            //    Note that we could send a string with serialized JSON and JSON.parse it on the script side,
            //    but that would cause script to run longer. Since script has timeout, unload the script as much
            //    as we can and do the parsing by client and framework. The script will get JavaScript objects.
            string argsJson = CreateBulkInsertScriptArguments(fileNames, currentCount, fileCount, maxScriptSize);
            var args = new dynamic[] { JsonConvert.DeserializeObject<dynamic>(argsJson) };

            // 6. execute the batch.
            StoredProcedureResponse<int> scriptResult = await client.ExecuteStoredProcedureAsync<int>(
                sproc.SelfLink,
                new RequestOptions { PartitionKey = new PartitionKey("Andersen") },
                args);

            // 7. Prepare for next batch.
            int currentlyInserted = scriptResult.Response;
            currentCount += currentlyInserted;
        }

        // 8. Validate
        int numDocs = 0;
        string continuation = string.Empty;
        do
        {
            // Read document feed and count the number of documents.
            FeedResponse<dynamic> response = await client.ReadDocumentFeedAsync(collectionLink, new FeedOptions { RequestContinuation = continuation });
            numDocs += response.Count;

            // Get the continuation so that we know when to stop.
            continuation = response.ResponseContinuation;
        }
        while (!string.IsNullOrEmpty(continuation));

        Console.WriteLine("Found {0} documents in the collection. There were originally {1} files in the Data directory\r\n", numDocs, fileCount);
    }

    private static async Task TryDeleteStoredProcedure(string collectionLink, string sprocId)
    {
        StoredProcedure sproc = client.CreateStoredProcedureQuery(collectionLink).Where(s => s.Id == sprocId).AsEnumerable().FirstOrDefault();
        if (sproc != null)
        {
            await client.DeleteStoredProcedureAsync(sproc.SelfLink);
        }
    }

    private static string CreateBulkInsertScriptArguments(string[] docFileNames, int currentIndex, int maxCount, int maxScriptSize)
    {
        var jsonDocumentArray = new StringBuilder();
        jsonDocumentArray.Append("[");

        if (currentIndex >= maxCount) return string.Empty;
        jsonDocumentArray.Append(File.ReadAllText(docFileNames[currentIndex]));

        int scriptCapacityRemaining = maxScriptSize;
        string separator = string.Empty;

        int i = 1;
        while (jsonDocumentArray.Length < scriptCapacityRemaining && (currentIndex + i) < maxCount)
        {
            jsonDocumentArray.Append(", " + File.ReadAllText(docFileNames[currentIndex + i]));
            i++;
        }

        jsonDocumentArray.Append("]");
        return jsonDocumentArray.ToString();
    }
</code>```

And here is the BulkImport.js file

```<code>function bulkImport(docs) {
var collection = getContext().getCollection();
var collectionLink = collection.getSelfLink();

   //count used as doc index
var count = 0;

// Validate input
if (!docs) throw new Error("The array is undefined or null.");

var docsLength = docs.length;
if (docsLength == 0) {
    getContext().getResponse().setBody(0);
}

// CRUD API to create a document.
tryCreate(docs[count], callback);

function tryCreate(doc, callback) {
    var options = {
        disableAutomaticIdGeneration: true
    };

    var isAccepted = collection.createDocument(collectionLink, doc, options, callback);

    if (!isAccepted) getContext().getResponse().setBody(count);
}

function callback(err, doc, options) {
    if (err) throw err;
    count++;

    if (count >= docsLength) {
          getContext().getResponse().setBody(count);
    } else {

        tryCreate(docs[count], callback);
    }
}
}
</code>```

And in the data folder i have 100 json files which was provided in the sample itself.Kindly help me to get create the new procedure i am using documentdb emulator.

答:
I can create the new procedure with documentdb emulator. As I know it is not support to execute stored procedure with documentDB Emulator exploer currently. Following is my detail steps:

1.Download the documentdb-emulator and install it in the local machine

2.Download the document demo code from github.

3.We can get local documentdb account master key from the document, and add it to the project

The DocumentDB Emulator supports only a single fixed account and a well-known master key. Key regeneration is not possible in the DocumentDB Emulator

```<code>// Connect to the DocumentDB Emulator running locally

   DocumentClient client = new DocumentClient(new Uri("https://localhost:8081"),"C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==");
</code>```

4.Open documentdb emulator to create db and collection

5.Execute the demo code and check the result from the azure emulator exploer.

Note:  According to the screenshot, we can find that there no input or result field on the selected  procedure tab with azure documentdb emulator.

If we use azure documentdb then we can use executed the procedure from the Azure portal with Azure documentdb.

If we have any issue about documentdb emulator we can give our feedback the azure documentdb team by click feedback on the documentdb emulator exploer.

Body:
So i am calling this method which was in the sample code provided by microsoft for documentdb but i get a null response when trying to create a new stored procedure.

private static async Task RunBulkImport(string collectionLink)
    {

        string Datafilepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Data");
        string inputDirectory = Datafilepath;
        string inputFileMask = "*.json";
        int maxFiles = 2000;
        int maxScriptSize = 50000;

        // 1. Get the files.
        string[] fileNames = Directory.GetFiles(inputDirectory, inputFileMask);
        DirectoryInfo di = new DirectoryInfo(inputDirectory);
        FileInfo[] fileInfos = di.GetFiles(inputFileMask);

        // 2. Prepare for import.
        int currentCount = 0;
        int fileCount = maxFiles != 0 ? Math.Min(maxFiles, fileNames.Length) : fileNames.Length;

        // 3. Create stored procedure for this script.
        string procedurepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"SP\BulkImport.js");
        string body = File.ReadAllText(procedurepath);
        StoredProcedure sproc = new StoredProcedure
        {
            Id = "BulkImport",
            Body = body
        };

        await TryDeleteStoredProcedure(collectionLink, sproc.Id);
        sproc = await client.CreateStoredProcedureAsync(collectionLink, sproc);

        while (currentCount < fileCount)
        {
            // 5. Create args for current batch.
            //    Note that we could send a string with serialized JSON and JSON.parse it on the script side,
            //    but that would cause script to run longer. Since script has timeout, unload the script as much
            //    as we can and do the parsing by client and framework. The script will get JavaScript objects.
            string argsJson = CreateBulkInsertScriptArguments(fileNames, currentCount, fileCount, maxScriptSize);
            var args = new dynamic[] { JsonConvert.DeserializeObject<dynamic>(argsJson) };

            // 6. execute the batch.
            StoredProcedureResponse<int> scriptResult = await client.ExecuteStoredProcedureAsync<int>(
                sproc.SelfLink,
                new RequestOptions { PartitionKey = new PartitionKey("Andersen") },
                args);

            // 7. Prepare for next batch.
            int currentlyInserted = scriptResult.Response;
            currentCount += currentlyInserted;
        }

        // 8. Validate
        int numDocs = 0;
        string continuation = string.Empty;
        do
        {
            // Read document feed and count the number of documents.
            FeedResponse<dynamic> response = await client.ReadDocumentFeedAsync(collectionLink, new FeedOptions { RequestContinuation = continuation });
            numDocs += response.Count;

            // Get the continuation so that we know when to stop.
            continuation = response.ResponseContinuation;
        }
        while (!string.IsNullOrEmpty(continuation));

        Console.WriteLine("Found {0} documents in the collection. There were originally {1} files in the Data directory\r\n", numDocs, fileCount);
    }

    private static async Task TryDeleteStoredProcedure(string collectionLink, string sprocId)
    {
        StoredProcedure sproc = client.CreateStoredProcedureQuery(collectionLink).Where(s => s.Id == sprocId).AsEnumerable().FirstOrDefault();
        if (sproc != null)
        {
            await client.DeleteStoredProcedureAsync(sproc.SelfLink);
        }
    }

    private static string CreateBulkInsertScriptArguments(string[] docFileNames, int currentIndex, int maxCount, int maxScriptSize)
    {
        var jsonDocumentArray = new StringBuilder();
        jsonDocumentArray.Append("[");

        if (currentIndex >= maxCount) return string.Empty;
        jsonDocumentArray.Append(File.ReadAllText(docFileNames[currentIndex]));

        int scriptCapacityRemaining = maxScriptSize;
        string separator = string.Empty;

        int i = 1;
        while (jsonDocumentArray.Length < scriptCapacityRemaining && (currentIndex + i) < maxCount)
        {
            jsonDocumentArray.Append(", " + File.ReadAllText(docFileNames[currentIndex + i]));
            i++;
        }

        jsonDocumentArray.Append("]");
        return jsonDocumentArray.ToString();
    }

And here is the BulkImport.js file

function bulkImport(docs) {
var collection = getContext().getCollection();
var collectionLink = collection.getSelfLink();

   //count used as doc index
var count = 0;

// Validate input
if (!docs) throw new Error("The array is undefined or null.");

var docsLength = docs.length;
if (docsLength == 0) {
    getContext().getResponse().setBody(0);
}

// CRUD API to create a document.
tryCreate(docs[count], callback);

function tryCreate(doc, callback) {
    var options = {
        disableAutomaticIdGeneration: true
    };

    var isAccepted = collection.createDocument(collectionLink, doc, options, callback);

    if (!isAccepted) getContext().getResponse().setBody(count);
}

function callback(err, doc, options) {
    if (err) throw err;
    count++;

    if (count >= docsLength) {
          getContext().getResponse().setBody(count);
    } else {

        tryCreate(docs[count], callback);
    }
}
}

And in the data folder i have 100 json files which was provided in the sample itself.Kindly help me to get create the new procedure i am using documentdb emulator.

Body:
I can create the new procedure with documentdb emulator. As I know it is not support to execute stored procedure with documentDB Emulator exploer currently. Following is my detail steps:

1.Download the documentdb-emulator and install it in the local machine

2.Download the document demo code from github.

3.We can get local documentdb account master key from the document, and add it to the project

The DocumentDB Emulator supports only a single fixed account and a well-known master key. Key regeneration is not possible in the DocumentDB Emulator

// Connect to the DocumentDB Emulator running locally

   DocumentClient client = new DocumentClient(new Uri("https://localhost:8081"),"C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==");

4.Open documentdb emulator to create db and collection

5.Execute the demo code and check the result from the azure emulator exploer.

Note:  According to the screenshot, we can find that there no input or result field on the selected  procedure tab with azure documentdb emulator.

If we use azure documentdb then we can use executed the procedure from the Azure portal with Azure documentdb.

If we have any issue about documentdb emulator we can give our feedback the azure documentdb team by click feedback on the documentdb emulator exploer.


来源: stackexchange

问:
should i always try to avoid grok parse errors?
I have a field in my logs that I match for as an IP address like this:

```<code>grok {
  match => [ "field1", "(?:(?<field2>%{IP})|(%{IP}),\+)"]
}
</code>```

Sometimes this field1 is blank so field2 never gets created in the doc.

This is good because I don't want this field to be added unless it is a valid IP address.

But when this happens the doc is tagged with _grokparsefailure. Is this bad? Does this mean I'm doing something wrong and I should avoid _grokparsefailures.

答: All _grokparsefailure is, is a breadcrumb for the maintainer signifying some grok rules may need updating. Performance-wise, it has no meaning for a rule as short as that one. If you really don't care about misses on a grok statement, you can tell it to tag it some other way (tag_on_failure => ["something"]).

ContentLicense: CC BY-SA 3.0

Body:
I have a field in my logs that I match for as an IP address like this:

grok {
  match => [ "field1", "(?:(?<field2>%{IP})|(%{IP}),\+)"]
}

Sometimes this field1 is blank so field2 never gets created in the doc.

This is good because I don't want this field to be added unless it is a valid IP address.

But when this happens the doc is tagged with _grokparsefailure. Is this bad? Does this mean I'm doing something wrong and I should avoid _grokparsefailures.


问:
SSIS Parameters With Functions
I've done quite a bit of searching on this but haven't been able to come up with a solid solution.  I have a use case where for example I want to include the date in the file name, let's say I use the following formula:

```<code>"EmployeeCount_"+(DT_STR,4,1252)DATEPART( "yyyy" , getdate() )+ RIGHT("0" + (DT_STR,4,1252)DATEPART( "mm" , getdate() ), 2)  + RIGHT("0" + (DT_STR,4,1252)DATEPART( "dd" , getdate() ), 2) +".csv"
</code>```

This works out great as a variable, but what if I want to pass this function as a parameter from SSMS?  Is there a way for Parameters to be evaluated as a expression?  I attempted passing the parameter into a variable to achieve the desired effect to no available.

Am I missing something here, or should I just be hard coding this into a variable / calculating this elsewhere and pulling it into SSIS from a table?

答:
First you have to create 2 variables p_Date of type DateTime and Filename of type String

In the properties tab set EvaluateAsExpressions = True for the variable Filename and Use the following expressions

```<code>"EmployeeCount_"+(DT_STR,4,1252)DATEPART( "yyyy" , @[User::p_Date]  )+ RIGHT("0" + (DT_STR,4,1252)DATEPART( "mm" ,  @[User::p_Date]  ), 2)  + RIGHT("0" + (DT_STR,4,1252)DATEPART( "dd" ,  @[User::p_Date] ), 2) +".csv"
</code>```

Add an Execute SQL Task

Set ResultSetproperty to Single Row

Fill the SqlCommand  and Connection property

Go to ResultSet Tab , Add a New Result Set like shown in the image below

Note: 0 in the image above means the index of column from the sql command your provided

Title: SSIS Parameters With Functions

Body:
I've done quite a bit of searching on this but haven't been able to come up with a solid solution.  I have a use case where for example I want to include the date in the file name, let's say I use the following formula:

"EmployeeCount_"+(DT_STR,4,1252)DATEPART( "yyyy" , getdate() )+ RIGHT("0" + (DT_STR,4,1252)DATEPART( "mm" , getdate() ), 2)  + RIGHT("0" + (DT_STR,4,1252)DATEPART( "dd" , getdate() ), 2) +".csv"

This works out great as a variable, but what if I want to pass this function as a parameter from SSMS?  Is there a way for Parameters to be evaluated as a expression?  I attempted passing the parameter into a variable to achieve the desired effect to no available.

Am I missing something here, or should I just be hard coding this into a variable / calculating this elsewhere and pulling it into SSIS from a table?

Body:
First you have to create 2 variables p_Date of type DateTime and Filename of type String

In the properties tab set EvaluateAsExpressions = True for the variable Filename and Use the following expressions

"EmployeeCount_"+(DT_STR,4,1252)DATEPART( "yyyy" , @[User::p_Date]  )+ RIGHT("0" + (DT_STR,4,1252)DATEPART( "mm" ,  @[User::p_Date]  ), 2)  + RIGHT("0" + (DT_STR,4,1252)DATEPART( "dd" ,  @[User::p_Date] ), 2) +".csv"

Add an Execute SQL Task

Set ResultSetproperty to Single Row

Fill the SqlCommand  and Connection property

Go to ResultSet Tab , Add a New Result Set like shown in the image below

Note: 0 in the image above means the index of column from the sql command your provided


问:
Apply filter to stream in Java
Given the following code I expect the output to be "-3-2-101231" since the filter should go through all the items of the stream, thus printing the item that is evaluating. When the allMatch function is evaluated it should print "1" since it is receiving a stream of positive integers, so it should short-circuit after finding that the first element is not negative.

Why does it print "-3-2-1011" instead of "-3-2-101231"?

```<code>    List<Integer> list = Arrays.asList(-3,-2,-1,0,1,2,3);
    Predicate<Integer> positive = i->{
        System.out.print(i);
        return i>0;
    };
    Predicate<Integer> negative = i->{
        System.out.print(i);
        return i<0;
    };

    list.stream().filter(positive).allMatch(negative);
</code>```

答:
No, the filter should not go through every item in the stream. That would be a waste. As soon the allMatch() operation sees a non-negative item, the pipeline terminates.

There is no guarantee that all items in the stream will be filtered; the guarantee is that any item that is tested by allMatch() has first passed the preceding filter.

The output you see is -3 -2 -1 0 1 from the filter, then 1 from the final predicate, which terminates the process. There's no need to fetch 2 from the upstream filter operation when the terminal operation has already determined its result.

In the words of the documentation, Stream is

— Laziness-seeking. Many stream operations, such as filtering, mapping, or duplicate removal, can be implemented lazily, exposing opportunities for optimization. For example, "find the first String with three consecutive vowels" need not examine all the input strings. Stream operations are divided into intermediate (Stream-producing) operations and terminal (value- or side-effect-producing) operations. Intermediate operations are always lazy.

And,

Processing streams lazily allows for significant efficiencies; in a pipeline such as the filter-map-sum example above, filtering, mapping, and summing can be fused into a single pass on the data, with minimal intermediate state. Laziness also allows avoiding examining all the data when it is not necessary; for operations such as "find the first string longer than 1000 characters", it is only necessary to examine just enough strings to find one that has the desired characteristics without examining all of the strings available from the source. (This behavior becomes even more important when the input stream is infinite and not merely large.)

Title: Apply filter to stream in Java

Body:
Given the following code I expect the output to be "-3-2-101231" since the filter should go through all the items of the stream, thus printing the item that is evaluating. When the allMatch function is evaluated it should print "1" since it is receiving a stream of positive integers, so it should short-circuit after finding that the first element is not negative.

Why does it print "-3-2-1011" instead of "-3-2-101231"?

    List<Integer> list = Arrays.asList(-3,-2,-1,0,1,2,3);
    Predicate<Integer> positive = i->{
        System.out.print(i);
        return i>0;
    };
    Predicate<Integer> negative = i->{
        System.out.print(i);
        return i<0;
    };

    list.stream().filter(positive).allMatch(negative);


问:
User data not showing on Html page in Ionic 2 and Firebase 3
I am using a project to get some user data from Firebase.  I want to put that data into a "Profile page".  Everything works except for one problem.  The data doesn't show on the html page until I click on an item in the page, like to edit some data for example.  The data will also show if I click back, then reenter the page.  So it's like the data loads the blank template, but never updates it once the data from Facebook is received.  Any suggestions?  Here is some of the code from the page.

profile.html

```<code><ion-header>
  <ion-navbar color="primary">
    <ion-title>Profile</ion-title>
    <ion-buttons end>
      <button ion-button item-left icon-right (click)="logOut()">
        <ion-icon name=""></ion-icon>
        Logout
      </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-list>
    <ion-list-header>
      Personal Information
    </ion-list-header>

    <ion-item (click)="updateName()">
      <ion-grid>
        <ion-row>
          <ion-col width-50>
            Name
          </ion-col>
          <ion-col *ngIf="userProfile?.firstName || userProfile?.lastName">
            {{userProfile?.firstName}} {{userProfile?.lastName}}
          </ion-col>
          <ion-col class="placeholder-profile" *ngIf="!userProfile?.firstName">
            <span>
              Tap here to edit.
            </span>
          </ion-col>
        </ion-row>
      </ion-grid>
    </ion-item>

    <ion-item>
      <ion-label class="dob-label">Date of Birth</ion-label>
      <ion-datetime displayFormat="MMM D, YYYY" pickerFormat="D MMM YYYY"
        [(ngModel)]="birthDate" (ionChange)="updateDOB(birthDate)"></ion-datetime>
    </ion-item>

    <ion-item (click)="updateEmail()">
      <ion-grid>
        <ion-row>
          <ion-col width-50>
            Email
          </ion-col>
          <ion-col width-50 *ngIf="userProfile?.email">
            {{userProfile?.email}}
          </ion-col>
          <ion-col class="placeholder-profile" *ngIf="!userProfile?.email">
            <span>
              Tap here to edit.
            </span>
          </ion-col>
        </ion-row>
      </ion-grid>
    </ion-item>

    <ion-item (click)="updatePassword()">
      <ion-grid>
        <ion-row>
          <ion-col width-50>
            Password
          </ion-col>
          <ion-col class="placeholder-profile">
            <span>
              Tap here to edit.
            </span>
          </ion-col>
        </ion-row>
      </ion-grid>
    </ion-item>
  </ion-list>
</ion-content>
</code>```

Here is the code from the profile.ts page

```<code>import { NavController, AlertController } from 'ionic-angular';
import { Component } from '@angular/core';
import { ProfileData } from '../../providers/profile-data';
import { AuthData } from '../../providers/auth-data';
import { LoginPage } from '../login/login';

@Component({
  selector: 'page-profile',
  templateUrl: 'profile.html',
})
export class ProfilePage {
  public userProfile: any;
  public birthDate: string;
  zone: NgZone;

  constructor(public navCtrl: NavController, public profileData: ProfileData,
    public authData: AuthData, public alertCtrl: AlertController) {
  }

  ionViewDidEnter(){
    this.profileData.getUserProfile().on('value', (data) => {
      this.userProfile = data.val();
      this.birthDate = this.userProfile.birthDate;
    });
  }
</code>```

I also tried wrapping it in an NgZone object as suggested by others, which looks like this:

```<code>import { NavController, AlertController } from 'ionic-angular';
import { Component } from '@angular/core';
import { ProfileData } from '../../providers/profile-data';
import { AuthData } from '../../providers/auth-data';
import { LoginPage } from '../login/login';
import { NgZone } from '@angular/core';

@Component({
  selector: 'page-profile',
  templateUrl: 'profile.html',
})
export class ProfilePage {
  public userProfile: any;
  public birthDate: string;
  zone: NgZone;

  constructor(public navCtrl: NavController, public profileData: ProfileData,
    public authData: AuthData, public alertCtrl: AlertController) {
    this.zone = new NgZone({});

    this.zone.run(() => {
      //Your promise code
      this.profileData.getUserProfile().on('value', (data) => {
        this.userProfile = data.val();
        this.birthDate = this.userProfile.birthDate;
      });
    });

  }
</code>```

None of this seems to work.  The data is there, it just doesn't show until I click on an item/UI object, then it populates correctly.  Help!

答:
You have to do it like below.Hope code is self-explanatory.If you have any question, please comment below.

How to install Angularfire2?

ProfileData.ts

```<code>import { AngularFire, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2';

@Injectable()
export class ProfileData {

     constructor(public af: AngularFire) {}

     getUserProfile(data: string): FirebaseObjectObservable<any> {
        return this.af.database.object(`path-to-your-firebase-object`);
      }
}
</code>```

YourComponent.ts

```<code>public profile: any;

 constructor(public profileData: ProfileData) {

    this.profileData.getUserProfile(your-user-id).subscribe(profileSnap => {
      this.profile= profileSnap ;
    });
  }
</code>```

Body:
I am using a project to get some user data from Firebase.  I want to put that data into a "Profile page".  Everything works except for one problem.  The data doesn't show on the html page until I click on an item in the page, like to edit some data for example.  The data will also show if I click back, then reenter the page.  So it's like the data loads the blank template, but never updates it once the data from Facebook is received.  Any suggestions?  Here is some of the code from the page.

profile.html

<ion-header>
  <ion-navbar color="primary">
    <ion-title>Profile</ion-title>
    <ion-buttons end>
      <button ion-button item-left icon-right (click)="logOut()">
        <ion-icon name=""></ion-icon>
        Logout
      </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-list>
    <ion-list-header>
      Personal Information
    </ion-list-header>

    <ion-item (click)="updateName()">
      <ion-grid>
        <ion-row>
          <ion-col width-50>
            Name
          </ion-col>
          <ion-col *ngIf="userProfile?.firstName || userProfile?.lastName">
            {{userProfile?.firstName}} {{userProfile?.lastName}}
          </ion-col>
          <ion-col class="placeholder-profile" *ngIf="!userProfile?.firstName">

              Tap here to edit.

          </ion-col>
        </ion-row>
      </ion-grid>
    </ion-item>

    <ion-item>
      <ion-label class="dob-label">Date of Birth</ion-label>
      <ion-datetime displayFormat="MMM D, YYYY" pickerFormat="D MMM YYYY"
        [(ngModel)]="birthDate" (ionChange)="updateDOB(birthDate)"></ion-datetime>
    </ion-item>

    <ion-item (click)="updateEmail()">
      <ion-grid>
        <ion-row>
          <ion-col width-50>
            Email
          </ion-col>
          <ion-col width-50 *ngIf="userProfile?.email">
            {{userProfile?.email}}
          </ion-col>
          <ion-col class="placeholder-profile" *ngIf="!userProfile?.email">

              Tap here to edit.

          </ion-col>
        </ion-row>
      </ion-grid>
    </ion-item>

    <ion-item (click)="updatePassword()">
      <ion-grid>
        <ion-row>
          <ion-col width-50>
            Password
          </ion-col>
          <ion-col class="placeholder-profile">

              Tap here to edit.

          </ion-col>
        </ion-row>
      </ion-grid>
    </ion-item>
  </ion-list>
</ion-content>

Here is the code from the profile.ts page

import { NavController, AlertController } from 'ionic-angular';
import { Component } from '@angular/core';
import { ProfileData } from '../../providers/profile-data';
import { AuthData } from '../../providers/auth-data';
import { LoginPage } from '../login/login';

@Component({
  selector: 'page-profile',
  templateUrl: 'profile.html',
})
export class ProfilePage {
  public userProfile: any;
  public birthDate: string;
  zone: NgZone;

  constructor(public navCtrl: NavController, public profileData: ProfileData,
    public authData: AuthData, public alertCtrl: AlertController) {
  }

  ionViewDidEnter(){
    this.profileData.getUserProfile().on('value', (data) => {
      this.userProfile = data.val();
      this.birthDate = this.userProfile.birthDate;
    });
  }

I also tried wrapping it in an NgZone object as suggested by others, which looks like this:

import { NavController, AlertController } from 'ionic-angular';
import { Component } from '@angular/core';
import { ProfileData } from '../../providers/profile-data';
import { AuthData } from '../../providers/auth-data';
import { LoginPage } from '../login/login';
import { NgZone } from '@angular/core';

@Component({
  selector: 'page-profile',
  templateUrl: 'profile.html',
})
export class ProfilePage {
  public userProfile: any;
  public birthDate: string;
  zone: NgZone;

  constructor(public navCtrl: NavController, public profileData: ProfileData,
    public authData: AuthData, public alertCtrl: AlertController) {
    this.zone = new NgZone({});

    this.zone.run(() => {
      //Your promise code
      this.profileData.getUserProfile().on('value', (data) => {
        this.userProfile = data.val();
        this.birthDate = this.userProfile.birthDate;
      });
    });

  }

None of this seems to work.  The data is there, it just doesn't show until I click on an item/UI object, then it populates correctly.  Help!

Body:
You have to do it like below.Hope code is self-explanatory.If you have any question, please comment below.

How to install Angularfire2?

ProfileData.ts

import { AngularFire, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2';

@Injectable()
export class ProfileData {

     constructor(public af: AngularFire) {}

     getUserProfile(data: string): FirebaseObjectObservable<any> {
        return this.af.database.object(`path-to-your-firebase-object`);
      }
}

YourComponent.ts

public profile: any;

 constructor(public profileData: ProfileData) {

    this.profileData.getUserProfile(your-user-id).subscribe(profileSnap => {
      this.profile= profileSnap ;
    });
  }


问:
Javascript - create text file on website
So I have a web page, and I would like to programaticly create a text file (lets say it has the words 'hello, I am a text file' in it) on a new directory on my website. The program will be in another directory on the website.

e.g.
https://www.example.com/txtbuild.html is trying to programaticly make https://www.example.com/texts/hi.txt

Is there a way to do this with HTML/Javascript?

EDIT:
I am on Github

答:
If, when you say "JavaScript", you're referring to a node.js application running on a server, then this is possible. It doesn't have to be node though; it could be a Django site, or an ASP.Net site, doesn't matter. You can't have JS code in the browser create files on your server... the JS in the browser is executing on a client machine, and doesn't have access to the server's file system.

You could create an endpoint to which your clients could send requests that would initiate the creation of the file.

You could also allow clients to PUT or POST files to your server, but again, this is something you control from the server side of the application. Your webpage (i.e., HTML file as you put it) cannot create files on the server itself. Your server allows clients to send it files in a specific manner, and the client must adhere to those rules.


问:
Does Owin Middleware support setting JWT tokens in HttpOnly cookies?
I'm using The Microsoft.Owin.Security.Jwt provider for auth in a HTML5/ASP .NET application - to make it more secure, is there anyway to instruct the API to write/read the token to a HttpOnly and Secure (HTTPS) only cookie? At the moment, it's returning the token via the HTTP response body and expecting the token to be sent on the 'Authorization' header.

Thanks.

答: JWT and Cookies are very different concepts and they should not be mixed.</p>


问:
Gitlab local project: Remove connection to original origin and upload to my new repo
So I followed and completed this ECMAScript 6 Tutorial yesterday, with no issues whatsoever. And since I am new to Git and was eager to practice the command lines as I go, I maintained some commits as I went through the tutorial (without pushing, of course, because the origin was not mine).

And then just today, I have realized that I did something wrong. Instead of cloning the project straight from the source, I should have created it inside my own Gitlab account instead, via the

feature. This way, I could have been able to push my changes to an origin, and then optionally continue adding more to the project later on, as part of my ECMAScript coding practice.

I tried the instructions from this answer, but it gave me a fatal: remote origin already exists error (see screenshot below).

The way I understand it, I cannot upload the local copy of the project to my new repo, because it is still connected to its original repo (correct me if I'm wrong).

QUESTION: Is there a way to do this?

Of course, I can always do the manual process: create a new project via Git Repo by URL, then go over the tutorial again... but if there's a faster way, I'd like to learn how. Please help.

答:
git remote add origin failed because there is already a remote called origin.

You can upload to a new remote without removing origin, just add it with a different name:

```<code>git remote add test19-gitlab YOUR_REPO_URL
</code>```

and push (the remote name is needed here):

```<code>git push test19-gitlab
</code>```

Body:
git remote add origin failed because there is already a remote called origin.

You can upload to a new remote without removing origin, just add it with a different name:

git remote add test19-gitlab YOUR_REPO_URL

and push (the remote name is needed here):

git push test19-gitlab


问:
Updating an HTML list using Js
So I have a js game like scrabble. Now when the user makes a new word, I would like the word to be added to a list that is displayed in a div on my page.
The issue is I quite don't understand, how I could keep my old word created and insert a new word with new formatting and everything in a list form.

I know there is a list tag --

```<code><ul>
     <li>apple</li>
     <li>ball</li>
</ul>
</code>```

but what I can't really figure out is how do I use java script to enter the word as a new list entry.

I have used js to display the word created by the following syntax

```<code>document.getElementById('currentword').innerHTML = word;
</code>```

where word is the variable that holds the current word created and currentword is the div id. but how do I use this kind of syntax for a list?
Please help!

Thanks

EDIT: I would also like the last entry to the list as the first item on my list. Seems like the list populates itself but the latest entry gets hidden and the list doesn't really auto scroll down as the items are added.
PS: Also incase someone knows how I could replace the tacky scroll bar option generated by CSS to a custom scroll bar. It would be great if you could point me in the correct direction!

答:
Basic idea:</p>

```<code>var li = document.createElement("li");
li.innerHTML = "new text";
document.getElementById("TheULsId").appendChild(li);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Updating an HTML list using Js

Body:
So I have a js game like scrabble. Now when the user makes a new word, I would like the word to be added to a list that is displayed in a div on my page.
The issue is I quite don't understand, how I could keep my old word created and insert a new word with new formatting and everything in a list form.

I know there is a list tag --

apple

ball

but what I can't really figure out is how do I use java script to enter the word as a new list entry.

I have used js to display the word created by the following syntax

document.getElementById('currentword').innerHTML = word;

where word is the variable that holds the current word created and currentword is the div id. but how do I use this kind of syntax for a list?
Please help!

Thanks

EDIT: I would also like the last entry to the list as the first item on my list. Seems like the list populates itself but the latest entry gets hidden and the list doesn't really auto scroll down as the items are added.
PS: Also incase someone knows how I could replace the tacky scroll bar option generated by CSS to a custom scroll bar. It would be great if you could point me in the correct direction!

Body:
Basic idea:

var li = document.createElement("li");
li.innerHTML = "new text";
document.getElementById("TheULsId").appendChild(li);


问:
What pattern is this using?
In order to add some behavior into onScroll event of ListView，I added some code by subclass ListView like this:

```<code>class MyListView extends ListView{
      public void setOnScrollListener(OnScrollListener listener){
            final OnScrollListener lis = new OnScrollListener(){
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                listener.onScrollStateChanged(view, scrollState);
                //below is added behavior of my Listview
                }
            }

        super.setOnScrollListener(lis);
      }
}
</code>```

and the usage of it is simple:

```<code>MyListView myList = new MyListView(...);
myList.setOnScrollListener(new OnScrollListener(){...});//here is the old logic
</code>```

this sounds like Decorator pattern but it is not, because there is no composite but only inheritance(in facto I do not need composite here).

So the problem is what should I call it?

答: It is called Inheritance. It is an OOP concept if you don't already know.

Title: What pattern is this using?

Body:
In order to add some behavior into onScroll event of ListView，I added some code by subclass ListView like this:

class MyListView extends ListView{
      public void setOnScrollListener(OnScrollListener listener){
            final OnScrollListener lis = new OnScrollListener(){
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                listener.onScrollStateChanged(view, scrollState);
                //below is added behavior of my Listview
                }
            }

        super.setOnScrollListener(lis);
      }
}

and the usage of it is simple:

MyListView myList = new MyListView(...);
myList.setOnScrollListener(new OnScrollListener(){...});//here is the old logic

this sounds like Decorator pattern but it is not, because there is no composite but only inheritance(in facto I do not need composite here).

So the problem is what should I call it?


问:
Build nested JSON in Javascript
I would like to replicate this example data set into nested JSON using JavaScript or Angularjs or any javascript library.

Data:

```<code>PrimaryId,FirstName,LastName,City,CarName,DogName
100,John,Smith,NewYork,Toyota,Spike
100,John,Smith,NewYork,BMW,Spike
100,John,Smith,NewYork,Toyota,Rusty
100,John,Smith,NewYork,BMW,Rusty
101,Ben,Swan,Sydney,Volkswagen,Buddy
101,Ben,Swan,Sydney,Ford,Buddy
101,Ben,Swan,Sydney,Audi,Buddy
101,Ben,Swan,Sydney,Volkswagen,Max
101,Ben,Swan,Sydney,Ford,Max
101,Ben,Swan,Sydney,Audi,Max
102,Julia,Brown,London,Mini,Lucy
</code>```

Javascript:

```<code>var file = reader.result;
var singleRow = readerFile.split(/\r\n|\n/);
var header = singleRow[0].split(',');
var result =[];

    for ( var i=1; i < file.length; i++ ){
        var elementData = singleRow[i].split(',');
        elementData = elementData.filter(function(n){ return n != "" });
        var Obj = {};

        for ( var j=0; j < header.length; j++ ){
            Obj[header[j]] = elementData[j];
            /*
              - How can i build child object and append back to Obj before j loop
              - How can i build multiple child for same parent
            */
        }
        result.push(Obj);
    }
    console.log(" Print the JSON Object : " + JSON.stringify(result));
</code>```

Desired Output:

```<code>{
    "data": [
        {
            "City": "NewYork",
            "FirstName": "John",
            "PrimaryId": 100,
            "LastName": "Smith",
            "CarName": [
                "Toyota",
                "BMW"
            ],
            "DogName": [
                "Spike",
                "Rusty"
            ]
        },
        {
            "City": "Sydney",
            "FirstName": "Ben",
            "PrimaryId": 101,
            "LastName": "Swan",
            "CarName": [
                "Volkswagen",
                "Ford",
                "Audi"
            ],
            "DogName": [
                "Buddy",
                "Max"
            ]
        },
        {
            "City": "London",
            "FirstName": "Julia",
            "PrimaryId": 102,
            "LastName": "Brown",
            "CarName": [
                "Mini"
            ],
            "DogName": [
                "Lucy"
            ]
        }
    ]
}
</code>```

If Firstname, Lastname and City has same values then CarName and DogName values should be child object under the same parent

答:
Made a fiddle for you, it gives the desired output with some things in a different order than you presented.

You can save the indexes of the headers:

```<code>var Index = {};
for(var k = 0; k < header.length; k++)
{
    Index[header[k]] = k;
}
</code>```

And keep a list of cities:

```<code>var cities = [];
....
cities.push(data[Index["City"]]);
</code>```

To use for later so that you don't keep making more objects if the city already exists:

```<code>obj = result.data[cities.indexOf(data[Index["City"]])];
</code>```

The JSFiddle: https://jsfiddle.net/3u28aon3/1/

Title: Build nested JSON in Javascript

Body:
I would like to replicate this example data set into nested JSON using JavaScript or Angularjs or any javascript library.

Data:

PrimaryId,FirstName,LastName,City,CarName,DogName
100,John,Smith,NewYork,Toyota,Spike
100,John,Smith,NewYork,BMW,Spike
100,John,Smith,NewYork,Toyota,Rusty
100,John,Smith,NewYork,BMW,Rusty
101,Ben,Swan,Sydney,Volkswagen,Buddy
101,Ben,Swan,Sydney,Ford,Buddy
101,Ben,Swan,Sydney,Audi,Buddy
101,Ben,Swan,Sydney,Volkswagen,Max
101,Ben,Swan,Sydney,Ford,Max
101,Ben,Swan,Sydney,Audi,Max
102,Julia,Brown,London,Mini,Lucy

Javascript:

var file = reader.result;
var singleRow = readerFile.split(/\r\n|\n/);
var header = singleRow[0].split(',');
var result =[];

    for ( var i=1; i < file.length; i++ ){
        var elementData = singleRow[i].split(',');
        elementData = elementData.filter(function(n){ return n != "" });
        var Obj = {};

        for ( var j=0; j < header.length; j++ ){
            Obj[header[j]] = elementData[j];
            /*
              - How can i build child object and append back to Obj before j loop
              - How can i build multiple child for same parent
            */
        }
        result.push(Obj);
    }
    console.log(" Print the JSON Object : " + JSON.stringify(result));

Desired Output:

{
    "data": [
        {
            "City": "NewYork",
            "FirstName": "John",
            "PrimaryId": 100,
            "LastName": "Smith",
            "CarName": [
                "Toyota",
                "BMW"
            ],
            "DogName": [
                "Spike",
                "Rusty"
            ]
        },
        {
            "City": "Sydney",
            "FirstName": "Ben",
            "PrimaryId": 101,
            "LastName": "Swan",
            "CarName": [
                "Volkswagen",
                "Ford",
                "Audi"
            ],
            "DogName": [
                "Buddy",
                "Max"
            ]
        },
        {
            "City": "London",
            "FirstName": "Julia",
            "PrimaryId": 102,
            "LastName": "Brown",
            "CarName": [
                "Mini"
            ],
            "DogName": [
                "Lucy"
            ]
        }
    ]
}

If Firstname, Lastname and City has same values then CarName and DogName values should be child object under the same parent

Body:
Made a fiddle for you, it gives the desired output with some things in a different order than you presented.

You can save the indexes of the headers:

var Index = {};
for(var k = 0; k < header.length; k++)
{
    Index[header[k]] = k;
}

And keep a list of cities:

var cities = [];
....
cities.push(data[Index["City"]]);

To use for later so that you don't keep making more objects if the city already exists:

obj = result.data[cities.indexOf(data[Index["City"]])];

The JSFiddle: https://jsfiddle.net/3u28aon3/1/


问:
QGroupBox find selected Radio Button
I have created a simple UI consisting of a QGroupBox with a bunch of QRadioButtons (32 to be exact) and I want to be able to find the selected one.

I've looked at forums and things, but the answers I've found don't work, and one referenced documentation on a nonexistant method of QGroupBox.

Given the below snippet, how would I find the selected QRadioButton, if any?

```<code>QGroupBox* thingGroup = ui->thingGroupBox;
</code>```

答:
If you want to get it when you select one of them you could use the toogled signal, connect it to some slot and use the sender () function and convert it to QRadioButton.

*.h

```<code>public slots:
    void onToggled(bool checked);
</code>```

*.cpp

```<code>QGroupBox *thingGroup = ui->groupBox;

QVBoxLayout *lay = new QVBoxLayout;

thingGroup->setLayout(lay);

for(int i = 0; i < 32; i++){
    QRadioButton *radioButton = new QRadioButton(QString::number(i));
    lay->addWidget(radioButton);
    connect(radioButton, &QRadioButton::toggled, this, &{your Class}::onToggled);
}
</code>```

slot:

```<code>void {your Class}::onToggled(bool checked)
{
    if(checked){
        //btn is Checked
        QRadioButton *btn = static_cast<QRadioButton *>(sender());
    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Title: QGroupBox find selected Radio Button

Body:
I have created a simple UI consisting of a QGroupBox with a bunch of QRadioButtons (32 to be exact) and I want to be able to find the selected one.

I've looked at forums and things, but the answers I've found don't work, and one referenced documentation on a nonexistant method of QGroupBox.

Given the below snippet, how would I find the selected QRadioButton, if any?

QGroupBox* thingGroup = ui->thingGroupBox;

Body:
If you want to get it when you select one of them you could use the toogled signal, connect it to some slot and use the sender () function and convert it to QRadioButton.

*.h

public slots:
    void onToggled(bool checked);

*.cpp

QGroupBox *thingGroup = ui->groupBox;

QVBoxLayout *lay = new QVBoxLayout;

thingGroup->setLayout(lay);

for(int i = 0; i < 32; i++){
    QRadioButton *radioButton = new QRadioButton(QString::number(i));
    lay->addWidget(radioButton);
    connect(radioButton, &QRadioButton::toggled, this, &{your Class}::onToggled);
}

slot:

void {your Class}::onToggled(bool checked)
{
    if(checked){
        //btn is Checked
        QRadioButton *btn = static_cast<QRadioButton *>(sender());
    }

}


问:
How to allow a class to be created by another without using 'friend' but allow inheritence?
I have three classes in total for my game engine, an abstract IComponent class in which all components inherit from it, a component class (for this example I will use RenderComponent), and a ComponentManager. I want the ComponentManager class to be able to use the constructor of RenderComponent, but I don't want any other classes to create an instance of RenderComponent, but I don't want to use 'friend' since I want customer user components to inherit from IComponent and automatically be used in the ComponentManager without being allowed to instantiate their own. The code example shows vaguely the behavior I want to occur:

```<code>class GameObject;

class IComponent
{
    private:
        IComponent() { }
        ~IComponent() { }
    public:
        GameObject* Parent;
}

class RenderComponent : IComponent
{
    public:
        RenderComponent() { }
        ~RenderComponent() { }
}

class ComponentManager
{
    public:
        ComponentManager() { }
        ~ComponentManager() { }

        // normally this would be a template function, but for the sake of this example I will directly use RenderComponent
        RenderComponent* CreateComponent()
        {
            // this would not throw a compiler error
            return new RenderComponent();
        }
}

int main()
{
    ComponentManager manager;

    // even though the constructor of RenderComponent is public, this would throw an error
    RenderComponent* render = new RenderComponent();

    // this however would work perfectly fine
    RenderComponent* render = manager.CreateComponent();

}
</code>```

To reiterate, I want it so that there is minimal user effort to creating components. The other option of course is to have the constructor for both public but have it so that although you can create a component wherever you want, it will be useless.

答:
If you use the factory design pattern, ComponentManager does not need to know anything about the concrete sub-types of IComponent. There is no need for it to be declared as a friend of the sub-types. It can simply use a factory to construct objects.

Creators of sub-types of IComponent will need to register a way for instances of the sub-type to be constructed. They register a function or a class with the factory that can construct an instance of the class.

An Example Program

```<code>#include <iostream>
#include <map>
#include <string>

class GameObject;

class IComponent
{
   // Make sure that sub-classes of IComponent can use the constructor
   // and the destructor.
   protected:
      IComponent() { }
      ~IComponent() { }

   public:
      GameObject* Parent;
};

// Define a function type that can construct a Component.
using ComponentConstructor = IComponent*  (*)();

// Define the interface for the factory.
class ComponentFactory
{
   public:

      // A type alias for simpler coding.
      using ConstructorMap = std::map<std::string, ComponentConstructor>;

      // Allow creators of sub-classes of IComponent to register a
      // function that can be used to construct the sub-type.
      static void registerComponentConstructor(std::string const& componentType,
                                               ComponentConstructor constructor);

      // Construct a Component by providing a name corresponding
      // to the derived sub-type of IComponent.
      static IComponent* constructComponent(std::string const& componentType);

   private:

      // Private function that maintains a map of
      // constructors.
      static ConstructorMap& getConstructrMap();
};

// -----------------------------------------------------
// BEGIN implementation of ComponentFactory.
// It can, obviously, be in a .cpp file of its own.
void ComponentFactory::registerComponentConstructor(std::string const& componentType,
                                                    ComponentConstructor constructor)
{
   getConstructrMap()[componentType] = constructor;
}

IComponent* ComponentFactory::constructComponent(std::string const& componentType)
{
   ConstructorMap& constructorMap = getConstructrMap();
   ConstructorMap::iterator iter = constructorMap.find(componentType);
   if ( iter != constructorMap.end() )
   {
      return iter->second();
   }
   else
   {
      return nullptr;
   }
}

ComponentFactory::ConstructorMap& ComponentFactory::getConstructrMap()
{
   static ConstructorMap theMap;
   return theMap;
}

// END implementation of ComponentFactory.
// -----------------------------------------------------

// ComponentManager can use ComponentFactory to
// construct Components.
class ComponentManager
{
   public:
      ComponentManager() { }
      ~ComponentManager() { }

      IComponent* CreateComponent(std::string const& componentType)
      {
         return ComponentFactory::constructComponent(componentType);
      }
};

// Test code.
// Construct IComponents by using appropriate names.
int main()
{
   ComponentManager m;
   IComponent* ic1 = m.CreateComponent("RenderComponent");
   if ( ic1 == nullptr )
   {
      std::cout << "Unable to construct a Component of type RenderComponent.\n";
   }
   else
   {
      std::cout << "Successfully constructed a Component of type RenderComponent.\n";
   }

   IComponent* ic2 = m.CreateComponent("AnotherTypeOfComponent");
   if ( ic2 == nullptr )
   {
      std::cout << "Unable to construct a Component of type AnotherTypeOfComponent.\n";
   }
   else
   {
      std::cout << "Successfully constructed a Component of type AnotherTypeOfComponent.\n";
   }

   IComponent* ic3 = m.CreateComponent("FooComponent");
   if ( ic3 == nullptr )
   {
      std::cout << "Unable to construct a Component of type FooComponent.\n";
   }
   else
   {
      std::cout << "Successfully constructed a Component of type FooComponent.\n";
   }
}

// Client components.
// Without these, no Component can be constructed.

namespace Module1
{
   class RenderComponent : IComponent
   {
      public:
         RenderComponent() { }
         ~RenderComponent() { }

         static IComponent* constructComponent()
         {
            return new RenderComponent();
         }

         struct Initer
         {
            Initer()
            {
               ComponentFactory::registerComponentConstructor("RenderComponent",
                                                              RenderComponent::constructComponent);
            }
         };
   };

   // The constructor makes sure that
   // RenderComponent::constructComponent() is
   // registered as the function to be called to
   // construct objects of type RenderComponent when
   // the name "RenderComponent" is used.
   //
   // A different method may be used for the purpose but
   // this seems like a straight forward method to do that.
   static RenderComponent::Initer initer;

}

namespace Module2
{
   class AnotherTypeOfComponent : IComponent
   {
      public:
         AnotherTypeOfComponent() { }
         ~AnotherTypeOfComponent() { }

         static IComponent* constructComponent()
         {
            return new AnotherTypeOfComponent();
         }

         struct Initer
         {
            Initer()
            {
               ComponentFactory::registerComponentConstructor("AnotherTypeOfComponent",
                                                              AnotherTypeOfComponent::constructComponent);
            }
         };
   };

   // The constructor makes sure that
   // AnotherTypeOfComponent::constructComponent() is
   // registered as the function to be called to
   // construct objects of type AnotherTypeOfComponent when
   // the name "AnotherTypeOfComponent" is used.
   static AnotherTypeOfComponent::Initer initer;
}
</code>```

Output

```<code>Successfully constructed a Component of type RenderComponent.
Successfully constructed a Component of type AnotherTypeOfComponent.
Unable to construct a Component of type FooComponent.
</code>```

Body:
I have three classes in total for my game engine, an abstract IComponent class in which all components inherit from it, a component class (for this example I will use RenderComponent), and a ComponentManager. I want the ComponentManager class to be able to use the constructor of RenderComponent, but I don't want any other classes to create an instance of RenderComponent, but I don't want to use 'friend' since I want customer user components to inherit from IComponent and automatically be used in the ComponentManager without being allowed to instantiate their own. The code example shows vaguely the behavior I want to occur:

class GameObject;

class IComponent
{
    private:
        IComponent() { }
        ~IComponent() { }
    public:
        GameObject* Parent;
}

class RenderComponent : IComponent
{
    public:
        RenderComponent() { }
        ~RenderComponent() { }
}

class ComponentManager
{
    public:
        ComponentManager() { }
        ~ComponentManager() { }

        // normally this would be a template function, but for the sake of this example I will directly use RenderComponent
        RenderComponent* CreateComponent()
        {
            // this would not throw a compiler error
            return new RenderComponent();
        }
}

int main()
{
    ComponentManager manager;

    // even though the constructor of RenderComponent is public, this would throw an error
    RenderComponent* render = new RenderComponent();

    // this however would work perfectly fine
    RenderComponent* render = manager.CreateComponent();

}

To reiterate, I want it so that there is minimal user effort to creating components. The other option of course is to have the constructor for both public but have it so that although you can create a component wherever you want, it will be useless.

Body:
If you use the factory design pattern, ComponentManager does not need to know anything about the concrete sub-types of IComponent. There is no need for it to be declared as a friend of the sub-types. It can simply use a factory to construct objects.

Creators of sub-types of IComponent will need to register a way for instances of the sub-type to be constructed. They register a function or a class with the factory that can construct an instance of the class.

An Example Program

#include <iostream>
#include <map>
#include <string>

class GameObject;

class IComponent
{
   // Make sure that sub-classes of IComponent can use the constructor
   // and the destructor.
   protected:
      IComponent() { }
      ~IComponent() { }

   public:
      GameObject* Parent;
};

// Define a function type that can construct a Component.
using ComponentConstructor = IComponent*  (*)();

// Define the interface for the factory.
class ComponentFactory
{
   public:

      // A type alias for simpler coding.
      using ConstructorMap = std::map<std::string, ComponentConstructor>;

      // Allow creators of sub-classes of IComponent to register a
      // function that can be used to construct the sub-type.
      static void registerComponentConstructor(std::string const& componentType,
                                               ComponentConstructor constructor);

      // Construct a Component by providing a name corresponding
      // to the derived sub-type of IComponent.
      static IComponent* constructComponent(std::string const& componentType);

   private:

      // Private function that maintains a map of
      // constructors.
      static ConstructorMap& getConstructrMap();
};

// -----------------------------------------------------
// BEGIN implementation of ComponentFactory.
// It can, obviously, be in a .cpp file of its own.
void ComponentFactory::registerComponentConstructor(std::string const& componentType,
                                                    ComponentConstructor constructor)
{
   getConstructrMap()[componentType] = constructor;
}

IComponent* ComponentFactory::constructComponent(std::string const& componentType)
{
   ConstructorMap& constructorMap = getConstructrMap();
   ConstructorMap::iterator iter = constructorMap.find(componentType);
   if ( iter != constructorMap.end() )
   {
      return iter->second();
   }
   else
   {
      return nullptr;
   }
}

ComponentFactory::ConstructorMap& ComponentFactory::getConstructrMap()
{
   static ConstructorMap theMap;
   return theMap;
}

// END implementation of ComponentFactory.
// -----------------------------------------------------

// ComponentManager can use ComponentFactory to
// construct Components.
class ComponentManager
{
   public:
      ComponentManager() { }
      ~ComponentManager() { }

      IComponent* CreateComponent(std::string const& componentType)
      {
         return ComponentFactory::constructComponent(componentType);
      }
};

// Test code.
// Construct IComponents by using appropriate names.
int main()
{
   ComponentManager m;
   IComponent* ic1 = m.CreateComponent("RenderComponent");
   if ( ic1 == nullptr )
   {
      std::cout << "Unable to construct a Component of type RenderComponent.\n";
   }
   else
   {
      std::cout << "Successfully constructed a Component of type RenderComponent.\n";
   }

   IComponent* ic2 = m.CreateComponent("AnotherTypeOfComponent");
   if ( ic2 == nullptr )
   {
      std::cout << "Unable to construct a Component of type AnotherTypeOfComponent.\n";
   }
   else
   {
      std::cout << "Successfully constructed a Component of type AnotherTypeOfComponent.\n";
   }

   IComponent* ic3 = m.CreateComponent("FooComponent");
   if ( ic3 == nullptr )
   {
      std::cout << "Unable to construct a Component of type FooComponent.\n";
   }
   else
   {
      std::cout << "Successfully constructed a Component of type FooComponent.\n";
   }
}

// Client components.
// Without these, no Component can be constructed.

namespace Module1
{
   class RenderComponent : IComponent
   {
      public:
         RenderComponent() { }
         ~RenderComponent() { }

         static IComponent* constructComponent()
         {
            return new RenderComponent();
         }

         struct Initer
         {
            Initer()
            {
               ComponentFactory::registerComponentConstructor("RenderComponent",
                                                              RenderComponent::constructComponent);
            }
         };
   };

   // The constructor makes sure that
   // RenderComponent::constructComponent() is
   // registered as the function to be called to
   // construct objects of type RenderComponent when
   // the name "RenderComponent" is used.
   //
   // A different method may be used for the purpose but
   // this seems like a straight forward method to do that.
   static RenderComponent::Initer initer;

}

namespace Module2
{
   class AnotherTypeOfComponent : IComponent
   {
      public:
         AnotherTypeOfComponent() { }
         ~AnotherTypeOfComponent() { }

         static IComponent* constructComponent()
         {
            return new AnotherTypeOfComponent();
         }

         struct Initer
         {
            Initer()
            {
               ComponentFactory::registerComponentConstructor("AnotherTypeOfComponent",
                                                              AnotherTypeOfComponent::constructComponent);
            }
         };
   };

   // The constructor makes sure that
   // AnotherTypeOfComponent::constructComponent() is
   // registered as the function to be called to
   // construct objects of type AnotherTypeOfComponent when
   // the name "AnotherTypeOfComponent" is used.
   static AnotherTypeOfComponent::Initer initer;
}

Output

Successfully constructed a Component of type RenderComponent.
Successfully constructed a Component of type AnotherTypeOfComponent.
Unable to construct a Component of type FooComponent.


问:
Making android listview layout scrollable
I have an xml file that has the layout in ASCII form:

```<code>---------------
| ImageView
--------------
| TextView
--------------
| List...
--------------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/com.some.app"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">
<ImageView
android:id="@+id/MovieCover"
android:layout_width="100dip"
android:layout_height="100dip"
/>
 <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="16sp"
    android:padding="10dp"
    android:id="@+id/TextHeader"
    android:background="#000000">
</TextView>
<ListView android:id="@+id/ListView02" android:layout_height="wrap_content"
 android:layout_width="fill_parent">
 </ListView>
 </LinearLayout>
</code>```

I'm having a problem displaying the layout when my ImageView and TextView takes up more than 3/4 of the screen. How do I make ImageView and TextView scrollable with the ListView that is being displayed? At this point of time, only the ListView to be scrolled and I want the entire layout to be scrollable as though they are one page on its own.

How can I do that?

答: How about putting the ImageView and TextView in a layout and putting this layout inside a ScrollView.?</p>

Body:
I have an xml file that has the layout in ASCII form:

---------------
| ImageView
--------------
| TextView
--------------
| List...
--------------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/com.some.app"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">
<ImageView
android:id="@+id/MovieCover"
android:layout_width="100dip"
android:layout_height="100dip"
/>
 <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="16sp"
    android:padding="10dp"
    android:id="@+id/TextHeader"
    android:background="#000000">
</TextView>
<ListView android:id="@+id/ListView02" android:layout_height="wrap_content"
 android:layout_width="fill_parent">
 </ListView>
 </LinearLayout>

I'm having a problem displaying the layout when my ImageView and TextView takes up more than 3/4 of the screen. How do I make ImageView and TextView scrollable with the ListView that is being displayed? At this point of time, only the ListView to be scrolled and I want the entire layout to be scrollable as though they are one page on its own.

How can I do that?


问:
GitBash cmd line branch delete
what does it mean that I see (feature/StoreTextVariable_134) (I assume branch I created earlier in and switched to in VS, and I deleted the local code earlier)?

how can I get rid of it?

I'm a GitBash newbie.

答:
what does it mean that I see (feature/StoreTextVariable_134)

feature/StoreTextVariable_134 is the branch of git that you are currently working on.

Type git branch to check how many branches in your source code.

how can I get rid of it?

Use git checkout  to move to the branch you need to work with.

output

Note: If there is a change in source code on the current branch then you need to commit before switching branches.

Please refer more detail here:
Git document

Title: GitBash cmd line branch delete


问:
how to do boost::asio::spawn with io_service-per-CPU?
My server is based on boost spawn echo server.

The server runs fine on single-core machine, not even one crash for several months. Even when it takes 100% CPU it still works fine.

But I need to handle more client requests, now I use multi-core machine. To use all the CPUs I run io_service on several thread, like this:

```<code>#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/asio/write.hpp>
#include <boost/thread/thread.hpp>
#include <iostream>
#include <memory>
#include <thread>
using namespace std;

using boost::asio::ip::tcp;

class session : public std::enable_shared_from_this<session>{
public:
    explicit session(tcp::socket socket)
        : socket_(std::move(socket)),
        timer_(socket_.get_io_service()),
        strand_(socket_.get_io_service())
    {}

    void go()
    {
        auto self(shared_from_this());
        boost::asio::spawn(strand_, [this, self](boost::asio::yield_context yield)
        {
           try {
               char data[1024] = {'3'};
               for( ; ;) {
                   timer_.expires_from_now(std::chrono::seconds(10));
                   std::size_t n = socket_.async_read_some(boost::asio::buffer(data, sizeof(data)), yield);
                   // do something with data
                   // write back something
                   boost::asio::async_write(socket_, boost::asio::buffer(data, sizeof(data)), yield);
               }
           } catch(...)   {
               socket_.close();
               timer_.cancel();
           }
        });

        boost::asio::spawn(strand_, [this, self](boost::asio::yield_context yield)
        {
           while(socket_.is_open()) {
               boost::system::error_code ignored_ec;
               timer_.async_wait(yield[ignored_ec]);
               if(timer_.expires_from_now() <= std::chrono::seconds(0))
                   socket_.close();
           }
        });
    }

private:
    tcp::socket socket_;
    boost::asio::steady_timer timer_;
    boost::asio::io_service::strand strand_;
};

int main(int argc, char* argv[]) {
    try {

        boost::asio::io_service io_service;

        boost::asio::spawn(io_service, [&](boost::asio::yield_context yield)
        {
            tcp::acceptor acceptor(io_service,
#define PORT "7788"
            tcp::endpoint(tcp::v4(), std::atoi(PORT)));

            for( ; ;) {
                boost::system::error_code ec;
                tcp::socket socket(io_service);
                acceptor.async_accept(socket, yield[ec]);
                if(!ec)
                    // std::make_shared<session>(std::move(socket))->go();
                    io_service.post(boost::bind(&session::go, std::make_shared<session>(std::move(socket))));
            }
        });

        // ----------- this works fine on single-core machine ------------
        {
            // io_service.run();
        }

        // ----------- this crashes (with multi core) ----------
        {
            auto thread_count = std::thread::hardware_concurrency(); // for multi core
            boost::thread_group threads;
            for(auto i = 0; i < thread_count; ++i)
                threads.create_thread(boost::bind(&boost::asio::io_service::run, &io_service));

            threads.join_all();
        }

    } catch(std::exception& e) {
        std::cerr << "Exception: " << e.what() << "\n";
    }

    return 0;
}
</code>```

The code works fine on single-core maching, but crashes all the time on 2-core/4-core/8-core machine. From the crash dump I don't see anything related to my code, just about something with boost::spawn and some randomly named lambda.

So I want to try this: Run io_service per CPU.

I found some demo, but it uses async function:

```<code>void server::start_accept()
{
  new_connection_.reset(new connection(
        io_service_pool_.get_io_service(), request_handler_));
  acceptor_.async_accept(new_connection_->socket(),
      boost::bind(&server::handle_accept, this,
        boost::asio::placeholders::error));
}

void server::handle_accept(const boost::system::error_code& e)
{
  if (!e)
  {
    new_connection_->start();
  }

  start_accept();
}
</code>```

The io_service_pool_.get_io_service() randomly pickup an io_service, but my code uses spawn

```<code>boost::asio::spawn(io_service, ...
</code>```

How to spawn with random io_service?

答:
Seems I was asking the wrong question, spawn cannot work with multiple io_service, but the socket can. I modified the code to this:

```<code>int main(int argc, char* argv[]) {
    try {

        boost::asio::io_service io_service;
        boost::asio::io_service::work work(io_service);

        auto core_count = std::thread::hardware_concurrency();
        // io_service_pool.hpp and io_service_pool.cpp from boost's example
        io_service_pool pool(core_count);

        boost::asio::spawn(io_service, [&](boost::asio::yield_context yield)
        {
#define PORT "7788"
            tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), std::atoi(PORT)));

            for( ; ;) {
                boost::system::error_code ec;
                boost::asio::io_service& ios = pool.get_io_service();
                tcp::socket socket(ios);
                acceptor.async_accept(socket, yield[ec]);
                if(!ec)
                    ios.post(boost::bind(&session::go, std::make_shared<session>(std::move(socket))));
            }
        });

        { // run all io_service
            thread t([&] { pool.run(); });
            t.detach();

            io_service.run();
        }

    } catch(std::exception& e) {
        std::cerr << "Exception: " << e.what() << "\n";
    }

    return 0;
}
</code>```

Now the server doesn't crash anymore. But I still have no idea what could cause the crash if I use a single io_service for all threads.

Body:
My server is based on boost spawn echo server.

The server runs fine on single-core machine, not even one crash for several months. Even when it takes 100% CPU it still works fine.

But I need to handle more client requests, now I use multi-core machine. To use all the CPUs I run io_service on several thread, like this:

#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/asio/write.hpp>
#include <boost/thread/thread.hpp>
#include <iostream>
#include <memory>
#include <thread>
using namespace std;

using boost::asio::ip::tcp;

class session : public std::enable_shared_from_this<session>{
public:
    explicit session(tcp::socket socket)
        : socket_(std::move(socket)),
        timer_(socket_.get_io_service()),
        strand_(socket_.get_io_service())
    {}

    void go()
    {
        auto self(shared_from_this());
        boost::asio::spawn(strand_, [this, self](boost::asio::yield_context yield)
        {
           try {
               char data[1024] = {'3'};
               for( ; ;) {
                   timer_.expires_from_now(std::chrono::seconds(10));
                   std::size_t n = socket_.async_read_some(boost::asio::buffer(data, sizeof(data)), yield);
                   // do something with data
                   // write back something
                   boost::asio::async_write(socket_, boost::asio::buffer(data, sizeof(data)), yield);
               }
           } catch(...)   {
               socket_.close();
               timer_.cancel();
           }
        });

        boost::asio::spawn(strand_, [this, self](boost::asio::yield_context yield)
        {
           while(socket_.is_open()) {
               boost::system::error_code ignored_ec;
               timer_.async_wait(yield[ignored_ec]);
               if(timer_.expires_from_now() <= std::chrono::seconds(0))
                   socket_.close();
           }
        });
    }

private:
    tcp::socket socket_;
    boost::asio::steady_timer timer_;
    boost::asio::io_service::strand strand_;
};

int main(int argc, char* argv[]) {
    try {

        boost::asio::io_service io_service;

        boost::asio::spawn(io_service, [&](boost::asio::yield_context yield)
        {
            tcp::acceptor acceptor(io_service,
#define PORT "7788"
            tcp::endpoint(tcp::v4(), std::atoi(PORT)));

            for( ; ;) {
                boost::system::error_code ec;
                tcp::socket socket(io_service);
                acceptor.async_accept(socket, yield[ec]);
                if(!ec)
                    // std::make_shared<session>(std::move(socket))->go();
                    io_service.post(boost::bind(&session::go, std::make_shared<session>(std::move(socket))));
            }
        });

        // ----------- this works fine on single-core machine ------------
        {
            // io_service.run();
        }

        // ----------- this crashes (with multi core) ----------
        {
            auto thread_count = std::thread::hardware_concurrency(); // for multi core
            boost::thread_group threads;
            for(auto i = 0; i < thread_count; ++i)
                threads.create_thread(boost::bind(&boost::asio::io_service::run, &io_service));

            threads.join_all();
        }

    } catch(std::exception& e) {
        std::cerr << "Exception: " << e.what() << "\n";
    }

    return 0;
}

The code works fine on single-core maching, but crashes all the time on 2-core/4-core/8-core machine. From the crash dump I don't see anything related to my code, just about something with boost::spawn and some randomly named lambda.

So I want to try this: Run io_service per CPU.

I found some demo, but it uses async function:

void server::start_accept()
{
  new_connection_.reset(new connection(
        io_service_pool_.get_io_service(), request_handler_));
  acceptor_.async_accept(new_connection_->socket(),
      boost::bind(&server::handle_accept, this,
        boost::asio::placeholders::error));
}

void server::handle_accept(const boost::system::error_code& e)
{
  if (!e)
  {
    new_connection_->start();
  }

  start_accept();
}

The io_service_pool_.get_io_service() randomly pickup an io_service, but my code uses spawn

boost::asio::spawn(io_service, ...

How to spawn with random io_service?

Body:
Seems I was asking the wrong question, spawn cannot work with multiple io_service, but the socket can. I modified the code to this:

int main(int argc, char* argv[]) {
    try {

        boost::asio::io_service io_service;
        boost::asio::io_service::work work(io_service);

        auto core_count = std::thread::hardware_concurrency();
        // io_service_pool.hpp and io_service_pool.cpp from boost's example
        io_service_pool pool(core_count);

        boost::asio::spawn(io_service, [&](boost::asio::yield_context yield)
        {
#define PORT "7788"
            tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), std::atoi(PORT)));

            for( ; ;) {
                boost::system::error_code ec;
                boost::asio::io_service& ios = pool.get_io_service();
                tcp::socket socket(ios);
                acceptor.async_accept(socket, yield[ec]);
                if(!ec)
                    ios.post(boost::bind(&session::go, std::make_shared<session>(std::move(socket))));
            }
        });

        { // run all io_service
            thread t([&] { pool.run(); });
            t.detach();

            io_service.run();
        }

    } catch(std::exception& e) {
        std::cerr << "Exception: " << e.what() << "\n";
    }

    return 0;
}

Now the server doesn't crash anymore. But I still have no idea what could cause the crash if I use a single io_service for all threads.


问:
Vue 2.0 vueify browserify-simple :: Autoprefixer Doesn't Work
I don't know what I'm doing wrong and I've asked around everywhere, but autoprefixer is just not working.

I started with this template:
https://github.com/vuejs-templates/browserify-simple

I installed autoprefixer:

```<code>  "devDependencies": {
    "autoprefixer": "^6.4.0",
</code>```

My vue.config.js file is in the root of my project. I added this to my vue.config.js file:

```<code>module.exports = {
  postcss: [
    require('autoprefixer')({
      browsers: ['last 2 versions', 'IE 10']
    })
  ]
}

console.log('is this working?')
</code>```

Not only does autoprefixer not prefix anything, but the log doesn't get output either. What's going on here?

答:
Here is my configure setting.</p>

```<code>const autoprefixer = require('autoprefixer')
module.exports = {
  // provide your own postcss plugins
  postcss: [require('autoprefixer')({
    browsers: ['last 50 versions']
  })]
}
</code>```

Body:
I don't know what I'm doing wrong and I've asked around everywhere, but autoprefixer is just not working.

I started with this template:
https://github.com/vuejs-templates/browserify-simple

I installed autoprefixer:

  "devDependencies": {
    "autoprefixer": "^6.4.0",

My vue.config.js file is in the root of my project. I added this to my vue.config.js file:

module.exports = {
  postcss: [
    require('autoprefixer')({
      browsers: ['last 2 versions', 'IE 10']
    })
  ]
}

console.log('is this working?')

Not only does autoprefixer not prefix anything, but the log doesn't get output either. What's going on here?

Body:
Here is my configure setting.

const autoprefixer = require('autoprefixer')
module.exports = {
  // provide your own postcss plugins
  postcss: [require('autoprefixer')({
    browsers: ['last 50 versions']
  })]
}


问:
return a json error in middleware?
I'm building an app and I'm using laravel5 as webAPI.
When the webAPI is in Maintenance Mode, I want to return a json error to app and I will get the status code in app to show a suitable message.

I rewrite the laravel CheckForMaintenanceMode for somereason and registed it in Kernel.

I write

```<code>if ($this->app->isDownForMaintenance()) {
    $ip = $request->getClientIp();
    $allowIp = "111.222.333.444";
    if ($allowIp != $ip) {
        return response()->json(['error' => "Maintenance!!"], 503);
    }
}
return $next($request);
</code>```

But I can get NOTHING in app side.I cannot get the message, the satus....

I writh the same code like return response()->json(['error' => "errormessage"], 422); in controller and I can get the message.status.. in app but I cannot do the same thing in a middleware.

why? how to do it?

答:
This worked:

```<code>if ($this->app->isDownForMaintenance()) {
    $ip = $request->getClientIp();
    $allowIp = "111.222.333.444";
    if ($allowIp != $ip) {
        return response(['Maintenance'], 503);
    }
}
return $next($request);
</code>```

And not register the middleware in Kernel global HTTP middleware but put it in the route(api.php),like:

```<code>Route::group(['middleware' => 'maintenance'], function(){******}
</code>```

I really donot know why but this worked for me.

Title: return a json error in middleware?

Body:
I'm building an app and I'm using laravel5 as webAPI.
When the webAPI is in Maintenance Mode, I want to return a json error to app and I will get the status code in app to show a suitable message.

I rewrite the laravel CheckForMaintenanceMode for somereason and registed it in Kernel.

I write

if ($this->app->isDownForMaintenance()) {
    $ip = $request->getClientIp();
    $allowIp = "111.222.333.444";
    if ($allowIp != $ip) {
        return response()->json(['error' => "Maintenance!!"], 503);
    }
}
return $next($request);

But I can get NOTHING in app side.I cannot get the message, the satus....

I writh the same code like return response()->json(['error' => "errormessage"], 422); in controller and I can get the message.status.. in app but I cannot do the same thing in a middleware.

why? how to do it?

Body:
This worked:

if ($this->app->isDownForMaintenance()) {
    $ip = $request->getClientIp();
    $allowIp = "111.222.333.444";
    if ($allowIp != $ip) {
        return response(['Maintenance'], 503);
    }
}
return $next($request);

And not register the middleware in Kernel global HTTP middleware but put it in the route(api.php),like:

Route::group(['middleware' => 'maintenance'], function(){******}

I really donot know why but this worked for me.


问:
Grid caption loads on bottom of table in IE8 when using jquery "html" to dynamically load table
I have a table I load dynamically on a website when a button is clicked.

For some reason, in IE8, when I click the button the table's CAPTION markup loads at the bottom of the grid.

The problem is due to this line of css:

```<code>vertical-align:bottom;
</code>```

If I remove it it, I'm fine.  I'm just curious if anyone knows the specific reason why this happens.

BTW, "IE sucks" is not specific enough.

You can see a full markup of an example below, or click here to see it in action:

```<code><html>
 <head>
  <title>Table Test</title>

  <style type="text/css">
   .grid caption {
   background-color:#005abb;
   color:#FFFFFF;
   padding:0 0.25em;
   vertical-align:bottom;
   }
  </style>

  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
  <script type="text/javascript">
   $(document).ready(function() {
     $( "#_button" ).click(function() {
     var newTableText = '<table cellspacing="0" cellpadding="4" border="0" class="grid"><tbody><caption>Now I\'m on da bottom</caption><tr class="gridHeader"><th>Code</th><th>A</th><th>P</th><th>R</th><th>RM</th><th>Totals</th><th>Percentages</th></tr><tr class = "gridRow"><td>1</td><td>1</td><td>0</td><td>0</td><td>0</td><td>1</td><td>50%</td></tr><tr class = "gridAlternatingRow"><td>2</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0%</td></tr></tbody></table>';
     $( "#_table" ).html(newTableText);
    return false;
   });
   });//End of document ready
  </script>
 <body>

 <button id="_button" type="button">Click Me and watch the caption move to bottom</button>
 <div id="_table" style="width: 700px;">
  <table cellspacing="0" cellpadding="4" border="0" class="grid"><tbody><caption>I'm on top</caption>
  <tr class="gridHeader"><th>Code</th><th>A</th><th>P</th><th>R</th><th>RM</th><th>Totals</th><th>Percentages</th></tr>
  <tr class = "gridRow"><td>1</td><td>1</td><td>0</td><td>0</td><td>0</td><td>1</td><td>50%</td></tr>
  <tr class = "gridAlternatingRow"><td>2</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0%</td></tr>
  </tbody></table>
 </div>

 </body>
</html>
</code>```

答:
The simple fix is to specify a DOCTYPE. A DOCTYPE tells the browser which set of rules you're playing by. Without it, IE will revert to quirks mode, which is essentially the IE 5.5 rendering engine. This will cause many strange side effects, including what you're observing.

I took your example and added the following, and it works fine in IE9 (and IE9 in IE8 mode):

```<code><!DOCTYPE html>
</code>```

Also, it's important to note that IE requires that nothing proceeds theDOCTYPE, otherwise quirks mode will be triggered. White space is OK, but no comments or other markup.

Body:
I have a table I load dynamically on a website when a button is clicked.

For some reason, in IE8, when I click the button the table's CAPTION markup loads at the bottom of the grid.

The problem is due to this line of css:

vertical-align:bottom;

If I remove it it, I'm fine.  I'm just curious if anyone knows the specific reason why this happens.

BTW, "IE sucks" is not specific enough.

You can see a full markup of an example below, or click here to see it in action:

  <title>Table Test</title>

 <button id="_button" type="button">Click Me and watch the caption move to bottom</button>

I'm on top

Code	A	P	R	RM	Totals	Percentages

1	1	0	0	0	1	50%

2	0	0	0	0	0	0%

Body:
The simple fix is to specify a DOCTYPE. A DOCTYPE tells the browser which set of rules you're playing by. Without it, IE will revert to quirks mode, which is essentially the IE 5.5 rendering engine. This will cause many strange side effects, including what you're observing.

I took your example and added the following, and it works fine in IE9 (and IE9 in IE8 mode):

<!DOCTYPE html>

Also, it's important to note that IE requires that nothing proceeds theDOCTYPE, otherwise quirks mode will be triggered. White space is OK, but no comments or other markup.


问:
The method showMessageDialog(Component, Object) in the type JOptionPane is not applicable for the arguments (new ActionListener(){}, String)
```<code>import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class GUIClass extends JFrame {

    public static void main (String[] args){
        // TODO Auto-generated method stub
        JFrame fm = new JFrame();
        final JTextField tf = new JTextField();
        JButton butn = new JButton("Click ME");
        tf.setBounds(50, 20, 130, 40);
        butn.setBounds(50, 80, 120, 30);
        butn.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            JOptionPane.showMessageDialog(this, tf.getText());
        }
        });
        fm.add(tf);
        fm.add(butn);
        fm.setLayout(null);
        fm.setVisible(true);
        fm.setSize(400, 300);

    }

}
</code>```

答:
```<code>JOptionPane.showMessageDialog(this, tf.getText());
</code>```

"this" refers to the ActionListener.

You want the frame to be the parent of the option pane:

```<code>JOptionPane.showMessageDialog(fm, tf.getText());
</code>```

Body:
JOptionPane.showMessageDialog(this, tf.getText());

"this" refers to the ActionListener.

You want the frame to be the parent of the option pane:

JOptionPane.showMessageDialog(fm, tf.getText());


答:
So the problem lies within...

```<code>butn.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        JOptionPane.showMessageDialog(this, tf.getText());
    }
});
</code>```

this, in this context, refers to the anonymous instance of the ActionListener, not the parent class.

A simple solution might be to use JOptionPane.showMessageDialog(tf, tf.getText());

Title: The method showMessageDialog(Component, Object) in the type JOptionPane is not applicable for the arguments (new ActionListener(){}, String)

Body:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class GUIClass extends JFrame {

    public static void main (String[] args){
        // TODO Auto-generated method stub
        JFrame fm = new JFrame();
        final JTextField tf = new JTextField();
        JButton butn = new JButton("Click ME");
        tf.setBounds(50, 20, 130, 40);
        butn.setBounds(50, 80, 120, 30);
        butn.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            JOptionPane.showMessageDialog(this, tf.getText());
        }
        });
        fm.add(tf);
        fm.add(butn);
        fm.setLayout(null);
        fm.setVisible(true);
        fm.setSize(400, 300);

    }

}

Body:
So the problem lies within...

butn.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        JOptionPane.showMessageDialog(this, tf.getText());
    }
});

this, in this context, refers to the anonymous instance of the ActionListener, not the parent class.

A simple solution might be to use JOptionPane.showMessageDialog(tf, tf.getText());


问:
C# Stack Array, Push method pushes the value to ALL entries
I create a stack array and initialize the first element like this:

```<code>Stack[] snowmen = new Stack[numberOfOperations+1];
snowmen[0] = new Stack();
</code>```

I then iterate through the array and want to perform 2 things:

Copy the stack from a specific index to the i-th position of the array

Push/Pop an integer from the new i-th stack

code for that:

```<code>for(int i = 1; i <= numberOfOperations; i++)
{
    . . .

    else if (addSnowball == 0)
    {
        snowmen[i] = new Stack();
        snowmen[i] = snowmen[copySnowmanNr];
        snowmen[i].Pop();
    }
    else
    {
        snowmen[i] = new Stack();
        snowmen[i] = snowmen[copySnowmanNr];
        snowmen[i].Push(addSnowball);
    }

    . . .
}
</code>```

If I call the push or pop method now, EVERY stack in my array will be changed, not only the i-th stack, which may tell me that my copies all refer to the same storage location. Am I right, what am I making wrong, what can I do?

答:
You are correct in that you are referring to the same stack. The following line copies the reference to the stack from the copySnowmanNr index to the i index.

```<code>snowmen[i] = snowmen[copySnowmanNr];
</code>```

To create a copy of the actual stack, do the following:

```<code>snowmen[i] = new Stack(snowmen[copySnowmanNr]);
</code>```

And as others have mentioned, your snowmen[i] = new Stack(); statement is unnecessary.

EDIT: As OP has pointed out in his answer, the above creates a reversed Stack. This is because it builds the new one by simply iterating over the old one. There is a Clone method which creates a shallow copy of the Stack in the correct order:

```<code>snowmen[i] = (Stack)snowmen[copySnowmanNr].Clone();
</code>```

Body:
I create a stack array and initialize the first element like this:

Stack[] snowmen = new Stack[numberOfOperations+1];
snowmen[0] = new Stack();

I then iterate through the array and want to perform 2 things:

Copy the stack from a specific index to the i-th position of the array

Push/Pop an integer from the new i-th stack

code for that:

for(int i = 1; i <= numberOfOperations; i++)
{
    . . .

    else if (addSnowball == 0)
    {
        snowmen[i] = new Stack();
        snowmen[i] = snowmen[copySnowmanNr];
        snowmen[i].Pop();
    }
    else
    {
        snowmen[i] = new Stack();
        snowmen[i] = snowmen[copySnowmanNr];
        snowmen[i].Push(addSnowball);
    }

    . . .
}

If I call the push or pop method now, EVERY stack in my array will be changed, not only the i-th stack, which may tell me that my copies all refer to the same storage location. Am I right, what am I making wrong, what can I do?

Body:
You are correct in that you are referring to the same stack. The following line copies the reference to the stack from the copySnowmanNr index to the i index.

snowmen[i] = snowmen[copySnowmanNr];

To create a copy of the actual stack, do the following:

snowmen[i] = new Stack(snowmen[copySnowmanNr]);

And as others have mentioned, your snowmen[i] = new Stack(); statement is unnecessary.

EDIT: As OP has pointed out in his answer, the above creates a reversed Stack. This is because it builds the new one by simply iterating over the old one. There is a Clone method which creates a shallow copy of the Stack in the correct order:

snowmen[i] = (Stack)snowmen[copySnowmanNr].Clone();


问:
How to zip multiple files from different folders and store that zip files in one folder using java
How to Zip multiple files from two different folders and store it in any of these two folder using java </p>

答:
This person had a similar question, check it out: Zipping a folder which contains subfolders

The answer to their question (Posted by dogbane) could answer yours, it is as follows:

You need to check if the file is a directory because you can't pass
  directories to the zip method.

Take a look at this page which shows how you can recursively zip
  a given directory.