问:
Why I cannot display Firebase data in ListView
Can someone help me in this problem, I try to display job from the firebase in Listview, but it doesn't display anything! I have tried different codes from topic at stack and different sites but receive error at

```<code>adapter=new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,retrieve());
</code>```

and this

```<code>lv.setAdapter(adapter);
</code>```

with nullexception

Javacode

```<code>package com.gumption.zeeshanahmed.jobaps;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.ArrayList;

 public class EditsJobs extends AppCompatActivity {

     ListView lv;
     ArrayAdapter<String> adapter;
     ArrayList<String> spacecrafts=new ArrayList<>();

// Declaring String variable ( In which we are storing firebase server URL
//).
     public static final String Firebase_Server_URL =
     "https://jobaps70.firebaseio.com/";

// Declaring String variables to store name & phone number get from
//EditText.
      String PriceHolder, JobDescriptionHolder;
      FirebaseHelper helper;

// Declaring Firebase object.
      Firebase firebase;

// Creating FirebaseAuth.
      FirebaseAuth firebaseAuth ;

// Creating FirebaseAuth.
      FirebaseUser firebaseUser;

// Creating Boolean variable that holds EditText is empty or not status.
      Boolean EditTextStatus ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edits_jobs);

//Actionbar
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setIcon(R.drawable.logo);
    getSupportActionBar().setBackgroundDrawable(new
    ColorDrawable(getResources().getColor(R.color.Snow)));

// Adding MainActivity context into Firebase context.

    Firebase.setAndroidContext(EditsJobs.this);

// Passing firebase Server URL into firebase object.

    firebase = new Firebase(Firebase_Server_URL);
    firebaseAuth = FirebaseAuth.getInstance();

// On activity start check whether there is user previously logged in or
//   not.

    if(firebaseAuth.getCurrentUser() == null){

        // Finishing current Profile activity.
        finish();

        // If user already not log in then Redirect to LoginActivity .
        Intent intent = new Intent(EditsJobs.this, LoginActivity.class);
        startActivity(intent);

        // Showing toast message.
        Toast.makeText(EditsJobs.this, "Please Log in to continue",
        Toast.LENGTH_LONG).show();

    }

    // Adding firebaseAuth current user info into firebaseUser object.
    firebaseUser = firebaseAuth.getCurrentUser();

    // Getting logged in user email from firebaseUser.getEmail() method and
     set into TextView.
    setTitle( firebaseUser.getEmail());
    setTitleColor(R.color.DarkGray);

    // ListView element

    lv = (ListView) findViewById(R.id.datadisplist);
    adapter=new ArrayAdapter<String>
    (this,android.R.layout.simple_list_item_1,retrieve());
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int
        position, long id) {
            Toast.makeText(EditsJobs.this, retrieve().get(position),
            Toast.LENGTH_SHORT).show();
         }
    });

}

 private void fetchData(DataSnapshot dataSnapshot)
{
    jobsdetails.clear();
    for (DataSnapshot ds : dataSnapshot.getChildren())
    {
        String jobs=ds.getValue(JobDetails.class).getjob();
        jobsdetails.add(jobs);
    }
}

//RETRIEVE
public ArrayList<String> retrieve(){
firebase.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        fetchData(dataSnapshot);
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String s) {
        fetchData(dataSnapshot);

    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {

    }

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String s) {

    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }

});

return spacecrafts;
}
}
</code>```

XML

```<code>   <?xml version="1.0" encoding="utf-8"?>
   <RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="com.gumption.zeeshanahmed.jobaps.EditsJobs">
   <TextView
    android:id="@+id/texteditjobs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/text_edit_jobs"
    android:textSize="40sp"
    android:textAlignment="center"/>

    <ListView
        android:id="@+id/datadisplist"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/texteditjobs"
        android:background="@color/Khaki"/>
       </RelativeLayout>
</code>```

JobDetail

```<code> public class JobDetails {

    private String price;
    private String jobDescription;
    private String jobSpinner;
    public String email;
    public JobDetails() {
        // This is default constructor.
    }

    public String getPrice() {

        return price;
    }

    public void setPrice(String pri) {

        this.price = pri;
    }

    public String getjobDescription() {

        return jobDescription;

    }

    public void setjobDescription(String jobd) {

        this.jobDescription = jobd;
    }

    public void setjob(String jry) {

        this.jobSpinner = jry ;

    }

    public String getjob() {

        return jobSpinner;

    }

    public void setemail(String jel) {

        this.email = jel ;

    }

    public String getemail() {

        return email;

    }
}
</code>```

Using textView

when i use text view the data is displayed only one atmost!

```<code>// Adding click listener to Show data button.
    ShowButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Adding addValueEventListener method on firebase object.
            firebase.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot MainSnapshot) {

              for (DataSnapshot SubSnapshot : MainSnapshot.getChildren()) {

              JobDetails jobdetails =SubSnapshot.getValue(JobDetails.class);
                    for
                        // Adding name and phone number of student into
                      string that is coming from server.

                        String ShowDataString = "Job: " +
                        jobdetails.getjob() + "\nJob Description: " +
                        jobdetails.getjobDescription() + "\n\n";

                        // Apply complete string variable into TextView.
                        ShowDataTextView.setText(ShowDataString);
               }
                    }
                }

                @Override
                public void onCancelled(FirebaseError firebaseError) {
                    System.out.println("Data Access Failed" +
                firebaseError.getMessage());
                }
            });
        }
        });
</code>```

with Xml

```<code>   <TextView
    android:id="@+id/showmetadata"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/show"
    android:textSize="40sp"
    android:textAlignment="center"/>
</code>```

It will be very helpful if someone help will me with this. Please and thank
you!

**Tried listview **

Now i tried listview, and it crashes here is the code and error

```<code> public class WorkActivity extends AppCompatActivity {

//    Spinner jobSpin;

ListView lv;
Button ShowButton;
// Define a String ArrayList for the job
private ArrayList<String> jobdes=new ArrayList<>();

// Define an ArrayAdapter for the list
private ArrayAdapter<String> arrayAdapter;

// Declaring String variable ( In which we are storing firebase server URL
).
public static final String Firebase_Server_URL =
"https://jobaps70.firebaseio.com/";
public static final String Firebase_Server_URL1 =
 "https://jobaps70.firebaseio.com/jobs";

// Declaring String variables to store name & phone number get from
EditText.
String PriceHolder, JobDescriptionHolder;
FirebaseHelper helper;

// Declaring Firebase object.
Firebase firebase,firebase1;

// Creating FirebaseAuth.
FirebaseAuth firebaseAuth ;

// Creating FirebaseAuth.
FirebaseUser firebaseUser;

// Creating Boolean variable that holds EditText is empty or not status.
Boolean EditTextStatus ;

TextView ShowDataTextView ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edits_jobs);

      //        Actionbar
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setIcon(R.drawable.logo);
    getSupportActionBar().setBackgroundDrawable(new
    ColorDrawable(getResources().getColor(R.color.Snow)));

    ShowButton = (Button)findViewById(R.id.show);

    // Adding MainActivity context into Firebase context.
    Firebase.setAndroidContext(WorkActivity.this);

    // Passing firebase Server URL into firebase object.
    firebase = new Firebase(Firebase_Server_URL);
    firebase1=new Firebase(Firebase_Server_URL1);

    firebaseAuth = FirebaseAuth.getInstance();

    // On activity start check whether there is user previously logged in or
       not.
    if(firebaseAuth.getCurrentUser() == null){

        // Finishing current Profile activity.
        finish();

        // If user already not log in then Redirect to LoginActivity .
        Intent intent = new Intent(WorkActivity.this, LoginActivity.class);
        startActivity(intent);

        // Showing toast message.
        Toast.makeText(WorkActivity.this, "Please Log in to continue",
        Toast.LENGTH_LONG).show();

    }

    // Adding firebaseAuth current user info into firebaseUser object.
    firebaseUser = firebaseAuth.getCurrentUser();

    // Getting logged in user email from firebaseUser.getEmail() method and
        set into TextView.
    setTitle( firebaseUser.getEmail());
    setTitleColor(R.color.DarkGray);
      firebase.child("jobs");

    // Associate the jobs' list with the corresponding ListView
    lv = (ListView) findViewById(R.id.lvshow);

    // Set the ArrayAdapter to the ListView
    arrayAdapter = new ArrayAdapter<String>(this,
       android.R.layout.simple_list_item_1, jobdes);
    lv.setAdapter(arrayAdapter);

    // Attach a ChildEventListener to the teacher database, so we can
          retrieve the job entries
    firebase.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {

            // Get the value from the DataSnapshot and add it to the jobs'
         list
            JobDetails jo = (JobDetails)
         dataSnapshot.getValue(JobDetails.class);
            String joString = String.valueOf(jo);
            arrayAdapter.add(joString);
 //

            // Notify the ArrayAdapter that there was a change
            arrayAdapter.notifyDataSetChanged();
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(FirebaseError databaseError) {

        }
    });
}

}
</code>```

Error

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.gumption.zeeshanahmed.jobaps, PID: 4774
              java.lang.RuntimeException: Unable to start activity
              ComponentInfo{com.gumption.zeeshanahmed.jobaps/
              com.gumption.zeeshanahmed.jobaps.WorkActivity}:
              java.lang.NullPointerException: Attempt to invoke virtual
              method 'void
             android.widget.ListView.setAdapter(android.widget.ListAdapter)'
             on a null object reference at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                  at android.app.ActivityThread.-wrap11(ActivityThread.java)
                  at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:148)at
 android.app.ActivityThread.main(ActivityThread.java:5417)
                  at java.lang.reflect.Method.invoke(Native Method) at
 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
 (ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main
 (ZygoteInit.java:616)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a
 null object reference at
 com.gumption.zeeshanahmed.jobaps.WorkActivity.onCreate
 (WorkActivity.java:109)
              at android.app.Activity.performCreate(Activity.java:6237) at
 android.app.Instrumentation.callActivityOnCreate
 (Instrumentation.java:1107) at
 android.app.ActivityThread.performLaunchActivity
 (ActivityThread.java:2369)atandroid.app.ActivityThread.handleLaunchActivity
 (ActivityThread.java:2476) at android.app.ActivityThread.-
  wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage
 (ActivityThread.java:1344) at android.os.Handler.dispatchMessage
 (Handler.java:102) at android.os.Looper.loop(Looper.java:148) at
 android.app.ActivityThread.main(ActivityThread.java:5417) at
 java.lang.reflect.Method.invoke(Native Method) at
 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
 (ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main
 (ZygoteInit.java:616)
</code>```

java Error line

It is showing error at this

```<code> lv.setAdapter(arrayAdapter);
</code>```

答:
The problem is, you are populating data too early. when you call retrieve() method it runs immediately and return an empty Arrylist. Firebase dosen't give you data instantly. It makes some delay while getting the data. so get all data first then populate your adapter.

or use

```<code>adapter.notifydatasetchanged();
</code>```

after getting data.

Body:
Can someone help me in this problem, I try to display job from the firebase in Listview, but it doesn't display anything! I have tried different codes from topic at stack and different sites but receive error at

adapter=new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,retrieve());

and this

lv.setAdapter(adapter);

with nullexception

Javacode

package com.gumption.zeeshanahmed.jobaps;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.ArrayList;

 public class EditsJobs extends AppCompatActivity {

     ListView lv;
     ArrayAdapter<String> adapter;
     ArrayList<String> spacecrafts=new ArrayList<>();

// Declaring String variable ( In which we are storing firebase server URL
//).
     public static final String Firebase_Server_URL =
     "https://jobaps70.firebaseio.com/";

// Declaring String variables to store name & phone number get from
//EditText.
      String PriceHolder, JobDescriptionHolder;
      FirebaseHelper helper;

// Declaring Firebase object.
      Firebase firebase;

// Creating FirebaseAuth.
      FirebaseAuth firebaseAuth ;

// Creating FirebaseAuth.
      FirebaseUser firebaseUser;

// Creating Boolean variable that holds EditText is empty or not status.
      Boolean EditTextStatus ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edits_jobs);

//Actionbar
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setIcon(R.drawable.logo);
    getSupportActionBar().setBackgroundDrawable(new
    ColorDrawable(getResources().getColor(R.color.Snow)));

// Adding MainActivity context into Firebase context.

    Firebase.setAndroidContext(EditsJobs.this);

// Passing firebase Server URL into firebase object.

    firebase = new Firebase(Firebase_Server_URL);
    firebaseAuth = FirebaseAuth.getInstance();

// On activity start check whether there is user previously logged in or
//   not.

    if(firebaseAuth.getCurrentUser() == null){

        // Finishing current Profile activity.
        finish();

        // If user already not log in then Redirect to LoginActivity .
        Intent intent = new Intent(EditsJobs.this, LoginActivity.class);
        startActivity(intent);

        // Showing toast message.
        Toast.makeText(EditsJobs.this, "Please Log in to continue",
        Toast.LENGTH_LONG).show();

    }

    // Adding firebaseAuth current user info into firebaseUser object.
    firebaseUser = firebaseAuth.getCurrentUser();

    // Getting logged in user email from firebaseUser.getEmail() method and
     set into TextView.
    setTitle( firebaseUser.getEmail());
    setTitleColor(R.color.DarkGray);

    // ListView element

    lv = (ListView) findViewById(R.id.datadisplist);
    adapter=new ArrayAdapter<String>
    (this,android.R.layout.simple_list_item_1,retrieve());
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int
        position, long id) {
            Toast.makeText(EditsJobs.this, retrieve().get(position),
            Toast.LENGTH_SHORT).show();
         }
    });

}

 private void fetchData(DataSnapshot dataSnapshot)
{
    jobsdetails.clear();
    for (DataSnapshot ds : dataSnapshot.getChildren())
    {
        String jobs=ds.getValue(JobDetails.class).getjob();
        jobsdetails.add(jobs);
    }
}

//RETRIEVE
public ArrayList<String> retrieve(){
firebase.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        fetchData(dataSnapshot);
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String s) {
        fetchData(dataSnapshot);

    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {

    }

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String s) {

    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }

});

return spacecrafts;
}
}

XML

   <?xml version="1.0" encoding="utf-8"?>
   <RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="com.gumption.zeeshanahmed.jobaps.EditsJobs">
   <TextView
    android:id="@+id/texteditjobs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/text_edit_jobs"
    android:textSize="40sp"
    android:textAlignment="center"/>

    <ListView
        android:id="@+id/datadisplist"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/texteditjobs"
        android:background="@color/Khaki"/>
       </RelativeLayout>

JobDetail

 public class JobDetails {

    private String price;
    private String jobDescription;
    private String jobSpinner;
    public String email;
    public JobDetails() {
        // This is default constructor.
    }

    public String getPrice() {

        return price;
    }

    public void setPrice(String pri) {

        this.price = pri;
    }

    public String getjobDescription() {

        return jobDescription;

    }

    public void setjobDescription(String jobd) {

        this.jobDescription = jobd;
    }

    public void setjob(String jry) {

        this.jobSpinner = jry ;

    }

    public String getjob() {

        return jobSpinner;

    }

    public void setemail(String jel) {

        this.email = jel ;

    }

    public String getemail() {

        return email;

    }
}

Using textView

when i use text view the data is displayed only one atmost!

// Adding click listener to Show data button.
    ShowButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Adding addValueEventListener method on firebase object.
            firebase.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot MainSnapshot) {

              for (DataSnapshot SubSnapshot : MainSnapshot.getChildren()) {

              JobDetails jobdetails =SubSnapshot.getValue(JobDetails.class);
                    for
                        // Adding name and phone number of student into
                      string that is coming from server.

                        String ShowDataString = "Job: " +
                        jobdetails.getjob() + "\nJob Description: " +
                        jobdetails.getjobDescription() + "\n\n";

                        // Apply complete string variable into TextView.
                        ShowDataTextView.setText(ShowDataString);
               }
                    }
                }

                @Override
                public void onCancelled(FirebaseError firebaseError) {
                    System.out.println("Data Access Failed" +
                firebaseError.getMessage());
                }
            });
        }
        });

with Xml

   <TextView
    android:id="@+id/showmetadata"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/show"
    android:textSize="40sp"
    android:textAlignment="center"/>

It will be very helpful if someone help will me with this. Please and thank
you!

**Tried listview **

Now i tried listview, and it crashes here is the code and error

 public class WorkActivity extends AppCompatActivity {

//    Spinner jobSpin;

ListView lv;
Button ShowButton;
// Define a String ArrayList for the job
private ArrayList<String> jobdes=new ArrayList<>();

// Define an ArrayAdapter for the list
private ArrayAdapter<String> arrayAdapter;

// Declaring String variable ( In which we are storing firebase server URL
).
public static final String Firebase_Server_URL =
"https://jobaps70.firebaseio.com/";
public static final String Firebase_Server_URL1 =
 "https://jobaps70.firebaseio.com/jobs";

// Declaring String variables to store name & phone number get from
EditText.
String PriceHolder, JobDescriptionHolder;
FirebaseHelper helper;

// Declaring Firebase object.
Firebase firebase,firebase1;

// Creating FirebaseAuth.
FirebaseAuth firebaseAuth ;

// Creating FirebaseAuth.
FirebaseUser firebaseUser;

// Creating Boolean variable that holds EditText is empty or not status.
Boolean EditTextStatus ;

TextView ShowDataTextView ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edits_jobs);

      //        Actionbar
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setIcon(R.drawable.logo);
    getSupportActionBar().setBackgroundDrawable(new
    ColorDrawable(getResources().getColor(R.color.Snow)));

    ShowButton = (Button)findViewById(R.id.show);

    // Adding MainActivity context into Firebase context.
    Firebase.setAndroidContext(WorkActivity.this);

    // Passing firebase Server URL into firebase object.
    firebase = new Firebase(Firebase_Server_URL);
    firebase1=new Firebase(Firebase_Server_URL1);

    firebaseAuth = FirebaseAuth.getInstance();

    // On activity start check whether there is user previously logged in or
       not.
    if(firebaseAuth.getCurrentUser() == null){

        // Finishing current Profile activity.
        finish();

        // If user already not log in then Redirect to LoginActivity .
        Intent intent = new Intent(WorkActivity.this, LoginActivity.class);
        startActivity(intent);

        // Showing toast message.
        Toast.makeText(WorkActivity.this, "Please Log in to continue",
        Toast.LENGTH_LONG).show();

    }

    // Adding firebaseAuth current user info into firebaseUser object.
    firebaseUser = firebaseAuth.getCurrentUser();

    // Getting logged in user email from firebaseUser.getEmail() method and
        set into TextView.
    setTitle( firebaseUser.getEmail());
    setTitleColor(R.color.DarkGray);
      firebase.child("jobs");

    // Associate the jobs' list with the corresponding ListView
    lv = (ListView) findViewById(R.id.lvshow);

    // Set the ArrayAdapter to the ListView
    arrayAdapter = new ArrayAdapter<String>(this,
       android.R.layout.simple_list_item_1, jobdes);
    lv.setAdapter(arrayAdapter);

    // Attach a ChildEventListener to the teacher database, so we can
          retrieve the job entries
    firebase.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {

            // Get the value from the DataSnapshot and add it to the jobs'
         list
            JobDetails jo = (JobDetails)
         dataSnapshot.getValue(JobDetails.class);
            String joString = String.valueOf(jo);
            arrayAdapter.add(joString);
 //

            // Notify the ArrayAdapter that there was a change
            arrayAdapter.notifyDataSetChanged();
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(FirebaseError databaseError) {

        }
    });
}

}

Error

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.gumption.zeeshanahmed.jobaps, PID: 4774
              java.lang.RuntimeException: Unable to start activity
              ComponentInfo{com.gumption.zeeshanahmed.jobaps/
              com.gumption.zeeshanahmed.jobaps.WorkActivity}:
              java.lang.NullPointerException: Attempt to invoke virtual
              method 'void
             android.widget.ListView.setAdapter(android.widget.ListAdapter)'
             on a null object reference at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                  at android.app.ActivityThread.-wrap11(ActivityThread.java)
                  at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:148)at
 android.app.ActivityThread.main(ActivityThread.java:5417)
                  at java.lang.reflect.Method.invoke(Native Method) at
 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
 (ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main
 (ZygoteInit.java:616)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a
 null object reference at
 com.gumption.zeeshanahmed.jobaps.WorkActivity.onCreate
 (WorkActivity.java:109)
              at android.app.Activity.performCreate(Activity.java:6237) at
 android.app.Instrumentation.callActivityOnCreate
 (Instrumentation.java:1107) at
 android.app.ActivityThread.performLaunchActivity
 (ActivityThread.java:2369)atandroid.app.ActivityThread.handleLaunchActivity
 (ActivityThread.java:2476) at android.app.ActivityThread.-
  wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage
 (ActivityThread.java:1344) at android.os.Handler.dispatchMessage
 (Handler.java:102) at android.os.Looper.loop(Looper.java:148) at
 android.app.ActivityThread.main(ActivityThread.java:5417) at
 java.lang.reflect.Method.invoke(Native Method) at
 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
 (ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main
 (ZygoteInit.java:616)

java Error line

It is showing error at this

 lv.setAdapter(arrayAdapter);

Body:
The problem is, you are populating data too early. when you call retrieve() method it runs immediately and return an empty Arrylist. Firebase dosen't give you data instantly. It makes some delay while getting the data. so get all data first then populate your adapter.

or use

adapter.notifydatasetchanged();

after getting data.


来源: stackexchange

问:
Creating flat list from single float or list of floats
I wish to iterate over a zip of objects and floats together using a parent class function. Sometimes the subclasses have three objects and three floats in a list, this works fine:

```<code>L = [A,B,C]
F = [1,2,3]

for f, o in zip(L,F):
    # do stuff
</code>```

Sometimes the subclass has one object and one float

```<code>L = A
F = 1

for f, o in zip(L,F):
    # TypeError
</code>```

This throws an exception because F is not iterable.

If I try:

```<code>F = list(F)
</code>```

This works for 2 or more floats but throws an exception for a single float (it's still not iterable :)).

If I try:

```<code>F = [F]
</code>```

This solves the 1 float case but now returns a nested list when there are two or more floats!

```<code>a = [1,2]
[a] = [[1,2]]
</code>```

Is there a simple builtin way to receive either a single float or list of floats and return a single flat list? Or do I need something like itertools.chain?

答:
Just check if you already have a list, and if not create one with a single element:

```<code>f = f if isinstance(f,list) else [f]
</code>```

For example:

```<code>>>> f = 1
>>> f = f if isinstance(f,list) else [f]
>>> f
[1]
>>> f = [1,2]
>>> f = f if isinstance(f,list) else [f]
>>> f
[1, 2]
</code>```

Note, I'm assuming your using lists but you could use collections.Iterable for a more generic solution.

Further note, I don't know where F/f came from, but ideally it would have been initially created this way rather than fixing it now.

ContentLicense: CC BY-SA 3.0

Body:
I wish to iterate over a zip of objects and floats together using a parent class function. Sometimes the subclasses have three objects and three floats in a list, this works fine:

L = [A,B,C]
F = [1,2,3]

for f, o in zip(L,F):
    # do stuff

Sometimes the subclass has one object and one float

L = A
F = 1

for f, o in zip(L,F):
    # TypeError

This throws an exception because F is not iterable.

If I try:

F = list(F)

This works for 2 or more floats but throws an exception for a single float (it's still not iterable :)).

If I try:

F = [F]

This solves the 1 float case but now returns a nested list when there are two or more floats!

a = [1,2]
[a] = [[1,2]]

Is there a simple builtin way to receive either a single float or list of floats and return a single flat list? Or do I need something like itertools.chain?

Body:
Just check if you already have a list, and if not create one with a single element:

f = f if isinstance(f,list) else [f]

For example:

>>> f = 1
>>> f = f if isinstance(f,list) else [f]
>>> f
[1]
>>> f = [1,2]
>>> f = f if isinstance(f,list) else [f]
>>> f
[1, 2]

Note, I'm assuming your using lists but you could use collections.Iterable for a more generic solution.

Further note, I don't know where F/f came from, but ideally it would have been initially created this way rather than fixing it now.


问:
Displaytag alternatives
I'm building an application using Struts 2 + Spring 3 + Hibernate 3. I was wondering if any of you knows of any alternative to the "displaytag" library to draw and manage tables.

Not that I dislike it so much, but I read this comment and made me wonder about other options. And I see it has not been updated in a while and I was wondering if there is some reason for that (like a better/more popular alternative available).

答: I think, you should interest the PrimeFaces library, especially, a datatable component. It works with Spring Framework.</p>

ContentLicense: CC BY-SA 2.5

Title: Displaytag alternatives


答: You can try a = a if isinstance(a, collections.Iterable) else [a]. This makes sure a is either iterable or converts it to list. Also you need not convert a, you could assign the result to another variable.

Title: Creating flat list from single float or list of floats


问:
local repo has lost its connection to remote
A couple of months ago I set up a new local repo linked to a remote on github.  I've been happily committing changes to my local and pushing them up to my origin without a problem until last week.
Suddenly when I tried to do a push to the remote I got

```<code>$ git push origin
fatal: 'origin' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

Stopping and restarting Bash seemed to fix the problem.  But yesterday I tried to push and got the same error.  Only this time stop/starting Bash didn't help.

My local repo appears fine.  I can examine the log and see all my commits.
The remote on github also appears ok.
I would like to find the ssh connection string on github and reset my gitconfig.  But I cannot find it. I remember copy pasting it when I created the repo.  But I can no longer locate it.

So in addition to asking for help to be able to push, I would also ask if anyone has seen this problem and what migh have caused it?

答:
Check what 'git remote -v' says.

To see the github ssh link, login and click on Clone or Download.

Finally, use 'git remote set-url origin ...' to make the change per https://help.github.com/articles/changing-a-remote-s-url/. Perhaps you changed the repo owner? Strange about the BASH though.

Body:
A couple of months ago I set up a new local repo linked to a remote on github.  I've been happily committing changes to my local and pushing them up to my origin without a problem until last week.
Suddenly when I tried to do a push to the remote I got

$ git push origin
fatal: 'origin' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Stopping and restarting Bash seemed to fix the problem.  But yesterday I tried to push and got the same error.  Only this time stop/starting Bash didn't help.

My local repo appears fine.  I can examine the log and see all my commits.
The remote on github also appears ok.
I would like to find the ssh connection string on github and reset my gitconfig.  But I cannot find it. I remember copy pasting it when I created the repo.  But I can no longer locate it.

So in addition to asking for help to be able to push, I would also ask if anyone has seen this problem and what migh have caused it?


问:
Array of Struct - Codable
Please direct me to a possible duplicate, but in my research I wasn't able to figure out a solution.

Here is the JSON Object I'm attempting to decode from my REST API:

```<code>{
    "name": "Oak",

    "leaves":[
    {
        "id": "1A",
        "damaged": false
    },
    {
        "id": "2A",
        "damaged": false
    },
    {
        "id": "3E",
        "damaged": false
    }
]

}
</code>```

Here is the code so far:

```<code>struct Tree: Codable {
     var name : String?
     var leaves : [Leaf]?

     init() {
        self.name = string()
        self.leaves = []
     }
 }

struct Leaf: Codable {
     var id : String?
     var damaged : Bool?

     init(){
        self.id = String()
        self.damaged = Bool()
     }
}
</code>```

Now when I consume the API I decode the response using:

```<code>let jsonDecoder = JSONDecoder()
let time = try jsonDecoder.decode(Tree.self, from: data)
</code>```

When I try to decode for this API I get:

"The data couldn’t be read because it isn’t in the correct format."

I appreciate any guidance you can provide, thank you!

Also, the init's are there due to their use as a singleton, I'm not looking for a suggestion to not use the singleton pattern, I'm just interested in finding what the problem with this decoding is.

Edit:

Thanks everyone for your responses! I thought the problem was coming from Array of custom Struct, but it was actually much simpler and I feel foolish. Check out my answer below.

So again, thanks everyone for the guidance that humbled myself!

答:
For anyone looking at this question for the custom Struct in an array for swift4 this code does work as expected.

I missed a parameter in my data when I asked the question thinking it wasn't the problem. The additional field is now below and my problem was that I was declaring the date as Int32? instead of Int64?.

```<code>{
    "name": "Oak",
    "discoveryDate": 1514178000000,

    "leaves":[
    {
        "id": "1A",
        "damaged": false
    },
    {
        "id": "2A",
        "damaged": false
    },
    {
        "id": "3E",
        "damaged": false
    }
]

}
</code>```

Which would change the structs to:

```<code>struct Tree: Codable {
     var name : String?
     var discoveryDate : Int64?
     var leaves : [Leaf]?

     init() {
        self.name = String()
        self.discoveryDate = Int64()
        self.leaves = []
     }
 }

struct Leaf: Codable {
     var id : String?
     var damaged : Bool?

     init(){
        self.id = String()
        self.damaged = Bool()
     }
}
</code>```

Title: Array of Struct - Codable

Body:
Please direct me to a possible duplicate, but in my research I wasn't able to figure out a solution.

Here is the JSON Object I'm attempting to decode from my REST API:

{
    "name": "Oak",

    "leaves":[
    {
        "id": "1A",
        "damaged": false
    },
    {
        "id": "2A",
        "damaged": false
    },
    {
        "id": "3E",
        "damaged": false
    }
]

}

Here is the code so far:

struct Tree: Codable {
     var name : String?
     var leaves : [Leaf]?

     init() {
        self.name = string()
        self.leaves = []
     }
 }

struct Leaf: Codable {
     var id : String?
     var damaged : Bool?

     init(){
        self.id = String()
        self.damaged = Bool()
     }
}

Now when I consume the API I decode the response using:

let jsonDecoder = JSONDecoder()
let time = try jsonDecoder.decode(Tree.self, from: data)

When I try to decode for this API I get:

"The data couldn’t be read because it isn’t in the correct format."

I appreciate any guidance you can provide, thank you!

Also, the init's are there due to their use as a singleton, I'm not looking for a suggestion to not use the singleton pattern, I'm just interested in finding what the problem with this decoding is.

Edit:

Thanks everyone for your responses! I thought the problem was coming from Array of custom Struct, but it was actually much simpler and I feel foolish. Check out my answer below.

So again, thanks everyone for the guidance that humbled myself!

Body:
For anyone looking at this question for the custom Struct in an array for swift4 this code does work as expected.

I missed a parameter in my data when I asked the question thinking it wasn't the problem. The additional field is now below and my problem was that I was declaring the date as Int32? instead of Int64?.

{
    "name": "Oak",
    "discoveryDate": 1514178000000,

    "leaves":[
    {
        "id": "1A",
        "damaged": false
    },
    {
        "id": "2A",
        "damaged": false
    },
    {
        "id": "3E",
        "damaged": false
    }
]

}

Which would change the structs to:

struct Tree: Codable {
     var name : String?
     var discoveryDate : Int64?
     var leaves : [Leaf]?

     init() {
        self.name = String()
        self.discoveryDate = Int64()
        self.leaves = []
     }
 }

struct Leaf: Codable {
     var id : String?
     var damaged : Bool?

     init(){
        self.id = String()
        self.damaged = Bool()
     }
}


问:
Selecting the second checkbox also selects the first one
I have a form with two checkboxes that allows the user to select yes or no based on the question asked. Now when I select the second checkbox, the first checkbox is also selected which is what I don't want. When I say the area within the second container is clicked, you have to directly click on the checkbox area (the label or the rest of the container won't select the checkbox like the first checkbox and it's container will). So when you click the second checkbox directly it also checks the first.

My question is, why is it allowing me to check anywhere within the first container, but not the second container? Additionally, why is the first being selected when I only want to select the second one?

HTML (disregard the inline CSS that will be moved over to stylesheet.css):

```<code><div style="background: #FFF; width: 1200px; height: 700px; display: block; margin: 100px auto; overflow: auto;">
    <div style="display: block; margin: 30px auto; height: 400px; width: 1000px">
      <h4 style="font-family: 'Lato', sans-serif; margin-top: 90px; letter-spacing: 1px;"><strong>Blah blah blah?</strong></h4>

      <div class="inline field" style="max-width: 500px;">

        <form role="form" action="" style="margin-top: 60px;">
          <div class="checkbox" style="height: 50px; border: 2px solid #f8f8f8; border-radius: 2px;">
            <label for="checkbox1" style="height: 46px; padding-top: 14px; width: 500px;">
              <input type="checkbox" id="checkbox1" class="checkbox-circle" value="true" style="background: red; margin-right: 20px;" />
              Yes</label>
          </div>

          <div class="checkbox" style="height: 50px; border: 2px solid #f8f8f8; border-radius: 2px;">
            <label for="checkbox1" style="height: 46px; padding-top: 14px; width: 500px;">
              <input type="checkbox" id="checkbox1" class="checkbox-circle" value="true" style="background: red; margin-right: 20px;" />
              No</label>
          </div>
        </form>

      </div>
    </div>
  </div>
</code>```

Image of the form:

答:
You have two label for="checkbox1" and both IDs are the same. These should be different.</p>

```<code>      <div class="checkbox">
        <label for="checkbox1" >
          <input type="checkbox" id="checkbox1"  />
          Yes</label>
      </div>
     <div class="checkbox">
        <label for="checkbox2" >
          <input type="checkbox" id="checkbox2"  />
          No</label>
      </div>
</code>```

Body:
I have a form with two checkboxes that allows the user to select yes or no based on the question asked. Now when I select the second checkbox, the first checkbox is also selected which is what I don't want. When I say the area within the second container is clicked, you have to directly click on the checkbox area (the label or the rest of the container won't select the checkbox like the first checkbox and it's container will). So when you click the second checkbox directly it also checks the first.

My question is, why is it allowing me to check anywhere within the first container, but not the second container? Additionally, why is the first being selected when I only want to select the second one?

HTML (disregard the inline CSS that will be moved over to stylesheet.css):

Blah blah blah?

        <form role="form" action="" style="margin-top: 60px;">

              <input type="checkbox" id="checkbox1" class="checkbox-circle" value="true" style="background: red; margin-right: 20px;" />
              Yes

              <input type="checkbox" id="checkbox1" class="checkbox-circle" value="true" style="background: red; margin-right: 20px;" />
              No

        </form>

Image of the form:

Body:
You have two label for="checkbox1" and both IDs are the same. These should be different.

      <div class="checkbox">
        <label for="checkbox1" >
          <input type="checkbox" id="checkbox1"  />
          Yes</label>
      </div>
     <div class="checkbox">
        <label for="checkbox2" >
          <input type="checkbox" id="checkbox2"  />
          No</label>
      </div>


问:
ASP.Net Core 2 configuration taking up a lot of memory. How do I get config information differently?
Ok, so I have an app that gets a pretty good amount of traffic. I have been working with the Microsoft Azure and Coding teams to resolve a problem with memory. They have seen the GB's of logs and how found that the Microsoft.Extensions.Configuration code is taking up a lion's share of the RAM when we are under heavy load.

In my API code I have a "base controller" that all of the other controllers inherit from. This allows me to share common methods and the like. In this base controller I have created a global variable:

```<code>   public IConfigurationRoot _configuration { get; }
</code>```

This is, I believe, the culprit... but I am not sure how to get rid of it. This _configuration variable allows me to get access to my appsettings.json environment variables. I am not sure how to get access to these in a different way.

For instance... in a GET call I need to know if we have caching on or not.

```<code>    bool isCaching = bool.Parse(_configuration["Data:Cache"]);
</code>```

One thought I had is to make the _configuration private to the BaseController and make methods inside of there to get the properties I need (i.e. caching) so that the other controllers don't have to pass around this _configuration object.
Not sure if make it private will do anything though....

答:
I am not sure why you need to be parsing the same values over and over again, when you could just read the configuration file during Startup and reuse it:</p>

```<code>public class MyConfiguration
{
    public bool CachingEnabled { get; set; }
    // more configuration data
}

public void ConfigureServices(IServiceCollection services)
{
    // your existing configuration
    var myConfiguration = new MyConfiguration
    {
        CachingEnabled = bool.Parse(Configuration["Data:Cache"]),
        // other properties
    }

    // register the data as a singleton since it won't change
    services.AddSingleton(myConfiguration);
}

public class MyController : Controller
{
    private readonly MyConfiguration configuration;

    public MyController(MyConfiguration config)
    {
        configuration = config;
    }
}
</code>```

Body:
Ok, so I have an app that gets a pretty good amount of traffic. I have been working with the Microsoft Azure and Coding teams to resolve a problem with memory. They have seen the GB's of logs and how found that the Microsoft.Extensions.Configuration code is taking up a lion's share of the RAM when we are under heavy load.

In my API code I have a "base controller" that all of the other controllers inherit from. This allows me to share common methods and the like. In this base controller I have created a global variable:

   public IConfigurationRoot _configuration { get; }

This is, I believe, the culprit... but I am not sure how to get rid of it. This _configuration variable allows me to get access to my appsettings.json environment variables. I am not sure how to get access to these in a different way.

For instance... in a GET call I need to know if we have caching on or not.

    bool isCaching = bool.Parse(_configuration["Data:Cache"]);

One thought I had is to make the _configuration private to the BaseController and make methods inside of there to get the properties I need (i.e. caching) so that the other controllers don't have to pass around this _configuration object.
Not sure if make it private will do anything though....

Body:
I am not sure why you need to be parsing the same values over and over again, when you could just read the configuration file during Startup and reuse it:

public class MyConfiguration
{
    public bool CachingEnabled { get; set; }
    // more configuration data
}

public void ConfigureServices(IServiceCollection services)
{
    // your existing configuration
    var myConfiguration = new MyConfiguration
    {
        CachingEnabled = bool.Parse(Configuration["Data:Cache"]),
        // other properties
    }

    // register the data as a singleton since it won't change
    services.AddSingleton(myConfiguration);
}

public class MyController : Controller
{
    private readonly MyConfiguration configuration;

    public MyController(MyConfiguration config)
    {
        configuration = config;
    }
}


问:
Error with datepicker ngx-bootstrap and Validators Angular 4
When I started to use the datepicker, the html changed to:

```<code><div class="form-group col-md-4">
<label for="arrivalDate">Entry and Departure</label>
<input formControlName="arrivalDate" class="form-control" id="arrivalDate" placeholder="mm/dd/yyyy - mm/dd/yyyy" bsDaterangepicker [minDate]="minDate" [bsConfig]="dpConfig">
</code>```

That have a component the next:

```<code>this._form = this.fb.group({
   // Search basic
   destination: ['', Validators.required],
   arrivalDate: [null, Validators.required],
   qtyAdults: [0, [Validators.required, Validators.min(1) ]],
   qtyChilds: [0, Validators.required ],
   childsage: this.fb.array([]),
   adultsage: this.fb.array([]),
   serviceType: [],
   qtyProduct: ['1', Validators.min(1)]
});
</code>```

So, while it was the input type date the Validators did not fail, but when changing it to the datepicker of ngx-bootstrap, it gives error.

The error in the next:

Error: There is no FormControl instance attached to form control
  element with name: 'arrivalDate'

Before when I was using  does not gives error, but with this datepicker, started to give that error

I'm using this https://valor-software.com/ngx-bootstrap/#/datepicker

答:
In the html I added a div with:

```<code>*ngIf = "isFormHotelActivate"
</code>```

and in the component:

```<code>_initFormHotels() {
    this._formT = this.fb.group({
       // Search basic
       origin: [''],
       destination: ['', Validators.required],
       arrivalDate: [null, Validators.required],
       qtyProduct: [1, Validators.min(1)]
    });
this.isFormHotelActivate = true;
}
</code>```

Body:
When I started to use the datepicker, the html changed to:

Entry and Departure
<input formControlName="arrivalDate" class="form-control" id="arrivalDate" placeholder="mm/dd/yyyy - mm/dd/yyyy" bsDaterangepicker [minDate]="minDate" [bsConfig]="dpConfig">

That have a component the next:

this._form = this.fb.group({
   // Search basic
   destination: ['', Validators.required],
   arrivalDate: [null, Validators.required],
   qtyAdults: [0, [Validators.required, Validators.min(1) ]],
   qtyChilds: [0, Validators.required ],
   childsage: this.fb.array([]),
   adultsage: this.fb.array([]),
   serviceType: [],
   qtyProduct: ['1', Validators.min(1)]
});

So, while it was the input type date the Validators did not fail, but when changing it to the datepicker of ngx-bootstrap, it gives error.

The error in the next:

Error: There is no FormControl instance attached to form control
  element with name: 'arrivalDate'

Before when I was using  does not gives error, but with this datepicker, started to give that error

I'm using this https://valor-software.com/ngx-bootstrap/#/datepicker

Body:
In the html I added a div with:

*ngIf = "isFormHotelActivate"

and in the component:

_initFormHotels() {
    this._formT = this.fb.group({
       // Search basic
       origin: [''],
       destination: ['', Validators.required],
       arrivalDate: [null, Validators.required],
       qtyProduct: [1, Validators.min(1)]
    });
this.isFormHotelActivate = true;
}


问:
C# How to determine a status of a Form
I have a tray app that starts ( Form 1 ) and shows on right click a "Login" menu strip item.
On click, I setup a Form 2, asking for user and pass.

On a successful authentication, I'd like to close Form 2 and continue with Form 1 ( ie. I would like to start a timer ).

I was thinking of just setting up a timer which would check the Form 2 status ( basically a getter function inside Form 2 ).

Still, I think there has to be an easier way than having something tick.

答: I dont think you need a timer or any thing for that just show the form as a Modal Dialogue and return to main form when closed.</p>

Title: C# How to determine a status of a Form


问:
How to delete single (many-) rows from one-to-many relations in Laravel 5.5
I got two models in Laravel: Label

```<code>class Label extends \Eloquent
{
    protected $fillable = [
        'channel_id',
        'name',
        'color',
    ];

    public function channel()
    {
        return $this->belongsTo('App\Channel');
    }
}
</code>```

And Channel

```<code>class Channel extends \Eloquent
{
    protected $fillable = [
        'name',
    ];

    public function labels()
    {
        return $this->hasMany('App\Label');
    }

}
</code>```

Now when a label is deleted, I want to make sure, the label belongs to the channel.

This works pretty good, as it even is atomic, so the row will just be deleted, if the label really belongs to the channel.

LabelController:

```<code>/**
 * Remove the specified resource from storage.
 *
 * @param  int $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    $channel = $this->getChannel();

    Label::where('id', $id)
        ->where('channel_id', $channel->id)
        ->delete();

    return back();
}
</code>```

And my question is now: How to build that with Eloquent, so it is elegant? Something like:

```<code>    $channel->labels()->destroy($id);
</code>```

But there is no destroy function on the relation.

Update:

I managed to achieve something in the right direction:

```<code>$channel->labels()->find($id)->delete();
</code>```

This deletes the label with $id BUT just if the label has the right channel_id assigned. If not, I get the following error, which I could catch and handle:

```<code>FatalThrowableError (E_ERROR) Call to a member function delete() on null
</code>```

Still, as Apache is threaded, there could be the case that another thread changes the channel_id after I read it. So the only way besides my query is to run a transaction?

答:
You can use findorfail:

$channel->labels()->findOrFail($id)->delete();

Body:
I got two models in Laravel: Label

class Label extends \Eloquent
{
    protected $fillable = [
        'channel_id',
        'name',
        'color',
    ];

    public function channel()
    {
        return $this->belongsTo('App\Channel');
    }
}

And Channel

class Channel extends \Eloquent
{
    protected $fillable = [
        'name',
    ];

    public function labels()
    {
        return $this->hasMany('App\Label');
    }

}

Now when a label is deleted, I want to make sure, the label belongs to the channel.

This works pretty good, as it even is atomic, so the row will just be deleted, if the label really belongs to the channel.

LabelController:

/**
 * Remove the specified resource from storage.
 *
 * @param  int $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    $channel = $this->getChannel();

    Label::where('id', $id)
        ->where('channel_id', $channel->id)
        ->delete();

    return back();
}

And my question is now: How to build that with Eloquent, so it is elegant? Something like:

    $channel->labels()->destroy($id);

But there is no destroy function on the relation.

Update:

I managed to achieve something in the right direction:

$channel->labels()->find($id)->delete();

This deletes the label with $id BUT just if the label has the right channel_id assigned. If not, I get the following error, which I could catch and handle:

FatalThrowableError (E_ERROR) Call to a member function delete() on null

Still, as Apache is threaded, there could be the case that another thread changes the channel_id after I read it. So the only way besides my query is to run a transaction?


问:
How to check supported architectures for my framework in terminal?
I want to know which architectures are supports my framework.

I referred some of stack overflow questions and tried like this in terminal

```<code>lipo -info /Users/admin/library/myFramework.framework
</code>```

But I didn't get any solution.

How to solve my problem.

答:
lipo -info pathToFramework/MyFramework.framework/MyFramework

you may get an error like

xcrun: error: active developer path ("/Applications/Xcode.app/Contents/Developer") does not exist, use xcode-select --switch path/to/Xcode.app to specify the Xcode that you wish to use for command line developer tools (or see man xcode-select)

select command Line tools

after this try again

lipo -info pathToFramework/MyFramework.framework/MyFramework

Body:
I want to know which architectures are supports my framework.

I referred some of stack overflow questions and tried like this in terminal

lipo -info /Users/admin/library/myFramework.framework

But I didn't get any solution.

How to solve my problem.


问:
asp.net core 2.0 app crashes when role based authorization faild
I want to authorize user based on roles:

```<code>[Authorize(Roles = "Administrator")]
public class TestController : Controller
{
    public IActionResult Index()
    {
        return Ok();
    }
}
</code>```

When the user has Claim(type: "Role", value: "Administrator"), it works ok. When he doesn't the application crashes. When debugging in VS, it just stops and IIS Express process ends. I don't see any exception. I only see this output debug output:

```<code>Application Insights Telemetry: {"name":"Microsoft.ApplicationInsights.Dev.2822d75fd5c24f0180cd7a0cd61c0e40.Message","time":"2017-12-06T12:03:16.7897859Z","iKey":"2822d75f-d5c2-4f01-80cd-7a0cd61c0e40","tags":{"ai.internal.sdkVersion":"aspnet5c:2.1.1","ai.location.ip":"127.0.0.1","ai.internal.nodeName":"MY-DESKTOP","ai.cloud.roleInstance":"MY-DESKTOP","ai.operation.parentId":"|a2488207-417e03727b6f68b7.","ai.operation.name":"GET test/Index","ai.operation.id":"a2488207-417e03727b6f68b7","ai.application.ver":"1.0.0.0"},"data":{"baseType":"MessageData","baseData":{"ver":2,
    "message":"Authorization failed for user: liero@mycompany.com.","severityLevel":"Information","properties":{"CategoryName":"Microsoft.AspNetCore.Authorization.DefaultAuthorizationService","AspNetCoreEnvironment":"Development","{OriginalFormat}":"Authorization failed for user: {UserName}.","DeveloperMode":"true","UserName":"liero@mycompany.com"}}}}

Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.

Application Insights Telemetry: {"name":"Microsoft.ApplicationInsights.Dev.2822d75fd5c24f0180cd7a0cd61c0e40.Message","time":"2017-12-06T12:03:16.7962379Z","iKey":"2822d75f-d5c2-4f01-80cd-7a0cd61c0e40","tags":{"ai.internal.sdkVersion":"aspnet5c:2.1.1","ai.location.ip":"127.0.0.1","ai.internal.nodeName":"MY-DESKTOP","ai.cloud.roleInstance":"MY-DESKTOP","ai.operation.parentId":"|a2488207-417e03727b6f68b7.","ai.operation.name":"GET test/Index","ai.operation.id":"a2488207-417e03727b6f68b7","ai.application.ver":"1.0.0.0"},"data":{"baseType":"MessageData","baseData":{"ver":2,
    "message":"Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.","severityLevel":"Information","properties":{"CategoryName":"Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker","AspNetCoreEnvironment":"Development","{OriginalFormat}":"Authorization failed for the request at filter '{AuthorizationFilter}'.","DeveloperMode":"true","AuthorizationFilter":"Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter"}}}}

Microsoft.AspNetCore.Mvc.ForbidResult:Information: Executing ForbidResult with authentication schemes ().

Application Insights Telemetry: {"name":"Microsoft.ApplicationInsights.Dev.2822d75fd5c24f0180cd7a0cd61c0e40.Message","time":"2017-12-06T12:03:16.8222130Z","iKey":"2822d75f-d5c2-4f01-80cd-7a0cd61c0e40","tags":{"ai.internal.sdkVersion":"aspnet5c:2.1.1","ai.location.ip":"127.0.0.1","ai.internal.nodeName":"MY-DESKTOP","ai.cloud.roleInstance":"MY-DESKTOP","ai.operation.parentId":"|a2488207-417e03727b6f68b7.","ai.operation.name":"GET test/Index","ai.operation.id":"a2488207-417e03727b6f68b7","ai.application.ver":"1.0.0.0"},"data":{"baseType":"MessageData","baseData":{"ver":2,
    "message":"Executing ForbidResult with authentication schemes ().","severityLevel":"Information","properties":{"CategoryName":"Microsoft.AspNetCore.Mvc.ForbidResult","AspNetCoreEnvironment":"Development","{OriginalFormat}":"Executing ForbidResult with authentication schemes ({Schemes}).","DeveloperMode":"true","Schemes":"System.String[]"}}}}
</code>```

EDIT:
I've noticed that this happens when using AddOpenIdConnect authentication builder. When I comment it out, it redirects me to some default "forbidden" url

```<code>services.AddAuthentication(sharedOptions =>
{
    sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
  .AddCookie(option => option.Cookie.SameSite = SameSiteMode.None)
  .AddOpenIdConnect(option =>
  {
      option.ClientId = config.ClientId;
      option.Authority = String.Format(config.AadInstance, config.Tenant);
      option.SignedOutRedirectUri = config.PostLogoutRedirectUri;
      option.Events = new OpenIdConnectEvents
      {
          OnRedirectToIdentityProvider = redirectContext =>
          {
              bool isAjaxRequest = redirectContext.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";
              if (isAjaxRequest)
              {
                  redirectContext.HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
                  redirectContext.HttpContext.Response.Headers["Location"] = "/Account/Login";
                  redirectContext.HandleResponse();
              }
              return Task.CompletedTask;
          }
      };
  });
</code>```

答:
from github: Core CLR crashes when using Authorize attribute and OpenIdConnect

This was patched in 2.0.1 by #1435
  https://www.nuget.org/packages/Microsoft.AspNetCore.Authentication.OpenIdConnect/

The workaround is to set
  sharedOptions.DefaultSignInScheme =
  CookieAuthenticationDefaults.AuthenticationScheme;

I've verified the workaround and it works

Body:
I want to authorize user based on roles:

[Authorize(Roles = "Administrator")]
public class TestController : Controller
{
    public IActionResult Index()
    {
        return Ok();
    }
}

When the user has Claim(type: "Role", value: "Administrator"), it works ok. When he doesn't the application crashes. When debugging in VS, it just stops and IIS Express process ends. I don't see any exception. I only see this output debug output:

Application Insights Telemetry: {"name":"Microsoft.ApplicationInsights.Dev.2822d75fd5c24f0180cd7a0cd61c0e40.Message","time":"2017-12-06T12:03:16.7897859Z","iKey":"2822d75f-d5c2-4f01-80cd-7a0cd61c0e40","tags":{"ai.internal.sdkVersion":"aspnet5c:2.1.1","ai.location.ip":"127.0.0.1","ai.internal.nodeName":"MY-DESKTOP","ai.cloud.roleInstance":"MY-DESKTOP","ai.operation.parentId":"|a2488207-417e03727b6f68b7.","ai.operation.name":"GET test/Index","ai.operation.id":"a2488207-417e03727b6f68b7","ai.application.ver":"1.0.0.0"},"data":{"baseType":"MessageData","baseData":{"ver":2,
    "message":"Authorization failed for user: liero@mycompany.com.","severityLevel":"Information","properties":{"CategoryName":"Microsoft.AspNetCore.Authorization.DefaultAuthorizationService","AspNetCoreEnvironment":"Development","{OriginalFormat}":"Authorization failed for user: {UserName}.","DeveloperMode":"true","UserName":"liero@mycompany.com"}}}}

Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.

Application Insights Telemetry: {"name":"Microsoft.ApplicationInsights.Dev.2822d75fd5c24f0180cd7a0cd61c0e40.Message","time":"2017-12-06T12:03:16.7962379Z","iKey":"2822d75f-d5c2-4f01-80cd-7a0cd61c0e40","tags":{"ai.internal.sdkVersion":"aspnet5c:2.1.1","ai.location.ip":"127.0.0.1","ai.internal.nodeName":"MY-DESKTOP","ai.cloud.roleInstance":"MY-DESKTOP","ai.operation.parentId":"|a2488207-417e03727b6f68b7.","ai.operation.name":"GET test/Index","ai.operation.id":"a2488207-417e03727b6f68b7","ai.application.ver":"1.0.0.0"},"data":{"baseType":"MessageData","baseData":{"ver":2,
    "message":"Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.","severityLevel":"Information","properties":{"CategoryName":"Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker","AspNetCoreEnvironment":"Development","{OriginalFormat}":"Authorization failed for the request at filter '{AuthorizationFilter}'.","DeveloperMode":"true","AuthorizationFilter":"Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter"}}}}

Microsoft.AspNetCore.Mvc.ForbidResult:Information: Executing ForbidResult with authentication schemes ().

Application Insights Telemetry: {"name":"Microsoft.ApplicationInsights.Dev.2822d75fd5c24f0180cd7a0cd61c0e40.Message","time":"2017-12-06T12:03:16.8222130Z","iKey":"2822d75f-d5c2-4f01-80cd-7a0cd61c0e40","tags":{"ai.internal.sdkVersion":"aspnet5c:2.1.1","ai.location.ip":"127.0.0.1","ai.internal.nodeName":"MY-DESKTOP","ai.cloud.roleInstance":"MY-DESKTOP","ai.operation.parentId":"|a2488207-417e03727b6f68b7.","ai.operation.name":"GET test/Index","ai.operation.id":"a2488207-417e03727b6f68b7","ai.application.ver":"1.0.0.0"},"data":{"baseType":"MessageData","baseData":{"ver":2,
    "message":"Executing ForbidResult with authentication schemes ().","severityLevel":"Information","properties":{"CategoryName":"Microsoft.AspNetCore.Mvc.ForbidResult","AspNetCoreEnvironment":"Development","{OriginalFormat}":"Executing ForbidResult with authentication schemes ({Schemes}).","DeveloperMode":"true","Schemes":"System.String[]"}}}}

EDIT:
I've noticed that this happens when using AddOpenIdConnect authentication builder. When I comment it out, it redirects me to some default "forbidden" url

services.AddAuthentication(sharedOptions =>
{
    sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
  .AddCookie(option => option.Cookie.SameSite = SameSiteMode.None)
  .AddOpenIdConnect(option =>
  {
      option.ClientId = config.ClientId;
      option.Authority = String.Format(config.AadInstance, config.Tenant);
      option.SignedOutRedirectUri = config.PostLogoutRedirectUri;
      option.Events = new OpenIdConnectEvents
      {
          OnRedirectToIdentityProvider = redirectContext =>
          {
              bool isAjaxRequest = redirectContext.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";
              if (isAjaxRequest)
              {
                  redirectContext.HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
                  redirectContext.HttpContext.Response.Headers["Location"] = "/Account/Login";
                  redirectContext.HandleResponse();
              }
              return Task.CompletedTask;
          }
      };
  });


问:
Regex to capture the useragent from the citrix logs
Need help in capturing the user agent details from the citrix logs. The log format of the citrix is quite different for the successful and denied. The samples are given below

For Successful authentication the user agent details are enclosed within  "". Details are after the keyword Browser_type ""

For Denied traffic , useragent details are not present within the "". It is present after the keyword Browser

Denied

Dec  8 05:20:53 netscaler02  12/08/2017:05:20:53  netscaler02 0-PPE-0 : AAA LOGIN_FAILED -adasd92 0 :  User renju - Client_ip X.X.X.X - Failure_reason "External authentication server denied access" - Browser Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36

Success

Dec  8 05:54:06 netscaler02  12/08/2017:11:54:06 GMT netscaler02 0-PPE-0 : SSLVPN LOGIN -78342434122 0 : Context renjus@1X.X.X.X - SessionId: xxx- User renju - Client_ip X.X.X.X - Nat_ip "Mapped Ip" - Vserver X.X.X.X:443 - Browser_type "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36" - SSLVPN_asdasdat_type ICA - Group(s) "N/A"

I do have a regex to capture the browser agent within ""

(?P(?<=Browser_type\s\").?(?=\s(?:\w+=|\")))"

Bud need a regex that capture the user agent from all the format.

Thanks in advance.

答:
Maybe you could match your logs like this:

Browser(?:_type)?\s"?(.+|[^"]+)

Match Browser with optional _type Browser(?:_type)

Followed by an optional double quote "?

Followed by a whitespace \s

Then capture in a group ( any character zero or more times .*

or |

all until you encounter a double quote [^"]+

Close the group )

Edit:

To capture "Browser" without the optional "_type" in a named capture group:

(?P<citrix_useragent>Browser)(?:_type)?\s"?(.+|[^"]+)


答:
You can design your objects so that they have a builtin __iter__ method along with __len__:

```<code>class CertainObject:
     def __init__(self):
         self.variables = [23, 4, 2]
     def __len__(self):
         return len(self.variables)
     def __iter__(self):
         for i in self.variables:
             yield i
</code>```

Case 1(Multiple objects):

```<code>L = [CertainObject(), CertainObject(),CertainObject()]
F = [1,2,3]

for f, o in zip(L,F):
   pass
</code>```

Case 1 (singe object):

```<code>A = CertainObject()
F = 1
for a, b in zip(A, [F]*len(A)):
    print(a, b)
</code>```

With __iter__, iterating over the instance of the object will not raise an error.

Body:
You can design your objects so that they have a builtin __iter__ method along with __len__:

class CertainObject:
     def __init__(self):
         self.variables = [23, 4, 2]
     def __len__(self):
         return len(self.variables)
     def __iter__(self):
         for i in self.variables:
             yield i

Case 1(Multiple objects):

L = [CertainObject(), CertainObject(),CertainObject()]
F = [1,2,3]

for f, o in zip(L,F):
   pass

Case 1 (singe object):

A = CertainObject()
F = 1
for a, b in zip(A, [F]*len(A)):
    print(a, b)

With __iter__, iterating over the instance of the object will not raise an error.


问:
Spring JDBCTemplates: execute a query with Join
I'm developing an app for DB querying, using Spring Boot and JDBCTemplates.

The problem is this: if I have to ask the db on a single table, I have no problems. But, if I have a join, how can I perform this task?

More specifically, the SQL commands to create tables are these:

```<code>CREATE TABLE firewall_items
(
    id       INT NOT NULL AUTO_INCREMENT,
    firewall_id      INT NOT NULL,
    date     DATE,
    src      VARCHAR(15),
    src_port INT,
    dst      VARCHAR(15),
    dst_port INT,
    protocol VARCHAR(4),
    PRIMARY KEY(id)
    );

CREATE TABLE firewalls (
    id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(20) NOT NULL,
    ip VARCHAR(15) NOT NULL,
    info TEXT,
    PRIMARY KEY(id)
    );
</code>```

The correspondings java class are these:

```<code>import java.util.Date;

public class FirewallItems
{
    private Date date;
    private String id;
    private String protocol;
    private String src;
    private String dst;
    private String src_port;
    private String dst_port;
    private String firewall_id;

    public FirewallItems() {}

    public FirewallItems(Date data, String identificativo, String protocollo, String sorgente, String destinazione,
            String porta_sorgente, String porta_destinazione, String firewall_id)
    {
        super();
        this.date = data;
        this.id = identificativo;
        this.protocol = protocollo;
        this.src = sorgente;
        this.dst = destinazione;
        this.src_port = porta_sorgente;
        this.dst_port = porta_destinazione;
        this.firewall_id = firewall_id;
    }

    /**
     * Return the date of the report
     * @return date
     */
    public Date getDate()
    {
        return date;
    }

    /**
     * Set the date of the report
     * @param date the report's date
     */
    public void setDate(Date date)
    {
        this.date = date;
    }

    /**
     * Return the id of the report
     * @return id
     */
    public String getId()
    {
        return id;
    }

    /**
     * Set the id of the report
     * @param id the report's id
     */
    public void setId(String id)
    {
        this.id = id;
    }

    /**
     * Return the protocol cecked by report
     * @return protocol
     */
    public String getProtocol()
    {
        return protocol;
    }

    /**
     * Set the protocol cecked by report
     * @param protocol
     */
    public void setProtocol(String protocol)
    {
        this.protocol = protocol;
    }

    /**
     * Return the source of firewall's drop
     * @return Src
     */
    public String getSrc()
    {
        return src;
    }

    /**
     * Set the source of firewall's drop
     * @param src the firewall's source drop
     */
    public void setSrc(String src)
    {
        this.src = src;
    }

    /**
     * Return the firewall's destionation drop
     * @return dst
     */
    public String getDst()
    {
        return dst;
    }

    /**
     * Set the firewall's destination drop
     * @param dst the firewall's destination drop
     */
    public void setDst(String dst)
    {
        this.dst = dst;
    }

    /**
     * Return the source's port
     * @return src_port
     */
    public String getSrc_port()
    {
        return src_port;
    }

    /**
     * Set the source's port
     * @param src_port the source's port
     */
    public void setSrc_port(String src_port)
    {
        this.src_port = src_port;
    }

    /**
     * Return the destination's port
     * @return dst_port
     */
    public String getDst_port()
    {
        return dst_port;
    }

    /**
     * Set the destination's port
     * @param dst_port the destination's port
     */
    public void setDst_port(String dst_port)
    {
        this.dst_port = dst_port;
    }

    /**
     * Return the id of firewall associated to report
     * @return firewall_id
     */
    public String getFirewall_id()
    {
        return firewall_id;
    }

    /**
     * Set the id of firewall associated to report
     * @param firewall_id the id of firewall associated to report
     */
    public void setFirewall_id(String firewall_id)
    {
        this.firewall_id = firewall_id;
    }
}

public class Firewall
{
    private String id;
    private String ip;
    private String info;
    private String name;

    /**
     * Empty constructor, which instantiates a Firewall specimen without setting default values
     */
    public Firewall() {}

    /**
     * Constructor instantiating a Firewall specimen specifying its initial values
     *
     * @param id the firewall's id code
     * @param ip the firewall's ip code
     * @param info the info about firewall
     * @param name firewall's name
     */
    public Firewall(String id, String ip, String info, String nome)
    {
        super();
        this.id = id;
        this.ip = ip;
        this.info = info;
        this.name = nome;
    }

    /**
     * Return the firewall's id
     * @return id
     */
    public String getId()
    {
        return id;
    }

    /**
     * Set firewall's id
     * @param id the firewall's id
     */
    public void setId(String id)
    {
        this.id = id;
    }

    /**
     * Return the firewall's ip
     * @return ip
     */
    public String getIp()
    {
        return ip;
    }

    /**
     * Set firewall's ip
     * @param ip the firewall's ip
     */
    public void setIp(String ip)
    {
        this.ip = ip;
    }

    /**
     * Return firewall's info
     * @return info
     */
    public String getInfo()
    {
        return info;
    }

    /**
     * Set firewall's info
     * @param info firewall's info fields
     */
    public void setInfo(String info)
    {
        this.info = info;
    }

    /**
     * Return firewall's name
     * @return name
     */
    public String getName()
    {
        return name;
    }

    /**
     * Set firewall's name
     * @param name firewall's name
     */
    public void setName(String name)
    {
        this.name = name;
    }
}
</code>```

The constraint is that firewall_Items.firewall_id = firewall.id (so, these are the variables that i must use to perform join).

Now, if i want perform this query:

```<code>SELECT info, src
FROM firewalls, firewall_items
WHERE firewall_items.firewall_id = firewalls.id;
</code>```

How my java code must be, using jdbctemplate?
Should i add to firewall class a collection to collect object of FirewallsItems, like an ArrayList?

Note1: i must use jdbctemplate project specifications. I can't use Hibernate or other instruments.

Note2: I know what rowmapper and resultset are, i regolary use them with query on a single table. What i nedd is to understand how to use them for a query with join, like that of the example.

Thanks a lot in advance for response!

答:
I know its late. There aren't a lot of good tutorial out there so incase someone else needs to know how to execute join query with spring and jdbc template. This is the way I did mine.
First ensure to import the following jars in your dao class like so

```<code>import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
</code>```

Then in your FirewallDao class, do something like

```<code>public List<Firewall> getData(){
    return template.query("SELECT firewalls.info, firewall_items.src FROM firewalls INNER JOIN firewall_items ON firewall_items.firewall_id = firewalls.id",new RowMapper<Firewall>(){
        public Firewall mapRow(ResultSet rs, int row) throws SQLException {
            Firewall f =new Firewall();
            f.setInfo(rs.getString(1));
            f.setSrc(rs.getString(2));
            return f;
        }
    });
}
</code>```

In you controller, something like

```<code>@Autowired
FirewallDao dao;

@RequestMapping("/viewinfo")
public ModelAndView viewinfo(){
    List<Firewall> list=dao.getData();
    return new ModelAndView("viewinfo","list",list);
}
</code>```

in ur view, do something like

```<code><table border="2" width="70%" cellpadding="2">
<tr><th>Info</th><th>Src</th></th><th>Edit</th></tr>
<c:forEach var="f" items="${list}">
<tr>
<td>${f.info}</td>
<td>${f.src}</td>
</tr>
</c:forEach>
</table>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm developing an app for DB querying, using Spring Boot and JDBCTemplates.

The problem is this: if I have to ask the db on a single table, I have no problems. But, if I have a join, how can I perform this task?

More specifically, the SQL commands to create tables are these:

CREATE TABLE firewall_items
(
    id       INT NOT NULL AUTO_INCREMENT,
    firewall_id      INT NOT NULL,
    date     DATE,
    src      VARCHAR(15),
    src_port INT,
    dst      VARCHAR(15),
    dst_port INT,
    protocol VARCHAR(4),
    PRIMARY KEY(id)
    );

CREATE TABLE firewalls (
    id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(20) NOT NULL,
    ip VARCHAR(15) NOT NULL,
    info TEXT,
    PRIMARY KEY(id)
    );

The correspondings java class are these:

import java.util.Date;

public class FirewallItems
{
    private Date date;
    private String id;
    private String protocol;
    private String src;
    private String dst;
    private String src_port;
    private String dst_port;
    private String firewall_id;

    public FirewallItems() {}

    public FirewallItems(Date data, String identificativo, String protocollo, String sorgente, String destinazione,
            String porta_sorgente, String porta_destinazione, String firewall_id)
    {
        super();
        this.date = data;
        this.id = identificativo;
        this.protocol = protocollo;
        this.src = sorgente;
        this.dst = destinazione;
        this.src_port = porta_sorgente;
        this.dst_port = porta_destinazione;
        this.firewall_id = firewall_id;
    }

    /**
     * Return the date of the report
     * @return date
     */
    public Date getDate()
    {
        return date;
    }

    /**
     * Set the date of the report
     * @param date the report's date
     */
    public void setDate(Date date)
    {
        this.date = date;
    }

    /**
     * Return the id of the report
     * @return id
     */
    public String getId()
    {
        return id;
    }

    /**
     * Set the id of the report
     * @param id the report's id
     */
    public void setId(String id)
    {
        this.id = id;
    }

    /**
     * Return the protocol cecked by report
     * @return protocol
     */
    public String getProtocol()
    {
        return protocol;
    }

    /**
     * Set the protocol cecked by report
     * @param protocol
     */
    public void setProtocol(String protocol)
    {
        this.protocol = protocol;
    }

    /**
     * Return the source of firewall's drop
     * @return Src
     */
    public String getSrc()
    {
        return src;
    }

    /**
     * Set the source of firewall's drop
     * @param src the firewall's source drop
     */
    public void setSrc(String src)
    {
        this.src = src;
    }

    /**
     * Return the firewall's destionation drop
     * @return dst
     */
    public String getDst()
    {
        return dst;
    }

    /**
     * Set the firewall's destination drop
     * @param dst the firewall's destination drop
     */
    public void setDst(String dst)
    {
        this.dst = dst;
    }

    /**
     * Return the source's port
     * @return src_port
     */
    public String getSrc_port()
    {
        return src_port;
    }

    /**
     * Set the source's port
     * @param src_port the source's port
     */
    public void setSrc_port(String src_port)
    {
        this.src_port = src_port;
    }

    /**
     * Return the destination's port
     * @return dst_port
     */
    public String getDst_port()
    {
        return dst_port;
    }

    /**
     * Set the destination's port
     * @param dst_port the destination's port
     */
    public void setDst_port(String dst_port)
    {
        this.dst_port = dst_port;
    }

    /**
     * Return the id of firewall associated to report
     * @return firewall_id
     */
    public String getFirewall_id()
    {
        return firewall_id;
    }

    /**
     * Set the id of firewall associated to report
     * @param firewall_id the id of firewall associated to report
     */
    public void setFirewall_id(String firewall_id)
    {
        this.firewall_id = firewall_id;
    }
}

public class Firewall
{
    private String id;
    private String ip;
    private String info;
    private String name;

    /**
     * Empty constructor, which instantiates a Firewall specimen without setting default values
     */
    public Firewall() {}

    /**
     * Constructor instantiating a Firewall specimen specifying its initial values
     *
     * @param id the firewall's id code
     * @param ip the firewall's ip code
     * @param info the info about firewall
     * @param name firewall's name
     */
    public Firewall(String id, String ip, String info, String nome)
    {
        super();
        this.id = id;
        this.ip = ip;
        this.info = info;
        this.name = nome;
    }

    /**
     * Return the firewall's id
     * @return id
     */
    public String getId()
    {
        return id;
    }

    /**
     * Set firewall's id
     * @param id the firewall's id
     */
    public void setId(String id)
    {
        this.id = id;
    }

    /**
     * Return the firewall's ip
     * @return ip
     */
    public String getIp()
    {
        return ip;
    }

    /**
     * Set firewall's ip
     * @param ip the firewall's ip
     */
    public void setIp(String ip)
    {
        this.ip = ip;
    }

    /**
     * Return firewall's info
     * @return info
     */
    public String getInfo()
    {
        return info;
    }

    /**
     * Set firewall's info
     * @param info firewall's info fields
     */
    public void setInfo(String info)
    {
        this.info = info;
    }

    /**
     * Return firewall's name
     * @return name
     */
    public String getName()
    {
        return name;
    }

    /**
     * Set firewall's name
     * @param name firewall's name
     */
    public void setName(String name)
    {
        this.name = name;
    }
}

The constraint is that firewall_Items.firewall_id = firewall.id (so, these are the variables that i must use to perform join).

Now, if i want perform this query:

SELECT info, src
FROM firewalls, firewall_items
WHERE firewall_items.firewall_id = firewalls.id;

How my java code must be, using jdbctemplate?
Should i add to firewall class a collection to collect object of FirewallsItems, like an ArrayList?

Note1: i must use jdbctemplate project specifications. I can't use Hibernate or other instruments.

Note2: I know what rowmapper and resultset are, i regolary use them with query on a single table. What i nedd is to understand how to use them for a query with join, like that of the example.

Thanks a lot in advance for response!

Body:
I know its late. There aren't a lot of good tutorial out there so incase someone else needs to know how to execute join query with spring and jdbc template. This is the way I did mine.
First ensure to import the following jars in your dao class like so

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

Then in your FirewallDao class, do something like

public List<Firewall> getData(){
    return template.query("SELECT firewalls.info, firewall_items.src FROM firewalls INNER JOIN firewall_items ON firewall_items.firewall_id = firewalls.id",new RowMapper<Firewall>(){
        public Firewall mapRow(ResultSet rs, int row) throws SQLException {
            Firewall f =new Firewall();
            f.setInfo(rs.getString(1));
            f.setSrc(rs.getString(2));
            return f;
        }
    });
}

In you controller, something like

@Autowired
FirewallDao dao;

@RequestMapping("/viewinfo")
public ModelAndView viewinfo(){
    List<Firewall> list=dao.getData();
    return new ModelAndView("viewinfo","list",list);
}

in ur view, do something like

<table border="2" width="70%" cellpadding="2">
<tr><th>Info</th><th>Src</th></th><th>Edit</th></tr>
<c:forEach var="f" items="${list}">
<tr>
<td>${f.info}</td>
<td>${f.src}</td>
</tr>
</c:forEach>
</table>


问:
SEO Friendly URL for PHP CMS
URL Rewrite for PHP CMS

Hosting: Godaddy Windows (.htaccess does not work)

Want to rewrite the url www.domainname.in/category.php?ct=6 as www.domainname.in/category/sports

Want to rewrite the url www.domainname.in/detail-news.php?p=70 as www.domainname.in/detail-news/dummy-teams-wins-the-match

ct=6 is sports
p=70 title is dummy teams wins the match

答:
You should use the slug field in your CMS table that field will contains the name or your title
example  :
The is of article is 70 in your demo exp :
www.domainname.in/detail-news.php?p=70

Then the slug will be 'dummy-teams-wins-the-match' saved to that article
and when a visitor type this link,
www.domainname.in/detail-news/dummy-teams-wins-the-match

The system's core will check if that slug exist in the database and it redirect to that article who contains the slug 'dummy-teams-wins-the-match' and id = 7

Title: SEO Friendly URL for PHP CMS


问:
Evaluating Binary expressions into Hexadecimals by hand
I had to take a quiz on bit's and all questions below are what I got wrong with correct answer displayed. I'm here because I need guidance on how to get these answers.

Evaluate each stated binary expression; assume the data type of all values are unsigned char. All answers must be stated as hexadecimal values.

For this question, I got 48. My reasoning behind this was that the starting bit value was 3. 011 and we shift it over to the left 4 places and got my answer (albeit wrong).

```<code>3 << 4         // Correct Answer is 30
</code>```

Everything below here I had absolutely no clue what I was doing or how these answers were achieved.  The only thing that I can speak of is that each uppercase letter has some assigned bit value to them like A - 10, B - 11, C - 12, etc. and that the & is sort of like a mask that converts bits from 1's to 0's if both bits column's being compared aren't both 1.

```<code>0xD7 & 0x3D    // Correct Answer is 15
               // How do you read 0xD7 and 0x3D in bits?

~0xBB          // Correct Answer 44

(3 | 5) << 1   // Correct Answer is 0E
</code>```

I have an exam coming up and I can't arrange a meeting with my teacher with my given time. Any help would be greatly appreciated! :)

EDITED: 0xBB | 0x44 , my answer was right. I misread his pen marking.

答:
A through F in hex have the assigned values 10 through 15 decimal or 1010 through 1111 in binary, it is simply convention (and it doesn't matter if it's uppercase or lowercase).

Four binary digits will always form a single hex digit, so the d7 example becomes 11010111.

You really need to read your text, this material is in there.

Body:
I had to take a quiz on bit's and all questions below are what I got wrong with correct answer displayed. I'm here because I need guidance on how to get these answers.

Evaluate each stated binary expression; assume the data type of all values are unsigned char. All answers must be stated as hexadecimal values.

For this question, I got 48. My reasoning behind this was that the starting bit value was 3. 011 and we shift it over to the left 4 places and got my answer (albeit wrong).

3 << 4         // Correct Answer is 30

Everything below here I had absolutely no clue what I was doing or how these answers were achieved.  The only thing that I can speak of is that each uppercase letter has some assigned bit value to them like A - 10, B - 11, C - 12, etc. and that the & is sort of like a mask that converts bits from 1's to 0's if both bits column's being compared aren't both 1.

0xD7 & 0x3D    // Correct Answer is 15
               // How do you read 0xD7 and 0x3D in bits?

~0xBB          // Correct Answer 44

(3 | 5) << 1   // Correct Answer is 0E

I have an exam coming up and I can't arrange a meeting with my teacher with my given time. Any help would be greatly appreciated! :)

EDITED: 0xBB | 0x44 , my answer was right. I misread his pen marking.


答:
You can use your case that returns a nested list, but then cast the list as a numpy array and use the flatten() function, then re-cast as a list if you want it that way.

```<code>a = list(np.array(a).flatten())
</code>```

This way, a = 1 will turn into [1], a = [1, 2] will turn into [1, 2], and a = [[1, 2]] will turn into [1, 2], so all outputs are lists.

Body:
I wish to iterate over a zip of objects and floats together using a parent class function. Sometimes the subclasses have three objects and three floats in a list, this works fine:

L = [A,B,C]
F = [1,2,3]

for f, o in zip(L,F):
    # do stuff

Sometimes the subclass has one object and one float

L = A
F = 1

for f, o in zip(L,F):
    # TypeError

This throws an exception because F is not iterable.

If I try:

F = list(F)

This works for 2 or more floats but throws an exception for a single float (it's still not iterable :)).

If I try:

F = [F]

This solves the 1 float case but now returns a nested list when there are two or more floats!

a = [1,2]
[a] = [[1,2]]

Is there a simple builtin way to receive either a single float or list of floats and return a single flat list? Or do I need something like itertools.chain?

Body:
You can use your case that returns a nested list, but then cast the list as a numpy array and use the flatten() function, then re-cast as a list if you want it that way.

a = list(np.array(a).flatten())

This way, a = 1 will turn into [1], a = [1, 2] will turn into [1, 2], and a = [[1, 2]] will turn into [1, 2], so all outputs are lists.


答:
So i found a working solution:</p>

```<code>//using this i force the delimiter to be some char that i want.
            var format = new OfficeOpenXml.ExcelTextFormat();
            format.Delimiter = 'º';
            format.TextQualifier = '"';
            format.DataTypes = new[] { eDataTypes.String };

//This calls the load using the format i want.
worksheet1.Cells[i, y].LoadFromText(item, format);
</code>```

Title: Having trouble with the file saved using ExcelPackage

Body:
So i have to create a XLSX File in this structure:

PAYMENT CUSTOMER    DT_CRIACAO          KEY_ORIGEM               VL_LIQUIDO
6129385 5026977    29/06/2017 00:00:00  AR_PREV-6129385/14634986    186,48
6129385 5026977    29/06/2017 00:00:00  AR_PREV-6129385/14634985    -35,52
6139889 5033198    29/06/2017 00:00:00  AR_PREV-6139889/14679162    492,94
6139889 5033198    29/06/2017 00:00:00  AR_PREV-6139889/14679163    -93,89

But when i create the file the ',' on VL_LIQUIDO splits and turn into a new column like this:

PAYMENT CUSTOMER    DT_CRIACAO          KEY_ORIGEM                VL_LIQUIDO
6129385 5026977     29/06/2017 00:00:00 AR_PREV-6129385/14634986    186    48
6129385 5026977     29/06/2017 00:00:00 AR_PREV-6129385/14634985    -35    52
6139889 5033198     29/06/2017 00:00:00 AR_PREV-6139889/14679162    492    94
6139889 5033198     29/06/2017 00:00:00 AR_PREV-6139889/14679163    -93    89

My Code is right, it is creating the file but something with this ExcelPackage lib is wrong cause is spliting the VL_LIQUIDO into 2 colums instead of 1.

Anyone already face a problem like this?

Body:
So i found a working solution:

//using this i force the delimiter to be some char that i want.
            var format = new OfficeOpenXml.ExcelTextFormat();
            format.Delimiter = 'º';
            format.TextQualifier = '"';
            format.DataTypes = new[] { eDataTypes.String };

//This calls the load using the format i want.
worksheet1.Cells[i, y].LoadFromText(item, format);


问:
Regex find string after key inside qoutes
Input:

blalasdl8ujd "key":"value", blblabla asdw
  "alo":"ebobo",blabla"www":"zzzz"

or

blalasdl8ujd key [any_chars_here] "value", blabla asdw
  "alo":"ebobo", bla"www":"zzzz"

I'm tring to extract value having only key and knowing that value is covered with "

Following regex key.*"(.*?)" returns the last match covered with " ("zzzz").
I need to fix it to return first.

https://regex101.com/r/CDfhBT/1

答:
You can use the non-greedy quantifier .*? between the key and the value group:

```<code>key.*?"(.*?)"
</code>```

Demo here.

Update

You might wonder why it captures the colon, :. It captures that because this is the next thing between quotes. So you can add optional quotes around key like this:

```<code>("?)key\1.*?"(.*?)"
</code>```

Another demo here.

Body:
You can use the non-greedy quantifier .*? between the key and the value group:

key.*?"(.*?)"

Demo here.

Update

You might wonder why it captures the colon, :. It captures that because this is the next thing between quotes. So you can add optional quotes around key like this:

("?)key\1.*?"(.*?)"

Another demo here.


问:
React Styleguidist and SASS
So my set up is pretty simple

styleguide.config.js

```<code>module.exports = {
    components: 'src/components/**/*.js',
    require: [
        path.join(__dirname, 'node_modules/bootstrap/scss/bootstrap.scss')
    ]
};
</code>```

Whenever I run npm run styleguide I get this error:

Module parse failed: Unexpected character @ You may need an appropriate loader to handle this file type.

bootstrap.scss looks like this:

```<code>@import "node_modules/bootstrap/scss/functions";
@import "node_modules/bootstrap/scss/mixins";
...
...
</code>```

I understand I need to add SASS-loader but the examples I found are using different context so I cant really figure them out yet.

p.s. SASS works outside React Styleguide when I run the app itself, not styleguide.

答:
Ok so the solution is to make sure that your main project can comiple SASS. But thats a different question.

I just had to add webpackConfig to

styleguide.config.js

```<code>module.exports = {
    components: 'src/kitchensink/**/*.js',
    webpackConfig: require('./config/webpack.config.dev.js'),
    require: [
        path.join(__dirname, './src/sass/bootstrap.scss')
    ]
};
</code>```

Title: React Styleguidist and SASS

Body:
So my set up is pretty simple

styleguide.config.js

module.exports = {
    components: 'src/components/**/*.js',
    require: [
        path.join(__dirname, 'node_modules/bootstrap/scss/bootstrap.scss')
    ]
};

Whenever I run npm run styleguide I get this error:

Module parse failed: Unexpected character @ You may need an appropriate loader to handle this file type.

bootstrap.scss looks like this:

@import "node_modules/bootstrap/scss/functions";
@import "node_modules/bootstrap/scss/mixins";
...
...

I understand I need to add SASS-loader but the examples I found are using different context so I cant really figure them out yet.

p.s. SASS works outside React Styleguide when I run the app itself, not styleguide.

Body:
Ok so the solution is to make sure that your main project can comiple SASS. But thats a different question.

I just had to add webpackConfig to

styleguide.config.js

module.exports = {
    components: 'src/kitchensink/**/*.js',
    webpackConfig: require('./config/webpack.config.dev.js'),
    require: [
        path.join(__dirname, './src/sass/bootstrap.scss')
    ]
};