问:
Google Map is not movable
Hey guys I am creating an app which gets the current co-ordinates of the user and then show them on the map which is implemented on the activity.

But my problem is that the map is not movable. I have tried getUiSettings().setScrollGesturesEnabled(true); but its not working.

The Code is given below:

```<code>public class Page1 extends AppCompatActivity implements OnMapReadyCallback {

private GoogleMap mMap;
String em,n;
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
TextView tv1;
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 2;
protected LocationManager locationManager;
Location location;

private ActionBarDrawerToggle drawerToggle;

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

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    nvDrawer = (NavigationView) findViewById(R.id.nvView);
    setupDrawerContent(nvDrawer);
    // Find our drawer view
    mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerToggle = setupDrawerToggle();
    // Tie DrawerLayout events to the ActionBarToggle
    mDrawer.addDrawerListener(drawerToggle);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.my_menu_option, menu);
    tv1= (TextView) nvDrawer.findViewById(R.id.textView5);
    Intent i=getIntent();
    em=i.getStringExtra("k");
    tv1.setText(em);
    return true;
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    Location nwLocation =getLocation(LocationManager.NETWORK_PROVIDER);
    if (nwLocation != null) {
        double latitude = nwLocation.getLatitude();
        double longitude = nwLocation.getLongitude();
        LatLng location = new LatLng(latitude,longitude);
        mMap.addMarker(new MarkerOptions().position(location).title("I am here"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
        float zoomLevel = 16; //This goes up to 21
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, zoomLevel));
        googleMap.getUiSettings().setScrollGesturesEnabled(true);
    }
    else {
        showSettingsAlert("Network");
    }
}

public Location getLocation(String provider) {
    if (locationManager.isProviderEnabled(provider)) {
        if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
        }
        else {
            if (locationManager != null) {
                location = locationManager.getLastKnownLocation(provider);
                return location;
            }
        }
    }
    return null;
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 ) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();

                }
                else if(grantResults[0]==PackageManager.PERMISSION_DENIED) {
                    Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
                }
                else {

                    Toast.makeText(this, "Never Ask Again", Toast.LENGTH_SHORT).show();
                }
            }
            return;
        }
    }
}

public void showSettingsAlert(String provider) {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
            Page1.this);

    alertDialog.setTitle(provider + " Settings");

    alertDialog.setMessage(provider + " is not enabled! Want to go to settings menu?");

    alertDialog.setPositiveButton("Settings",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    Page1.this.startActivity(intent);
                }
            });

    alertDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

    alertDialog.show();
}

private ActionBarDrawerToggle setupDrawerToggle() {

    return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open,  R.string.drawer_close);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (drawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    switch (item.getItemId()) {
        case R.id.m1:
            onMapReady(mMap);
            return true;
        case R.id.m2:
            Intent i=new Intent(this,AboutUs.class);
            startActivity(i);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

private void setupDrawerContent(final NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    selectDrawerItem(menuItem);
                    View headerLayout = navigationView.getHeaderView(0);
                    return true;
                }
            });
}

public void selectDrawerItem(MenuItem menuItem) {
    // Create a new fragment and specify the fragment to show based on nav item clicked
    switch(menuItem.getItemId()) {
        case R.id.nav_first_fragment:
            mFirst(menuItem);
            mDrawer.closeDrawers();
            break;
        case R.id.nav_second_fragment:
            /*Intent i = new Intent(Page1.this, ShowInfo.class);
            i.putExtra("j", em);
            startActivity(i);*/
            Toast.makeText(this, "Location Updated", Toast.LENGTH_SHORT).show();
            int a=0;
            Intent i=getIntent();
            a=i.getIntExtra("u",0);
            Location nwLocation =getLocation(LocationManager.NETWORK_PROVIDER);
            if (nwLocation != null) {
                double latitude = nwLocation.getLatitude();
                double longitude = nwLocation.getLongitude();
                updateLocation(a,latitude,longitude);
            }
            else {
                showSettingsAlert("Network");
            }
            break;
        case R.id.sub1:
            startActivity(new Intent(this, ShowInfo.class));
            break;
        case R.id.sub2:
            startActivity(new Intent(this, LoginPage.class));
            finish();
            break;
        default:
            mFirst(menuItem);
            mDrawer.closeDrawers();
    }

    menuItem.setChecked(true);
    setTitle(menuItem.getTitle());
    mDrawer.closeDrawers();
}

public void updateLocation(int userid,double xCoordinate,double yCoordinate){
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("userId", userid);
        jsonObject.put("deviceName", "Mi4i");
        jsonObject.put("xCoordinate",xCoordinate);
        jsonObject.put("yCoordinate",yCoordinate);
        jsonObject.toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    final OkHttpClient client = new OkHttpClient();
    RequestBody body = RequestBody.create(JSON, String.valueOf(jsonObject));
    final Request request = new Request.Builder()
            .url("http://172.31.4.91:8090/rest/saveLocation")
            .post(body)
            .build();
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            } /*else {

            }*/
        }
    });
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    drawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    drawerToggle.onConfigurationChanged(newConfig);
}
</code>```

}

The UI for this activity is :-

```<code><fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.pb.larcenytest.Page1" >

<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <!-- The main content view where fragments are loaded -->
    <FrameLayout
        android:id="@+id/flContent"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

<include
    layout="@layout/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
</LinearLayout>

<android.support.design.widget.NavigationView
android:id="@+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/nav_header"
android:background="@android:color/white"
app:menu="@menu/drawer_view" />
</android.support.v4.widget.DrawerLayout>

</fragment>
</code>```

答:
you are getting location from Network provider   , this takes time

what about add location.LocationListener

```<code>public class Page1 extends AppCompatActivity implements OnMapReadyCallback,location.LocationListener {

    @Override
            public void onLocationChanged(Location location)
            {
    CameraPosition position = new CameraPosition.Builder()
                                .target(new LatLng(Location.getLatitude, Location.getLongitude))
                                .zoom(17).build();
                        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(position));
            }
    }
</code>```

Title: Google Map is not movable

Body:
Hey guys I am creating an app which gets the current co-ordinates of the user and then show them on the map which is implemented on the activity.

But my problem is that the map is not movable. I have tried getUiSettings().setScrollGesturesEnabled(true); but its not working.

The Code is given below:

public class Page1 extends AppCompatActivity implements OnMapReadyCallback {

private GoogleMap mMap;
String em,n;
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
TextView tv1;
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 2;
protected LocationManager locationManager;
Location location;

private ActionBarDrawerToggle drawerToggle;

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

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    nvDrawer = (NavigationView) findViewById(R.id.nvView);
    setupDrawerContent(nvDrawer);
    // Find our drawer view
    mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerToggle = setupDrawerToggle();
    // Tie DrawerLayout events to the ActionBarToggle
    mDrawer.addDrawerListener(drawerToggle);
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.my_menu_option, menu);
    tv1= (TextView) nvDrawer.findViewById(R.id.textView5);
    Intent i=getIntent();
    em=i.getStringExtra("k");
    tv1.setText(em);
    return true;
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    Location nwLocation =getLocation(LocationManager.NETWORK_PROVIDER);
    if (nwLocation != null) {
        double latitude = nwLocation.getLatitude();
        double longitude = nwLocation.getLongitude();
        LatLng location = new LatLng(latitude,longitude);
        mMap.addMarker(new MarkerOptions().position(location).title("I am here"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
        float zoomLevel = 16; //This goes up to 21
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, zoomLevel));
        googleMap.getUiSettings().setScrollGesturesEnabled(true);
    }
    else {
        showSettingsAlert("Network");
    }
}

public Location getLocation(String provider) {
    if (locationManager.isProviderEnabled(provider)) {
        if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
        }
        else {
            if (locationManager != null) {
                location = locationManager.getLastKnownLocation(provider);
                return location;
            }
        }
    }
    return null;
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 ) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();

                }
                else if(grantResults[0]==PackageManager.PERMISSION_DENIED) {
                    Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
                }
                else {

                    Toast.makeText(this, "Never Ask Again", Toast.LENGTH_SHORT).show();
                }
            }
            return;
        }
    }
}

public void showSettingsAlert(String provider) {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
            Page1.this);

    alertDialog.setTitle(provider + " Settings");

    alertDialog.setMessage(provider + " is not enabled! Want to go to settings menu?");

    alertDialog.setPositiveButton("Settings",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    Page1.this.startActivity(intent);
                }
            });

    alertDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

    alertDialog.show();
}

private ActionBarDrawerToggle setupDrawerToggle() {

    return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open,  R.string.drawer_close);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (drawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    switch (item.getItemId()) {
        case R.id.m1:
            onMapReady(mMap);
            return true;
        case R.id.m2:
            Intent i=new Intent(this,AboutUs.class);
            startActivity(i);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

private void setupDrawerContent(final NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    selectDrawerItem(menuItem);
                    View headerLayout = navigationView.getHeaderView(0);
                    return true;
                }
            });
}

public void selectDrawerItem(MenuItem menuItem) {
    // Create a new fragment and specify the fragment to show based on nav item clicked
    switch(menuItem.getItemId()) {
        case R.id.nav_first_fragment:
            mFirst(menuItem);
            mDrawer.closeDrawers();
            break;
        case R.id.nav_second_fragment:
            /*Intent i = new Intent(Page1.this, ShowInfo.class);
            i.putExtra("j", em);
            startActivity(i);*/
            Toast.makeText(this, "Location Updated", Toast.LENGTH_SHORT).show();
            int a=0;
            Intent i=getIntent();
            a=i.getIntExtra("u",0);
            Location nwLocation =getLocation(LocationManager.NETWORK_PROVIDER);
            if (nwLocation != null) {
                double latitude = nwLocation.getLatitude();
                double longitude = nwLocation.getLongitude();
                updateLocation(a,latitude,longitude);
            }
            else {
                showSettingsAlert("Network");
            }
            break;
        case R.id.sub1:
            startActivity(new Intent(this, ShowInfo.class));
            break;
        case R.id.sub2:
            startActivity(new Intent(this, LoginPage.class));
            finish();
            break;
        default:
            mFirst(menuItem);
            mDrawer.closeDrawers();
    }

    menuItem.setChecked(true);
    setTitle(menuItem.getTitle());
    mDrawer.closeDrawers();
}

public void updateLocation(int userid,double xCoordinate,double yCoordinate){
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("userId", userid);
        jsonObject.put("deviceName", "Mi4i");
        jsonObject.put("xCoordinate",xCoordinate);
        jsonObject.put("yCoordinate",yCoordinate);
        jsonObject.toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    final OkHttpClient client = new OkHttpClient();
    RequestBody body = RequestBody.create(JSON, String.valueOf(jsonObject));
    final Request request = new Request.Builder()
            .url("http://172.31.4.91:8090/rest/saveLocation")
            .post(body)
            .build();
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            } /*else {

            }*/
        }
    });
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    drawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    drawerToggle.onConfigurationChanged(newConfig);
}

}

The UI for this activity is :-

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.pb.larcenytest.Page1" >

<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/flContent"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

<include
    layout="@layout/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
</LinearLayout>

<android.support.design.widget.NavigationView
android:id="@+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/nav_header"
android:background="@android:color/white"
app:menu="@menu/drawer_view" />
</android.support.v4.widget.DrawerLayout>

</fragment>

Body:
you are getting location from Network provider   , this takes time

what about add location.LocationListener

public class Page1 extends AppCompatActivity implements OnMapReadyCallback,location.LocationListener {

    @Override
            public void onLocationChanged(Location location)
            {
    CameraPosition position = new CameraPosition.Builder()
                                .target(new LatLng(Location.getLatitude, Location.getLongitude))
                                .zoom(17).build();
                        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(position));
            }
    }


来源: stackexchange

问:
Cant start new activity. It keeps crashing
When pressing the button, new activity should open but app instantly crashes. I have searched for answer and making a few adjustments to my code and only thing i dont know how to do is Manifest, can u help me with that?

```<code>  <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="Starting.Programm"
  android:versionCode="1"
  android:versionName="1.0">
<application android:label="@string/app_name"
android:icon="@drawable/ic_launcher">
    <activity android:name="MainActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name="InformationActivity"
              android:label="@string/app_name"
              >
        </activity>
</application>
</code>```

MainActivity:

```<code>package Starting.Programm;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends InformationActivity
{

/** Called when the activity is first created. */
@Override
 protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

}
 public void startJourney(View view) {
     Intent intent = new Intent(this, InformationActivity.class);
     startActivity(intent);

}
}
</code>```

main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<Button android:id="@+id/button_StartApp"
    android:layout_width="100dp"
    android:layout_height="60dp"
    android:text="@string/button_StartApp"
    android:layout_gravity="center"
    android:layout_marginTop="70dp"
    android:layout_marginLeft="115dp"
    android:onClick="startJourney"
/>

</LinearLayout>
</code>```

And next activity which should be opening

```<code>package Starting.Programm;

import android.app.Activity;
import android.os.Bundle;

class InformationActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.information);

}

}
</code>```

答:
```<code><activity> android:name=".InformationActivity" </activity>
</code>```

Remove     android:label="@string/app_name" too. I don't think it is needed.

ContentLicense: CC BY-SA 3.0

Body:
When pressing the button, new activity should open but app instantly crashes. I have searched for answer and making a few adjustments to my code and only thing i dont know how to do is Manifest, can u help me with that?

  <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="Starting.Programm"
  android:versionCode="1"
  android:versionName="1.0">
<application android:label="@string/app_name"
android:icon="@drawable/ic_launcher">
    <activity android:name="MainActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name="InformationActivity"
              android:label="@string/app_name"
              >
        </activity>
</application>

MainActivity:

package Starting.Programm;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends InformationActivity
{

/** Called when the activity is first created. */
@Override
 protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

}
 public void startJourney(View view) {
     Intent intent = new Intent(this, InformationActivity.class);
     startActivity(intent);

}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<Button android:id="@+id/button_StartApp"
    android:layout_width="100dp"
    android:layout_height="60dp"
    android:text="@string/button_StartApp"
    android:layout_gravity="center"
    android:layout_marginTop="70dp"
    android:layout_marginLeft="115dp"
    android:onClick="startJourney"
/>

</LinearLayout>

And next activity which should be opening

package Starting.Programm;

import android.app.Activity;
import android.os.Bundle;

class InformationActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.information);

}

}

Body:
<activity> android:name=".InformationActivity" </activity>

Remove     android:label="@string/app_name" too. I don't think it is needed.


问:
Manually installing an updated APK fails with "signatures do not match the previously installed version"
I've built a silly app to share among a few friends. No need to put it up on the app-store.

I built the first apk (signed), uploaded it to a web-server and all worked well.

A small issue arose, I fixed it, re-built, signed with the same keystore and uploaded it again. It now seems that I am unable to install from the new apk. The debugger tells me:

```<code>signatures do not match the previously installed version
</code>```

So I uninstalled the old version by opening the app drawer and dragging it onto the "uninstall" button. When opening "Settings -> Apps", I don't see it anywhere anymore. I don't see any traces of the app on my device.

Yet I still get the above error message.

Is it possible some information still lingers on the device somewhere? Is there any way I can verify that?

答:
If you are seeing this while conducting connected tests, make sure to include .test when uninstalling via adb because uninstalling via app -> settings does not get rid of the test package

```<code>adb uninstall your.broken.package.test
</code>```

if you just uninstall via

```<code>adb uninstall your.broken.package
</code>```

your test package will still be there. This was only something i noticed while using the gradle command line, haven't come across this problem within android studio

Body:
I've built a silly app to share among a few friends. No need to put it up on the app-store.

I built the first apk (signed), uploaded it to a web-server and all worked well.

A small issue arose, I fixed it, re-built, signed with the same keystore and uploaded it again. It now seems that I am unable to install from the new apk. The debugger tells me:

signatures do not match the previously installed version

So I uninstalled the old version by opening the app drawer and dragging it onto the "uninstall" button. When opening "Settings -> Apps", I don't see it anywhere anymore. I don't see any traces of the app on my device.

Yet I still get the above error message.

Is it possible some information still lingers on the device somewhere? Is there any way I can verify that?

Body:
If you are seeing this while conducting connected tests, make sure to include .test when uninstalling via adb because uninstalling via app -> settings does not get rid of the test package

adb uninstall your.broken.package.test

if you just uninstall via

adb uninstall your.broken.package

your test package will still be there. This was only something i noticed while using the gradle command line, haven't come across this problem within android studio


问:
How to optimize this query with large data
```<code>select ticket_type,f_rows.remaining_uses,t.source,count(t.id) as total
FROM (
    -- Filter rows to get those where remaining_uses > 0 and status = 1
    SELECT * FROM (
        --Get all the latest rows for each ticket
        SELECT ticket_id,final_remaining_uses AS remaining_uses,final_status AS status,action_when
        FROM TicketHistory th
        INNER JOIN (SELECT max(th.id) AS id FROM TicketHistory GROUP BY ticket_id) maxid ON th.id = maxid.id
    ) latest_rows
    WHERE remaining_uses > 0 AND status = 1 --and (action_when < current_date and action_when > current_date -30)
) f_rows
INNER JOIN Ticket t ON f_rows.ticket_id = t.id
WHERE t.expiry_date >= current_date -1 and source in (0,1,2,6,7,8) and (created_date < current_date and created_date > current_date - 30)

GROUP BY ticket_type, f_rows.remaining_uses, t.source
order by source, ticket_type, remaining_uses;
</code>```

What I'm doing here is getting the latest rows for each ticket from history table.
then filtering rows for tickets which are not active and there is not usage left on that ticket.
then filtering the data with expiry date and other checks

Is there is a way to optimize this query? currently this query take a very long time and postgresql crashes before it returns any data.

both ticket and ticket history has more than 11M rows each.

EDIT

```<code>CREATE TABLE ticket
(
  id serial NOT NULL,
  source integer NOT NULL,
  status integer NOT NULL,
  ticket_type integer NOT NULL,
  remaining_uses integer NOT NULL,
  expiry_date timestamp with time zone NOT NULL,
  price numeric(20,2) NOT NULL,
  created_date timestamp with time zone NOT NULL,
  pax_type integer NOT NULL,
  last_updated timestamp with time zone NOT NULL,
  service integer,
  client_id character varying(50),
  CONSTRAINT skybus_ticket_pkey PRIMARY KEY (id),
  CONSTRAINT skybus_ticket_sale_id_fkey FOREIGN KEY (sale_id)
      REFERENCES skybus_sale (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED
)
WITH (
  OIDS=FALSE
);
ALTER TABLE ticket
  OWNER TO umd;

-- Index: ticket_client_id_idx

-- DROP INDEX ticket_client_id_idx;

CREATE INDEX ticket_client_id_idx
  ON ticket
  USING btree
  (client_id COLLATE pg_catalog."default");

-- Index: ticket_profile_id_idx

-- DROP INDEX ticket_profile_id_idx;

CREATE INDEX ticket_profile_id_idx
  ON ticket
  USING btree
  (profile_id);

-- Index: ticket_sale_id

-- DROP INDEX ticket_sale_id;

CREATE INDEX skybus_ticket_sale_id
  ON ticket
  USING btree
  (sale_id);

-- Index: ticket_ticket_number

-- DROP INDEX ticket_ticket_number;

CREATE INDEX ticket_ticket_number
  ON ticket
  USING btree
  (ticket_number COLLATE pg_catalog."default");

-- Index: ticket_ticket_number_like

-- DROP INDEX ticket_ticket_number_like;

CREATE INDEX ticket_ticket_number_like
  ON ticket
  USING btree
  (ticket_number COLLATE pg_catalog."default" varchar_pattern_ops);

-- Index: ticket_topup_for_idx

-- DROP INDEX ticket_topup_for_idx;

CREATE INDEX ticket_topup_for_idx
  ON ticket
  USING btree
  (topup_for COLLATE pg_catalog."default");
</code>```

--===============================

```<code>CREATE TABLE tickethistory
(
  id serial NOT NULL,
  ticket_id integer,
  action integer NOT NULL,
  action_result integer NOT NULL,
  initial_status integer NOT NULL,
  final_status integer NOT NULL,
  final_remaining_uses integer NOT NULL,
  ticket_type integer NOT NULL,
  action_when timestamp with time zone NOT NULL,
  last_updated timestamp with time zone NOT NULL,
  service integer,
  CONSTRAINT tickethistory_pkey PRIMARY KEY (id),
  CONSTRAINT tickethistory_ticket_id_fkey FOREIGN KEY (ticket_id)
      REFERENCES ticket (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED
)
WITH (
  OIDS=FALSE
);
ALTER TABLE tickethistory
  OWNER TO umd;

-- Index: tickethistory_ticket_id

-- DROP INDEX tickethistory_ticket_id;

CREATE INDEX tickethistory_ticket_id
  ON tickethistory
  USING btree
  (ticket_id);
</code>```

--===== Execution plan -- this is with row_number() change

```<code>    "HashAggregate  (cost=4526158.63..4526158.64 rows=1 width=16) (actual time=382849.323..382849.376 rows=41 loops=1)"
"  ->  Nested Loop  (cost=3880592.94..4526158.62 rows=1 width=16) (actual time=380338.613..382825.688 rows=11745 loops=1)"
"        ->  Subquery Scan on sub  (cost=3880592.94..4463424.47 rows=6563 width=8) (actual time=126346.043..258837.523 rows=293717 loops=1)"
"              Filter: ((sub.remaining_uses > 0) AND (sub.rn = 1) AND (sub.status = 1))"
"              Rows Removed by Filter: 15244064"
"              ->  WindowAgg  (cost=3880592.94..4191436.42 rows=15542174 width=203) (actual time=126345.775..237172.180 rows=15537781 loops=1)"
"                    ->  Sort  (cost=3880592.94..3919448.38 rows=15542174 width=203) (actual time=126345.757..180461.191 rows=15537781 loops=1)"
"                          Sort Key: th.ticket_id, th.*"
"                          Sort Method: external merge  Disk: 3050616kB"
"                          ->  Seq Scan on skybus_tickethistory th  (cost=0.00..483544.74 rows=15542174 width=203) (actual time=14.091..53312.782 rows=15537781 loops=1)"
"        ->  Index Scan using skybus_ticket_pkey on skybus_ticket t  (cost=0.00..9.55 rows=1 width=12) (actual time=0.418..0.418 rows=0 loops=293717)"
"              Index Cond: (id = sub.ticket_id)"
"              Filter: ((source = ANY ('{0,1,2,6,7,8}'::integer[])) AND (created_date < ('now'::cstring)::date) AND (expiry_date >= (('now'::cstring)::date - 1)) AND (created_date > (('now'::cstring)::date - 30)) AND (ticket_type = ANY ('{2,3,4,5,6,7,16,17, (...)"
"              Rows Removed by Filter: 1"
"Total runtime: 383045.381 ms"
</code>```

答:
You could use row_number() to get the latest row for each ticket in a single pass:

```<code>with    last_history as
        (
        select  *
        from    (
                select  row_number() over (partition by ticket_id
                                           order by th desc) rn
                ,       *
                from    TicketHistory
                ) sub
        where   rn = 1 -- Latest history row only
        )
select  *
from    ticket t
join    th
on      t.id = th.ticket_id
where   remaining_uses > 0
        and <... other conditions ...>
</code>```

Body:
select ticket_type,f_rows.remaining_uses,t.source,count(t.id) as total
FROM (
    -- Filter rows to get those where remaining_uses > 0 and status = 1
    SELECT * FROM (
        --Get all the latest rows for each ticket
        SELECT ticket_id,final_remaining_uses AS remaining_uses,final_status AS status,action_when
        FROM TicketHistory th
        INNER JOIN (SELECT max(th.id) AS id FROM TicketHistory GROUP BY ticket_id) maxid ON th.id = maxid.id
    ) latest_rows
    WHERE remaining_uses > 0 AND status = 1 --and (action_when < current_date and action_when > current_date -30)
) f_rows
INNER JOIN Ticket t ON f_rows.ticket_id = t.id
WHERE t.expiry_date >= current_date -1 and source in (0,1,2,6,7,8) and (created_date < current_date and created_date > current_date - 30)

GROUP BY ticket_type, f_rows.remaining_uses, t.source
order by source, ticket_type, remaining_uses;

What I'm doing here is getting the latest rows for each ticket from history table.
then filtering rows for tickets which are not active and there is not usage left on that ticket.
then filtering the data with expiry date and other checks

Is there is a way to optimize this query? currently this query take a very long time and postgresql crashes before it returns any data.

both ticket and ticket history has more than 11M rows each.

EDIT

CREATE TABLE ticket
(
  id serial NOT NULL,
  source integer NOT NULL,
  status integer NOT NULL,
  ticket_type integer NOT NULL,
  remaining_uses integer NOT NULL,
  expiry_date timestamp with time zone NOT NULL,
  price numeric(20,2) NOT NULL,
  created_date timestamp with time zone NOT NULL,
  pax_type integer NOT NULL,
  last_updated timestamp with time zone NOT NULL,
  service integer,
  client_id character varying(50),
  CONSTRAINT skybus_ticket_pkey PRIMARY KEY (id),
  CONSTRAINT skybus_ticket_sale_id_fkey FOREIGN KEY (sale_id)
      REFERENCES skybus_sale (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED
)
WITH (
  OIDS=FALSE
);
ALTER TABLE ticket
  OWNER TO umd;

-- Index: ticket_client_id_idx

-- DROP INDEX ticket_client_id_idx;

CREATE INDEX ticket_client_id_idx
  ON ticket
  USING btree
  (client_id COLLATE pg_catalog."default");

-- Index: ticket_profile_id_idx

-- DROP INDEX ticket_profile_id_idx;

CREATE INDEX ticket_profile_id_idx
  ON ticket
  USING btree
  (profile_id);

-- Index: ticket_sale_id

-- DROP INDEX ticket_sale_id;

CREATE INDEX skybus_ticket_sale_id
  ON ticket
  USING btree
  (sale_id);

-- Index: ticket_ticket_number

-- DROP INDEX ticket_ticket_number;

CREATE INDEX ticket_ticket_number
  ON ticket
  USING btree
  (ticket_number COLLATE pg_catalog."default");

-- Index: ticket_ticket_number_like

-- DROP INDEX ticket_ticket_number_like;

CREATE INDEX ticket_ticket_number_like
  ON ticket
  USING btree
  (ticket_number COLLATE pg_catalog."default" varchar_pattern_ops);

-- Index: ticket_topup_for_idx

-- DROP INDEX ticket_topup_for_idx;

CREATE INDEX ticket_topup_for_idx
  ON ticket
  USING btree
  (topup_for COLLATE pg_catalog."default");

--===============================

CREATE TABLE tickethistory
(
  id serial NOT NULL,
  ticket_id integer,
  action integer NOT NULL,
  action_result integer NOT NULL,
  initial_status integer NOT NULL,
  final_status integer NOT NULL,
  final_remaining_uses integer NOT NULL,
  ticket_type integer NOT NULL,
  action_when timestamp with time zone NOT NULL,
  last_updated timestamp with time zone NOT NULL,
  service integer,
  CONSTRAINT tickethistory_pkey PRIMARY KEY (id),
  CONSTRAINT tickethistory_ticket_id_fkey FOREIGN KEY (ticket_id)
      REFERENCES ticket (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED
)
WITH (
  OIDS=FALSE
);
ALTER TABLE tickethistory
  OWNER TO umd;

-- Index: tickethistory_ticket_id

-- DROP INDEX tickethistory_ticket_id;

CREATE INDEX tickethistory_ticket_id
  ON tickethistory
  USING btree
  (ticket_id);

--===== Execution plan -- this is with row_number() change

    "HashAggregate  (cost=4526158.63..4526158.64 rows=1 width=16) (actual time=382849.323..382849.376 rows=41 loops=1)"
"  ->  Nested Loop  (cost=3880592.94..4526158.62 rows=1 width=16) (actual time=380338.613..382825.688 rows=11745 loops=1)"
"        ->  Subquery Scan on sub  (cost=3880592.94..4463424.47 rows=6563 width=8) (actual time=126346.043..258837.523 rows=293717 loops=1)"
"              Filter: ((sub.remaining_uses > 0) AND (sub.rn = 1) AND (sub.status = 1))"
"              Rows Removed by Filter: 15244064"
"              ->  WindowAgg  (cost=3880592.94..4191436.42 rows=15542174 width=203) (actual time=126345.775..237172.180 rows=15537781 loops=1)"
"                    ->  Sort  (cost=3880592.94..3919448.38 rows=15542174 width=203) (actual time=126345.757..180461.191 rows=15537781 loops=1)"
"                          Sort Key: th.ticket_id, th.*"
"                          Sort Method: external merge  Disk: 3050616kB"
"                          ->  Seq Scan on skybus_tickethistory th  (cost=0.00..483544.74 rows=15542174 width=203) (actual time=14.091..53312.782 rows=15537781 loops=1)"
"        ->  Index Scan using skybus_ticket_pkey on skybus_ticket t  (cost=0.00..9.55 rows=1 width=12) (actual time=0.418..0.418 rows=0 loops=293717)"
"              Index Cond: (id = sub.ticket_id)"
"              Filter: ((source = ANY ('{0,1,2,6,7,8}'::integer[])) AND (created_date < ('now'::cstring)::date) AND (expiry_date >= (('now'::cstring)::date - 1)) AND (created_date > (('now'::cstring)::date - 30)) AND (ticket_type = ANY ('{2,3,4,5,6,7,16,17, (...)"
"              Rows Removed by Filter: 1"
"Total runtime: 383045.381 ms"

Body:
You could use row_number() to get the latest row for each ticket in a single pass:

with    last_history as
        (
        select  *
        from    (
                select  row_number() over (partition by ticket_id
                                           order by th desc) rn
                ,       *
                from    TicketHistory
                ) sub
        where   rn = 1 -- Latest history row only
        )
select  *
from    ticket t
join    th
on      t.id = th.ticket_id
where   remaining_uses > 0
        and <... other conditions ...>


问:
How to access particular fields from JSON content by using php?
i want to get the values of different fields in Json by using php</p>

答:
json_decode($string) will return an object from which you can get the values you assigned.

For example:

```<code>$myObject = new MyObject();
$myObject -> att1 = 5;

$string = json_encode($myObject);

//here's how you get the value:

$myJsonDecodedObject = json_decode($string);
$value = $myJsonDecodedObject -> att1;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
json_decode($string) will return an object from which you can get the values you assigned.

For example:

$myObject = new MyObject();
$myObject -> att1 = 5;

$string = json_encode($myObject);

//here's how you get the value:

$myJsonDecodedObject = json_decode($string);
$value = $myJsonDecodedObject -> att1;


问:
How can I optimize this jquery script? Different classes and same function
I have this jquery function but it is too long for me. Is there any way to make as one jquery change function. I need your help.

```<code> $(document).ready(function () {
                $('.sub-cat select').change(function () {
                    if ($('.sub-cat select option:selected').text() == "Other") {
                        $('.sub-cat .other-category').show();
                    }
                    else {
                        $('.sub-cat .other-category').hide();
                    }
                });
                $('.prod-type select').change(function () {
                    if ($('.prod-type select option:selected').text() == "Other") {
                        $('.prod-type .other-category').show();
                    }
                    else {
                        $('.prod-type .other-category').hide();
                    }
                });
                $('.prod-finnish select').change(function () {
                    if ($('.prod-finnish select option:selected').text() == "Other") {
                        $('.prod-finnish .other-category').show();
                    }
                    else {
                        $('.prod-finnish .other-category').hide();
                    }
                });
                $('.prod-color select').change(function () {
                    if ($('.prod-color select option:selected').text() == "Other") {
                        $('.prod-color .other-category').show();
                    }
                    else {
                        $('.prod-color .other-category').hide();
                    }
                });
                $('.prod-included select').change(function () {
                    if ($('.prod-included select option:selected').text() == "Other") {
                        $('.prod-included .other-category').show();
                    }
                    else {
                        $('.prod-included .other-category').hide();
                    }
                });
                $('.prod-series select').change(function () {
                    if ($('.prod-series select option:selected').text() == "Other") {
                        $('.prod-series .other-category').show();
                    }
                    else {
                        $('.prod-series .other-category').hide();
                    }
                });
            });
</code>```

答:
Please check below code. On selection of other option

            $(document).ready(function () {

                $('select').change(function () {
                    if($(this).find('option:selected').text() == "other"){
                        $(this).next().show();
                    }
                    else{
                        $(this).next().hide();
                    }
                });

            });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    </head>
    <body>
        <div class="sub-cat">
            <select>
                <option value="volvo">Volvo</option>
                <option value="saab">Saab</option>
                <option value="mercedes">Mercedes</option>
                <option value="audi">Audi</option>
                <option value="other">other</option>
            </select>
            <div class="other-category" style="display: none;">
                <p>sub-cat other-category</p>
            </div>
        </div>
        <div class="prod-type">
            <select>
                <option value="volvo">Volvo</option>
                <option value="saab">Saab</option>
                <option value="mercedes">Mercedes</option>
                <option value="audi">Audi</option>
                <option value="other">other</option>
            </select>
            <div class="other-category" style="display: none;">
                <p>prod-type other-category</p>
            </div>
        </div>

    </body>

</html></code>```

show below div .

Body:
I have this jquery function but it is too long for me. Is there any way to make as one jquery change function. I need your help.

 $(document).ready(function () {
                $('.sub-cat select').change(function () {
                    if ($('.sub-cat select option:selected').text() == "Other") {
                        $('.sub-cat .other-category').show();
                    }
                    else {
                        $('.sub-cat .other-category').hide();
                    }
                });
                $('.prod-type select').change(function () {
                    if ($('.prod-type select option:selected').text() == "Other") {
                        $('.prod-type .other-category').show();
                    }
                    else {
                        $('.prod-type .other-category').hide();
                    }
                });
                $('.prod-finnish select').change(function () {
                    if ($('.prod-finnish select option:selected').text() == "Other") {
                        $('.prod-finnish .other-category').show();
                    }
                    else {
                        $('.prod-finnish .other-category').hide();
                    }
                });
                $('.prod-color select').change(function () {
                    if ($('.prod-color select option:selected').text() == "Other") {
                        $('.prod-color .other-category').show();
                    }
                    else {
                        $('.prod-color .other-category').hide();
                    }
                });
                $('.prod-included select').change(function () {
                    if ($('.prod-included select option:selected').text() == "Other") {
                        $('.prod-included .other-category').show();
                    }
                    else {
                        $('.prod-included .other-category').hide();
                    }
                });
                $('.prod-series select').change(function () {
                    if ($('.prod-series select option:selected').text() == "Other") {
                        $('.prod-series .other-category').show();
                    }
                    else {
                        $('.prod-series .other-category').hide();
                    }
                });
            });

Body:
Please check below code. On selection of other option

            $(document).ready(function () {

                $('select').change(function () {
                    if($(this).find('option:selected').text() == "other"){
                        $(this).next().show();
                    }
                    else{
                        $(this).next().hide();
                    }
                });

            });

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    </head>
    <body>
        <div class="sub-cat">
            <select>
                <option value="volvo">Volvo</option>
                <option value="saab">Saab</option>
                <option value="mercedes">Mercedes</option>
                <option value="audi">Audi</option>
                <option value="other">other</option>
            </select>
            <div class="other-category" style="display: none;">
                <p>sub-cat other-category</p>
            </div>
        </div>
        <div class="prod-type">
            <select>
                <option value="volvo">Volvo</option>
                <option value="saab">Saab</option>
                <option value="mercedes">Mercedes</option>
                <option value="audi">Audi</option>
                <option value="other">other</option>
            </select>
            <div class="other-category" style="display: none;">
                <p>prod-type other-category</p>
            </div>
        </div>

    </body>

</html>

show below div .


问:
how to import h5py on datalab?
Does anybody know how to install h5py on datalab? pip install h5py doesn't work. apt-get install python-h5py is working in the shell but it doesn't recognize the package in datalab notebook!

Thnaks

答: Just make sure you run it using bash syntax: !pip install h5py in any notebook cell.

Title: how to import h5py on datalab?


问:
Convert SQL query to Android Azure Mobile Service query - DISTINCT Statement
SQL Statement:

```<code>SELECT DISTINCT * messages FROM messages WHERE sender_id = 1
</code>```

Into Azure Mobile Service

```<code>messagesTable.where().field("sender_id").eq(1).execute().get();
</code>```

The problem is selecting DISTINCT columns. This is on android.

答:
It sounds like you want to use Android client SDK for Azure Mobile Apps to write the code for querying the DISTINCT column, but there is not any method directly support it via Query interface on Android client SDK.

The only way is calling a custom API from android client to execute custom SQL statements at the backend server, please refer to the subsection How to: Execute custom SQL statements of the document section Custom APIs and the data/execute method for Node.js backend.

Body:
SQL Statement:

SELECT DISTINCT * messages FROM messages WHERE sender_id = 1

Into Azure Mobile Service

messagesTable.where().field("sender_id").eq(1).execute().get();

The problem is selecting DISTINCT columns. This is on android.


问:
Powershell to executable .bat
I'm trying to get the script below, which is in Powershell, converted to an executable .bat file. The basic idea is that I have a bunch of files of which the file name exists out of 3 parts:

Part 1: TKSYSTEMID

Part 2: Variable name

Part 3: YYYY MM DD HHMM

So a simple example would look like: TKSYSTEMID NOTES YYYY MM DD HHMM

I'm looking for a .bat file that can replace the TKSYSTEM ID and the YYYY MM DD HHMM with something the user gets prompted to input.

The powershell script I have so far is:

```<code>$NEWSYSTEMID = Read-Host -Prompt 'Please input SEJ SYSTEM ID'
Write-Host "Changing TKSYSTEMID to '$NEWSYSTEMID'"
dir | Rename-Item -NewName {$_.name -replace 'TKSYSTEMID',$NEWSYSTEMID}

$NEWDATETIME = Read-Host -Prompt 'Please input the upload date and time'
Write-Host "Changing YYYY MM DD HHMM to '$NEWDATETIME'"
dir | Rename-Item -NewName {$_.name -replace 'YYYY MM DD HHMM',$NEWDATETIME}
</code>```

Could someone be so kind as to show me how to convert this or to provide a .bat script for this? It would mean the world.

答:
You can wrap the powershell code into batch file like:</p>

```<code><# : batch portion
@echo off & setlocal

(for %%I in ("%~f0";%*) do @echo(%%~I) | ^
powershell -noprofile "$argv = $input | ?{$_}; iex (${%~f0} | out-string)"

goto :EOF
: end batch / begin powershell #>

$NEWSYSTEMID = Read-Host -Prompt 'Please input SEJ SYSTEM ID'
Write-Host "Changing TKSYSTEMID to '$NEWSYSTEMID'"
dir | Rename-Item -NewName {$_.name -replace 'TKSYSTEMID',$NEWSYSTEMID}

$NEWDATETIME = Read-Host -Prompt 'Please input the upload date and time'
Write-Host "Changing YYYY MM DD HHMM to '$NEWDATETIME'"
dir | Rename-Item -NewName {$_.name -replace 'YYYY MM DD HHMM',$NEWDATETIME}
</code>```

Title: Powershell to executable .bat

Body:
I'm trying to get the script below, which is in Powershell, converted to an executable .bat file. The basic idea is that I have a bunch of files of which the file name exists out of 3 parts:

Part 1: TKSYSTEMID

Part 2: Variable name

Part 3: YYYY MM DD HHMM

So a simple example would look like: TKSYSTEMID NOTES YYYY MM DD HHMM

I'm looking for a .bat file that can replace the TKSYSTEM ID and the YYYY MM DD HHMM with something the user gets prompted to input.

The powershell script I have so far is:

$NEWSYSTEMID = Read-Host -Prompt 'Please input SEJ SYSTEM ID'
Write-Host "Changing TKSYSTEMID to '$NEWSYSTEMID'"
dir | Rename-Item -NewName {$_.name -replace 'TKSYSTEMID',$NEWSYSTEMID}

$NEWDATETIME = Read-Host -Prompt 'Please input the upload date and time'
Write-Host "Changing YYYY MM DD HHMM to '$NEWDATETIME'"
dir | Rename-Item -NewName {$_.name -replace 'YYYY MM DD HHMM',$NEWDATETIME}

Could someone be so kind as to show me how to convert this or to provide a .bat script for this? It would mean the world.

Body:
You can wrap the powershell code into batch file like:

<# : batch portion
@echo off & setlocal

(for %%I in ("%~f0";%*) do @echo(%%~I) | ^
powershell -noprofile "$argv = $input | ?{$_}; iex (${%~f0} | out-string)"

goto :EOF
: end batch / begin powershell #>

$NEWSYSTEMID = Read-Host -Prompt 'Please input SEJ SYSTEM ID'
Write-Host "Changing TKSYSTEMID to '$NEWSYSTEMID'"
dir | Rename-Item -NewName {$_.name -replace 'TKSYSTEMID',$NEWSYSTEMID}

$NEWDATETIME = Read-Host -Prompt 'Please input the upload date and time'
Write-Host "Changing YYYY MM DD HHMM to '$NEWDATETIME'"
dir | Rename-Item -NewName {$_.name -replace 'YYYY MM DD HHMM',$NEWDATETIME}


问:
Joining two JPA Entities with oneToMany relationship
I have two entites A,B.In this A is parent and have below table structure.

Table-A

A1-->Acolumn

Table-B

B1-->A1
B2-->A1

I need to fetch A1 row and its associated rows in Table B(B1,B2) based on a where condition on both table A and B.

When I use Left outer join fetch JPA is returning two rows with same value in Table-b(B1-A1 or B2-A1).

Even I have tried using normal join.Pls let me know what I am missing.

I am using @Query to specify query.
SELECT a From TableA a  LEFT OUTER JOIN FETCH a.TablesBCollection p where a.TableAColum =?1 and p.TableBColumn<>p.TableBColumn.

```<code>@Entity
@Table(name = "USER", schema = "USER_PROFILE")
public class User implements java.io.Serializable {

private BigDecimal userId;
private String firstNm;
private String lastNm;
private String userIndex;
private Set<UserPhone> userPhones = new HashSet<UserPhone>(0);

public User(){
}

public User(BigDecimal userId,String firstNm,String lastNm){
this.userId=userId;
this.firstNm=firstNm;
this.lastNm=lastNm;
}

public User(BigDecimal userId,String firstNm,String lastNm,Set<UserPhone> userPhones){
this.userId=userId;
this.firstNm=firstNm;
this.lastNm=lastNm;
this.userPhones=userPhones;
}

@Id
@Column(name = "USER_ID", unique = true, nullable = false, precision = 22, scale = 0)
public BigDecimal userId() {
 return this.userId;
    }

public void setuserId(BigDecimal userId) {
        this.userId = userId;
    }

@Column(name = "FIRST_NM", nullable = false, length=50)
public String firstNm() {
 return this.firstNm;
    }

public void setfirstNm(String firstNm) {
        this.firstNm = firstNm;
    }

@Column(name = "LAST_NM", nullable = false, length=50 )
public String lastNm() {
 return this.lastNm;
    }

public void setlastNm(String lastNm) {
        this.lastNm = lastNm;
    }

@Column(name = "USER_INDEX", nullable = false, length=50 )
public String userIndex() {
 return this.userIndex;
    }

public void setUserIndex(String userIndex) {
        this.userIndex = userIndex;
    }

@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
public Set<UserPhone> getuserPhones() {
    return this.userPhones;
    }

public void setUserPhones(Set<UserPhone> userPhones) {
    this.userPhones = userPhones;
    }

}

@Entity
@Table(name = "USER_PHONE", schema = "USER_PROFILE")
public class UserPhone implements java.io.Serializable {

private BigDecimal userPhoneId;
private String city;
private String State;
private User user;

public UserPhone(){
}

public UserPhone(BigDecimal userPhoneId){
this.userPhoneId = userPhoneId;
}

public UserPhone(BigDecimal userPhoneId,String city,String State,User user){
this.userPhoneId = userPhoneId;
this.city = city;
this.State = State;
this.user = user;
}

@Id
@Column(name = "USER_PHONE_ID", unique = true, nullable = false, precision = 22, scale = 0)
public BigDecimal userPhoneId() {
 return this.userPhoneId;
    }

public void setUserPhoneId(BigDecimal userPhoneId) {
        this.userPhoneId = userPhoneId;
    }

@Column(name = "CITY", nullable = false, length=50 )
public String city() {
 return this.city;
    }

public void setCity(String city) {
        this.city = city;
    }

@Column(name = "STATE", nullable = false, length=50 )
public String state() {
 return this.state;
    }

public void setState(String state) {
        this.state = state;
    }

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "USER_ID")
public User getUser() {
        return this.user;
    }

public void setUser(User user) {
        this.user = user;
    }

}

@QUERY("Select a from User a LEFT OUTER JOIN FETCH a.userPhones p where a.userIndex =?1 and p.city<>p.state")
</code>```

答:
Why don't you generate the database tables as POJO by connecting your IDE to your database.
You can create a JPA project in IDE and connect to your DB,it will ask for the relationship between columns, you can mention it there and it will create the desired POJOs for you.

Body:
I have two entites A,B.In this A is parent and have below table structure.

Table-A

A1-->Acolumn

Table-B

B1-->A1
B2-->A1

I need to fetch A1 row and its associated rows in Table B(B1,B2) based on a where condition on both table A and B.

When I use Left outer join fetch JPA is returning two rows with same value in Table-b(B1-A1 or B2-A1).

Even I have tried using normal join.Pls let me know what I am missing.

I am using @Query to specify query.
SELECT a From TableA a  LEFT OUTER JOIN FETCH a.TablesBCollection p where a.TableAColum =?1 and p.TableBColumn<>p.TableBColumn.

@Entity
@Table(name = "USER", schema = "USER_PROFILE")
public class User implements java.io.Serializable {

private BigDecimal userId;
private String firstNm;
private String lastNm;
private String userIndex;
private Set<UserPhone> userPhones = new HashSet<UserPhone>(0);

public User(){
}

public User(BigDecimal userId,String firstNm,String lastNm){
this.userId=userId;
this.firstNm=firstNm;
this.lastNm=lastNm;
}

public User(BigDecimal userId,String firstNm,String lastNm,Set<UserPhone> userPhones){
this.userId=userId;
this.firstNm=firstNm;
this.lastNm=lastNm;
this.userPhones=userPhones;
}

@Id
@Column(name = "USER_ID", unique = true, nullable = false, precision = 22, scale = 0)
public BigDecimal userId() {
 return this.userId;
    }

public void setuserId(BigDecimal userId) {
        this.userId = userId;
    }

@Column(name = "FIRST_NM", nullable = false, length=50)
public String firstNm() {
 return this.firstNm;
    }

public void setfirstNm(String firstNm) {
        this.firstNm = firstNm;
    }

@Column(name = "LAST_NM", nullable = false, length=50 )
public String lastNm() {
 return this.lastNm;
    }

public void setlastNm(String lastNm) {
        this.lastNm = lastNm;
    }

@Column(name = "USER_INDEX", nullable = false, length=50 )
public String userIndex() {
 return this.userIndex;
    }

public void setUserIndex(String userIndex) {
        this.userIndex = userIndex;
    }

@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
public Set<UserPhone> getuserPhones() {
    return this.userPhones;
    }

public void setUserPhones(Set<UserPhone> userPhones) {
    this.userPhones = userPhones;
    }

}

@Entity
@Table(name = "USER_PHONE", schema = "USER_PROFILE")
public class UserPhone implements java.io.Serializable {

private BigDecimal userPhoneId;
private String city;
private String State;
private User user;

public UserPhone(){
}

public UserPhone(BigDecimal userPhoneId){
this.userPhoneId = userPhoneId;
}

public UserPhone(BigDecimal userPhoneId,String city,String State,User user){
this.userPhoneId = userPhoneId;
this.city = city;
this.State = State;
this.user = user;
}

@Id
@Column(name = "USER_PHONE_ID", unique = true, nullable = false, precision = 22, scale = 0)
public BigDecimal userPhoneId() {
 return this.userPhoneId;
    }

public void setUserPhoneId(BigDecimal userPhoneId) {
        this.userPhoneId = userPhoneId;
    }

@Column(name = "CITY", nullable = false, length=50 )
public String city() {
 return this.city;
    }

public void setCity(String city) {
        this.city = city;
    }

@Column(name = "STATE", nullable = false, length=50 )
public String state() {
 return this.state;
    }

public void setState(String state) {
        this.state = state;
    }

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "USER_ID")
public User getUser() {
        return this.user;
    }

public void setUser(User user) {
        this.user = user;
    }

}

@QUERY("Select a from User a LEFT OUTER JOIN FETCH a.userPhones p where a.userIndex =?1 and p.city<>p.state")


问:
Adding a solution file to asp.net 1.1 application using Visual Studio 2010
I'm trying to migrate an old asp.net 1.1 application to target the new .net 4.0 framework. There are good guides available on this (https://learn.microsoft.com/en-us/archive/msdn-magazine/2010/september/app-migration-migrate-your-asp-net-1-1-apps-to-visual-studio-2010). However, all approaches start with the assumption that the 1.1 project contains a solution file which one has to open using VS 2010 and go through the conversion wizard.

In my case, the project does not have any solution file, giving me a sort of chicken and egg issue.

Is there a way to add a 1.1 .net soution file with or without VS 2010? Using command line tools? What is so special about a solution file anyway?

答: Just open the ASP.NET 1.1 project file. A solution file will be created.</p>

ContentLicense: CC BY-SA 4.0


问:
Iterative procedure with nested loops in functional paradigm
I'm learning functional programming (in Haskell) by re-writing some of my old C++ code. One example I'm working on involves the Floyd-Warshall graph search which runs on a 2D NxN adjacency matrix to find the shortest path between all pairs. It uses three nested for loops to scan the 2D array and iteratively reach a solution.

The C++ code would typically be:

```<code>int size = adjacencyMatrix.size();
for ( int k = 0; k < size; k++)
{
    for ( int i = 0; i < size; i++)
    {
        for ( int j = 0; j < size; j++)
        {
            double sum = adjacencyMatrix[i][k] + adjacencyMatrix[k][j];
            if ( sum < adjacencyMatrix[i][j] )
            {
                    adjacencyMatrix[i][j] = sum;
            }
        }
    }
}
</code>```

The key to such a graph search is its iterative method. For example the code above is very sequential; it can only be parallelised to a moderate extent as some calculations can't be done till others have completed.

Furthermore, having access to the index of the matrix means some clever manipulations within the array can be done. The innermost loop of the above graph search uses adjacencyMatrix[i][k], adjacencyMatrix[k][j] and adjacencyMatrix[i][j]. I'm aware of the map function in Haskell, but that doesn't seem to have the same power and flexibility as using array indices.

Aside from trying to simulate an imperative procedure in Haskell I can't work out how re-write the above code in a 'pure' functional style.

How does an iterative procedure that uses complex nested loops to access array indices, such as the graph search above, translate to the functional paradigm?

答:
Aside from trying to simulate an imperative procedure in Haskell I can't work out how re-write the above code in a 'pure' functional style.

I'm not sure you can always rewrite a fundamentally imperative algorithm in a functional style. That said, here's how one would translate your example in Haskell. Note that in general, whenever you find yourself really needing to have mutable variables for a bit, you probably want to use the ST monad. For arrays, you have the efficient array package.

Here's what a full translation of that algorithm can look like

import Data.Array.Unboxed (UArray)
import Data.Array.ST (runSTUArray, newListArray, readArray, writeArray)
import Data.Maybe (fromMaybe)
import Control.Monad (when)
import Data.Foldable (for_)

-- | Takes as input the number of vertices, function to weigh edges, and returns
-- a matrix of the shortest distance between every two vertices.
floydWarshall :: Int -> ((Int,Int) -> Maybe Double) -> UArray (Int,Int) Double
floydWarshall n weight = runSTUArray $ do
    -- initialize the array with the right values
    arr <- newListArray ((0,0),(n-1,n-1))
                        [ if i == j then 0 else fromMaybe (1 / 0) (weight (i,j))
                        | i<-[0..(n-1)], j<-[0..(n-1)] ]

    -- iteratively improve the shortest distances
    for_ [0..(n-1)] $ \k ->
      for_ [0..(n-1)] $ \i ->
        for_ [0..(n-1)] $ \j -> do
          arr_ik <- readArray arr (i,k)
          arr_kj <- readArray arr (k,j)
          arr_ij <- readArray arr (i,j)
          let sum = arr_ik + arr_kj
          when (sum < arr_ij)
            (writeArray arr (i,j) sum)

    return arr
```

Body:
I'm learning functional programming (in Haskell) by re-writing some of my old C++ code. One example I'm working on involves the Floyd-Warshall graph search which runs on a 2D NxN adjacency matrix to find the shortest path between all pairs. It uses three nested for loops to scan the 2D array and iteratively reach a solution.

The C++ code would typically be:

int size = adjacencyMatrix.size();
for ( int k = 0; k < size; k++)
{
    for ( int i = 0; i < size; i++)
    {
        for ( int j = 0; j < size; j++)
        {
            double sum = adjacencyMatrix[i][k] + adjacencyMatrix[k][j];
            if ( sum < adjacencyMatrix[i][j] )
            {
                    adjacencyMatrix[i][j] = sum;
            }
        }
    }
}

The key to such a graph search is its iterative method. For example the code above is very sequential; it can only be parallelised to a moderate extent as some calculations can't be done till others have completed.

Furthermore, having access to the index of the matrix means some clever manipulations within the array can be done. The innermost loop of the above graph search uses adjacencyMatrix[i][k], adjacencyMatrix[k][j] and adjacencyMatrix[i][j]. I'm aware of the map function in Haskell, but that doesn't seem to have the same power and flexibility as using array indices.

Aside from trying to simulate an imperative procedure in Haskell I can't work out how re-write the above code in a 'pure' functional style.

How does an iterative procedure that uses complex nested loops to access array indices, such as the graph search above, translate to the functional paradigm?


问:
How to remove tabStrip in android?
I want to remove the tab color strip . I tried setStripEnabled(false); but that did not work. Also tried android:tabStripEnabled="false" in xml code. The tab strip still appears on the tab bar. Can someone tell me how I can remove the blue strip that occurs in the tab bar.

```<code>JAVA CODE:

public class TabsFragmentActivity extends FragmentActivity implements TabHost.OnTabChangeListener {
private TabHost mTabHost;
private HashMap mapTabInfo = new HashMap();
private TabInfo mLastTab = null;

private class TabInfo {
     private String tag;
     private Class clss;
     private Bundle args;
     private Fragment fragment;
     TabInfo(String tag, Class clazz, Bundle args) {
         this.tag = tag;
         this.clss = clazz;
         this.args = args;
     }

}

class TabFactory implements TabContentFactory {

    private final Context mContext;

    /**
     * @param context
     */
    public TabFactory(Context context) {
        mContext = context;
    }

    /** (non-Javadoc)
     * @see android.widget.TabHost.TabContentFactory#createTabContent(java.lang.String)
     */
    public View createTabContent(String tag) {
        View v = new View(mContext);
        v.setMinimumWidth(0);
        v.setMinimumHeight(0);
        return v;
    }

}
/** (non-Javadoc)
 * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
 */
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Step 1: Inflate layout
    setContentView(R.layout.tabs_layout);
    // Step 2: Setup TabHost
    initialiseTabHost(savedInstanceState);
    if (savedInstanceState != null) {
        mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab")); //set the tab as per the saved state

    }
}

/** (non-Javadoc)
 * @see android.support.v4.app.FragmentActivity#onSaveInstanceState(android.os.Bundle)
 */
protected void onSaveInstanceState(Bundle outState) {
    outState.putString("tab", mTabHost.getCurrentTabTag()); //save the tab selected
    super.onSaveInstanceState(outState);
}

/**
 * Step 2: Setup TabHost
 */
private void initialiseTabHost(Bundle args) {
    mTabHost = (TabHost)findViewById(android.R.id.tabhost);
    mTabHost.setup();

    TabInfo tabInfo = null;
    Resources res = getResources();
    this.mTabHost.getTabWidget().setStripEnabled(false);
    TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab1").setIndicator("",res.getDrawable(R.drawable.ic_launcher)), ( tabInfo = new TabInfo("Tab1", Tab1Fragment.class, args)));
    this.mapTabInfo.put(tabInfo.tag, tabInfo);
    TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab2").setIndicator("",res.getDrawable(R.drawable.ic_launcher)), ( tabInfo = new TabInfo("Tab2", Tab2Fragment.class, args)));
    this.mapTabInfo.put(tabInfo.tag, tabInfo);
    TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("",res.getDrawable(R.drawable.ic_launcher)), ( tabInfo = new TabInfo("Tab3", Tab3Fragment.class, args)));
    this.mapTabInfo.put(tabInfo.tag, tabInfo);

    // Default to first tab
    this.onTabChanged("Tab1");
    //
    mTabHost.setOnTabChangedListener(this);
}

/**
 * @param activity
 * @param tabHost
 * @param tabSpec
 * @param clss
 * @param args
 */
private static void addTab(TabsFragmentActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec, TabInfo tabInfo) {
    // Attach a Tab view factory to the spec
    tabSpec.setContent(activity.new TabFactory(activity));
    String tag = tabSpec.getTag();

    // Check to see if we already have a fragment for this tab, probably
    // from a previously saved state.  If so, deactivate it, because our
    // initial state is that a tab isn't shown.
    tabInfo.fragment = activity.getSupportFragmentManager().findFragmentByTag(tag);
    if (tabInfo.fragment != null && !tabInfo.fragment.isDetached()) {
        FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
        ft.detach(tabInfo.fragment);
        ft.commit();
        activity.getSupportFragmentManager().executePendingTransactions();
    }

    tabHost.addTab(tabSpec);
}

/** (non-Javadoc)
 * @see android.widget.TabHost.OnTabChangeListener#onTabChanged(java.lang.String)
 */
public void onTabChanged(String tag) {
    TabInfo newTab = (TabInfo) this.mapTabInfo.get(tag);
    if (mLastTab != newTab) {
        FragmentTransaction ft = this.getSupportFragmentManager().beginTransaction();
        if (mLastTab != null) {
            if (mLastTab.fragment != null) {
                ft.detach(mLastTab.fragment);
            }
        }
        if (newTab != null) {
            if (newTab.fragment == null) {
                newTab.fragment = Fragment.instantiate(this,
                        newTab.clss.getName(), newTab.args);
                ft.add(R.id.realtabcontent, newTab.fragment, newTab.tag);
            } else {
                ft.attach(newTab.fragment);
            }
        }

        mLastTab = newTab;
        ft.commit();
        this.getSupportFragmentManager().executePendingTransactions();
    }
}
</code>```

XML Code -

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    <TabHost
        android:id="@android:id/tabhost"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:tabStripEnabled="false">
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            >

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="0"/>

        <FrameLayout
            android:id="@+android:id/realtabcontent"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1"/>

        <TabWidget
            android:id="@android:id/tabs"
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:background="@drawable/tabbar_bg"
            android:tabStripEnabled="false"/>

    </LinearLayout>
</TabHost>
</LinearLayout>
</code>```

答:
Simply set child background as null and you have done. For more detail check my answer

```<code>fragmentTabHost.getTabWidget().getChildAt("Your tab position").setBackground(null);
</code>```

Try my answer
Link

Title: How to remove tabStrip in android?

Body:
I want to remove the tab color strip . I tried setStripEnabled(false); but that did not work. Also tried android:tabStripEnabled="false" in xml code. The tab strip still appears on the tab bar. Can someone tell me how I can remove the blue strip that occurs in the tab bar.

JAVA CODE:

public class TabsFragmentActivity extends FragmentActivity implements TabHost.OnTabChangeListener {
private TabHost mTabHost;
private HashMap mapTabInfo = new HashMap();
private TabInfo mLastTab = null;

private class TabInfo {
     private String tag;
     private Class clss;
     private Bundle args;
     private Fragment fragment;
     TabInfo(String tag, Class clazz, Bundle args) {
         this.tag = tag;
         this.clss = clazz;
         this.args = args;
     }

}

class TabFactory implements TabContentFactory {

    private final Context mContext;

    /**
     * @param context
     */
    public TabFactory(Context context) {
        mContext = context;
    }

    /** (non-Javadoc)
     * @see android.widget.TabHost.TabContentFactory#createTabContent(java.lang.String)
     */
    public View createTabContent(String tag) {
        View v = new View(mContext);
        v.setMinimumWidth(0);
        v.setMinimumHeight(0);
        return v;
    }

}
/** (non-Javadoc)
 * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
 */
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Step 1: Inflate layout
    setContentView(R.layout.tabs_layout);
    // Step 2: Setup TabHost
    initialiseTabHost(savedInstanceState);
    if (savedInstanceState != null) {
        mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab")); //set the tab as per the saved state

    }
}

/** (non-Javadoc)
 * @see android.support.v4.app.FragmentActivity#onSaveInstanceState(android.os.Bundle)
 */
protected void onSaveInstanceState(Bundle outState) {
    outState.putString("tab", mTabHost.getCurrentTabTag()); //save the tab selected
    super.onSaveInstanceState(outState);
}

/**
 * Step 2: Setup TabHost
 */
private void initialiseTabHost(Bundle args) {
    mTabHost = (TabHost)findViewById(android.R.id.tabhost);
    mTabHost.setup();

    TabInfo tabInfo = null;
    Resources res = getResources();
    this.mTabHost.getTabWidget().setStripEnabled(false);
    TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab1").setIndicator("",res.getDrawable(R.drawable.ic_launcher)), ( tabInfo = new TabInfo("Tab1", Tab1Fragment.class, args)));
    this.mapTabInfo.put(tabInfo.tag, tabInfo);
    TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab2").setIndicator("",res.getDrawable(R.drawable.ic_launcher)), ( tabInfo = new TabInfo("Tab2", Tab2Fragment.class, args)));
    this.mapTabInfo.put(tabInfo.tag, tabInfo);
    TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("",res.getDrawable(R.drawable.ic_launcher)), ( tabInfo = new TabInfo("Tab3", Tab3Fragment.class, args)));
    this.mapTabInfo.put(tabInfo.tag, tabInfo);

    // Default to first tab
    this.onTabChanged("Tab1");
    //
    mTabHost.setOnTabChangedListener(this);
}

/**
 * @param activity
 * @param tabHost
 * @param tabSpec
 * @param clss
 * @param args
 */
private static void addTab(TabsFragmentActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec, TabInfo tabInfo) {
    // Attach a Tab view factory to the spec
    tabSpec.setContent(activity.new TabFactory(activity));
    String tag = tabSpec.getTag();

    // Check to see if we already have a fragment for this tab, probably
    // from a previously saved state.  If so, deactivate it, because our
    // initial state is that a tab isn't shown.
    tabInfo.fragment = activity.getSupportFragmentManager().findFragmentByTag(tag);
    if (tabInfo.fragment != null && !tabInfo.fragment.isDetached()) {
        FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
        ft.detach(tabInfo.fragment);
        ft.commit();
        activity.getSupportFragmentManager().executePendingTransactions();
    }

    tabHost.addTab(tabSpec);
}

/** (non-Javadoc)
 * @see android.widget.TabHost.OnTabChangeListener#onTabChanged(java.lang.String)
 */
public void onTabChanged(String tag) {
    TabInfo newTab = (TabInfo) this.mapTabInfo.get(tag);
    if (mLastTab != newTab) {
        FragmentTransaction ft = this.getSupportFragmentManager().beginTransaction();
        if (mLastTab != null) {
            if (mLastTab.fragment != null) {
                ft.detach(mLastTab.fragment);
            }
        }
        if (newTab != null) {
            if (newTab.fragment == null) {
                newTab.fragment = Fragment.instantiate(this,
                        newTab.clss.getName(), newTab.args);
                ft.add(R.id.realtabcontent, newTab.fragment, newTab.tag);
            } else {
                ft.attach(newTab.fragment);
            }
        }

        mLastTab = newTab;
        ft.commit();
        this.getSupportFragmentManager().executePendingTransactions();
    }
}

XML Code -

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    <TabHost
        android:id="@android:id/tabhost"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:tabStripEnabled="false">
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            >

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="0"/>

        <FrameLayout
            android:id="@+android:id/realtabcontent"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1"/>

        <TabWidget
            android:id="@android:id/tabs"
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:background="@drawable/tabbar_bg"
            android:tabStripEnabled="false"/>

    </LinearLayout>
</TabHost>
</LinearLayout>

Body:
Simply set child background as null and you have done. For more detail check my answer

fragmentTabHost.getTabWidget().getChildAt("Your tab position").setBackground(null);

Try my answer
Link


问:
Inserting WorkSheet with Open XML - "...unreadable content..."
When I follow this tutorial:

http://msdn.microsoft.com/en-us/library/cc881781.aspx

to open an Excel document and insert an empty worksheet the final result is a message telling "Excel found unreadable content in ... Do you want to recover the contents of this workbook...". If I recover all the inserted sheets are blank (even if I add content programatically)

After renaming the xlsx to .zip and examining it shows that the worksheets have been created, and content added.

Anyone with any similar problems? It may be something with not creating relationships between newly created parts...

答:
That error message means that the XML that makes up your excel document is not conforming to the XML Schema and is invalid.  You can use the Open XML SDK 2.0 Productivity Tool to see where the issue is located.

I also copied the code from the bottom of your link and got it to work like Chris said in his comment.  Does your code look like this below?

```<code>// Open the document for editing.
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
{
    // Add a blank WorksheetPart.
    WorksheetPart newWorksheetPart =
       spreadSheet.WorkbookPart.AddNewPart<WorksheetPart>();
    newWorksheetPart.Worksheet = new Worksheet(new SheetData());

    Sheets sheets = spreadSheet.WorkbookPart.Workbook.GetFirstChild<Sheets>();
    string relationshipId =
       spreadSheet.WorkbookPart.GetIdOfPart(newWorksheetPart);
    // Get a unique ID for the new worksheet.
    uint sheetId = 1;
    if (sheets.Elements<Sheet>().Count() > 0)
    {
        sheetId =
        sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
    }

    // Give the new worksheet a name.
    string sheetName = "Sheet" + sheetId;

    // Append the new worksheet and associate it with the workbook.
    Sheet sheet = new Sheet()
    { Id = relationshipId, SheetId = sheetId, Name = sheetName };
    sheets.Append(sheet);

    string docName = @"C:\Users\Public\Documents\Sheet7.xlsx";
    InsertWorksheet(docName);
}

// Given a document name, inserts a new worksheet.
public static void InsertWorksheet(string docName)
{
    // Open the document for editing.
    using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
    {
        // Add a blank WorksheetPart.
        WorksheetPart newWorksheetPart = spreadSheet.WorkbookPart.AddNewPart<WorksheetPart>();
        newWorksheetPart.Worksheet = new Worksheet(new SheetData());

        Sheets sheets = spreadSheet.WorkbookPart.Workbook.GetFirstChild<Sheets>();
        string relationshipId = spreadSheet.WorkbookPart.GetIdOfPart(newWorksheetPart);

        // Get a unique ID for the new worksheet.
        uint sheetId = 1;
        if (sheets.Elements<Sheet>().Count() > 0)
        {
            sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
        }

        // Give the new worksheet a name.
        string sheetName = "Sheet" + sheetId;

        // Append the new worksheet and associate it with the workbook.
        Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
        sheets.Append(sheet);
    }
}
</code>```

Body:
That error message means that the XML that makes up your excel document is not conforming to the XML Schema and is invalid.  You can use the Open XML SDK 2.0 Productivity Tool to see where the issue is located.

I also copied the code from the bottom of your link and got it to work like Chris said in his comment.  Does your code look like this below?

// Open the document for editing.
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
{
    // Add a blank WorksheetPart.
    WorksheetPart newWorksheetPart =
       spreadSheet.WorkbookPart.AddNewPart<WorksheetPart>();
    newWorksheetPart.Worksheet = new Worksheet(new SheetData());

    Sheets sheets = spreadSheet.WorkbookPart.Workbook.GetFirstChild<Sheets>();
    string relationshipId =
       spreadSheet.WorkbookPart.GetIdOfPart(newWorksheetPart);
    // Get a unique ID for the new worksheet.
    uint sheetId = 1;
    if (sheets.Elements<Sheet>().Count() > 0)
    {
        sheetId =
        sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
    }

    // Give the new worksheet a name.
    string sheetName = "Sheet" + sheetId;

    // Append the new worksheet and associate it with the workbook.
    Sheet sheet = new Sheet()
    { Id = relationshipId, SheetId = sheetId, Name = sheetName };
    sheets.Append(sheet);

    string docName = @"C:\Users\Public\Documents\Sheet7.xlsx";
    InsertWorksheet(docName);
}

// Given a document name, inserts a new worksheet.
public static void InsertWorksheet(string docName)
{
    // Open the document for editing.
    using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
    {
        // Add a blank WorksheetPart.
        WorksheetPart newWorksheetPart = spreadSheet.WorkbookPart.AddNewPart<WorksheetPart>();
        newWorksheetPart.Worksheet = new Worksheet(new SheetData());

        Sheets sheets = spreadSheet.WorkbookPart.Workbook.GetFirstChild<Sheets>();
        string relationshipId = spreadSheet.WorkbookPart.GetIdOfPart(newWorksheetPart);

        // Get a unique ID for the new worksheet.
        uint sheetId = 1;
        if (sheets.Elements<Sheet>().Count() > 0)
        {
            sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
        }

        // Give the new worksheet a name.
        string sheetName = "Sheet" + sheetId;

        // Append the new worksheet and associate it with the workbook.
        Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
        sheets.Append(sheet);
    }
}


问:
Attempting to provide github credentials to jenkins pipeline job
I'm trying to set up the credentials for github in a jenkins pipeline job. I have the following in my pipeline script:

```<code>pipeline {
    agent any
    git([url: 'ssh://git@github.com/user/repname/', branch: 'master', credentialsId: 'xxx-xxx-xxx'])
</code>```

Where does the credentialsId come from? Is this created elsewhere in Jenkins?

Update:
I pulled the credentials id from this page:

But now I am seeing this error:

Started by user anonymous
  org.codehaus.groovy.control.MultipleCompilationErrorsException:
  startup failed: WorkflowScript: 3: Undefined section "git" @ line 3,
  column 5.

答:
As you found yourself, it's the credentials id provided in the credentials view.

Now, as for your second problem, you're using declarative pipeline, it requires that you have the following structure:

```<code>pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                git([url: 'ssh://git@github.com/user/repname/', branch: 'master', credentialsId: 'xxx-xxx-xxx'])
            }
        }
    }
}
</code>```

E.g. you need to put the git step insde of the stages, stage and steps clauses (documentation of this can be found here).

Alternatively you can use scripted pipeline, then it becomes:

```<code>node {
    git([url: 'ssh://git@github.com/user/repname/', branch: 'master', credentialsId: 'xxx-xxx-xxx'])
}
</code>```

However, when you're creating simple pipelines, then declarative pipelines provides a lot of nice to have features. See my answer here for a comparison between declarative and scripted pipelines.

Body:
I'm trying to set up the credentials for github in a jenkins pipeline job. I have the following in my pipeline script:

pipeline {
    agent any
    git([url: 'ssh://git@github.com/user/repname/', branch: 'master', credentialsId: 'xxx-xxx-xxx'])

Where does the credentialsId come from? Is this created elsewhere in Jenkins?

Update:
I pulled the credentials id from this page:

But now I am seeing this error:

Started by user anonymous
  org.codehaus.groovy.control.MultipleCompilationErrorsException:
  startup failed: WorkflowScript: 3: Undefined section "git" @ line 3,
  column 5.

Body:
As you found yourself, it's the credentials id provided in the credentials view.

Now, as for your second problem, you're using declarative pipeline, it requires that you have the following structure:

pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                git([url: 'ssh://git@github.com/user/repname/', branch: 'master', credentialsId: 'xxx-xxx-xxx'])
            }
        }
    }
}

E.g. you need to put the git step insde of the stages, stage and steps clauses (documentation of this can be found here).

Alternatively you can use scripted pipeline, then it becomes:

node {
    git([url: 'ssh://git@github.com/user/repname/', branch: 'master', credentialsId: 'xxx-xxx-xxx'])
}

However, when you're creating simple pipelines, then declarative pipelines provides a lot of nice to have features. See my answer here for a comparison between declarative and scripted pipelines.


问:
How to set text view if something happened in another class
I have a text view in my ActivityMain and I have an adapter(for my recycler view) that if the user touches something value of text view should be changed.

Text view is in another part of the screen and is not related to recycler view.

how can I do that?

thank you.

答:
One way is to create a callback function. You need to define an interface as a contractor between your activity and the other class that you need to inform the activity.

Implement the interface inside your activity and pass its reference to the other class and call that reference whenever you need.


问:
How to add and remove active class to anchor tag within li using Jquery/Javascript
I need one help. I have multiple li values I need to add active class when clicked any value and removed from others using Jquery/Javascript.I am explaining my code below.

```<code><ul id="ulCategory">
   <li><a href='javascript:void(0)' onclick='savesubcat()'>ABC</li>
<li><a href='javascript:void(0)' onclick='savesubcat()'>ABF</li>
<li><a href='javascript:void(0)' onclick='savesubcat()'>ABK</li>

</ul>
</code>```

My active class is given below.

```<code>.active {text-align: left; color: #fff; background-color:#ffbb00; text-decoration: none;}
</code>```

Here I need while user will click on one value that only will be remain active and other will not have the active class.Please help me.

答:
Simply bind a click handler to the elements in question and use the .addClass() and .removeClass() methods.

Also, call your savesubcat() function from there too, rather than using the inline onclick= attribute.

var anchors = $("#ulCategory li a").click(function() {
  //savesubcat()
  $(this).addClass("active")
  anchors.not(this).removeClass("active")
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active {text-align: left; color: #fff; background-color:#ffbb00; text-decoration: none;}</code>```

href='javascript:void(0)'>ABC

href='javascript:void(0)'>ABF

href='javascript:void(0)'>ABK

```

Put the JS at the end of the body, and/or wrap it in a document ready handler.

(I'm assuming the savesubcat() function doesn't cause page navigation or refresh, because if it did then any classes set before the refresh would be cleared.)

Body:
I need one help. I have multiple li values I need to add active class when clicked any value and removed from others using Jquery/Javascript.I am explaining my code below.

ABC

ABF

ABK

My active class is given below.

.active {text-align: left; color: #fff; background-color:#ffbb00; text-decoration: none;}

Here I need while user will click on one value that only will be remain active and other will not have the active class.Please help me.

Body:
Simply bind a click handler to the elements in question and use the .addClass() and .removeClass() methods.

Also, call your savesubcat() function from there too, rather than using the inline onclick= attribute.

var anchors = $("#ulCategory li a").click(function() {
  //savesubcat()
  $(this).addClass("active")
  anchors.not(this).removeClass("active")
})

.active {text-align: left; color: #fff; background-color:#ffbb00; text-decoration: none;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="ulCategory">
   <li><a href='javascript:void(0)'>ABC</li>
   <li><a href='javascript:void(0)'>ABF</li>
   <li><a href='javascript:void(0)'>ABK</li>
</ul>

Put the JS at the end of the body, and/or wrap it in a document ready handler.

(I'm assuming the savesubcat() function doesn't cause page navigation or refresh, because if it did then any classes set before the refresh would be cleared.)


问:
How can I transload data between two delphi applications over internet?
Hi
let me make my question clear. Two people using my app are connected to the internet. Both have each other's IP and they want to chat (like Y!messanger) with each other.
I think I need to use Indy components; right? Which component should I use?
Thanks in advance</p>

答:
In general, you are looking to create a "Client/Server" type application.  A quick Google search for "indy client server example" pulls up lots of results, including this one: http://www.devarticles.com/c/a/Delphi-Kylix/A-Real-World-Client-Server-Application-in-Delphi/

In reality, this gets a lot more complicated when you have firewalls and NATs with private IP addresses.  You will have to consider how your application will either get around or through these types of technologies.


问:
MongoDB - Find by keyword - different data types
I'm using MongoDB as my database engine and trying to execute a find query based on a given keyword. If all of the data fields are type of String, then I could perform the find query like this:

```<code>test.find({
    $or: [
        {'field1': {'$regex': req.body.keyword} },
        {'field2': {'$regex': req.body.keyword} }
    ]})
    .then(function(records) {
        if(records.length >= 1) {
            return res.json({error: false, message: null, data: records});
        } else {
            return res.json({error: false, message: "No results", data: null});
        }
    });
</code>```

However, I have some fields that has a field type of Number and $reqex cannot be used with any other types than String.

Is it even possible to perform a find query on different data types? Any help/ideas/thoughts are much appreciated!

答: Try using the .toString() method to convert the numbers to strings as you pass them to the $regex operator.

Body:
I'm using MongoDB as my database engine and trying to execute a find query based on a given keyword. If all of the data fields are type of String, then I could perform the find query like this:

test.find({
    $or: [
        {'field1': {'$regex': req.body.keyword} },
        {'field2': {'$regex': req.body.keyword} }
    ]})
    .then(function(records) {
        if(records.length >= 1) {
            return res.json({error: false, message: null, data: records});
        } else {
            return res.json({error: false, message: "No results", data: null});
        }
    });

However, I have some fields that has a field type of Number and $reqex cannot be used with any other types than String.

Is it even possible to perform a find query on different data types? Any help/ideas/thoughts are much appreciated!