问:
API data is not getting at first loading ionic2, angular2
I am struggling from last couple days.I am using ionic2/3 angular 2 and wordpress for data.
I am trying to load categories data at home page at first load but i am not getting. In browser it's coming properly and also when i click on menu button entire data is showing properly. I checked all blogs but didn't get any proper solution.
Please help me if any one had same issues and solved.Thanks in advance.
I am attaching my codes here.</p>

```<code>enter code here
Home.ts-
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import * as WC from 'woocommerce-api';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  woocommerce: any;
  categories: any[];

         //   Home=HomePage;

  constructor(public navCtrl: NavController) {
      this.categories=[];

  }

  ionViewDidLoad(){
     this.getCatData();
  }

  getCatData(){
    this.woocommerce = WC({
    url:'http://www.example.com/',
    consumerKey: 'ck_7dfe0aec65ahgcdhgcdhcdhf36288d1fa2e4c01',
    consumerSecret: 'cs_da53e5b228eb6235bshhcskhc7a68541ad809743'
  });
  this.woocommerce.getAsync("products/categories").then((data)=>{
        console.log(JSON.parse(data.body).product_categories);
        this.categories = JSON.parse(data.body).product_categories;

  },(err)=>{
    console.log(err);
  })
}

}
Home.html-
<ion-header>
  <ion-navbar color="header">
         <ion-buttons left>
              <button ion-button menuToggle>
                <ion-icon name="menu"></ion-icon>
              </button>
         </ion-buttons>
         <ion-buttons right>
              <button ion-button icon-only>
                 <ion-icon name="search"></ion-icon>
              </button>
          </ion-buttons>
    <ion-title>
      KAAIROS EXPORTS
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
  <!-- slider -->
    <ion-card>
        <ion-slides loop="true" autoplay="false" pager>
          <ion-slide *ngFor= "let number of [1,2,3,4,5]"><img src="./assets/img/{{number}}.jpg"/></ion-slide>
        </ion-slides>
        </ion-card>
     <!-- end-slider    -->
    <!-- <ion-grid> Hi this is second line
    </ion-grid> -->
    <ion-item *ngFor="let category of categories">
      <h2> {{ category.name }} </h2>
    </ion-item>
</ion-content>
app.component.ts-
import { TabsPage } from './../pages/tabs/tabs';
import { HomePage } from './../pages/home/home';
import { Component, ViewChild } from '@angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
//import { Menu } from '../pages/menu/menu';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;

 // rootPage: any = Menu;
  rootPage = TabsPage;

  constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen) {
    this.initializeApp();

  }

  initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.statusBar.styleDefault();
      this.splashScreen.hide();
    });
  }
  // go_to_home(){
  //   this.nav.setRoot(HomePage);
  // }
}

app.html-
<ion-menu side="left" [content]="content">
    <ion-header>
        <ion-toolbar>
            <ion-title>Menu</ion-title>
        </ion-toolbar>
    </ion-header>
    <ion-content>
        <!-- <ion-list>
            <!-- <ion-item (click)="go_to_home()" menuClose>
                Home
            </ion-item> -->
           <!--  <ion-item (click)="go_to_about()" menuClose>
                About
            </ion-item> -->
             <!-- <ion-item (click)="go_to_contact()" menuClose>
                Contact Us
            <!-- </ion-item> -->

    </ion-content>
</ion-menu>
<!-- Disable swipe-to-go-back because it's poor UX to combine STGB with side menus -->
<ion-nav [root]="rootPage" #content swipeBackEnabled="true"></ion-nav>

app.module:-
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import { AboutusPage } from '../pages/aboutus/aboutus';
import { ContactusPage } from '../pages/contactus/contactus';
import { CategoryPage } from '../pages/category/category';
import { ProductsByCategoryPage } from '../pages/products-by-category/products-by-category';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { WooCommerceProvider } from '../providers/woocommerce/woocommerce';
import { HttpModule } from '@angular/http';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    TabsPage,
    AboutusPage,
    ContactusPage,
    CategoryPage,
    //ProductListPage,
    ProductsByCategoryPage
  ],
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp,{
      mode:'ios'
}),
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    TabsPage,
    AboutusPage,
    ContactusPage,
    CategoryPage,
    ProductsByCategoryPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    WooCommerceProvider
  ]
})
export class AppModule {}
</code>```

答:
This is because your data is asynchronously loaded. The view has already been rendered by the time your data arrives.

One way to fix this is to add some kind of "refresh" method and call it when you receive the data (e.g., in .getAsync().then(...)).

Body:
I am struggling from last couple days.I am using ionic2/3 angular 2 and wordpress for data.
I am trying to load categories data at home page at first load but i am not getting. In browser it's coming properly and also when i click on menu button entire data is showing properly. I checked all blogs but didn't get any proper solution.
Please help me if any one had same issues and solved.Thanks in advance.
I am attaching my codes here.

enter code here
Home.ts-
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import * as WC from 'woocommerce-api';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  woocommerce: any;
  categories: any[];

         //   Home=HomePage;

  constructor(public navCtrl: NavController) {
      this.categories=[];

  }

  ionViewDidLoad(){
     this.getCatData();
  }

  getCatData(){
    this.woocommerce = WC({
    url:'http://www.example.com/',
    consumerKey: 'ck_7dfe0aec65ahgcdhgcdhcdhf36288d1fa2e4c01',
    consumerSecret: 'cs_da53e5b228eb6235bshhcskhc7a68541ad809743'
  });
  this.woocommerce.getAsync("products/categories").then((data)=>{
        console.log(JSON.parse(data.body).product_categories);
        this.categories = JSON.parse(data.body).product_categories;

  },(err)=>{
    console.log(err);
  })
}

}
Home.html-
<ion-header>
  <ion-navbar color="header">
         <ion-buttons left>
              <button ion-button menuToggle>
                <ion-icon name="menu"></ion-icon>
              </button>
         </ion-buttons>
         <ion-buttons right>
              <button ion-button icon-only>
                 <ion-icon name="search"></ion-icon>
              </button>
          </ion-buttons>
    <ion-title>
      KAAIROS EXPORTS
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>

    <ion-card>
        <ion-slides loop="true" autoplay="false" pager>
          <ion-slide *ngFor= "let number of [1,2,3,4,5]"></ion-slide>
        </ion-slides>
        </ion-card>

    <ion-item *ngFor="let category of categories">

 {{ category.name }}

    </ion-item>
</ion-content>
app.component.ts-
import { TabsPage } from './../pages/tabs/tabs';
import { HomePage } from './../pages/home/home';
import { Component, ViewChild } from '@angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
//import { Menu } from '../pages/menu/menu';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;

 // rootPage: any = Menu;
  rootPage = TabsPage;

  constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen) {
    this.initializeApp();

  }

  initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.statusBar.styleDefault();
      this.splashScreen.hide();
    });
  }
  // go_to_home(){
  //   this.nav.setRoot(HomePage);
  // }
}

app.html-
<ion-menu side="left" [content]="content">
    <ion-header>
        <ion-toolbar>
            <ion-title>Menu</ion-title>
        </ion-toolbar>
    </ion-header>
    <ion-content>

    </ion-content>
</ion-menu>

<ion-nav [root]="rootPage" #content swipeBackEnabled="true"></ion-nav>

app.module:-
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import { AboutusPage } from '../pages/aboutus/aboutus';
import { ContactusPage } from '../pages/contactus/contactus';
import { CategoryPage } from '../pages/category/category';
import { ProductsByCategoryPage } from '../pages/products-by-category/products-by-category';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { WooCommerceProvider } from '../providers/woocommerce/woocommerce';
import { HttpModule } from '@angular/http';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    TabsPage,
    AboutusPage,
    ContactusPage,
    CategoryPage,
    //ProductListPage,
    ProductsByCategoryPage
  ],
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp,{
      mode:'ios'
}),
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    TabsPage,
    AboutusPage,
    ContactusPage,
    CategoryPage,
    ProductsByCategoryPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    WooCommerceProvider
  ]
})
export class AppModule {}


来源: stackexchange

问:
Refreshing GridView items
I am working on an Android app that has one activity and five fragments.

On one of the fragments there is a GridView populated from a remote database.

I am trying to understand the behaviour of the GridView, but without success.

Just after a new app launch, the items are shown as expected. But later, if I change the database rows, adding, removing or updating them, the gridview is not updated.

As last solution, I have included a button to refresh the gridview items, but also no succes.

This the method to get the remote items:

```<code>   private void getUpicksFromDB(int id) {

        upicks.clear();

        AsyncTask<Integer, Void, Void> asyncTask = new AsyncTask<Integer, Void, Void>() {
            @Override
            protected Void doInBackground(Integer... addressesIds) {
                //  Log.d("HOLA PERFIL", "UID REGISTRADO ANTES DE CARGAR REECYCLER: " + user_id);

                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://.../upicks_todos.php")
                        .build();
                try {
                    okhttp3.Response response = client.newCall(request).execute();

                    JSONArray array = new JSONArray(response.body().string());

                    Log.d("aNTES","EN ONCREATE  4.5 numero de objetos "+array.length());
                    for (int i = 0; i < array.length(); i++) {

                        JSONObject object = array.getJSONObject(i);
                        Log.d("HOLA ADDRESSES", "DIRECCION LEIDA: " + i);
                        Upicks upicks = new Upicks(object.getInt("id_servicio"),
                                object.getString("driver_servicio"),
                                object.getString("inicio_servicio"),
                                object.getString("lat_origen_servicio"),
                                object.getString("lon_origen_servicio"),
                                object.getString("lat_destino_servicio"),
                                object.getString("lon_destino_servicio"),
                                object.getString("cliente_servicio"),
                                object.getString("final_servicio"),
                                object.getString("distancia_servicio"),
                                object.getString("tarifa_servicio"),
                                object.getString("origen_servicio"),
                                object.getString("destino_servicio"),
                                object.getString("estado_servicio"),
                                object.getString("tiempo_servicio")
                        );
                        Log.d("aNTES","EN ONCREATE  4.5 id leido "+object.getString("id_servicio"));
                        MisUpicksFragment.this.upicks.add(upicks);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {

                adapter.notifyDataSetChanged();
                Log.d("aNTES","EN ONCREATE  5 estouy en getpicks despues de notify");
            }
        };

        asyncTask.execute(id);
    }
</code>```

And this is the button to refresh the items:

```<code> botonrefrescar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                recyclerView.setAdapter(null);
                recyclerView.setAdapter(adapter);
                getUpicksFromDB(0);
                adapter.notifyDataSetChanged();

            }
        });
</code>```

I am trying to find a solution for two days.

Thank you

EDIT:

```<code>public class MisUpicksFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private SessionManager session;
    private ProgressDialog loading;
    private EditText txtbusqueda;
    private Button botonbuscar,botonrefrescar;

    //movies
    private static final String TAG = MainActivity.class.getSimpleName();
    public List<Upicks> upicks;
    private RecyclerView recyclerView;
    private GridLayoutManager gridLayout;
    private UpicksAdapter adapter;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private String user_id;
    private Button btnNew;

    private OnFragmentInteractionListener mListener;

    public MisUpicksFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MensajesFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MisUpicksFragment newInstance(String param1, String param2) {
        MisUpicksFragment fragment = new MisUpicksFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        Log.d("MISUPICKS","ESTOE EN MISUPICKS ONCREATE");

        View view = inflater.inflate(R.layout.fragment_misupicks, container, false);

        txtbusqueda = (EditText) view.findViewById(R.id.txtbusqueda);

        botonbuscar =(Button) view.findViewById(R.id.btnbuscar);
        botonrefrescar =(Button) view.findViewById(R.id.btnRefrescar);

        botonbuscar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String busqueda = txtbusqueda.getText().toString();
                getUpicksBusquedaFromDB(0, busqueda);
            }
        });

        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);

        upicks = new ArrayList<>();

        gridLayout = new GridLayoutManager(getActivity(), 2);
        recyclerView.setLayoutManager(gridLayout);

        adapter = new UpicksAdapter(getActivity(), upicks);

        recyclerView.setAdapter(adapter);

    Log.d("aNTES","EN ONCREATE 1 ANTES DE CLEAR");
        upicks.clear();
        Log.d("aNTES","EN ONCREATE 2 DESPUES  DE CLEAR");
        getUpicksFromDB(0);
        Log.d("aNTES","EN ONCREATE DESPUES  DE GETUPICKS");

        botonrefrescar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                recyclerView.setAdapter(null);
                recyclerView.setAdapter(adapter);
                getUpicksFromDB(0);
                adapter.notifyDataSetChanged();

            }
        });

        return view;
    }
    private void getUpicksBusquedaFromDB(int id, final String busqueda) {

        upicks.clear();

        Log.d("estoy en directorio= ",busqueda);

        Log.d("Texto buscado= ",busqueda);
        AsyncTask<Integer, Void, Void> asyncTask = new AsyncTask<Integer, Void, Void>() {
            @Override
            protected Void doInBackground(Integer... addressesIds) {

                String URL = "http://.../upicks_todos_busca.php?id="+busqueda;
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(URL)
                        .build();
                try {
                    okhttp3.Response response = client.newCall(request).execute();
                    Log.d("Texto buscado=estoy ",busqueda);
                    JSONArray array = new JSONArray(response.body().string());

                    for (int i = 0; i < array.length(); i++) {
                        Log.d("Texto buscado loop= ",busqueda);
                        JSONObject object = array.getJSONObject(i);
                        Log.d("HOLA ADDRESSES", "DIRECCION LEIDA: " + i);
                        Upicks upicks = new Upicks(object.getInt("id_servicio"),
                                object.getString("driver_servicio"),
                                object.getString("inicio_servicio"),
                                object.getString("lat_origen_servicio"),
                                object.getString("lon_origen_servicio"),
                                object.getString("lat_destino_servicio"),
                                object.getString("lon_destino_servicio"),
                                object.getString("cliente_servicio"),
                                object.getString("final_servicio"),
                                object.getString("distancia_servicio"),
                                object.getString("tarifa_servicio"),
                                object.getString("origen_servicio"),
                                object.getString("destino_servicio"),
                                object.getString("estado_servicio"),
                                object.getString("tiempo_servicio")
                        );

                        MisUpicksFragment.this.upicks.add(upicks);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {

                recyclerView.swapAdapter(adapter, true);

            }
        };

        asyncTask.execute(id);
    }

    private void getUpicksFromDB(int id) {

        Log.d("aNTES","EN ONCREATE 3 estouy en getpicks antes de clear");
        upicks.clear();
        Log.d("aNTES","EN ONCREATE 4 estouy en getpicks despues de clear");
        Log.d("MISUPICKS","ESTOE EN MISUPICKS getupicksfromddb");

        AsyncTask<Integer, Void, Void> asyncTask = new AsyncTask<Integer, Void, Void>() {
            @Override
            protected Void doInBackground(Integer... addressesIds) {
                //  Log.d("HOLA PERFIL", "UID REGISTRADO ANTES DE CARGAR REECYCLER: " + user_id);

                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://j../upicks_todos.php")
                        .build();
                try {
                    okhttp3.Response response = client.newCall(request).execute();

                    JSONArray array = new JSONArray(response.body().string());

                    Log.d("aNTES","EN ONCREATE  4.5 numero de objetos "+array.length());
                    for (int i = 0; i < array.length(); i++) {

                        JSONObject object = array.getJSONObject(i);
                        Log.d("HOLA ADDRESSES", "DIRECCION LEIDA: " + i);
                        Upicks upicks = new Upicks(object.getInt("id_servicio"),
                                object.getString("driver_servicio"),
                                object.getString("inicio_servicio"),
                                object.getString("lat_origen_servicio"),
                                object.getString("lon_origen_servicio"),
                                object.getString("lat_destino_servicio"),
                                object.getString("lon_destino_servicio"),
                                object.getString("cliente_servicio"),
                                object.getString("final_servicio"),
                                object.getString("distancia_servicio"),
                                object.getString("tarifa_servicio"),
                                object.getString("origen_servicio"),
                                object.getString("destino_servicio"),
                                object.getString("estado_servicio"),
                                object.getString("tiempo_servicio")
                        );
                        Log.d("aNTES","EN ONCREATE  4.5 id leido "+object.getString("id_servicio"));
                        MisUpicksFragment.this.upicks.add(upicks);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {

                recyclerView.setAdapter(null);
                recyclerView.setAdapter(adapter);

                adapter.notifyDataSetChanged();

            }
        };

        asyncTask.execute(id);
    }

    private void logoutUser() {
        session.setLogin(false);

        // Launching the login activity
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        startActivity(intent);
        //finish();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

}
</code>```

答:
```<code>If(null != upicks){
    adapter = new UpicksAdapter(getActivity(), upicks);
    recyclerView.setAdapter(adapter);
    recyclerView.swapAdapter(adapter, true);
    adapter.notifyDataSetChanged();
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Refreshing GridView items

Body:
I am working on an Android app that has one activity and five fragments.

On one of the fragments there is a GridView populated from a remote database.

I am trying to understand the behaviour of the GridView, but without success.

Just after a new app launch, the items are shown as expected. But later, if I change the database rows, adding, removing or updating them, the gridview is not updated.

As last solution, I have included a button to refresh the gridview items, but also no succes.

This the method to get the remote items:

   private void getUpicksFromDB(int id) {

        upicks.clear();

        AsyncTask<Integer, Void, Void> asyncTask = new AsyncTask<Integer, Void, Void>() {
            @Override
            protected Void doInBackground(Integer... addressesIds) {
                //  Log.d("HOLA PERFIL", "UID REGISTRADO ANTES DE CARGAR REECYCLER: " + user_id);

                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://.../upicks_todos.php")
                        .build();
                try {
                    okhttp3.Response response = client.newCall(request).execute();

                    JSONArray array = new JSONArray(response.body().string());

                    Log.d("aNTES","EN ONCREATE  4.5 numero de objetos "+array.length());
                    for (int i = 0; i < array.length(); i++) {

                        JSONObject object = array.getJSONObject(i);
                        Log.d("HOLA ADDRESSES", "DIRECCION LEIDA: " + i);
                        Upicks upicks = new Upicks(object.getInt("id_servicio"),
                                object.getString("driver_servicio"),
                                object.getString("inicio_servicio"),
                                object.getString("lat_origen_servicio"),
                                object.getString("lon_origen_servicio"),
                                object.getString("lat_destino_servicio"),
                                object.getString("lon_destino_servicio"),
                                object.getString("cliente_servicio"),
                                object.getString("final_servicio"),
                                object.getString("distancia_servicio"),
                                object.getString("tarifa_servicio"),
                                object.getString("origen_servicio"),
                                object.getString("destino_servicio"),
                                object.getString("estado_servicio"),
                                object.getString("tiempo_servicio")
                        );
                        Log.d("aNTES","EN ONCREATE  4.5 id leido "+object.getString("id_servicio"));
                        MisUpicksFragment.this.upicks.add(upicks);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {

                adapter.notifyDataSetChanged();
                Log.d("aNTES","EN ONCREATE  5 estouy en getpicks despues de notify");
            }
        };

        asyncTask.execute(id);
    }

And this is the button to refresh the items:

 botonrefrescar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                recyclerView.setAdapter(null);
                recyclerView.setAdapter(adapter);
                getUpicksFromDB(0);
                adapter.notifyDataSetChanged();

            }
        });

I am trying to find a solution for two days.

Thank you

EDIT:

public class MisUpicksFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private SessionManager session;
    private ProgressDialog loading;
    private EditText txtbusqueda;
    private Button botonbuscar,botonrefrescar;

    //movies
    private static final String TAG = MainActivity.class.getSimpleName();
    public List<Upicks> upicks;
    private RecyclerView recyclerView;
    private GridLayoutManager gridLayout;
    private UpicksAdapter adapter;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private String user_id;
    private Button btnNew;

    private OnFragmentInteractionListener mListener;

    public MisUpicksFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MensajesFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MisUpicksFragment newInstance(String param1, String param2) {
        MisUpicksFragment fragment = new MisUpicksFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        Log.d("MISUPICKS","ESTOE EN MISUPICKS ONCREATE");

        View view = inflater.inflate(R.layout.fragment_misupicks, container, false);

        txtbusqueda = (EditText) view.findViewById(R.id.txtbusqueda);

        botonbuscar =(Button) view.findViewById(R.id.btnbuscar);
        botonrefrescar =(Button) view.findViewById(R.id.btnRefrescar);

        botonbuscar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String busqueda = txtbusqueda.getText().toString();
                getUpicksBusquedaFromDB(0, busqueda);
            }
        });

        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);

        upicks = new ArrayList<>();

        gridLayout = new GridLayoutManager(getActivity(), 2);
        recyclerView.setLayoutManager(gridLayout);

        adapter = new UpicksAdapter(getActivity(), upicks);

        recyclerView.setAdapter(adapter);

    Log.d("aNTES","EN ONCREATE 1 ANTES DE CLEAR");
        upicks.clear();
        Log.d("aNTES","EN ONCREATE 2 DESPUES  DE CLEAR");
        getUpicksFromDB(0);
        Log.d("aNTES","EN ONCREATE DESPUES  DE GETUPICKS");

        botonrefrescar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                recyclerView.setAdapter(null);
                recyclerView.setAdapter(adapter);
                getUpicksFromDB(0);
                adapter.notifyDataSetChanged();

            }
        });

        return view;
    }
    private void getUpicksBusquedaFromDB(int id, final String busqueda) {

        upicks.clear();

        Log.d("estoy en directorio= ",busqueda);

        Log.d("Texto buscado= ",busqueda);
        AsyncTask<Integer, Void, Void> asyncTask = new AsyncTask<Integer, Void, Void>() {
            @Override
            protected Void doInBackground(Integer... addressesIds) {

                String URL = "http://.../upicks_todos_busca.php?id="+busqueda;
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(URL)
                        .build();
                try {
                    okhttp3.Response response = client.newCall(request).execute();
                    Log.d("Texto buscado=estoy ",busqueda);
                    JSONArray array = new JSONArray(response.body().string());

                    for (int i = 0; i < array.length(); i++) {
                        Log.d("Texto buscado loop= ",busqueda);
                        JSONObject object = array.getJSONObject(i);
                        Log.d("HOLA ADDRESSES", "DIRECCION LEIDA: " + i);
                        Upicks upicks = new Upicks(object.getInt("id_servicio"),
                                object.getString("driver_servicio"),
                                object.getString("inicio_servicio"),
                                object.getString("lat_origen_servicio"),
                                object.getString("lon_origen_servicio"),
                                object.getString("lat_destino_servicio"),
                                object.getString("lon_destino_servicio"),
                                object.getString("cliente_servicio"),
                                object.getString("final_servicio"),
                                object.getString("distancia_servicio"),
                                object.getString("tarifa_servicio"),
                                object.getString("origen_servicio"),
                                object.getString("destino_servicio"),
                                object.getString("estado_servicio"),
                                object.getString("tiempo_servicio")
                        );

                        MisUpicksFragment.this.upicks.add(upicks);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {

                recyclerView.swapAdapter(adapter, true);

            }
        };

        asyncTask.execute(id);
    }

    private void getUpicksFromDB(int id) {

        Log.d("aNTES","EN ONCREATE 3 estouy en getpicks antes de clear");
        upicks.clear();
        Log.d("aNTES","EN ONCREATE 4 estouy en getpicks despues de clear");
        Log.d("MISUPICKS","ESTOE EN MISUPICKS getupicksfromddb");

        AsyncTask<Integer, Void, Void> asyncTask = new AsyncTask<Integer, Void, Void>() {
            @Override
            protected Void doInBackground(Integer... addressesIds) {
                //  Log.d("HOLA PERFIL", "UID REGISTRADO ANTES DE CARGAR REECYCLER: " + user_id);

                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://j../upicks_todos.php")
                        .build();
                try {
                    okhttp3.Response response = client.newCall(request).execute();

                    JSONArray array = new JSONArray(response.body().string());

                    Log.d("aNTES","EN ONCREATE  4.5 numero de objetos "+array.length());
                    for (int i = 0; i < array.length(); i++) {

                        JSONObject object = array.getJSONObject(i);
                        Log.d("HOLA ADDRESSES", "DIRECCION LEIDA: " + i);
                        Upicks upicks = new Upicks(object.getInt("id_servicio"),
                                object.getString("driver_servicio"),
                                object.getString("inicio_servicio"),
                                object.getString("lat_origen_servicio"),
                                object.getString("lon_origen_servicio"),
                                object.getString("lat_destino_servicio"),
                                object.getString("lon_destino_servicio"),
                                object.getString("cliente_servicio"),
                                object.getString("final_servicio"),
                                object.getString("distancia_servicio"),
                                object.getString("tarifa_servicio"),
                                object.getString("origen_servicio"),
                                object.getString("destino_servicio"),
                                object.getString("estado_servicio"),
                                object.getString("tiempo_servicio")
                        );
                        Log.d("aNTES","EN ONCREATE  4.5 id leido "+object.getString("id_servicio"));
                        MisUpicksFragment.this.upicks.add(upicks);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {

                recyclerView.setAdapter(null);
                recyclerView.setAdapter(adapter);

                adapter.notifyDataSetChanged();

            }
        };

        asyncTask.execute(id);
    }

    private void logoutUser() {
        session.setLogin(false);

        // Launching the login activity
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        startActivity(intent);
        //finish();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

}


问:
selecting query from one file
so i have some kind of code on a page like this

<?php
$a = $_GET['act'];
if ($a){
include('show.php');
} else {
include('show.php');
}
?>
```

<p>and on other page like this </p>

<pre class="lang-html prettyprint-override"><code><?php
$sql2 = "SELECT * from DONE ";
$b = mysqli_query ($con,$sql2);
$r = mysqli_fetch_assoc($b);
.......
?>

<?php
$sql3 = "SELECT * from ONGOING ";
$b = mysqli_query ($con,$sql3);
$r = mysqli_fetch_assoc($b);
.......
?>
</code>```

my question , is it possible when the condition is met it execute the first query and when the condition doesn't met it execute the second query , when both of the query placed on same page ?

答:
Instead of adding condition in main page add it in included page so that your query can executed condition wise
Main page

```<code><?php
    $a = $_GET['act'];
    include('show.php');
?>
</code>```

show.php

```<code><?php
if ($a){
$sql2 = "SELECT * from DONE ";
$b = mysqli_query ($con,$sql2);
$r = mysqli_fetch_assoc($b);
//.......
}
else
{
$sql3 = "SELECT * from ONGOING ";
$b = mysqli_query ($con,$sql3);
$r = mysqli_fetch_assoc($b);
//.......
}
?>
</code>```

Title: selecting query from one file

Body:
so i have some kind of code on a page like this

<?php
$a = $_GET['act'];
if ($a){
include('show.php');
} else {
include('show.php');
}
?>

and on other page like this

<?php
$sql2 = "SELECT * from DONE ";
$b = mysqli_query ($con,$sql2);
$r = mysqli_fetch_assoc($b);
.......
?>

<?php
$sql3 = "SELECT * from ONGOING ";
$b = mysqli_query ($con,$sql3);
$r = mysqli_fetch_assoc($b);
.......
?>

my question , is it possible when the condition is met it execute the first query and when the condition doesn't met it execute the second query , when both of the query placed on same page ?

Body:
Instead of adding condition in main page add it in included page so that your query can executed condition wise
Main page

<?php
    $a = $_GET['act'];
    include('show.php');
?>

show.php

<?php
if ($a){
$sql2 = "SELECT * from DONE ";
$b = mysqli_query ($con,$sql2);
$r = mysqli_fetch_assoc($b);
//.......
}
else
{
$sql3 = "SELECT * from ONGOING ";
$b = mysqli_query ($con,$sql3);
$r = mysqli_fetch_assoc($b);
//.......
}
?>


问:
Mongodb Pymongo create an index for nested object
I have an object like so:

```<code>{
    "field1": "somestring",
    "field2": {
        "nestedfield1": "somestring",
        "nestedfield2": "somestring"
    }
}
</code>```

i can create an index on field1 like so db.collection.createIndex('field1') and it will work as expected. But what if I want an index on both nested fields.

Do I have to do db.collection.createIndex('field2.nestedfield1') to create that index or will db.collection.createIndex('field2') automatically create that?

I will be searching using 'field2.nestedfield1' in my queries and want an index for that.

Thanks

答:
You can't index nested field at once, you have to index each item inside separately.

To create an index on the nested field, just give its full field path with . separator,

```<code>db.collection.createIndex('field2.nestedfield1')
</code>```

Body:
I have an object like so:

{
    "field1": "somestring",
    "field2": {
        "nestedfield1": "somestring",
        "nestedfield2": "somestring"
    }
}

i can create an index on field1 like so db.collection.createIndex('field1') and it will work as expected. But what if I want an index on both nested fields.

Do I have to do db.collection.createIndex('field2.nestedfield1') to create that index or will db.collection.createIndex('field2') automatically create that?

I will be searching using 'field2.nestedfield1' in my queries and want an index for that.

Thanks

Body:
You can't index nested field at once, you have to index each item inside separately.

To create an index on the nested field, just give its full field path with . separator,

db.collection.createIndex('field2.nestedfield1')


问:
How can I simplify form validation?
The code below seems to work pretty well for doing basic required form validation.

The form displays a red Name is required message when the field is dirty + invalid and a Great! message if the field is dirty + valid.

But it's a mess having repeat this code for each and every field in the form:

```<code><form name="myForm">
    <div class="control-group"
     ng-class="{error: myForm.name.$invalid && myForm.name.$dirty}">
        <label>Name:</label>
        <input type="text" name="name" ng-model="user.name" required/>
        <span ng-show="myForm.name.$invalid && myForm.name.$dirty"
            class="help-inline">Name is required</span>
        <span ng-show="myForm.names.$valid && myForm.names.$dirty">Great!</span>
    </div>
</form>
</code>```

I would like to be able to specify the ng-show and ng-class attributes in some easier way.

答:
Check out my angularJS form validaton on codpen link

I have showed an example how to validate required, minlength, maxlength, email, password case, confirm password match on my demo.

Here is the code:

var myApp = angular.module('myApp',[]);
myApp.controller('mainController',['$scope', function($scope) {

}]);
myApp.directive('validConfirmPassword', function() {
 return {
  require:'ngModel',
  link: function(scope, elem, attrs, ctrl) {
   ctrl.$parsers.unshift(function(viewValue, $scope) {
    var noMatch = viewValue != scope.myForm.password.$viewValue;
    ctrl.$setValidity('noMatch', !noMatch)
   })
  }
 }
}) ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.content{ margin-top:50px;  }
.danger-text { color: red; }</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

        AngularJS Form Validation
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample07" aria-controls="navbarsExample07" aria-expanded="false" aria-label="Toggle navigation">

        </button>

    <form name="myForm" novalidate>

        First Name
        <input type="text" name="firstname" ng-model="firstname" id="firstname"  class="form-control" required>

Please enter your first name

        Last Name
        <input type="text" name="last_name" ng-model="last_name" id="last_name"  class="form-control"  required>

Please enter your last name

       Username
       <input type="text" name="username" id="username" ng-model="username" class="form-control" ng-required="true" ng-minlength="4" ng-maxlength="10" >

Please enter username

Username is too short

Username is too long

       Email
       <input type="email" name="email" id="email" class="form-control" ng-model="email">

Enter a valid email address

       Password
       <input type="password" class="form-control" id="password" name="password" ng-model="password" ng-minlength="8" ng-maxlength="20" ng-pattern="/(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z])/" required  />

Password is required

Passwords must be between 8 and 20 characters.

Must contain one lower & uppercase letter, and one non-alpha character (a number or a symbol.)

       Confirm Password
       <input type="password" id="confirm_password" name="confirm_password" class="form-control" ng-model="confirm_password" valid-confirm-password required  />

Please confirm your password.

Passwords do not match.

       <button type="submit"  class="btn btn-primary">Submit</button>

    </form>

```

Title: How can I simplify form validation?

Body:
The code below seems to work pretty well for doing basic required form validation.

The form displays a red Name is required message when the field is dirty + invalid and a Great! message if the field is dirty + valid.

But it's a mess having repeat this code for each and every field in the form:

<form name="myForm">

        Name:
        <input type="text" name="name" ng-model="user.name" required/>
        Name is required
        Great!

</form>

I would like to be able to specify the ng-show and ng-class attributes in some easier way.

Body:
Check out my angularJS form validaton on codpen link

I have showed an example how to validate required, minlength, maxlength, email, password case, confirm password match on my demo.

Here is the code:

var myApp = angular.module('myApp',[]);
myApp.controller('mainController',['$scope', function($scope) {

}]);
myApp.directive('validConfirmPassword', function() {
 return {
  require:'ngModel',
  link: function(scope, elem, attrs, ctrl) {
   ctrl.$parsers.unshift(function(viewValue, $scope) {
    var noMatch = viewValue != scope.myForm.password.$viewValue;
    ctrl.$setValidity('noMatch', !noMatch)
   })
  }
 }
})

.content{ margin-top:50px;  }
.danger-text { color: red; }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="myApp">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
      <div class="container">
        <a class="navbar-brand" href="#">AngularJS Form Validation</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample07" aria-controls="navbarsExample07" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
    </nav>

 <div class="container content" ng-controller="mainController">
  <div class="row">
   <div class="col-sm-12">
    <form name="myForm" novalidate>
     <div class="row">
         <div class="col-md-6 mb-3">

        <label for="first_name">First Name</label>
        <input type="text" name="firstname" ng-model="firstname" id="firstname"  class="form-control" required>
        <p ng-show="myForm.firstname.$touched && myForm.firstname.$invalid" class="danger-text">Please enter your first name</p>

      </div>
      <div class="col-md-6 mb-3">

        <label for="last_name">Last Name</label>
        <input type="text" name="last_name" ng-model="last_name" id="last_name"  class="form-control"  required>
        <p ng-show="myForm.last_name.$invalid && myForm.last_name.$touched" class="danger-text">Please enter your last name</p>

      </div>
     </div> <!-- End of row -->
     <div class="row">
      <div class="col-md-6 mb-3">
       <label for="username">Username</label>
       <input type="text" name="username" id="username" ng-model="username" class="form-control" ng-required="true" ng-minlength="4" ng-maxlength="10" >
       <p ng-show="myForm.username.$error.required && myForm.username.$touched" class="danger-text">Please enter username</p>
       <p ng-show="myForm.username.$error.minlength" class="danger-text">Username is too short</p>
       <p ng-show="myForm.username.$error.maxlength" class="danger-text">Username is too long</p>
      </div>
      <div class="col-md-6 mb-3">
       <label for="email">Email</label>
       <input type="email" name="email" id="email" class="form-control" ng-model="email">
       <p ng-show="myForm.email.$invalid && !myForm.email.$pristine" class="danger-text">Enter a valid email address</p>
      </div>
     </div> <!-- ENd of row -->
     <div class="row">
      <div class="col-md-6 mb-3">
       <label for="password">Password</label>
       <input type="password" class="form-control" id="password" name="password" ng-model="password" ng-minlength="8" ng-maxlength="20" ng-pattern="/(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z])/" required  />
   <p class="danger-text" ng-show="myForm.password.$error.required && myForm.password.$touched">Password is required</p>
   <p class="danger-text" ng-show="!myForm.password.$error.required && (myForm.password.$error.minlength || myForm.password.$error.maxlength) && myForm.password.$dirty">Passwords must be between 8 and 20 characters.</p>
   <p class="danger-text" ng-show="!myForm.password.$error.required && !myForm.password.$error.minlength && !myForm.password.$error.maxlength && myForm.password.$error.pattern && myForm.password.$dirty">Must contain one lower &amp; uppercase letter, and one non-alpha character (a number or a symbol.)</p>
      </div> <!-- End of col md 6 -->
      <div class="col-md-6 mb-3">
       <label>Confirm Password</label>
       <input type="password" id="confirm_password" name="confirm_password" class="form-control" ng-model="confirm_password" valid-confirm-password required  />
   <p class="danger-text" ng-show="myForm.confirm_password.$error.required && myForm.confirm_password.$dirty">Please confirm your password.</p>
   <p class="danger-text" ng-show="!myForm.confirm_password.$error.required && myForm.confirm_password.$error.noMatch && myForm.password.$dirty">Passwords do not match.</p>
      </div>
     </div> <!-- ENd of row -->
     <div class="row">
      <div class="col-md-12">
       <button type="submit"  class="btn btn-primary">Submit</button>
      </div>
     </div>
    </form> <!-- End of form -->
   </div> <!-- End of col sm 12 -->
  </div> <!-- End of row -->
 </div> <!-- End of container -->
  </div>


问:
What does '@' char mean before parameter name in method declaration?

Possible Duplicates:

  What does the @ symbol before a variable name mean in C#?

  What's the use/meaning of the @ character in variable names in C#?

Hi,

I have one quick question. What does '@' char mean before parameter name in method declaration? Like following:

```<code>protected void Method1(Type1 @arg1, Type2 arg2)
...
</code>```

I use c# with .net 3.5.

Thanks.

答:
It is used to have reserved words as parameters. Example:

```<code>string @string = "abc";
</code>```

or:

```<code>string @class = "foo";
</code>```

arg1 is not a reserved word so using @ is not necessary. This being said, using reserved words to name your parameters is not a good idea. There are cases though where this is useful. For example in ASP.NET MVC some HTML extension methods take an anonymous object as parameter to emit html attributes. So you have syntax like this:

```<code><%= Html.ActionLink("text", "action", "controller", null, new { @class = "abc" }) %>
</code>```

which generates:

```<code><a href="/controller/action" class="abc">text</a>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Possible Duplicates:

  What does the @ symbol before a variable name mean in C#?

  What's the use/meaning of the @ character in variable names in C#?

Hi,

I have one quick question. What does '@' char mean before parameter name in method declaration? Like following:

protected void Method1(Type1 @arg1, Type2 arg2)
...

I use c# with .net 3.5.

Thanks.

Body:
It is used to have reserved words as parameters. Example:

string @string = "abc";

or:

string @class = "foo";

arg1 is not a reserved word so using @ is not necessary. This being said, using reserved words to name your parameters is not a good idea. There are cases though where this is useful. For example in ASP.NET MVC some HTML extension methods take an anonymous object as parameter to emit html attributes. So you have syntax like this:

<%= Html.ActionLink("text", "action", "controller", null, new { @class = "abc" }) %>

which generates:

<a href="/controller/action" class="abc">text</a>


问:
unwraping div tags between two elements
I want to remove the div's between two specific elements

item1

item2

item3

item4

```
</div>
</div>
</p>

<p>i want to remove the div's between  id test1 and id ulid
how to use unwrap here
expected output</p>

```

item1

item2

item3

item4

```

答:
You are unwrapping div elements which are parent elements of ul#ulid.

You can just call unwrap() on #ulid multiple times until you reach the element you want to keep (i.e., #test1). You can check if you have reached the element using attr(). This is easy because the objective is to remove every parent until #test1 is the parent. There is an extremely useful parent() function implemented in jQuery.

Here's a simple snippet that demonstrates this. (I'm using CSS to show that the elements are being removed.)

$(document).ready(function() {
  $("#unwrap").click(function() {
    while ($("#ulid").parent().attr("id") !== "test1") { // while the id of the parent is not "test1"
      $("#ulid").unwrap();
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#test1 {
  color: red;
}

#test2 {
  color: black;
}</code>```

item1

item2

item3

item4

<button id="unwrap">Unwrap</button>```
</div>
</div>
</p>

<p>Here's what the HTML looks like after it has been unwrapped:</p>

```

item1

item2

item3

item4

```

And your problem is (hopefully) solved!

All that you really required was a simple loop. Hope this helps.

Title: unwraping div tags between two elements

Body:
I want to remove the div's between two specific elements

item1

item2

item3

item4

i want to remove the div's between  id test1 and id ulid
how to use unwrap here
expected output

item1

item2

item3

item4

Body:
You are unwrapping div elements which are parent elements of ul#ulid.

You can just call unwrap() on #ulid multiple times until you reach the element you want to keep (i.e., #test1). You can check if you have reached the element using attr(). This is easy because the objective is to remove every parent until #test1 is the parent. There is an extremely useful parent() function implemented in jQuery.

Here's a simple snippet that demonstrates this. (I'm using CSS to show that the elements are being removed.)

$(document).ready(function() {
  $("#unwrap").click(function() {
    while ($("#ulid").parent().attr("id") !== "test1") { // while the id of the parent is not "test1"
      $("#ulid").unwrap();
    }
  });
});

#test1 {
  color: red;
}

#test2 {
  color: black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test1">
  <div id="test2">
    <div id="test3">
      <div id="test4">
        <div id="test5">
          <div id="test6">
            <ul id="ulid">
              <li>item1</li>
              <li>item2</li>
              <li>item3</li>
              <li>item4</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<button id="unwrap">Unwrap</button>

Here's what the HTML looks like after it has been unwrapped:

<div id="test1">
  <ul id="ulid">
    <li>item1</li>
    <li>item2</li>
    <li>item3</li>
    <li>item4</li>
  </ul>
</div>

And your problem is (hopefully) solved!

All that you really required was a simple loop. Hope this helps.


答:
```<code><?php

$a = $_GET['act'];
if($a)
$sql = "SELECT * from DONE ";
else
$sql = "SELECT * from ONGOING ";

$b = mysqli_query ($con,$sql);
$r = mysqli_fetch_assoc($b);
.......
?>
</code>```

Title: selecting query from one file


问:
How to identify the difference between file and folder ondropping in javascript?
I have a container which allows dropping of files and folder. I want to identify the drop item type( file or folder ) and the exact folder or file path of dropped item.

Note: I am able to get item details if I use webkitGetAsEntry() but I don't want to use this.

Someone suggested me to use files[0].size == 4096 ( for identifying folder) and its not giving exactly 4096. Its varying.

Thanks in advance.

答:
This can may help. It can be improved but do the job:

```<code>function drop_type(string)
{
    return /(\.[a-z0-9]{2,5})$/i.test(string) ? 'file' : 'directory';
}
</code>```

Here is JSFIDDLE.

This is dirty solution but works. In regex you can add extensions and match it.

Body:
This can may help. It can be improved but do the job:

function drop_type(string)
{
    return /(\.[a-z0-9]{2,5})$/i.test(string) ? 'file' : 'directory';
}

Here is JSFIDDLE.

This is dirty solution but works. In regex you can add extensions and match it.


问:
show messagebox if select query returns no rows in vb.net
I had this problem where if select query has rows, it will pass the data to datagridview, but if the query result has no rows, messagebox will appear containing "No records for this code."

this is my code:

```<code>Private Sub txtScheduleID_KeyDown(sender As Object, e As KeyEventArgs) Handles txtScheduleID.KeyDown
    If (e.KeyCode = Keys.Space) Then

        Dim TextboxValue As String = RTrim(txtScheduleID.Text)
        Dim vals = TextboxValue.Split(" ").Last()

        sqlCon.Open()
        Try
            Dim QUERY As String

            QUERY = "SELECT [Class Schedule LINE].SchedID, ListofSubjects.[Course No.], ListofSubjects.[Descriptive Title], Section.Section, Curriculum.[Lab.] + Curriculum.[Lec.], UtlyTIMETable.[FROM Time] +'-'+ UtlyTIMETable.[TO Time] + '   ' + UtlyDAY.Day + '   ' + UtlyRoom.Building + ' ' +UtlyRoom.[Room No.], UtlyInstructor.[Last Name] + ', ' + LEFT (UtlyInstructor.[First Name],1)+'.' " &
                    "FROM   [Class Schedule LINE] INNER JOIN Curriculum ON [Class Schedule LINE].[Subject Code] = Curriculum.[Subject Code] INNER JOIN ListofSubjects ON Curriculum.SubjectID = ListofSubjects.SubjectID INNER JOIN Section ON [Class Schedule LINE].Section = Section.SectionID INNER JOIN UtlyTIMETable ON [Class Schedule LINE].TimeID = UtlyTIMETable.TimeID INNER JOIN UtlyDAY ON [Class Schedule LINE].DayID = UtlyDAY.DayID INNER JOIN UtlyRoom ON [Class Schedule LINE].RoomID = UtlyRoom.RoomID INNER JOIN UtlyInstructor ON [Class Schedule LINE].InstructorID = UtlyInstructor.IntructorID " &
                    "WHERE  ([Class Schedule LINE].SchedID =  '" + vals + "') "
            CMD = New SqlCommand(QUERY, sqlCon)
            Reader = CMD.ExecuteReader
            While Reader.Read
                table.Rows.Add(Reader.GetInt32(0), Reader.GetString(1), Reader.GetString(2), Reader.GetString(3), Reader.GetDecimal(4), Reader.GetString(5), Reader.GetString(6))
                dgvSubjectsEnrolled.DataSource = table
            End While
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
        sqlCon.Close()
    End If
End Sub
</code>```

Please edit my code. thanks

答:
It is not an error for a reader to not have rows.

```<code>If Reader.HasRows Then
 While Reader.Read
'Your code
Else
MessageBox.Show()
End If
</code>```

How about putting your connection.Close in a Finally block so you are sure it will close even if there is an error. Check its state first.

Body:
I had this problem where if select query has rows, it will pass the data to datagridview, but if the query result has no rows, messagebox will appear containing "No records for this code."

this is my code:

Private Sub txtScheduleID_KeyDown(sender As Object, e As KeyEventArgs) Handles txtScheduleID.KeyDown
    If (e.KeyCode = Keys.Space) Then

        Dim TextboxValue As String = RTrim(txtScheduleID.Text)
        Dim vals = TextboxValue.Split(" ").Last()

        sqlCon.Open()
        Try
            Dim QUERY As String

            QUERY = "SELECT [Class Schedule LINE].SchedID, ListofSubjects.[Course No.], ListofSubjects.[Descriptive Title], Section.Section, Curriculum.[Lab.] + Curriculum.[Lec.], UtlyTIMETable.[FROM Time] +'-'+ UtlyTIMETable.[TO Time] + '   ' + UtlyDAY.Day + '   ' + UtlyRoom.Building + ' ' +UtlyRoom.[Room No.], UtlyInstructor.[Last Name] + ', ' + LEFT (UtlyInstructor.[First Name],1)+'.' " &
                    "FROM   [Class Schedule LINE] INNER JOIN Curriculum ON [Class Schedule LINE].[Subject Code] = Curriculum.[Subject Code] INNER JOIN ListofSubjects ON Curriculum.SubjectID = ListofSubjects.SubjectID INNER JOIN Section ON [Class Schedule LINE].Section = Section.SectionID INNER JOIN UtlyTIMETable ON [Class Schedule LINE].TimeID = UtlyTIMETable.TimeID INNER JOIN UtlyDAY ON [Class Schedule LINE].DayID = UtlyDAY.DayID INNER JOIN UtlyRoom ON [Class Schedule LINE].RoomID = UtlyRoom.RoomID INNER JOIN UtlyInstructor ON [Class Schedule LINE].InstructorID = UtlyInstructor.IntructorID " &
                    "WHERE  ([Class Schedule LINE].SchedID =  '" + vals + "') "
            CMD = New SqlCommand(QUERY, sqlCon)
            Reader = CMD.ExecuteReader
            While Reader.Read
                table.Rows.Add(Reader.GetInt32(0), Reader.GetString(1), Reader.GetString(2), Reader.GetString(3), Reader.GetDecimal(4), Reader.GetString(5), Reader.GetString(6))
                dgvSubjectsEnrolled.DataSource = table
            End While
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
        sqlCon.Close()
    End If
End Sub

Please edit my code. thanks

Body:
It is not an error for a reader to not have rows.

If Reader.HasRows Then
 While Reader.Read
'Your code
Else
MessageBox.Show()
End If

How about putting your connection.Close in a Finally block so you are sure it will close even if there is an error. Check its state first.


问:
SQL- I need script text file need to know which tables and views and stored procedures having that script
I am having script text file that inside having

Create procedure

Create table

alter table

alter procedure

alter view

create view etc..

I need to know views, SPs, tables names and its roles (create or alter) when I run the script.

Example following are text file.

and the result should be following

proc, alter, bal.vendor
table, select, manager
table, create, employee
table, alter, persons

答:
You can use sql query:

```<code>SELECT name, type, type_desc, create_date, modify_date
FROM sys.objects
WHERE modify_date > '01-01-2017' -- pass your date
</code>```

name: is the name of the sp, table or view that was modified or created

type: indicates type of the object

The objects that were newly created will have the same date for both create_date and modify_date. Use this modified query to show if it was new or modified:

```<code>SELECT name, type, type_desc,
case when  create_date = modify_date then 'Created' Else 'Altered' end
        FROM sys.objects
        WHERE modify_date > '01-01-2017'
</code>```

Body:
You can use sql query:

SELECT name, type, type_desc, create_date, modify_date
FROM sys.objects
WHERE modify_date > '01-01-2017' -- pass your date

name: is the name of the sp, table or view that was modified or created

type: indicates type of the object

The objects that were newly created will have the same date for both create_date and modify_date. Use this modified query to show if it was new or modified:

SELECT name, type, type_desc,
case when  create_date = modify_date then 'Created' Else 'Altered' end
        FROM sys.objects
        WHERE modify_date > '01-01-2017'


问:
UpdateException when using SQL Server Compact with Entity Framework
I am trying to use Entity Framework with SQL Server Compact. I can perform reading such as :

```<code>var context = new TestEntities();

foreach (var p in context.Personnes)
{
    Console.WriteLine(p.prenom + " " + p.nom);
}
</code>```

but I can't perform insert :

```<code>var context = new TestEntities();

context.Personnes.AddObject(new Personne() {nom = "Test", prenom = "Test" });

context.SaveChanges();
</code>```

An UpdateException is raised when I try to do this. The Personne table has just 3 columns: id (int, primary key), nom (varchar) and prenom (varchar).

Here is the display I have when I run the program :

System.Data.EntityCommandCompilationException:
  Une erreur s'est produite lors de la
  préparation de la définition de la
  commande. Pour plus de détails,
  consultez l'exception interne. --->
  System.NotSupportedException: Les clès
  et les valeurs générées par le serveur
  ne sont pas prises en charge par SQL
  Server Compact.

System.Data.SqlServerCe.SqlGen.DmlSqlGenerator.GenerateInsertSql(DbInsertCommandTree
  tree, List1& parameters, Boolean
  isLocalProvider)
         … System.Data.SqlServerCe.SqlGen.SqlGenerator.GenerateSql(DbCommandTree
  tree, List1& parameters, CommandType&
  commandType, Boolean isLocalProvider)
         … System.Data.SqlServerCe.SqlCeProviderServices.CreateCommand(DbProviderManifest
  providerManifest, DbCommandTree
  commandTree)
         … System.Data.SqlServerCe.SqlCeProviderServices.CreateDbCommandDefinition(DbProviderManifest
  providerManifest, DbCommandTree
  commandTree)
         … System.Data.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree
  commandTree)
         … System.Data.Common.DbProviderServices.CreateCommand(DbCommandTree
  commandTree)
         … System.Data.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree
  commandTree)
         --- Fin de la trace de la pile d'exception interne ---
         … System.Data.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree
  commandTree)
         … System.Data.Mapping.Update.Internal.DynamicUpdateCommand.CreateCommand(UpdateTranslator
  translator, Dictionary2
  identifierValues)
         … System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator
  translator, EntityConnection
  connection, Dictionary2
  identifierValues, List`1
  generatedValues)
         … System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager
  stateManager, IEntityAdapter adapter)

Thank you :)

答:
SqlServer Compact doesn't support server-side key generation. You must generate key on application side. So set id explicitly. Here is example.

```<code>context.Personnes.AddObject(new Personne() {id = lastId++, nom = "Test", prenom = "Test" });
</code>```

You have to maintain lastId. Code that I wrote above will work only in single thread.

Body:
I am trying to use Entity Framework with SQL Server Compact. I can perform reading such as :

var context = new TestEntities();

foreach (var p in context.Personnes)
{
    Console.WriteLine(p.prenom + " " + p.nom);
}

but I can't perform insert :

var context = new TestEntities();

context.Personnes.AddObject(new Personne() {nom = "Test", prenom = "Test" });

context.SaveChanges();

An UpdateException is raised when I try to do this. The Personne table has just 3 columns: id (int, primary key), nom (varchar) and prenom (varchar).

Here is the display I have when I run the program :

System.Data.EntityCommandCompilationException:
  Une erreur s'est produite lors de la
  préparation de la définition de la
  commande. Pour plus de détails,
  consultez l'exception interne. --->
  System.NotSupportedException: Les clès
  et les valeurs générées par le serveur
  ne sont pas prises en charge par SQL
  Server Compact.

System.Data.SqlServerCe.SqlGen.DmlSqlGenerator.GenerateInsertSql(DbInsertCommandTree
  tree, List1& parameters, Boolean
  isLocalProvider)
         … System.Data.SqlServerCe.SqlGen.SqlGenerator.GenerateSql(DbCommandTree
  tree, List1& parameters, CommandType&
  commandType, Boolean isLocalProvider)
         … System.Data.SqlServerCe.SqlCeProviderServices.CreateCommand(DbProviderManifest
  providerManifest, DbCommandTree
  commandTree)
         … System.Data.SqlServerCe.SqlCeProviderServices.CreateDbCommandDefinition(DbProviderManifest
  providerManifest, DbCommandTree
  commandTree)
         … System.Data.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree
  commandTree)
         … System.Data.Common.DbProviderServices.CreateCommand(DbCommandTree
  commandTree)
         … System.Data.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree
  commandTree)
         --- Fin de la trace de la pile d'exception interne ---
         … System.Data.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree
  commandTree)
         … System.Data.Mapping.Update.Internal.DynamicUpdateCommand.CreateCommand(UpdateTranslator
  translator, Dictionary2
  identifierValues)
         … System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator
  translator, EntityConnection
  connection, Dictionary2
  identifierValues, List`1
  generatedValues)
         … System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager
  stateManager, IEntityAdapter adapter)

Thank you :)

Body:
SqlServer Compact doesn't support server-side key generation. You must generate key on application side. So set id explicitly. Here is example.

context.Personnes.AddObject(new Personne() {id = lastId++, nom = "Test", prenom = "Test" });

You have to maintain lastId. Code that I wrote above will work only in single thread.


答:
Use a variable to tell which query to run.</p>

```<code><?php
    $a = $_GET['act'];
    if ($a){
        include('show.php');
        $code = 1;
    }
    else {
        include('show.php');
        $code = 2;
    }
?>

<?php
    if($code == 1){
        $sql = "SELECT * from DONE ";
    }
    else{
        $sql = "SELECT * from ONGOING ";
    }
?>

<?php
    $b = mysqli_query ($con,$sql);
    $r = mysqli_fetch_assoc($b);
    .......
?>
</code>```

Title: selecting query from one file

Body:
Use a variable to tell which query to run.

<?php
    $a = $_GET['act'];
    if ($a){
        include('show.php');
        $code = 1;
    }
    else {
        include('show.php');
        $code = 2;
    }
?>

<?php
    if($code == 1){
        $sql = "SELECT * from DONE ";
    }
    else{
        $sql = "SELECT * from ONGOING ";
    }
?>

<?php
    $b = mysqli_query ($con,$sql);
    $r = mysqli_fetch_assoc($b);
    .......
?>


问:
How can Increase performance on my Ionic3 Anguar4 app?
Now I am working with Ionic3, Angular4 android app. It is taking a while to load initially. I mean I got a black blank screen for few seconds.How can I speed up this and avoid the black screen?</p>

答: Obviously, you will need to profile your app and to see why it's slow (if it's indeed "slow"), but people generally use Splash Screen while loading the app, to avoid the blank screen.</p>


答:
```<code><?php
$a = $_GET['act'];
if ($a){
include('show.php?condition=ok');
} else {
include('show.php?condition=notok');
}
?>
</code>```

and on other page like this

```<code><?php
if($_GET['condition']=='ok')
{
$sql2 = "SELECT * from DONE ";
$b = mysqli_query ($con,$sql2);
$r = mysqli_fetch_assoc($b);
.......
}
else if($_GET['condition']=='notok') {

$sql3 = "SELECT * from ONGOING ";
$b = mysqli_query ($con,$sql3);
$r = mysqli_fetch_assoc($b);
.......
} else {

//other stuff

}
?>
</code>```

Title: selecting query from one file

Body:
so i have some kind of code on a page like this

<?php
$a = $_GET['act'];
if ($a){
include('show.php');
} else {
include('show.php');
}
?>

and on other page like this

<?php
$sql2 = "SELECT * from DONE ";
$b = mysqli_query ($con,$sql2);
$r = mysqli_fetch_assoc($b);
.......
?>

<?php
$sql3 = "SELECT * from ONGOING ";
$b = mysqli_query ($con,$sql3);
$r = mysqli_fetch_assoc($b);
.......
?>

my question , is it possible when the condition is met it execute the first query and when the condition doesn't met it execute the second query , when both of the query placed on same page ?

Body:
<?php
$a = $_GET['act'];
if ($a){
include('show.php?condition=ok');
} else {
include('show.php?condition=notok');
}
?>

and on other page like this

<?php
if($_GET['condition']=='ok')
{
$sql2 = "SELECT * from DONE ";
$b = mysqli_query ($con,$sql2);
$r = mysqli_fetch_assoc($b);
.......
}
else if($_GET['condition']=='notok') {

$sql3 = "SELECT * from ONGOING ";
$b = mysqli_query ($con,$sql3);
$r = mysqli_fetch_assoc($b);
.......
} else {

//other stuff

}
?>


问:
How to prevent tableview section head from sticking while scrolling?
I have a tableview with many sections. I am using an actual tableview cell which I dequeue to use as a custom section header. The issue I am having is when I scroll the section header "sticks" to the top of the table until the next section appears.

How can I prevent this from happening and actually have it scroll up like normal?

Here is my code

```<code>func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if section == 3 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell") as! HeaderTableViewCell
        return cell
    }
    return UIView()
}
</code>```

答:
Set UITableViewStyle to UITableViewStyleGrouped, the headers will scroll up with the cells.
and

```<code>func tableView(_ tableView: UITableView,
heightForFooterInSection section: Int) -> CGFloat
{
    return 0.000001;
}
</code>```

Body:
I have a tableview with many sections. I am using an actual tableview cell which I dequeue to use as a custom section header. The issue I am having is when I scroll the section header "sticks" to the top of the table until the next section appears.

How can I prevent this from happening and actually have it scroll up like normal?

Here is my code

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if section == 3 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell") as! HeaderTableViewCell
        return cell
    }
    return UIView()
}

Body:
Set UITableViewStyle to UITableViewStyleGrouped, the headers will scroll up with the cells.
and

func tableView(_ tableView: UITableView,
heightForFooterInSection section: Int) -> CGFloat
{
    return 0.000001;
}


答:
You do not need a loop for this. You are missing the contents function in jQuery.

It returns the child elements of the selected element.

```<code>$('div[id^="test"][id!="test1"]').contents().unwrap();
</code>```

Title: unwraping div tags between two elements

Body:
You do not need a loop for this. You are missing the contents function in jQuery.

It returns the child elements of the selected element.

$('div[id^="test"][id!="test1"]').contents().unwrap();


问:
disable wp-pagenavi on pages with template using the wordpress loop
How can i disable wp-pagenavi on pages using templates and the wordpress loop? It seems that wp-pagenavi adds itself automatically wherever the wordpress loop is used, not counting that it is a page or not. </p>

答:
My bad..the theme called wppagenavi(), thus pagenavi is not added automagically.

By removing that call from templates of choice i can achieve what i wanted. :-)


问:
Fixed footer in landscape and portrait mode in Android
I would like to have a fixed footer something like this:

I tried to achieve this using relative layout:

```<code>   <RelativeLayout
        android:id="@+id/footer"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/_12sdp"
        android:layout_alignParentBottom="true">
        <TextView
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:layout_gravity="center_horizontal"
            android:textColor="@color/material_grey_850"
            android:gravity="center_horizontal"
            android:text="Version 1.0 Demo"
            android:layout_marginTop="@dimen/_22sdp"
            android:textSize="@dimen/_15sdp"
            android:id="@+id/versionText" />
        <TextView
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:layout_gravity="center_horizontal"
            android:textColor="@color/material_grey_850"
            android:gravity="center_horizontal"
            android:text="Copyright (c) 2017 Aglive Pty Ltd"
            android:layout_marginTop="@dimen/_8sdp"
            android:textSize="@dimen/_15sdp"
            android:id="@+id/copyrightText"
            android:layout_alignParentBottom="false"
            android:layout_below="@id/versionText" />
        <RelativeLayout
            android:orientation="vertical"
            android:layout_column="0"
            android:layout_row="2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_columnSpan="7"
            android:layout_marginTop="7.0dp"
            android:layout_marginBottom="7.0dp"
            android:id="@+id/relative"
            android:layout_below="@id/copyrightText">
            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_gravity="center_horizontal"
                android:textColor="@color/material_grey_850"
                android:gravity="center_horizontal"
                android:text="Terms of Service"
                android:layout_marginTop="21.5sp"
                android:layout_alignParentBottom="true"
                android:textSize="@dimen/_15sdp"
                android:layout_marginRight="5.5sp"
                android:id="@+id/termsOfService"
                android:layout_alignParentLeft="true"
                android:layout_marginLeft="@dimen/_15sdp" />
            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_gravity="center_horizontal"
                android:textColor="@color/material_grey_850"
                android:gravity="center_horizontal"
                android:text="Contact Us"
                android:layout_marginTop="21.5sp"
                android:layout_alignParentBottom="true"
                android:textSize="@dimen/_15sdp"
                android:layout_marginRight="@dimen/_15sdp"
                android:id="@+id/contactUs"
                android:layout_alignParentRight="true" />
        </RelativeLayout>
    </RelativeLayout>
</code>```

But the problem here is that whenever the keyboard opens up the footer moves up. For which I tried to add WindowSoftInputMode =  SoftInput.AdjustPan. It worked for the keyboard issue but whenever the screen rotates to landscape mode the footer overlaps the other text. Also my relative layout does not come as required.  The relative layout seems to be covering other text.

答:
Adding,

```<code>android:configChanges="keyboardHidden|orientation|screenSize"
</code>```

into your <activity> node in manifest.xml will do the trick.

now, you can listen configuration changes into an override method onConfigurationChanged in your activity.

```<code>@Override
public void onConfigurationChanged(Configuration newConfig) {
  super.onConfigurationChanged(newConfig);
  // Perform any action here... resetting the layout or.. values or smoething
}
</code>```

Body:
I would like to have a fixed footer something like this:

I tried to achieve this using relative layout:

   <RelativeLayout
        android:id="@+id/footer"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/_12sdp"
        android:layout_alignParentBottom="true">
        <TextView
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:layout_gravity="center_horizontal"
            android:textColor="@color/material_grey_850"
            android:gravity="center_horizontal"
            android:text="Version 1.0 Demo"
            android:layout_marginTop="@dimen/_22sdp"
            android:textSize="@dimen/_15sdp"
            android:id="@+id/versionText" />
        <TextView
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:layout_gravity="center_horizontal"
            android:textColor="@color/material_grey_850"
            android:gravity="center_horizontal"
            android:text="Copyright (c) 2017 Aglive Pty Ltd"
            android:layout_marginTop="@dimen/_8sdp"
            android:textSize="@dimen/_15sdp"
            android:id="@+id/copyrightText"
            android:layout_alignParentBottom="false"
            android:layout_below="@id/versionText" />
        <RelativeLayout
            android:orientation="vertical"
            android:layout_column="0"
            android:layout_row="2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_columnSpan="7"
            android:layout_marginTop="7.0dp"
            android:layout_marginBottom="7.0dp"
            android:id="@+id/relative"
            android:layout_below="@id/copyrightText">
            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_gravity="center_horizontal"
                android:textColor="@color/material_grey_850"
                android:gravity="center_horizontal"
                android:text="Terms of Service"
                android:layout_marginTop="21.5sp"
                android:layout_alignParentBottom="true"
                android:textSize="@dimen/_15sdp"
                android:layout_marginRight="5.5sp"
                android:id="@+id/termsOfService"
                android:layout_alignParentLeft="true"
                android:layout_marginLeft="@dimen/_15sdp" />
            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_gravity="center_horizontal"
                android:textColor="@color/material_grey_850"
                android:gravity="center_horizontal"
                android:text="Contact Us"
                android:layout_marginTop="21.5sp"
                android:layout_alignParentBottom="true"
                android:textSize="@dimen/_15sdp"
                android:layout_marginRight="@dimen/_15sdp"
                android:id="@+id/contactUs"
                android:layout_alignParentRight="true" />
        </RelativeLayout>
    </RelativeLayout>

But the problem here is that whenever the keyboard opens up the footer moves up. For which I tried to add WindowSoftInputMode =  SoftInput.AdjustPan. It worked for the keyboard issue but whenever the screen rotates to landscape mode the footer overlaps the other text. Also my relative layout does not come as required.  The relative layout seems to be covering other text.

Body:
Adding,

android:configChanges="keyboardHidden|orientation|screenSize"

into your <activity> node in manifest.xml will do the trick.

now, you can listen configuration changes into an override method onConfigurationChanged in your activity.

@Override
public void onConfigurationChanged(Configuration newConfig) {
  super.onConfigurationChanged(newConfig);
  // Perform any action here... resetting the layout or.. values or smoething
}


答:
This is precisely why PHP has functions. In your included file organize those two things into separate chunks of code:

```<code><?php
function fromDone($con) {
  $b = mysqli_query($con,"SELECT * from DONE ");
  $r = mysqli_fetch_assoc($b);
  .......
}

function fromOngoing($con) {
  $b = mysqli_query ($con,"SELECT * from ONGOING");
  $r = mysqli_fetch_assoc($b);
  .......
}
?>
</code>```

Then in your main file you can do this:

```<code><?php
if ($_GET['act']) {
  fromDone($con);
} else {
  fromOngoing($con);
}
?>
</code>```

Title: selecting query from one file

Body:
This is precisely why PHP has functions. In your included file organize those two things into separate chunks of code:

<?php
function fromDone($con) {
  $b = mysqli_query($con,"SELECT * from DONE ");
  $r = mysqli_fetch_assoc($b);
  .......
}

function fromOngoing($con) {
  $b = mysqli_query ($con,"SELECT * from ONGOING");
  $r = mysqli_fetch_assoc($b);
  .......
}
?>

Then in your main file you can do this:

<?php
if ($_GET['act']) {
  fromDone($con);
} else {
  fromOngoing($con);
}
?>


问:
Visual studio Run-Time Check Failure #2 - Stack around the variable 'temp' was corrupted
I've written a function to partition elements for a quick sort algorithm for sorting an array of cstrings

```<code>void partition(char words[][MAXWORDLEN + 1], int start, int end, int& partitionIndex) {
char pivot[MAXWORDLEN + 1]; //choose last element to be the pivot
strcpy(pivot, words[end]);
partitionIndex = start; //partition index is initalized to the first index
for (int i = start; i < end; ++i) { //iterate through the array
    if (strcmp(words[i], words[end]) < 0) {
        char temp[MAXWORDLEN];
        strcpy(temp, words[i]); //swap the element with the element corresponding to the partition index
        strcpy(words[i], words[partitionIndex]);
        strcpy(words[partitionIndex], temp);
        partitionIndex++;
    }
}
cout << end << endl;
char temp[MAXWORDLEN + 1];
strcpy(temp, words[end]);
strcpy(words[end], words[partitionIndex]);
strcpy(words[partitionIndex], temp);
</code>```

}

However, when I run the program, I get a run time check failure. MAXWORDLENGTH is 6 and all words in the array are between 4-6 characters long. So I'm confused why the variable temp can't seemed to be copied to words at index partitionIndex

答:
Change this:

```<code>char temp[MAXWORDLEN];
</code>```

to this:

```<code>char temp[MAXWORDLEN + 1];
</code>```

since the pivot array has this size too.

So when temp was of size 6 and the word it contains had 6 characters, the null terminator would be overwritten, meaning that the copy would fail and invoke Undefined Behavior. We don't really know what garbage values are going to be written into the target array via copying, if any.

Body:
I've written a function to partition elements for a quick sort algorithm for sorting an array of cstrings

void partition(char words[][MAXWORDLEN + 1], int start, int end, int& partitionIndex) {
char pivot[MAXWORDLEN + 1]; //choose last element to be the pivot
strcpy(pivot, words[end]);
partitionIndex = start; //partition index is initalized to the first index
for (int i = start; i < end; ++i) { //iterate through the array
    if (strcmp(words[i], words[end]) < 0) {
        char temp[MAXWORDLEN];
        strcpy(temp, words[i]); //swap the element with the element corresponding to the partition index
        strcpy(words[i], words[partitionIndex]);
        strcpy(words[partitionIndex], temp);
        partitionIndex++;
    }
}
cout << end << endl;
char temp[MAXWORDLEN + 1];
strcpy(temp, words[end]);
strcpy(words[end], words[partitionIndex]);
strcpy(words[partitionIndex], temp);

}

However, when I run the program, I get a run time check failure. MAXWORDLENGTH is 6 and all words in the array are between 4-6 characters long. So I'm confused why the variable temp can't seemed to be copied to words at index partitionIndex

Body:
Change this:

char temp[MAXWORDLEN];

to this:

char temp[MAXWORDLEN + 1];

since the pivot array has this size too.

So when temp was of size 6 and the word it contains had 6 characters, the null terminator would be overwritten, meaning that the copy would fail and invoke Undefined Behavior. We don't really know what garbage values are going to be written into the target array via copying, if any.


问:
Having trouble with graph3d installation in RStudio
Trying to install graph3d I get an error message reproduced here

```<code>  > require("graph3d")

Loading required package: graph3d
Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called 'graph3d'

    > version
               _
platform       x86_64-w64-mingw32
arch           x86_64
os             mingw32
system         x86_64, mingw32
status
major          3
minor          4.1
year           2017
month          06
day            30
svn rev        72865
language       R
version.string R version 3.4.1 (2017-06-30)
nickname       Single Candle
>
</code>```

On a different computer with an older version of R I get no error message

```<code>    > version
               _
platform       x86_64-w64-mingw32
arch           x86_64
os             mingw32
system         x86_64, mingw32
status
major          3
minor          2.5
year           2016
month          04
day            14
svn rev        70478
language       R
version.string R version 3.2.5 (2016-04-14)
nickname       Very, Very Secure Dishes

    > require("graph3d")
    >
</code>```

Going back to the newer version and using install.packages command produces the message below

```<code>>install.packages("graph3d")
</code>```

Installing package into 'C:/Users/XXXXXXXXX/Documents/R/win-library/3.4'
(as 'lib' is unspecified)
Warning in install.packages :

```<code> package 'graph3d' is not available (for R version 3.4.1)
>
</code>```

答:
Try to install it via devtools, that worked for me:</p>

```<code>if(!require(devtools)) install.packages("devtools")
devtools::install_github("kassambara/graph3d")
</code>```

Body:
Trying to install graph3d I get an error message reproduced here

  > require("graph3d")

Loading required package: graph3d
Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called 'graph3d'

    > version
               _
platform       x86_64-w64-mingw32
arch           x86_64
os             mingw32
system         x86_64, mingw32
status
major          3
minor          4.1
year           2017
month          06
day            30
svn rev        72865
language       R
version.string R version 3.4.1 (2017-06-30)
nickname       Single Candle
>

On a different computer with an older version of R I get no error message

    > version
               _
platform       x86_64-w64-mingw32
arch           x86_64
os             mingw32
system         x86_64, mingw32
status
major          3
minor          2.5
year           2016
month          04
day            14
svn rev        70478
language       R
version.string R version 3.2.5 (2016-04-14)
nickname       Very, Very Secure Dishes

    > require("graph3d")
    >

Going back to the newer version and using install.packages command produces the message below

>install.packages("graph3d")

Installing package into 'C:/Users/XXXXXXXXX/Documents/R/win-library/3.4'
(as 'lib' is unspecified)
Warning in install.packages :

 package 'graph3d' is not available (for R version 3.4.1)
>

Body:
Try to install it via devtools, that worked for me:

if(!require(devtools)) install.packages("devtools")
devtools::install_github("kassambara/graph3d")


问:
gwt export to file
i have a problem with gwt application. i have an array of strings in the client application and i want to export it to a file, but it isn't probably possible so i have to use servlet, right? but i don't really know how.</p>

答: In this case using servlet is a good idea or maybe RPC is better. What do you think? So far I wrote a separate servlet that writes an array of strings to a file. But I don't know how to connect to the gwt project. Will this created file be HttpServletResponse response in this case?</p>

Title: gwt export to file


问:
Why do I need to use a const reference parameter in a << overloading function when using an overloaded post-decrement operator?
I have the following << overloading function:

```<code>ostream& operator<<(ostream& output, HW4& rhs)
{

    for(int i = 0; i < HW4::size; ++i)
    {
        output << rhs.array[i] << "    ";
    }

    return output;
}
</code>```

And I also have this post-decrement overloading function:

```<code>HW4 HW4::operator--(int)
{
    HW4 temp = *this;
    int hold;
    for(int i = 0; i < size/2; ++i)
    {
        hold = array[i];
        array[i] = array[size - i - 1];
        array[size - i - 1] = hold;
    }

    return temp;
}
</code>```

I don't understand why

cout << object2-- << endl << endl;

won't compile unless I change the << overloading function to have a const reference parameter like this

```<code>ostream& operator<<(ostream& output, const HW4& rhs)
</code>```

答:
HW4::operator--(int) returns by value, then what object2-- returns would be a temporary object which can't be bound to an lvalue reference to non-const.

On the other hand, temporary object can be bound to lvalue reference to const. That's why making operator<< taking const HW4& works. Conventionally operator<< is supposed for outputting only, it shouldn't change the object passed; so you should declare operator<< taking const HW4& as the parameter.

Body:
I have the following << overloading function:

ostream& operator<<(ostream& output, HW4& rhs)
{

    for(int i = 0; i < HW4::size; ++i)
    {
        output << rhs.array[i] << "    ";
    }

    return output;
}

And I also have this post-decrement overloading function:

HW4 HW4::operator--(int)
{
    HW4 temp = *this;
    int hold;
    for(int i = 0; i < size/2; ++i)
    {
        hold = array[i];
        array[i] = array[size - i - 1];
        array[size - i - 1] = hold;
    }

    return temp;
}

I don't understand why

cout << object2-- << endl << endl;

won't compile unless I change the << overloading function to have a const reference parameter like this

ostream& operator<<(ostream& output, const HW4& rhs)


问:
How to get input for days of the week to always be sorted M-Su
I'm using some java code and android to get some input from the user based on checkboxes clicked. Each of these checkboxes correspond to days of the week, so M, T, W, Th, F, S and Su are all the possible string values.

If the user clicks M-Su in order, the string will come out as "M, T, W, Th..." etc. in order. But if he clicks them in any different order, well as you can guess it just puts it based on what is clicked first. I already deal with the logic of removing the string values if they uncheck the box but was a little confused as to how I should go about setting up a system where M is always first, then T, and W and Su is always last.

The user can click only "Su, M, F" as their options but I want it to appear as "M, F, Su" after it orders it.

I was thinking maybe using a hashmap to create a priority system for the strings to do some comparison, but haven't done this before and was wondering how should I go about doing this the most efficient way?

Thank you!

答:
You could use a function that maps the days to numbers which can then be sorted accordingly. Another way to do this might be through the use of an enum containing a String value which is the abbreviation of the day and an int value which is the numeric value e.g:

```<code>public enum Days{

    Sunday("Su", 1),
    Monday("M", 2);

    String day;
    int val;

    Days(String day, int val) {
        this.day = day;
        this.val = val;
    }
}
</code>```

From here, you could then perhaps implement static functions to get an enum value from a String or an int. This way, from a given input from the user, you can store the associated int and when you want to get the corresponding String value, you can just use your implemented method to get the associated String.

Body:
You could use a function that maps the days to numbers which can then be sorted accordingly. Another way to do this might be through the use of an enum containing a String value which is the abbreviation of the day and an int value which is the numeric value e.g:

public enum Days{

    Sunday("Su", 1),
    Monday("M", 2);

    String day;
    int val;

    Days(String day, int val) {
        this.day = day;
        this.val = val;
    }
}

From here, you could then perhaps implement static functions to get an enum value from a String or an int. This way, from a given input from the user, you can store the associated int and when you want to get the corresponding String value, you can just use your implemented method to get the associated String.


问:
Can a same job with different build parameters be executed in Jenkins by different users
I have a Job named CheckStatus which performs the operation of checking the status of different applications. I have a build in parameter which shows the list of all applications, say AAA, BBB, CCC, DDD, EEE, FFF.

I come and start the job with application AAA as build parameter to check the status. Is it possible for others users who have access, to run the same job with same or different applications (like AAA, CCC, DDD) as a parameter and get the output?

Does this kind of execution supported by Jenkins. If not, how can we make sure that this type of parallel execution of the same job with same or different users be supported.

答: Yes. Each freestyle job has a property you can set that to prevent concurrent execution of the job. If that is not checked, then multiple builds can run at the same time, regardless of parameter. </p>