text:
Q: Execute batch file through java, passing file path as arguments which contains space I am trying update the classpath, in batch file by providing library location.
I am calling bat file through java, by passing library location as a arguments,
my code executes perfectly if there is no space in library path location,
If library path contains space, bat file throws exception, could not find or load a main class
below is my code
public class TestBat {
 public static void main(String[] args) throws IOException {
  ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "start",
    "C:\\Users\\graymatter\\Desktop\\MyBatch.bat",
    "D:\\Testing\\Main Plan");
  pb.start();
 }
}

This code executes perfect,
If path has "D:\Testing\MainPlan", insted of "D:\Testing\Main Plan"
Here is my bat file
@echo off
setlocal EnableDelayedExpansion

set DIR1=%1
echo %DIR1%
set CLASSPATH=.
FOR %%F IN ("%DIR1%"\lib\*.jar) DO (set CLASSPATH=!CLASSPATH!;%%F)

java -cp %CLASSPATH% com.pentaho.support.TestBat %*

So as per my knowledge am getting this error because of that space in path,
I tried a lot, by using escape sequence,
but no use.
Even referred @ Spaces in file path in java
Thanks

A: If the argument contains spaces, it needs to be quoted. Use  "\"D:\\Testing\\Main Plan\""
The batch file should look
@echo off
  setlocal EnableDelayedExpansion

  set "DIR1=%~1"
  echo %DIR1%
  set CLASSPATH=.
  FOR %%F IN ("%DIR1%\lib\*.jar") DO (set "CLASSPATH=!CLASSPATH!;%%F")

  java -cp "%CLASSPATH%" com.pentaho.support.TestBat %*

Where %~1 represent the first argument to batch file without quotes if it has any. Then, all the variable read/set are enclosed in quotes to handle any problem whith spaces.


text:
Q: framework not found Mapbox iOS Xcode React-Native I've been getting this error for a number of days whilst attempting to install and use mapbox Whilst Mapbox works on Android, it does not work on iOS for me consistently resulting in an error on build which is framework not found Mapbox
When installing via CocoaPods I'm getting an error from xcode
framework not found Mapbox

Ld /Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Products/Debug-iphonesimulator/clustr.app/clustr normal x86_64
    cd /Users/michaelstokes/clustr/clustr_app/ios
    export IPHONEOS_DEPLOYMENT_TARGET=8.0
    export PATH="/Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode-beta.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch x86_64 -isysroot /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.2.sdk -L/Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Products/Debug-iphonesimulator -L/Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Products/Debug-iphonesimulator/React -L/Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Products/Debug-iphonesimulator/Stripe -L/Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Products/Debug-iphonesimulator/react-native-mapbox-gl -L/Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Products/Debug-iphonesimulator/yoga -F/Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Products/Debug-iphonesimulator -F/Users/michaelstokes/Documents/FacebookSDK -filelist /Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Intermediates.noindex/Clustr.build/Debug-iphonesimulator/clustr.build/Objects-normal/x86_64/clustr.LinkFileList -Xlinker -rpath -Xlinker @executable_path/Frameworks -Xlinker -rpath -Xlinker @loader_path/Frameworks -Xlinker -rpath -Xlinker @executable_path/Frameworks -mios-simulator-version-min=8.0 -Xlinker -object_path_lto -Xlinker /Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Intermediates.noindex/Clustr.build/Debug-iphonesimulator/clustr.build/Objects-normal/x86_64/clustr_lto.o -Xlinker -export_dynamic -Xlinker -no_deduplicate -Xlinker -objc_abi_version -Xlinker 2 -fobjc-arc -fobjc-link-runtime -ObjC -lReact -lStripe -lreact-native-mapbox-gl -lstdc++ -lyoga -framework AddressBook -framework Foundation -framework JavaScriptCore -framework Mapbox -framework PassKit -framework Security -framework WebKit -framework XCTest -weak_framework Contacts -ObjC -lc++ -Xlinker -sectcreate -Xlinker __TEXT -Xlinker __entitlements -Xlinker /Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Intermediates.noindex/Clustr.build/Debug-iphonesimulator/clustr.build/clustr.app.xcent /Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Products/Debug-iphonesimulator/libReact.a /Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Products/Debug-iphonesimulator/libRCTAnimation.a -framework FBSDKLoginKit /Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Products/Debug-iphonesimulator/libRCTActionSheet.a /Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Products/Debug-iphonesimulator/libRCTGeolocation.a /Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Products/Debug-iphonesimulator/libRCTImage.a /Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Products/Debug-iphonesimulator/libRCTLinking.a /Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Products/Debug-iphonesimulator/libRCTNetwork.a -framework FBSDKShareKit -framework Bolts /Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Products/Debug-iphonesimulator/libRCTSettings.a /Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Products/Debug-iphonesimulator/libRCTText.a /Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Products/Debug-iphonesimulator/libRCTVibration.a -framework FBSDKCoreKit /Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Products/Debug-iphonesimulator/libRCTWebSocket.a -lAirMaps -lRNDeviceInfo -lPods-clustr -lRCTCamera -lreact-native-branch -lRNGeocoder -lReact -lyoga -lcxxreact -ljschelpers -lRNVectorIcons -lTPSStripe -Xlinker -dependency_info -Xlinker /Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Intermediates.noindex/Clustr.build/Debug-iphonesimulator/clustr.build/Objects-normal/x86_64/clustr_dependency_info.dat -o /Users/michaelstokes/Library/Developer/Xcode/DerivedData/Clustr-fkpfvfogtttxepgdsdrkmamfpvax/Build/Products/Debug-iphonesimulator/clustr.app/clustr

ld: framework not found Mapbox
clang: error: linker command failed with exit code 1 (use -v to see invocation)
My podfile is as follows:

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'clustr' do

  # Flexbox Layout Manager Used By React Natve
  pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga/Yoga.podspec'

  # React Native
  pod 'React', path: '../node_modules/react-native', subspecs: [
    # Comment out any unneeded subspecs to reduce bundle size.
    'Core',
    'DevSupport',
    'RCTActionSheet',
    'RCTAnimation',
    'RCTBlob',
    'RCTCameraRoll',
    'RCTGeolocation',
    'RCTImage',
    'RCTNetwork',
    'RCTPushNotification',
    'RCTSettings',
    'RCTTest',
    'RCTText',
    'RCTVibration',
    'RCTWebSocket',
    'RCTLinkingIOS'
  ]

  # Mapbox
  pod 'react-native-mapbox-gl', :path => '../node_modules/@mapbox/react-native-mapbox-gl'

  pod 'Stripe', '~> 10.1.0'

  inherit! :search_paths
end
When running pod install I get

MacBook-Pro:ios michaelstokes$ pod install
Analyzing dependencies
Fetching podspec for `React` from `../node_modules/react-native`
Fetching podspec for `react-native-mapbox-gl` from `../node_modules/@mapbox/react-native-mapbox-gl`
Fetching podspec for `yoga` from `../node_modules/react-native/ReactCommon/yoga/Yoga.podspec`
Downloading dependencies
Using React (0.50.4)
Using Stripe (10.1.0)
Using react-native-mapbox-gl (6.0.1)
Using yoga (0.50.4.React)
Generating Pods project
Integrating client project
Sending stats
Pod installation complete! There are 19 dependencies from the Podfile and 4 total pods installed.

[!] Automatically assigning platform ios with version 8.0 on target clustr because no platform was specified. Please specify a platform for this target in your Podfile. See `https://guides.cocoapods.org/syntax/podfile.html#platform`.

[!] The `clustr [Debug]` target overrides the `FRAMEWORK_SEARCH_PATHS` build setting defined in `Pods/Target Support Files/Pods-clustr/Pods-clustr.debug.xcconfig'. This can lead to problems with the CocoaPods installation
    - Use the `$(inherited)` flag, or
    - Remove the build settings from the target.

[!] The `clustr [Release]` target overrides the `FRAMEWORK_SEARCH_PATHS` build setting defined in `Pods/Target Support Files/Pods-clustr/Pods-clustr.release.xcconfig'. This can lead to problems with the CocoaPods installation
    - Use the `$(inherited)` flag, or
    - Remove the build settings from the target.

Thanks very much!
I was getting framework not found Mapbox but after Following an answer over at target overrides the FRAMEWORK_SEARCH_PATHS build settings target overrides the FRAMEWORK_SEARCH_PATHS build settings about adding $(inherited) to framework search paths that resolved it but then there were following issues on build relating to libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

A: To resolve the issue of framework not found Mapbox during build I had to add $(inherited) to framework search paths and then the build was succesfull but follows with an issue when trying to include Mapbox views so whilst this is a partial answer, it resolves the issue of framework not found Mapbox but then there are following issues over at Mapbox: libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

A: If you are getting this error whilst installing it on a iOS Simulator, you'll have to add it in the Framework Search Paths (as mentioned above) - however, use the options for debug and release:
Device

Any iOS SDK

Simulator

Any iOS Simulator SDK

I put the first option into the Framework Search Paths, and the project built fine on a physical device. However, when I went to use it on a Simualtor, it failed - this is why.
Here is my path:
$(SRCROOT)/../node_modules/@mapbox/react-native-mapbox-gl/ios

redpajama_set_name: RedPajamaStackExchange


text:
Q: change the url and display the ajax content $(function(){
  $("a[rel='tab']").click(function(e){

    //get the link location that was clicked
    pageurl = $(this).attr('href');
    $("#Content").fadeOut(800);

    setTimeout(function(){
      $.ajax({url:pageurl+'?rel=tab',success: function(data){

        $("#Content").fadeIn(900);
        $('#Content').html(data);

      }});
    }, 900);
    //to get the ajax content and display in div with id 'content'

    //to change the browser URL to 'pageurl'
    if(pageurl!=window.location){
      window.history.pushState({path:pageurl},'',pageurl);
    }

    return false;
  });

});

I want to change content by ajax with change url ,, I use above code but it is make site very slow . How can I make it fast when I click to any page in site ?
Thanks

A: The fadeIn()/fadeOut()/setTimeout() delays are slowing things down. Reduce or remove them.
$(function(){
  $("a[rel='tab']").click(function(e){

    //get the link location that was clicked
    pageurl = $(this).attr('href');
    $("#Content").fadeOut(50);

    $.ajax({url:pageurl+'?rel=tab',success: function(data){

      $('#Content').html(data);
      $("#Content").fadeIn(25);

    }});

    //to get the ajax content and display in div with id 'content'

    //to change the browser URL to 'pageurl'
    if(pageurl!=window.location){
      window.history.pushState({path:pageurl},'',pageurl);
    }

    return false;
  });

});


text:
Q: GStream Backend Error could not demultiplex stream python error I am trying to compare subsequent frames to the first frame of a video using compare_ssim and then saving that as a separate video. But the output video gives me an error stating GStream Backend Error could not demultiplex stream. I made sure that the frame_size for the Videowriter is the same as what I am trying to record. The following is the code:
import cv2
import numpy as np
from skimage.metrics import structural_similarity as compare_ssim

label = 0
initial_frame = None
start = True

video = cv2.VideoCapture("vid1.mp4")

frame_width = int(video.get(3))
frame_height = int(video.get(4))
frame_size = (frame_height,frame_width)
fps = 30
print(frame_width, frame_height, frame_size)

output = cv2.VideoWriter('output_video_from_file.avi', cv2.VideoWriter_fourcc('M','J','P','G'), fps, frame_size)

while video.isOpened():
    ret, frame = video.read()

    if start:
        initial_frame = frame[:,:,2]
        start = False

    curr_frame = frame[:,:,2]
    (score, diff) = compare_ssim(initial_frame, curr_frame, full=True)
    diff = (diff * 255).astype("uint8")

    print(diff.shape) #same as frame_size
    label += 1
    print("On frame {}".format(label))

    output.write(diff)
    if cv2.waitKey(1) == ord('q'):
        break
video.release()
cv2.destroyAllWindows()


text:
Q: How to make a regex for files ending in .php? I'm trying to write a very simple regular expression that matches any file name that doesn't end in .php.  I came up with the following...
(.*?)(?!\.php)$

...however this matches all filenames.  If someone could point me in the right direction I'd be very grateful.

A: Almost:
.*(?!\.php)....$

The last four dots make sure that there is something to look ahead at, when the look-ahead is checked.
The outer parentheses are unnecessary since you are interested in the entire match.
The reluctant .*? is unnecessary, since backtracking four steps is more efficient than checking the following condition with every step.

A: Instead of using negative lookahead, sometimes it's easier to use the negation outside the regex at the hosting language level. In many languages, the boolean complement operator is the unary !.
So you can write something like this:
! str.hasMatch(/\.php$/)

Depending on language, you can also skip regex altogether and use something like (e.g. Java):
! str.endsWith(".php")

As for the problem with the original pattern itself:
(.*?)(?!\.php)$   // original pattern, doesn't work!

This matches, say, file.php, because the (.*?) can capture file.php, and looking ahead, you can't match \.php, but you can match a $, so altogether it's a match! You may want to use look behind, or if it's not supported, you can lookahead at the start of the string.
^(?!.*\.php$).*$  // negative lookahead, works

This will match all strings that does not end with ".php" using negative lookahead.
References

*

*regular-expressions.info/Lookarounds
Related questions

*

*How does the regular expression (?<=#)[^#]+(?=#) work?

A: You are at the end of the string and looking ahead. What you want is a look behind instead:
(.*)$(?<!\.php)

Note that not all regular expression engines support lookbehind assertions.


text:
Q: How to keep websockets listening as a background service? I have a service to handle my websocket events however it stops listening when the UI is closed - however, I can still emit messages (eg. location data). How do I keep websockets running in the background so it will listen for events on boot or when the main UI thread is closed?
public class HomeActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    public static final String TAG = HomeActivity.class.getSimpleName();
    public static final String PREFS_NAME = "MyPrefsFile";
    String userName = "init";
    String token = "init";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo wInfo = wifiManager.getConnectionInfo();
        String macAddress = wInfo.getMacAddress();
        TextView textView = (TextView) findViewById(R.id.txtMac);
        textView.setText(macAddress);

        startService(new Intent(getBaseContext(), wsService.class));

        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        userName = settings.getString("username","does not exist");
        token = settings.getString("token","does not exist");
        textView = (TextView) findViewById(R.id.txtEmail);
        textView.setText(userName);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("Beacon");

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        } else if (id == R.id.nav_logout) {
            Log.i(TAG, "<<<<---- LOGOUT ---->>> ");
            Intent i = new Intent(getApplicationContext(), HomeActivity.class);
            startActivity(i);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

This is the service being started from the activity above:
public class wsService extends Service implements OnPreparedListener {
    public static final String PREFS_NAME = "MyPrefsFile";
    double longitude = 0;
    double latitude = 0;
    long time = 0;
    float speed = 0;
    float accuracy = 0;
    float bearing = 0;
    boolean sound_stopped = true;
    String userName = "init";
    String token = "init";
    public static final String TAG = wsService.class.getSimpleName();
    private LocationRequest mLocationRequest;
    MediaPlayer mp;

    /** indicates how to behave if the service is killed */
    int mStartMode;

    /** interface for clients that bind */
    IBinder mBinder;

    /** indicates whether onRebind should be used */
    boolean mAllowRebind;
    private Socket mSocket;
    {
        try {
            mSocket = IO.socket("http://192.168.0.2:5000");
        } catch (URISyntaxException e) {}

    }

    /** Called when the service is being created. */
    @Override
    public void onCreate() {
        Log.d(TAG, "-- Starting wsService --");
        new LongOperation().execute("test");
        mp = MediaPlayer.create(this, R.raw.led);
        String locationProvider = LocationManager.NETWORK_PROVIDER;
        mLocationRequest = LocationRequest.create() // Create the LocationRequest object
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                .setFastestInterval(1 * 1000); // 1 second, in milliseconds
        // Acquire a reference to the system Location Manager
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
    }

    private class LongOperation extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            Log.d(TAG, "-- Starting BACKGROUND wsService --");
            mSocket.connect();
            mSocket.on("to_mobile", onCommand);
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {

        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }

    //Listening new message event to receive message
    private Emitter.Listener onCommand = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            JSONObject data = (JSONObject)args[0];
            String command = null;
            try {
                command = data.getString("command");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            Log.i(TAG, "<<<<---- RECEIVING COMMAND ----->>> " + command);
            if (command.equals("ping_audio_start")) {
                start_sound();
            }
            if (command.equals("ping_audio_stop")) {
                stop_sound();
            }
            if (command.equals("ping_gps")) {
                Log.i(TAG, "<<<<---- RESPONDING GPS REQUEST ----->>> ");
                mSocket.emit("from_mobile", gps_string);
            }

        }
    };

    String gps_string = "HELLO FROM DROID";
    private void handleNewLocation(Location location) {
        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo wInfo = wifiManager.getConnectionInfo();
        String macAddress = wInfo.getMacAddress();
        longitude = location.getLongitude();
        latitude = location.getLatitude();
        time = location.getTime();
        speed = location.getSpeed();
        accuracy = location.getAccuracy();
        bearing = location.getBearing();
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        userName = settings.getString("username","does not exist");
        token = settings.getString("token","does not exist");
        gps_string = "{ \"mac\":\"" + macAddress
                + "\", \"userName\":\"" + userName
                + "\", \"token\":\"" + token
                + "\", \"time\":\"" + time
                + "\", \"longitude\":\"" + longitude
                + "\", \"latitude\":\"" + latitude
                + "\", \"speed\":\"" + speed
                + "\", \"accuracy\":\"" + accuracy
                + "\", \"bearing\":\"" + bearing
                + "\"}";
        mSocket.emit("from_mobile", gps_string);
        Log.i(TAG, "<<<<---- SENDING GPS DATA ---->>> ");
    }

    // Define a listener that responds to location updates
    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            handleNewLocation(location);
        }
        public void onStatusChanged(String provider, int status, Bundle extras) {}

        public void onProviderEnabled(String provider) {}

        public void onProviderDisabled(String provider) {}
    };

    public void start_sound() {
        Log.i(TAG, "<<<<---- START PING ----->>>");
        mp.release();
        mp = MediaPlayer.create(this, R.raw.led);
        mp.setLooping(true);
        mp.start();
        mp.setVolume(1, 1);
        sound_stopped = false;

    }
    public void stop_sound() {
        Log.i(TAG, "<<<<---- STOP PING ----->>> ");
        mp.stop();
        sound_stopped = true;
    }

    public void onPrepared(MediaPlayer player) {
        player.start();
    }
        /** The service is starting, due to a call to startService() */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return mStartMode;
    }

    /** A client is binding to the service with bindService() */
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    /** Called when all clients have unbound with unbindService() */
    @Override
    public boolean onUnbind(Intent intent) {
        return mAllowRebind;
    }

    /** Called when a client is binding to the service with bindService()*/
    @Override
    public void onRebind(Intent intent) {

    }

    /** Called when The service is no longer used and is being destroyed */
    @Override
    public void onDestroy() {

    }
}

A: IntentService is running only for as long as the it needs to handle the Intent. i.e if there are no intents left to process, the service closes automatically.
Try a normal service instead.


text:
Q: search in tableview with database data thats split into many arrays? I am quite a new developer in the Swift language and iOS platform. I have been reading many guides and tutorials on implementing search functionality in a table.
But, none match my need well. So, my question is: How would I go about implementing search for a table that has data from a database and is populated from 4 arrays ?
Code of the table
import UIKit

class VieworderTVC: UIViewController,UITableViewDataSource, UITableViewDelegate  {

    var deleteOrderIndexPath: NSIndexPath? = nil

    @IBAction func btnRefresh(sender: UIBarButtonItem) {

            orderIDData.removeAll()
            ItemNoData.removeAll()
            BPnoData.removeAll()
            QuantityData.removeAll()
            self.tblview.reloadData()
            get_data_from_url("http://100.1.1.25/sfc/orders.php")

            return
    }

    @IBOutlet weak var tblview: UITableView!;

    var orderIDData:Array< String > = Array < String >()
    var ItemNoData:Array< String > = Array < String >()
    var BPnoData:Array< String > = Array < String >()
    var QuantityData:Array< String > = Array < String >()

    override func viewDidLoad() {
        super.viewDidLoad()
        get_data_from_url("http://100.1.1.25/sfc/orders.php")

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return orderIDData.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! OrderViewCell
        print(indexPath.row)
        cell.orderLabel.text = orderIDData[indexPath.row]
        cell.lblitem.text = ItemNoData[indexPath.row]
        cell.lblbp.text = BPnoData[indexPath.row]
        cell.lblquantity.text = QuantityData[indexPath.row]
        return cell
    }

    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            deleteOrderIndexPath = indexPath
            let OrderToDelete = orderIDData[indexPath.row]
            confirmDelete(OrderToDelete)
        }
    }

    // Delete Confirmation and Handling
    func confirmDelete(planet: String) {
        let alert = UIAlertController(title: "Delete Planet", message: "Are you sure you want to permanently delete order \(planet)?", preferredStyle: .ActionSheet)

        let DeleteAction = UIAlertAction(title: "Delete", style: .Destructive, handler: handleDeletePlanet)
        let CancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: cancelDeleteOrder)

        alert.addAction(DeleteAction)
        alert.addAction(CancelAction)

        self.presentViewController(alert, animated: true, completion: nil)
    }

    func handleDeletePlanet(alertAction: UIAlertAction!) -> Void {
        if let indexPath = deleteOrderIndexPath {
            tblview.beginUpdates()

            let OrderNo = orderIDData[indexPath.row];

            let myUrl = NSURL(string: "http://100.1.1.25/sfc/deleteorder.php");let request = NSMutableURLRequest(URL:myUrl!);
            request.HTTPMethod = "POST";

            // Compose a query string

            let postString = "OrderNo=\(OrderNo)";

            request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

            let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
                data, response, error in

                if error != nil
                {
                    print("error=\(error)")
                    return
                }

                // You can print out response object
                print("response = \(response)")

                // Print out response body
                let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("responseString = \(responseString)")

                //Let's convert response sent from a server side script to a NSDictionary object:

                //var err: NSError?
                let myJSON = try! NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary

                if let parseJSON = myJSON {
                    let resultValue = parseJSON["status"] as? String!;

                    print("result: \(resultValue)");
                    var isOrderDeleted:Bool = false;

                    if (resultValue == "Success") {isOrderDeleted = true;}

                    var DisplayMessage: String = parseJSON["message"] as! String!;
                    if (!isOrderDeleted) {
                        DisplayMessage = parseJSON["message"] as! String!
                    }

                    dispatch_async(dispatch_get_main_queue(), {
                        let alerting = UIAlertController(title:"Alert", message:DisplayMessage, preferredStyle: UIAlertControllerStyle.Alert);

                        let ok = UIAlertAction(title: "Ok", style:UIAlertActionStyle.Default, handler: nil)

                        alerting.addAction(ok);
                        self.presentViewController(alerting, animated: true, completion: nil)
                    });

                }

            }

            task.resume()

            orderIDData.removeAtIndex(indexPath.row)
            ItemNoData.removeAtIndex(indexPath.row)
            BPnoData.removeAtIndex(indexPath.row)
            QuantityData.removeAtIndex(indexPath.row)

            // Note that indexPath is wrapped in an array:  [indexPath]
            tblview.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)

            deleteOrderIndexPath = nil

            tblview.endUpdates()
        }
    }

    func cancelDeleteOrder(alertAction: UIAlertAction!) {
        deleteOrderIndexPath = nil
    }

    func get_data_from_url(url:String)
    {
        let httpMethod = "GET"

        let url = NSURL(string: url)
        let urlRequest = NSMutableURLRequest(URL: url!,
            cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
            timeoutInterval: 15.0)
        let queue = NSOperationQueue()
        NSURLConnection.sendAsynchronousRequest(
            urlRequest,
            queue: queue,
            completionHandler: {(response: NSURLResponse?,
                data: NSData?,
                error: NSError?) in
                if data!.length > 0 && error == nil{
                    let json = NSString(data: data!, encoding: NSASCIIStringEncoding)
                    self.extract_json(json!)
                }else if data!.length == 0 && error == nil{
                    print("Nothing was downloaded")
                } else if error != nil{
                    print("Error happened = \(error)")
                }
            }
        )
    }

    func extract_json(data:NSString)
    {
        //let parseError: NSError?
        let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!
        let json: AnyObject? = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableContainers)

            if let orders_list = json as? NSArray
            {
                for (var i = 0; i < orders_list.count ; i++ )
                {
                    if let orders_obj = orders_list[i] as? NSDictionary
                    {
                        if let order_id = orders_obj["OrderID"] as? String
                        {

                            if let order_ItemNo = orders_obj["ItemNo"] as? String
                            {
                                if let order_bpNo = orders_obj["BPno"] as? String
                                {
                                    if let order_quantity = orders_obj["Quantity"] as? String
                                    {
                                    //TableData.append(order_id + " [" + order_ItemNo + "]")

                                    orderIDData.append(order_id)
                                    ItemNoData.append(order_ItemNo)
                                    BPnoData.append(order_bpNo)
                                    QuantityData.append(order_quantity)
                                    }
                                }
                            }
                        }
                    }
                }
            }
        do_table_refresh();
    }

    func do_table_refresh()
    {
        dispatch_async(dispatch_get_main_queue(), {
            self.tblview.reloadData()
            return
        })
    }

Code of the cell
import UIKit

class OrderViewCell: UITableViewCell {

  @IBOutlet weak var orderLabel: UILabel!
  @IBOutlet weak var lblitem: UILabel!

  @IBOutlet weak var lblquantity: UILabel!
  @IBOutlet weak var lblbp: UILabel!

}

A: I had managed to solve this issue via:
import UIKit

extension UITableViewCell {
    func setTransparent() {
        let bgView: UIView = UIView()
        bgView.backgroundColor = .clearColor()

        self.backgroundView = bgView
        self.backgroundColor = .clearColor()
    }
}

class VieworderTVC: UIViewController,UITableViewDataSource, UITableViewDelegate {

    var manualBP = ""

    var deleteOrderIndexPath: NSIndexPath? = nil

    @IBAction func btnRefresh(sender: UIBarButtonItem) {

            orderIDData.removeAll()
            ItemNoData.removeAll()
            BPnoData.removeAll()
            QuantityData.removeAll()
            self.tblview.reloadData()
            get_data_from_url("http://x.x.x/sfc/orders.php")

            return
    }

    @IBAction func filterOrder(sender: AnyObject) {
        // 1
        let optionMenu = UIAlertController(title: nil, message: "Choose Option", preferredStyle: .ActionSheet)

        // 2
        let BPAction = UIAlertAction(title: "Filter by BP number", style: .Default, handler: {
            (alert: UIAlertAction!) -> Void in

//            let alertController = UIAlertController(title: "How to enter BP number?", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
//
//
//            let manEnt = UIAlertAction(title: "Manual", style: UIAlertActionStyle.Default, handler: {(alert :UIAlertAction!) in

                //1. Create the alert controller.
                let alert = UIAlertController(title: "BP number entry", message: "Enter the BP number:", preferredStyle: .Alert)

                //2. Add the text field. You can configure it however you need.
                alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
                    textField.text = ""
                })

                //3. Grab the value from the text field
                alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in

                    let textField = alert.textFields![0] as UITextField

                    self.manualBP = textField.text!

                    if(textField.text != "" && (textField.text?.characters.count)! > 10 && self.BPnoData.contains(self.manualBP)){
                        print("Text field: \(textField.text!)")

                        //going to attempt to remove the orders that dont match bp number entered
                        var repcount: Int = 0;

                        repeat{

                            if(self.BPnoData[repcount] != self.manualBP) {

                                self.orderIDData.removeAtIndex(repcount)
                                self.ItemNoData.removeAtIndex(repcount)
                                self.BPnoData.removeAtIndex(repcount)
                                self.QuantityData.removeAtIndex(repcount)

                                //i = 0;
                        } else {
                                repcount++
                            }

                        }while (repcount < self.orderIDData.count)

//                        for (var i = 0; i < self.orderIDData.count + 1; i++ ) {
//                            if(self.BPnoData[i] != self.manualBP) {
//
//                                self.orderIDData.removeAtIndex(i)
//                                self.ItemNoData.removeAtIndex(i)
//                                self.BPnoData.removeAtIndex(i)
//                                self.QuantityData.removeAtIndex(i)
//
//
//                                //i = 0;
//                            }
//                            print(i)
//
//                        }
                        self.tblview.reloadData()

                    } else if (textField.text == "") {
                        alert.title = "No bp number entered!"
                        alert.message = "Blank entry not allowed!"
                        self.presentViewController(alert, animated: true, completion: nil)

                   } else if ((textField.text?.characters.count)! < 6) {
                        alert.title = "BP number entered is too short!"
                        alert.message = "Please try again!"
                        self.presentViewController(alert, animated: true, completion: nil)
                    }else if ((textField.text?.characters.count)! > 43) {
                        alert.title = "BP number entered is too long!"
                        alert.message = "Please try again!"
                        self.presentViewController(alert, animated: true, completion: nil)
                    }else if (!self.BPnoData.contains(self.manualBP)) {
                        alert.title = "BP number entered is not a valid one!"
                        alert.message = "Please try again!"
                        self.presentViewController(alert, animated: true, completion: nil)
                    }

                }))

                let noAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil)
                alert.addAction(noAction)

                // 4. Present the alert.
                self.presentViewController(alert, animated: true, completion: nil)

            //})
            //alertController.addAction(manEnt)

//            let okAction = UIAlertAction(title: "By Scan", style: UIAlertActionStyle.Default, handler: {(alert :UIAlertAction!) in
//
//                self.performSegueWithIdentifier("byscan", sender: self)
//            })
//            alertController.addAction(okAction)

//            let noAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: nil)
//            alertController.addAction(noAction)
//
//            self.presentViewController(alertController, animated: true, completion: nil)

        })

        let saveAction = UIAlertAction(title: "Clear Filter", style: .Default, handler: {
            (alert: UIAlertAction!) -> Void in

            self.orderIDData.removeAll()
            self.ItemNoData.removeAll()
            self.BPnoData.removeAll()
            self.QuantityData.removeAll()
            self.tblview.reloadData()
            self.get_data_from_url("http://x.x.x/sfc/orders.php")

        })

        //
        let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: {
            (alert: UIAlertAction!) -> Void in
            print("Cancelled");
        })

        // 4
        optionMenu.addAction(BPAction)
        optionMenu.addAction(saveAction)
        optionMenu.addAction(cancelAction)

        // 5
        self.presentViewController(optionMenu, animated: true, completion: nil)

    }

    @IBOutlet weak var tblview: UITableView!;

    var orderIDData:Array< String > = Array < String >()
    var ItemNoData:Array< String > = Array < String >()
    var BPnoData:Array< String > = Array < String >()
    var QuantityData:Array< String > = Array < String >()

    var filteredOrder = [orderitem]()

    override func viewDidLoad() {
        super.viewDidLoad()
        get_data_from_url("http://x.x.x/sfc/orders.php")

        tblview.tableFooterView = UIView(frame:CGRectZero)

        tblview.backgroundColor = .clearColor()
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return orderIDData.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! OrderViewCell
        //print(indexPath.row)
        cell.orderLabel.text = orderIDData[indexPath.row]
        cell.lblitem.text = ItemNoData[indexPath.row]
        cell.lblbp.text = BPnoData[indexPath.row]
        cell.lblquantity.text = QuantityData[indexPath.row]

        //cell.backgroundColor = UIColor.clearColor()

        cell.setTransparent()

        return cell
    }

    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            deleteOrderIndexPath = indexPath
            let OrderToDelete = orderIDData[indexPath.row]
            confirmDelete(OrderToDelete)
        }
    }

    // Delete Confirmation and Handling
    func confirmDelete(planet: String) {
        let alert = UIAlertController(title: "Delete Order", message: "Are you sure you want to permanently delete order \(planet)?", preferredStyle: .ActionSheet)

        let DeleteAction = UIAlertAction(title: "Delete", style: .Destructive, handler: handleDeletePlanet)
        let CancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: cancelDeleteOrder)

        alert.addAction(DeleteAction)
        alert.addAction(CancelAction)

        self.presentViewController(alert, animated: true, completion: nil)
    }

    func handleDeletePlanet(alertAction: UIAlertAction!) -> Void {
        if let indexPath = deleteOrderIndexPath {
            tblview.beginUpdates()

            let OrderNo = orderIDData[indexPath.row];

            let myUrl = NSURL(string: "http://x.x.x/sfc/deleteorder.php");let request = NSMutableURLRequest(URL:myUrl!);
            request.HTTPMethod = "POST";

            // Compose a query string

            let postString = "OrderNo=\(OrderNo)";

            request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

            let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
                data, response, error in

                if error != nil
                {
                    print("error=\(error)")
                    return
                }

                // You can print out response object
                print("response = \(response)")

                // Print out response body
                let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("responseString = \(responseString)")

                //Let's convert response sent from a server side script to a NSDictionary object:

                //var err: NSError?
                let myJSON = try! NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary

                if let parseJSON = myJSON {
                    let resultValue = parseJSON["status"] as? String!;

                    print("result: \(resultValue)");
                    var isOrderDeleted:Bool = false;

                    if (resultValue == "Success") {isOrderDeleted = true;}

                    var DisplayMessage: String = parseJSON["message"] as! String!;
                    if (!isOrderDeleted) {
                        DisplayMessage = parseJSON["message"] as! String!
                    }

                    dispatch_async(dispatch_get_main_queue(), {
                        let alerting = UIAlertController(title:"Alert", message:DisplayMessage, preferredStyle: UIAlertControllerStyle.Alert);

                        let ok = UIAlertAction(title: "Ok", style:UIAlertActionStyle.Default, handler: nil)

                        alerting.addAction(ok);
                        self.presentViewController(alerting, animated: true, completion: nil)
                    });

                }

            }

            task.resume()

            orderIDData.removeAtIndex(indexPath.row)
            ItemNoData.removeAtIndex(indexPath.row)
            BPnoData.removeAtIndex(indexPath.row)
            QuantityData.removeAtIndex(indexPath.row)

            // Note that indexPath is wrapped in an array:  [indexPath]
            tblview.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)

            deleteOrderIndexPath = nil

            tblview.endUpdates()
        }
    }

    func cancelDeleteOrder(alertAction: UIAlertAction!) {
        deleteOrderIndexPath = nil
    }

    func get_data_from_url(url:String)
    {
//        let httpMethod = "GET"
//
//        let url = NSURL(string: url)
//        let urlRequest = NSMutableURLRequest(URL: url!,
//            cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
//            timeoutInterval: 15.0)
//        let queue = NSOperationQueue()
//        NSURLConnection.sendAsynchronousRequest(
//            urlRequest,
//            queue: queue,
//            completionHandler: {(response: NSURLResponse?,
//                data: NSData?,
//                error: NSError?) in
//                if data!.length > 0 && error == nil{
//                    let json = NSString(data: data!, encoding: NSASCIIStringEncoding)
//                    self.extract_json(json!)
//                }else if data!.length == 0 && error == nil{
//                    print("Nothing was downloaded")
//                } else if error != nil{
//                    print("Error happened = \(error)")
//                }
//            }
//        )

        let url : NSURL = NSURL(string: url)!
        let request: NSURLRequest = NSURLRequest(URL: url)
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: config)

        let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in

            let json = NSString(data: data!, encoding: NSASCIIStringEncoding)
            self.extract_json(json!)

        });

        task.resume()

    }

    func extract_json(data:NSString)
    {
        //let parseError: NSError?
        let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!
        let json: AnyObject? = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableContainers)

            if let orders_list = json as? NSArray
            {
                for (var i = 0; i < orders_list.count ; i++ )
                {
                    if let orders_obj = orders_list[i] as? NSDictionary
                    {
                        if let order_id = orders_obj["OrderID"] as? String
                        {

                            if let order_ItemNo = orders_obj["ItemNo"] as? String
                            {
                                if let order_bpNo = orders_obj["BPno"] as? String
                                {
                                    if let order_quantity = orders_obj["Quantity"] as? String
                                    {
                                    //TableData.append(order_id + " [" + order_ItemNo + "]")

                                    orderIDData.append(order_id)
                                    ItemNoData.append(order_ItemNo)
                                    BPnoData.append(order_bpNo)
                                    QuantityData.append(order_quantity)
                                    }
                                }
                            }
                        }
                    }
                }
            }
        do_table_refresh();
    }

    func do_table_refresh()
    {
        dispatch_async(dispatch_get_main_queue(), {
            self.tblview.reloadData()
            return
        })
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

}

Here is a link to a nice tutorial by Tom Elliot:
https://www.raywenderlich.com/157864/uisearchcontroller-tutorial-getting-started


text:
Q: API Gateway Custom headers won't persist I'd like to add a custom header to an API Gateway resource. I select the resource on API Gateway and select Enable CORS. Then add custom-header to the Access-Control-Allow-Headers comma separated list. No matter what I do I can't save the new custom header to Api gateway.  I'm following the Amplify documentation.
'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,my-custom-header'. Api gateway shows successfully added. But when I go back to enable CORS I don't see the update. I have also redeployed the api, but it still does not reflect the new change.

A: This can also be thrown when the API call is not authorized properly. The CORS errors can be shown even if it is not a CORS error.
I had the same issue in trying to use amplify with an existing API gateway. I used the following article to help fix this issue. https://www.qloudx.com/using-angular-to-invoke-apis-hosted-on-amazon-api-gateway-secured-using-cognito-user-pools/?unapproved=53&moderation-hash=3e2d91efec236374c2e551b5810590f8#comment-53
If might not be the solution you are looking for but does help you get moving in the right direction.


text:
Q: How can I use JSOUP in a JSP file to get the number of Google search results? I found a solution here but It is in java format and I want to use it in a jsp file internally. My code is like this but it shows null when loaded in localhost tomcat:
<html>
<head>
  <title>Number of Google Search Results</title>
</head>
<body>
<%@ page import="org.jsoup.Jsoup" %>
<%@ page import="org.jsoup.nodes.Document" %>
<%@ page import="org.jsoup.nodes.Element" %>
<%@ page import="org.jsoup.select.Elements" %>
<%
String url = "https://www.google.com/search?q=query";
Document document = Jsoup //
                   .connect(url) //
                   .userAgent("Mozilla/5.0 (Windows; U; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)") //
                   .get();
Element divResultStats = document.select("div#result-stats").first();
%>
<% out.print(divResultStats); %>
</body>
</html>


text:
Q: Delete not working in hibernate I am using mysql. Following query is working in mysql browser but when I use this query in hibernate it gives me exception near inner select like:
unexpected token: ( near line 1, column 104

This is giving error on second select clause.
Query is :
delete from table
where columnA in (
  select columnA
  from (
      select columnA
      from table
      group by columnA
      having count(*) > 1
      ) t
)

Do anyone have idea why this is so and how to resolve that?

A: Your alias 't' is never used. Simply try this :)
DELETE FROM table
WHERE columnA IN (SELECT columnA
      FROM table
      GROUP BY columnA
      HAVING COUNT(*) > 1);

If you are dealing with Hibernate try to use Hibernate Query Language (HQL). For example, we use HQL to delete entities with more flexibility, such as removing products whose prices are greater than a specified amount.
Query query = session.createQuery("delete Product where price > :maxPrice");
query.setParameter("maxPrice", new Float(1000f));

int result = query.executeUpdate();

if (result > 0) {
    System.out.println("Expensive products was removed");
}

You can also use method execute(HibernateCallback action) from class HibernateTemplate. It could look like this:
final Criterion criteria;
HibernateTemplate template;
template.execute(new HibernateCallback() {
    @Override
    public Object doInHibernate(Session session) throws HibernateException, SQLException {
        List toDelete = session.createCriteria(Student.class).add(criteria).list();
        for (Object o: toDelete){
            session.delete(o);
        }
    }
});

IMHO this solution is not very efficient, because you must read all entries before you remove them. What is more you must remove each entry individually, which is very unefficient.


text:
Q: Cannot import typings for Proxy I am trying to import the type information for Proxy, see picture:

It looks like it's located at lib.es6.d.ts, but when I try to select that, I get:

Anybody see a similar issue with Proxy and Webstorm? I have seen it many times, finally asking about it.

A: Typescript varies in what it actually allows, based on what output language version you specify. If you tell Typescript that you want to output code compatible with ES5 for instance, it will not load the lib.es6.d.ts definitions, because you haven't told it you'll be running in an environment that supports that stuff. For instance see Typescript- What is target in tsconfig? and Need clarification of the target and lib compiler options.
In your case, since Proxy only exists on modern environments, I'm assuming that you never expect your code to work on older environments. Based on that assumption, you should be safe in telling Typescript
target: 'es6'

in your Typescript configuration.

A: Alright so I can get it to compile like so (in my case using Function as the return type):
   const getProxy = function (method: Function, rule: Object, props?: Array<string>): Function {

        return new Proxy(method, {
          get: function (target, prop) {
               return function(){ }  // everytime, a function is returned.
          }
       });

   }

so that seems to work for me for the moment.


text:
Q: Validation Box, a bit hard User must click a service from a column. Code in function is too big and propietary, cant modify, code is working fine, this is the important part.
    this.addDeliveredServicePressed = function() {
        //big code ...............................
        //Important bit ORIGINAL

        var rowCallback = function(nRow, aData, iDisplayIndex) {
          /* Set onclick action */
          nRow.onclick = deliveredServiceClicked;
          return nRow;
          //Follow up code...
        }
    };

When clicking on a row, it calls a function deliveredServiceClicked, which does something, then returns it and the follow up code, builds the table.
I used a Jquery function in the rowCallback function with a Jquery Plugin, the problem is boss want the "box" to "EXACTLY" match the css style of the other boxes on the webpage. So what i did was create some kind of "bridge" on nRow.onclick, to call an HTML DIV with the YES/NO option (i did this to use the CSS classes already created), the No option is a close function, the YES function, should run a function that changes a global variable so it validates and run the nRow.onclick=deliveredServiceClicked;
This is the Primary Function after i changed it.
   this.addDeliveredServicePressed = function() {
      var rowCallback = function(nRow, aData, iDisplayIndex) {
         /* Set onclick action */
         if (confirmedglobal==1){
            alert("serviceclicked");
            nRow.onclick = deliveredServiceClicked;
            confirmedglobal=0;
           //This confirmedglobal=0, puts the global back to 0 so after the first YES it resets it back to 0, so it keeps asking.
            return nRow;
         }else if (confirmedglobal==0){
            //This is the redirect to the HTML dialogue, using some util
            nRow.onclick = ConfirmService;
         }
      };

This is my function for the YES onclick
   this.Confirmed = function (){
      confirmedglobal = 1;
      addDeliveredServicePressed();
       //diag box close util to be added, not now
   }

So to resume this function, in my plan, should put the global on 1, and then execute function addDeliveredServicePressed, which is the main function, from the start so it updates the marks that i want. What it is doing right now is setting the global to 1, but its NOT going to addDeliver.... so it changes the global, but nothing happens, when i close and open again it no longers ask for YES NO, but it adds and builds the table perfectly fine.
So my question is this, why is addDeliveredServicePressed(); on my Confirmed function not being executed, what other approach for this would you use??, ive think about a lot of options and i came with global variable and the if as the better solution even tho global variables are not the best option.
In any case im a noob in js. so its not like im probably not missing anything
FOLLOW UP TO QUESTION
on the same js there is only this more
   deliveredServicesTable = $('#deliveredServices').dataTable( {
        "bDestroy": true,
        "oLanguage": {
            "sEmptyTable": translate.msg("info.no.delivered.services"),
            "sInfo": "",
            "sInfoEmpty": "",
            "sZeroRecords": ""
        },
        "bFilter": false,
        "fnRowCallback": rowCallback,
        "fnHeaderCallback": headerCallback,
        "bLengthChange": false,
        "bProcessing": true,
        "bPaginate": false,
        "aoColumns": columns,
        "sScrollX": "95%",
        "sScrollY": "158px",
        "aaData": (sessvars.state.visit != null &&
            sessvars.state.visit.currentVisitService != null &&
            sessvars.state.visit.currentVisitService.visitDeliveredServices !== null ?
            sessvars.state.visit.currentVisitService.visitDeliveredServices : null)
    });
    $(window).bind('resize', function () {
        deliveredServicesTable.fnAdjustColumnSizing();
    } );
}

and on a file called "jquery.datatables.js" there is like a jquery plugin for some use on functions but i think i dont need anything from there, and its like a 35k lines code, and there are multiple functions
/**
 * This function allows you to 'post process' each row after it have been
 * generated for each table draw, but before it is rendered on screen. This
 * function might be used for setting the row class name etc.
 *  @type function
 *  @param {node} nRow "TR" element for the current row
 *  @param {array} aData Raw data array for this row
 *  @param {int} iDisplayIndex The display index for the current table draw
 *  @param {int} iDisplayIndexFull The index of the data in the full list of
 *    rows (after filtering)
 *  @dtopt Callbacks
 *
 *  @example
 *    $(document).ready(function() {
 *      $('#example').dataTable( {
 *        "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
 *          // Bold the grade for all 'A' grade browsers
 *          if ( aData[4] == "A" )
 *          {
 *            $('td:eq(4)', nRow).html( '<b>A</b>' );
 *          }
 *        }
 *      } );
 *    } );
 */
"fnRowCallback": null,


text:
Q: After Binded Spinner , How to Do not select first item? public void DatabaseConn(){
DataBaseHelper myDbHelper = new DataBaseHelper(this.getApplicationContext());
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}

SQLiteDatabase db = myDbHelper.getReadableDatabase();
//SQLiteDatabase db = SQLiteDatabase.openDatabase("/data/data/com.example.abc2/databases/DB_BusData", null, 0);
Cursor c = db.rawQuery("SELECT * FROM Tbl_Driver", null);
startManagingCursor(c);
//create an array to specify which fields we want to display
String[] from = new String[]{"Driver_Name"};
//create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
//create simple cursor adapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
//get reference to our spinner
Spinner s = (Spinner) findViewById( R.id.DriverSpin);
s.setAdapter(adapter);

db.close();
}

This is the code how i bind my Spinner with my DataBase,
But After Binded Spinner, will automatically selected first item,
i would like to let User select the Spinner by themself, how to do with this?

A: read this documentation page: http://developer.android.com/reference/android/widget/AbsSpinner.html

A: Just add a default selection after populating the spinner something like --select driver-- then do a check in your listener to not do anything when the spinner position is 0

A: SQLiteDatabase db = myDbHelper.getReadableDatabase();
//SQLiteDatabase db = SQLiteDatabase.openDatabase("/data/data/com.example.abc2/databases/DB_BusData", null, 0);
Cursor c = db.rawQuery("SELECT * FROM Tbl_Vehicle", null);
//=====Add Additional=====
MatrixCursor extras = new MatrixCursor(new String[] { "_id", "Plat_No" });
extras.addRow(new String[] { "-1","< Select Vehicle >" });
Cursor[] cursors = { extras, c };
c = new MergeCursor(cursors);
//===========================

Just Add the First Items as blank or i have added "< Select Vehicle >" as the first item


text:
Q: JAVA SAX parsing into hash map and printing out I don't know if I'm parsing in correctly or if i'm printing out incorrectly from a the hashmap?  I think i must be parsing incorrectly because when I check the values I get null.
main.java
public static void main(String[] args) throws Exception
    {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        xr.setContentHandler(new DrugbankHandler());
        xr.parse("c:\\drugbank.xml");
      System.out.println(DrugbankHandler.lookupCache);
       // DrugbankHandler.printMap();

contenthandler.java
public class DrugbankHandler implements ContentHandler {

    boolean drugFound;
    boolean nameFound;
    boolean drugInteraction;
    boolean drugID;
    boolean packager;
    boolean calculatedProperties;
    boolean kindFound;
    boolean inChiKeyValueFound;
    boolean nextValueIsInChiKey;
    boolean isSmallMolecule;
    boolean property;
    boolean previousTagWasDrugID;

    DrugModel tempDrugModel;

    /**
     * stores key (drugbank-id), value (drug model) pairs
     */
    public final static  HashMap<String, DrugModel> lookupCache = new HashMap<String, DrugModel>(
            7000);

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes atts) throws SAXException {

        //System.out.print(atts);
        if (tempDrugModel != null && tempDrugModel.drugbankID.equals("DB00002")) {
            System.out.println(localName);
            if (localName.equals("value")) {
                System.out.print("");
            }
        }

        if (localName.equals("drug-interaction")) {
            drugInteraction = true;
            return;
        }

        if (localName.equals("drug") && !drugInteraction
                && atts.getLength() > 0) {
            if (atts.getValue("type").equals("biotech"))
                return;
            drugFound = true;
            tempDrugModel = new DrugModel();
            String type = atts.getValue("type");
            if (type.startsWith("small"))
                isSmallMolecule = true;
            else
                isSmallMolecule = false;

            tempDrugModel.isSmallMolecule = isSmallMolecule;

            return;
        }
        if (localName.equals("drugbank-id")) {
            drugID = true;
            return;
        }
        if (previousTagWasDrugID && localName.equals("name")) {
            nameFound = true;
            return;
        }
        // if drug is a small molecule read its InChIKey value
        /**
         * <calculated-properties> <property> <kind>InChI</kind>
         * <value>InChIKey=hurensohn</value> <source>JChem</source> </property>
         * .... </calculated-properties>
         */
        if (isSmallMolecule) {
            if (calculatedProperties && localName.equals("property")) {
                property = true;
                return;
            }
            if (property && localName.equals("kind")) {
                kindFound = true;
                return;
            }
            if (localName.equals("calculated-properties")) {
                calculatedProperties = true;
                return;
            }
            if (nextValueIsInChiKey && localName.equals("value")) {
                inChiKeyValueFound = true;
                nextValueIsInChiKey = false;
                return;
            }
        } else {
            // TODO which id or feature to lookup peptides in chembl?
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if (drugFound && !drugInteraction && localName.equals("drug")) {
            drugFound = false;
            lookupCache.put(tempDrugModel.drugbankID, tempDrugModel);
            return;
        }

        if (localName.equals("drugbank-id")) {
            previousTagWasDrugID = true;
        }
        if (localName.equals("drug-interaction")) {
            drugInteraction = false;
        }
    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        if (!drugFound)
            return;

        if (nameFound) {
            tempDrugModel.name = new String(ch, start, length);
            previousTagWasDrugID = false;
            nameFound = false;
            return;
        }
        if (drugID) {
            tempDrugModel.drugbankID = new String(ch, start, length);
            drugID = false;
            return;
        }
        if (kindFound) {
            String kind = new String(ch, start, length);
            if (kind.equals("InChIKey")) {
                nextValueIsInChiKey = true;
            }
            kindFound = false;
            return;
        }
        if (inChiKeyValueFound) {
            // skip the "InChIKey=" prefix of length 9
            String k = new String(ch, start + 9, length - 9);
            tempDrugModel.InChiKey = k;
            inChiKeyValueFound = false;
            return;
        }
    }

    public static void printMap() {
        /*Iterator it = lookupCache.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Integer key = (Integer)entry.getKey();
            String val = (String)entry.getValue();

            System.out.println(lookupCache);

        }*/
         System.out.println(lookupCache);
 }
    // ignored methods following...

    @Override
    public void ignorableWhitespace(char[] ch, int start, int length)
            throws SAXException {
    }

    @Override
    public void processingInstruction(String target, String data)
            throws SAXException {
    }

    @Override
    public void skippedEntity(String name) throws SAXException {
    }

    @Override
    public void setDocumentLocator(Locator locator) {
    }

    @Override
    public void startDocument() throws SAXException {
    }

    @Override
    public void endDocument() throws SAXException {
    }

    @Override
    public void startPrefixMapping(String prefix, String uri)
            throws SAXException {
    }

    @Override
    public void endPrefixMapping(String prefix) throws SAXException {
    }
}

sample xml
<?xml version="1.0" encoding="UTF-8"?>
<drugs xmlns="http://drugbank.ca" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" schemaVersion="2.0" xs:schemaLocation="http://www.drugbank.ca/docs/drugbank.xsd">
<drug type="biotech" created="2005-06-13 07:24:05 -0600" updated="2013-05-12 21:37:25 -0600" version="4.0">
  <drugbank-id>DB00001</drugbank-id>
  <name>Lepirudin</name>
  <description>Lepirudin is identical to natural hirudin except for substitution of leucine for isoleucine at the N-terminal end of the molecule and the absence of a sulfate group on the tyrosine at position 63. It is produced via yeast cells.
</description>
  <cas-number>120993-53-5</cas-number>
  <general-references># Smythe MA, Stephens JL, Koerber JM, Mattson JC: A comparison of lepirudin and argatroban outcomes. Clin Appl Thromb Hemost. 2005 Oct;11(4):371-4. "Pubmed":http://www.ncbi.nlm.nih.gov/pubmed/16244762
# Tardy B, Lecompte T, Boelhen F, Tardy-Poncet B, Elalamy I, Morange P, Gruel Y, Wolf M, Francois D, Racadot E, Camarasa P, Blouch MT, Nguyen F, Doubine S, Dutrillaux F, Alhenc-Gelas M, Martin-Toutain I, Bauters A, Ffrench P, de Maistre E, Grunebaum L, Mouton C, Huisse MG, Gouault-Heilmann M, Lucke V: Predictive factors for thrombosis and major bleeding in an observational study in 181 patients with heparin-induced thrombocytopenia treated with lepirudin. Blood. 2006 Sep 1;108(5):1492-6. Epub 2006 May 11. "Pubmed":http://www.ncbi.nlm.nih.gov/pubmed/16690967
# Lubenow N, Eichler P, Lietz T, Greinacher A: Lepirudin in patients with heparin-induced thrombocytopenia - results of the third prospective study (HAT-3) and a combined analysis of HAT-1, HAT-2, and HAT-3. J Thromb Haemost. 2005 Nov;3(11):2428-36. "Pubmed":http://www.ncbi.nlm.nih.gov/pubmed/16241940
# Askari AT, Lincoff AM: Antithrombotic Drug Therapy in Cardiovascular Disease. 2009 Oct; pp. 440–. ISBN 9781603272346. "Google books":http://books.google.com/books?id=iadLoXoQkWEC&pg=PA440. </general-references>
  <synthesis-reference/>
  <indication>For the treatment of heparin-induced thrombocytopenia</indication>
  <pharmacology>Lepirudin is used to break up clots and to reduce thrombocytopenia. It binds to thrombin and prevents thrombus or clot formation. It is a highly potent, selective, and essentially irreversible inhibitor of thrombin and clot-bond thrombin. Lepirudin requires no cofactor for its anticoagulant action. Lepirudin is a recombinant form of hirudin, an endogenous anticoagulant found in medicinal leeches.</pharmacology>
  <mechanism-of-action>Lepirudin forms a stable non-covalent complex with alpha-thrombin, thereby abolishing its ability to cleave fibrinogen and initiate the clotting cascade. The inhibition of thrombin prevents the blood clotting cascade. </mechanism-of-action>
  <toxicity>In case of overdose (eg, suggested by excessively high aPTT values) the risk of bleeding is increased.</toxicity>
  <biotransformation>Lepirudin is thought to be metabolized by release of amino acids via catabolic hydrolysis of the parent drug. However, con-clusive data are not available. About 48% of the administration dose is excreted in the urine which consists of unchanged drug (35%) and other fragments of the parent drug.</biotransformation>
  <absorption>Bioavailability is 100% following injection.</absorption>
  <half-life>Approximately 1.3 hours</half-life>
  <protein-binding/>
  <route-of-elimination>Lepirudin is thought to be metabolized by release of amino acids via catabolic hydrolysis of the parent drug. About 48% of the administration dose is excreted in the urine which consists of unchanged drug (35%) and other fragments of the parent drug.</route-of-elimination>
  <volume-of-distribution>* 12.2 L [Healthy young subjects (n = 18, age 18-60 years)]
* 18.7 L [Healthy elderly subjects (n = 10, age 65-80 years)]
* 18 L [Renally impaired patients (n = 16, creatinine clearance below 80 mL/min)]
* 32.1 L [HIT patients (n = 73)]</volume-of-distribution>
  <clearance>* 164 ml/min [Healthy 18-60 yrs]
* 139 ml/min [Healthy 65-80 yrs]
* 61 ml/min [renal impaired]
* 114 ml/min [HIT (Heparin-induced thrombocytopenia)]</clearance>
  <secondary-accession-numbers>
    <secondary-accession-number>BIOD00024</secondary-accession-number>
    <secondary-accession-number>BTD00024</secondary-accession-number>
  </secondary-accession-numbers>
  <groups>
    <group>approved</group>
  </groups>
  <taxonomy>
    <kingdom/>
    <substructures/>
  </taxonomy>
  <synonyms>
    <synonym>Hirudin variant-1</synonym>
  </synonyms>
  <salts/>
  <brands>
    <brand>Refludan</brand>
  </brands>
  <mixtures/>
  <packagers>
    <packager>
      <name>Bayer Healthcare</name>
      <url>http://www.bayerhealthcare.com</url>
    </packager>
    <packager>
      <name>Berlex Labs</name>
      <url>http://www.berlex.com</url>
    </packager>
  </packagers>
  <manufacturers>
    <manufacturer generic="false">Bayer healthcare pharmaceuticals inc</manufacturer>
  </manufacturers>
  <prices>
    <price>
      <description>Refludan 50 mg vial</description>
      <cost currency="USD">273.19</cost>
      <unit>vial</unit>
    </price>
  </prices>
  <categories>
    <category>Antithrombins</category>
    <category>Fibrinolytic Agents</category>
  </categories>
  <affected-organisms>
    <affected-organism>Humans and other mammals</affected-organism>
  </affected-organisms>
  <dosages>
    <dosage>
      <form>Powder, for solution</form>
      <route>Intravenous</route>
      <strength/>
    </dosage>
  </dosages>
  <atc-codes>
    <atc-code>B01AE02</atc-code>
    <category/>
  </atc-codes>
  <ahfs-codes>
    <ahfs-code>20:12.04.12</ahfs-code>
  </ahfs-codes>
  <patents>
    <patent>
      <number>5180668</number>
      <country>United States</country>
      <approved>1993-01-19</approved>
      <expires>2010-01-19</expires>
    </patent>
    <patent>
      <number>1339104</number>
      <country>Canada</country>
      <approved>1997-07-29</approved>
      <expires>2014-07-29</expires>
    </patent>
  </patents>
  <food-interactions/>
  <drug-interactions>
    <drug-interaction>
      <drug>DB01381</drug>
      <name>Ginkgo biloba</name>
      <description>Additive anticoagulant/antiplatelet effects may increase bleed risk. Concomitant therapy should be avoided.</description>
    </drug-interaction>
    <drug-interaction>
      <drug>DB00374</drug>
      <name>Treprostinil</name>
      <description>The prostacyclin analogue, Treprostinil, increases the risk of bleeding when combined with the anticoagulant, Lepirudin. Monitor for increased bleeding during concomitant thearpy. </description>
    </drug-interaction>
  </drug-interactions>
  <protein-sequences>
    <fasta>
      <fasta>#<PolypeptideSequence:0x007f1d1efef190></fasta>
    </fasta>
  </protein-sequences>
  <experimental-properties>
    <property>
      <kind>Melting Point</kind>
      <value>65 °C</value>
      <source>Otto, A. & Seckler, R. Eur. J. Biochem. 202:67-73 (1991)</source>
    </property>
    <property>
      <kind>Hydrophobicity</kind>
      <value>-0.777</value>
      <source/>
    </property>
    <property>
      <kind>Isoelectric Point</kind>
      <value>4.04</value>
      <source/>
    </property>
    <property>
      <kind>Molecular Weight</kind>
      <value>6963.4250</value>
      <source/>
    </property>
    <property>
      <kind>Molecular Formula</kind>
      <value>C287H440N80O110S6</value>
      <source/>
    </property>
  </experimental-properties>
  <external-identifiers>
    <external-identifier>
      <resource>Drugs Product Database (DPD)</resource>
      <identifier>2240996</identifier>
    </external-identifier>
    <external-identifier>
      <resource>KEGG Drug</resource>
      <identifier>D06880</identifier>
    </external-identifier>
    <external-identifier>
      <resource>National Drug Code Directory</resource>
      <identifier>50419-150-57</identifier>
    </external-identifier>
    <external-identifier>
      <resource>PharmGKB</resource>
      <identifier>PA450195</identifier>
    </external-identifier>
    <external-identifier>
      <resource>UniProtKB</resource>
      <identifier>P01050</identifier>
    </external-identifier>
    <external-identifier>
      <resource>Wikipedia</resource>
      <identifier>Lepirudin</identifier>
    </external-identifier>
  </external-identifiers>
  <external-links>
    <external-link>
      <resource>RxList</resource>
      <url>http://www.rxlist.com/cgi/generic/lepirudin.htm</url>
    </external-link>
    <external-link>
      <resource>Drugs.com</resource>
      <url>http://www.drugs.com/cdi/lepirudin.html</url>
    </external-link>
  </external-links>
  <targets>
    <target>
      <id>BE0000048</id>
      <name>Prothrombin</name>
      <organism>Human</organism>
      <actions>
        <action>inhibitor</action>
      </actions>
      <references># Turpie AG: Anticoagulants in acute coronary syndromes. Am J Cardiol. 1999 Sep 2;84(5A):2M-6M. "Pubmed":http://www.ncbi.nlm.nih.gov/pubmed/10505536
# Warkentin TE: Venous thromboembolism in heparin-induced thrombocytopenia. Curr Opin Pulm Med. 2000 Jul;6(4):343-51. "Pubmed":http://www.ncbi.nlm.nih.gov/pubmed/10912644
# Eriksson BI: New therapeutic options in deep vein thrombosis prophylaxis. Semin Hematol. 2000 Jul;37(3 Suppl 5):7-9. "Pubmed":http://www.ncbi.nlm.nih.gov/pubmed/11055889
# Fabrizio MC: Use of ecarin clotting time (ECT) with lepirudin therapy in heparin-induced thrombocytopenia and cardiopulmonary bypass. J Extra Corpor Technol. 2001 May;33(2):117-25. "Pubmed":http://www.ncbi.nlm.nih.gov/pubmed/11467439
# Szaba FM, Smiley ST: Roles for thrombin and fibrin(ogen) in cytokine/chemokine production and macrophage adhesion in vivo. Blood. 2002 Feb 1;99(3):1053-9. "Pubmed":http://www.ncbi.nlm.nih.gov/pubmed/11807012
# Chen X, Ji ZL, Chen YZ: TTD: Therapeutic Target Database. Nucleic Acids Res. 2002 Jan 1;30(1):412-5. "Pubmed":http://www.ncbi.nlm.nih.gov/pubmed/11752352</references>
      <known-action>yes</known-action>
      <components>
        <polypeptide id="P00734">
          <name>Prothrombin</name>
          <general-function>Involved in blood clotting cascade</general-function>
          <specific-function>Thrombin, which cleaves bonds after Arg and Lys, converts fibrinogen to fibrin and activates factors V, VII, VIII, XIII, and, in complex with thrombomodulin, protein C</specific-function>
          <gene-name>F2</gene-name>
          <locus>11p11-q12</locus>
          <cellular-location>Secreted protein; extracellular space</cellular-location>
          <transmembrane-regions>None</transmembrane-regions>
          <theoretical-pi>5.7</theoretical-pi>
          <molecular-weight>70037.0</molecular-weight>
          <chromosome-location/>
          <external-identifiers>
            <external-identifier>
              <resource>HUGO Gene Nomenclature Committee (HGNC)</resource>
              <identifier>HGNC:3535</identifier>
            </external-identifier>
            <external-identifier>
              <resource>GenAtlas</resource>
              <identifier>F2</identifier>
            </external-identifier>
            <external-identifier>
              <resource>GeneCards</resource>
              <identifier>F2</identifier>
            </external-identifier>
            <external-identifier>
              <resource>GenBank Gene Database</resource>
              <identifier>M17262</identifier>
            </external-identifier>
            <external-identifier>
              <resource>GenBank Protein Database</resource>
              <identifier>339641</identifier>
            </external-identifier>
            <external-identifier>
              <resource>UniProtKB</resource>
              <identifier>P00734</identifier>
            </external-identifier>
          </external-identifiers>
          <synonyms>
            <synonym>Activated Factor II [IIa]</synonym>
            <synonym>Coagulation factor II</synonym>
            <synonym>EC 3.4.21.5</synonym>
            <synonym>Prothrombin precursor</synonym>
            <synonym>Thrombin</synonym>
          </synonyms>
          <amino-acid-sequence>
            <fasta>>Prothrombin precursor
MAHVRGLQLPGCLALAALCSLVHSQHVFLAPQQARSLLQRVRRANTFLEEVRKGNLEREC
VEETCSYEEAFEALESSTATDVFWAKYTACETARTPRDKLAACLEGNCAEGLGTNYRGHV
NITRSGIECQLWRSRYPHKPEINSTTHPGADLQENFCRNPDSSTTGPWCYTTDPTVRRQE
CSIPVCGQDQVTVAMTPRSEGSSVNLSPPLEQCVPDRGQQYQGRLAVTTHGLPCLAWASA
QAKALSKHQDFNSAVQLVENFCRNPDGDEEGVWCYVAGKPGDFGYCDLNYCEEAVEEETG
DGLDEDSDRAIEGRTATSEYQTFFNPRTFGSGEADCGLRPLFEKKSLEDKTERELLESYI
DGRIVEGSDAEIGMSPWQVMLFRKSPQELLCGASLISDRWVLTAAHCLLYPPWDKNFTEN
DLLVRIGKHSRTRYERNIEKISMLEKIYIHPRYNWRENLDRDIALMKLKKPVAFSDYIHP
VCLPDRETAASLLQAGYKGRVTGWGNLKETWTANVGKGQPSVLQVVNLPIVERPVCKDST
RIRITDNMFCAGYKPDEGKRGDACEGDSGGPFVMKSPFNNRWYQMGIVSWGEGCDRDGKY
GFYTHVFRLKKWIQKVIDQFGE</fasta>
          </amino-acid-sequence>
          <gene-sequence>
            <fasta>>1869 bp
ATGGCGCACGTCCGAGGCTTGCAGCTGCCTGGCTGCCTGGCCCTGGCTGCCCTGTGTAGC
CTTGTGCACAGCCAGCATGTGTTCCTGGCTCCTCAGCAAGCACGGTCGCTGCTCCAGCGG
GTCCGGCGAGCCAACACCTTCTTGGAGGAGGTGCGCAAGGGCAACCTAGAGCGAGAGTGC
GTGGAGGAGACGTGCAGCTACGAGGAGGCCTTCGAGGCTCTGGAGTCCTCCACGGCTACG
GATGTGTTCTGGGCCAAGTACACAGCTTGTGAGACAGCGAGGACGCCTCGAGATAAGCTT
GCTGCATGTCTGGAAGGTAACTGTGCTGAGGGTCTGGGTACGAACTACCGAGGGCATGTG
AACATCACCCGGTCAGGCATTGAGTGCCAGCTATGGAGGAGTCGCTACCCACATAAGCCT
GAAATCAACTCCACTACCCATCCTGGGGCCGACCTACAGGAGAATTTCTGCCGCAACCCC
GACAGCAGCACCACGGGACCCTGGTGCTACACTACAGACCCCACCGTGAGGAGGCAGGAA
TGCAGCATCCCTGTCTGTGGCCAGGATCAAGTCACTGTAGCGATGACTCCACGCTCCGAA
GGCTCCAGTGTGAATCTGTCACCTCCATTGGAGCAGTGTGTCCCTGATCGGGGGCAGCAG
TACCAGGGGCGCCTGGCGGTGACCACACATGGGCTCCCCTGCCTGGCCTGGGCCAGCGCA
CAGGCCAAGGCCCTGAGCAAGCACCAGGACTTCAACTCAGCTGTGCAGCTGGTGGAGAAC
TTCTGCCGCAACCCAGACGGGGATGAGGAGGGCGTGTGGTGCTATGTGGCCGGGAAGCCT
GGCGACTTTGGGTACTGCGACCTCAACTATTGTGAGGAGGCCGTGGAGGAGGAGACAGGA
GATGGGCTGGATGAGGACTCAGACAGGGCCATCGAAGGGCGTACCGCCACCAGTGAGTAC
CAGACTTTCTTCAATCCGAGGACCTTTGGCTCGGGAGAGGCAGACTGTGGGCTGCGACCT
CTGTTCGAGAAGAAGTCGCTGGAGGACAAAACCGAAAGAGAGCTCCTGGAATCCTACATC
GACGGGCGCATTGTGGAGGGCTCGGATGCAGAGATCGGCATGTCACCTTGGCAGGTGATG
CTTTTCCGGAAGAGTCCCCAGGAGCTGCTGTGTGGGGCCAGCCTCATCAGTGACCGCTGG
GTCCTCACCGCCGCCCACTGCCTCCTGTACCCGCCCTGGGACAAGAACTTCACCGAGAAT
GACCTTCTGGTGCGCATTGGCAAGCACTCCCGCACAAGGTACGAGCGAAACATTGAAAAG
ATATCCATGTTGGAAAAGATCTACATCCACCCCAGGTACAACTGGCGGGAGAACCTGGAC
CGGGACATTGCCCTGATGAAGCTGAAGAAGCCTGTTGCCTTCAGTGACTACATTCACCCT
GTGTGTCTGCCCGACAGGGAGACGGCAGCCAGCTTGCTCCAGGCTGGATACAAGGGGCGG
GTGACAGGCTGGGGCAACCTGAAGGAGACGTGGACAGCCAACGTTGGTAAGGGGCAGCCC
AGTGTCCTGCAGGTGGTGAACCTGCCCATTGTGGAGCGGCCGGTCTGCAAGGACTCCACC
CGGATCCGCATCACTGACAACATGTTCTGTGCTGGTTACAAGCCTGATGAAGGGAAACGA
GGGGATGCCTGTGAAGGTGACAGTGGGGGACCCTTTGTCATGAAGAGCCCCTTTAACAAC
CGCTGGTATCAAATGGGCATCGTCTCATGGGGTGAAGGCTGTGACCGGGATGGGAAATAT
GGCTTCTACACACATGTGTTCCGCCTGAAGAAGTGGATACAGAAGGTCATTGATCAGTTT
GGAGAGTAG</fasta>
          </gene-sequence>
          <pfams>
            <pfam>
              <identifier>PF00594</identifier>
              <name>Gla</name>
            </pfam>
            <pfam>
              <identifier>PF00051</identifier>
              <name>Kringle</name>
            </pfam>
            <pfam>
              <identifier>PF00089</identifier>
              <name>Trypsin</name>
            </pfam>
          </pfams>
          <go-classifiers>
            <go-classifier>
              <id/>
              <category>component</category>
              <description>extracellular region</description>
            </go-classifier>
            <go-classifier>
              <id/>
              <category>function</category>
              <description>binding</description>
            </go-classifier>
            <go-classifier>
              <id/>
              <category>function</category>
              <description>catalytic activity</description>
            </go-classifier>
            <go-classifier>
              <id/>
              <category>function</category>
              <description>thrombin activity</description>
            </go-classifier>
            <go-classifier>
              <id/>
              <category>function</category>
              <description>hydrolase activity</description>
            </go-classifier>
            <go-classifier>
              <id/>
              <category>function</category>
              <description>calcium ion binding</description>
            </go-classifier>
            <go-classifier>
              <id/>
              <category>function</category>
              <description>peptidase activity</description>
            </go-classifier>
            <go-classifier>
              <id/>
              <category>function</category>
              <description>ion binding</description>
            </go-classifier>
            <go-classifier>
              <id/>
              <category>function</category>
              <description>endopeptidase activity</description>
            </go-classifier>
            <go-classifier>
              <id/>
              <category>function</category>
              <description>cation binding</description>
            </go-classifier>
            <go-classifier>
              <id/>
              <category>function</category>
              <description>serine-type endopeptidase activity</description>
            </go-classifier>
            <go-classifier>
              <id/>
              <category>process</category>
              <description>protein metabolism</description>
            </go-classifier>
            <go-classifier>
              <id/>
              <category>process</category>
              <description>proteolysis</description>
            </go-classifier>
            <go-classifier>
              <id/>
              <category>process</category>
              <description>cellular protein metabolism</description>
            </go-classifier>
            <go-classifier>
              <id/>
              <category>process</category>
              <description>organismal physiological process</description>
            </go-classifier>
            <go-classifier>
              <id/>
              <category>process</category>
              <description>regulation of body fluids</description>
            </go-classifier>
            <go-classifier>
              <id/>
              <category>process</category>
              <description>physiological process</description>
            </go-classifier>
            <go-classifier>
              <id/>
              <category>process</category>
              <description>hemostasis</description>
            </go-classifier>
            <go-classifier>
              <id/>
              <category>process</category>
              <description>blood coagulation</description>
            </go-classifier>
            <go-classifier>
              <id/>
              <category>process</category>
              <description>metabolism</description>
            </go-classifier>
            <go-classifier>
              <id/>
              <category>process</category>
              <description>macromolecule metabolism</description>
            </go-classifier>
          </go-classifiers>
        </polypeptide>
      </components>
    </target>
  </targets>
  <enzymes/>
  <carriers/>
  <transporters/>

A: Have you tried defining an XSD schema for the XML and using a JaxBContentHandler?
In my opinion is a much better implementation because:

*

*You can also retrieve the results from the POJO objects you have unmarshalled.

*If the XML format changes, you will only have to change the XSD schema and regenerate the POJO classes.
Only drawback I have seen is performance unmarshalling very big XML files.
Sample:
    // Create a JAXB context from the POJO classes (you should have defined the XSD before)
    final JAXBContext context = JAXBContext.newInstance(Drugs.class);

    Unmarshaller unmarshaller;
    unmarshaller = context.createUnmarshaller();
    unmarshaller.setSchema(null);
    // create a new XML parser
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    XMLReader reader = factory.newSAXParser().getXMLReader();

    // JAXB marshaller
    reader.setContentHandler(unmarshaller.getUnmarshallerHandler());

    // This is the buffer from you are reading (i.e. this can be the XML file)
    reader.parse(new InputSource(inputBuffer));

    Drugs result = (Drugs) marshaller.getUnmarshallerHandler().getResult();
    // Now you can build a hashmap with the drugs you have retrieved


text:
Q: What is the shortcut to hide the navigator view in Apple Keynote? I want to show only the slide, without the left-side slide thumbnails in the Navigator View. How can this view be made hidden?
I am on Keynote version 7.3.1 (5249)
Thanks

A: Note that Navigatior View is designed to show the thumbnails for navigation.  Slide Only view shows only the slide without the thumbnails.
There is no built in shortcut to change views.  However, a custom keyboard shortcut can be added in the System Preferences.
To create a shortcut:

*

*Go to System Preferences

*Keyboard

*Shortcuts Tab

*Select App Shortcuts in the left pane

*Click the Plus button

*Set Application to Keynote from the dropdown

*Type the Menu command EXACTLY as it appears in the menu

*Choose a key combination

Now you can change view with custom shortcut.

Adding custom shortcut:

Switching views:


text:
Q: after Git OverWrite master branch with another branch, did all history get deleted for master branch ? after Git OverWrite master branch with another branch, did all history get deleted for master branch ?
I want to overwrite another branch with master branch but same time I wanted to keep all commit history for master, is that possible?


text:
Q: make circular checkbox using jquery using xml reading of contents of a particular thing i am adding checkboxes and its description.But the problem is that i want visual of my checkbox like radiobutton but it should work like checkbox.I mean i can check and uncheck it.Moreover on space of tick(in checkboxes),it should be dot(may be of any color if possible).
$(xml).find("Layer[Name='"+layerName+"']").find("IndustryComponent").each(function()
            {
                var layerDesciption= $(this).attr('Name');
                if($(this).is(':empty'))
                {
                    $(".InsideLayerContainer").append("<input type='checkbox' name='' value='' disabled='true'>"+layerDesciption+"
");
                }
                else
                {
                    $(".InsideLayerContainer").append("<input type='checkbox' name='' value=''>"+layerDesciption+"
");
                }
            });

A: UPDATE
Check this DEMO http://jsfiddle.net/yeyene/Xqr4n/2/
HTML
<input class="myCheck" type="checkbox" name="vehicle" value="Bike">check 1

<input class="myCheck" type="checkbox" name="vehicle" value="Bike">check 2

<input class="myCheck" type="checkbox" name="vehicle" value="Bike">check 3

JQUERY
$('input[type=checkbox]').each(function(){
    $(this).wrap('');
});

$('.circle').on("click", function(){
    if($(this).css("background-color") == 'rgb(223, 223, 223)') {
        $(this).find('.myCheck').prop('checked', true);
        $(this).css({'background-color':'rgb(0, 64, 212)'});
    }
    else {
        $(this).find('.myCheck').prop('checked', false);
        $(this).css({'background-color':'rgb(223, 223, 223)'});
    }
});

A: You need to use a image overlay for that.
Create two images one for unchecked view and one for checked view then based on the click value update a hidden checkbox and change the visible image also

A: I wouldn't really recommend it, but you can always make radio buttons work like checkboxes, if that's what you're really after ?
$('input[type="radio"]').on('click', function() {
    this.checked = !$(this).data('checked')
    $(this).data('checked', !$(this).data('checked'));
});

FIDDLE