Programs & Examples On #Receiver

Flutter - The method was called on null

As stated in the above answers, it's always a good practice to initialize the variables, but if you have something which you don't know what value should it takes, and you want to leave it uninitialized so you have to make sure that you are updating it before using it.

For example: Assume we have double _bmi; and you don't know what value should it takes, so you can leave it as it is, but before using it, you have to update its value first like calling a function that calculating BMI like follows:

String calculateBMI (){
_bmi = weight / pow( height/100, 2);
return _bmi.toStringAsFixed(1);}

or whatever, what I mean is, you can leave the variable as it is, but before using it make sure you have initialized it using whatever the method you are using.

Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

stream = activity.getContentResolver().openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;

bitmap = BitmapFactory.decodeStream(stream, null, options);
int Height = bitmap.getHeight();
int Width = bitmap.getWidth();
enter code here
int newHeight = 1000;
float scaleFactor = ((float) newHeight) / Height;
float newWidth = Width * scaleFactor;

float scaleWidth = scaleFactor;
float scaleHeight = scaleFactor;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
resizedBitmap= Bitmap.createBitmap(bitmap, 0, 0,Width, Height, matrix, true);
bitmap.recycle();

Then in Appliaction tag, add largeheapsize="true

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

Thanks to @Bolling idea I have implement to support to avoid any nullable from List

public void setList(ArrayList<ThisIsAdapterListObject> _newList) {
    //get the current items
    if (ThisIsAdapterList != null) {
        int currentSize = ThisIsAdapterList.size();
        ThisIsAdapterList.clear();
        //tell the recycler view that all the old items are gone
        notifyItemRangeRemoved(0, currentSize);
    }

    if (_newList != null) {
        if (ThisIsAdapterList == null) {
            ThisIsAdapterList = new ArrayList<ThisIsAdapterListObject>();
        }
        ThisIsAdapterList.addAll(_newList);
        //tell the recycler view how many new items we added
        notifyItemRangeInserted(0, _newList.size());
    }
}

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

in your baseadapter class constructor try to initialize LayoutInflater, normally i preferred this way,

public ClassBaseAdapter(Context context,ArrayList<Integer> listLoanAmount) {
    this.context = context;
    this.listLoanAmount = listLoanAmount;
    this.layoutInflater = LayoutInflater.from(context);
}

at the top of the class create LayoutInflater variable, hope this will help you

App crashing when trying to use RecyclerView on android 5.0

I experienced this crash even though I had the RecyclerView.LayoutManager properly set. I had to move the RecyclerView initialization code into the onViewCreated(...) callback to fix this issue.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_listing, container, false);
    rootView.setTag(TAG);
    return inflater.inflate(R.layout.fragment_listing, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    mLayoutManager = new LinearLayoutManager(getActivity());
    mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

    mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    mRecyclerView.setLayoutManager(mLayoutManager);

    mAdapter = new ListingAdapter(mListing);
    mRecyclerView.setAdapter(mAdapter);
}

Android: Internet connectivity change listener

I have noticed that no one mentioned WorkManger solution which is better and support most of android devices.

You should have a Worker with network constraint AND it will fired only if network available, i.e:

val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
val worker = OneTimeWorkRequestBuilder<MyWorker>().setConstraints(constraints).build()

And in worker you do whatever you want once connection back, you may fire the worker periodically .

i.e:

inside dowork() callback:

notifierLiveData.postValue(info)

Disable Proximity Sensor during call

Proximity Sensor Dial

*#*#7378423#*#*

1) Service Tests - (If present)

2) Proximity Switch

3) Test on sensor (Next to logo(top) of mobile)

4) Yes if works, then u can keep on and proximity switch forever which gives beep all the time and consumes lot of battery

OR

4) No it doesn't work - Then simply clean the mobile screen or screen guard and clear the blocked screen from sensor. It works charm.

Technically, Its not any software solution, but hardware solution will work.

How to make an HTTP request + basic auth in Swift

my solution works as follows:

import UIKit


class LoginViewController: UIViewController, NSURLConnectionDataDelegate {

  @IBOutlet var usernameTextField: UITextField
  @IBOutlet var passwordTextField: UITextField

  @IBAction func login(sender: AnyObject) {
    var url = NSURL(string: "YOUR_URL")
    var request = NSURLRequest(URL: url)
    var connection = NSURLConnection(request: request, delegate: self, startImmediately: true)

  }

  func connection(connection:NSURLConnection!, willSendRequestForAuthenticationChallenge challenge:NSURLAuthenticationChallenge!) {

    if challenge.previousFailureCount > 1 {

    } else {
        let creds = NSURLCredential(user: usernameTextField.text, password: passwordTextField.text, persistence: NSURLCredentialPersistence.None)
        challenge.sender.useCredential(creds, forAuthenticationChallenge: challenge)

    }

}

  func connection(connection:NSURLConnection!, didReceiveResponse response: NSURLResponse) {
    let status = (response as NSHTTPURLResponse).statusCode
    println("status code is \(status)")
    // 200? Yeah authentication was successful
  }


  override func viewDidLoad() {
    super.viewDidLoad()

  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

  }  
}

You can use this class as the implementation of a ViewController. Connect your fields to the IBOutlet annotated vars and your Button to the IBAction annotated function.

Explanation: In function login you create your request with NSURL, NSURLRequest and NSURLConnection. Essential here is the delegate which references to this class (self). For receiving the delegates calls you need to

  • Add the protocol NSURLConnectionDataDelegate to the class
  • Implement the protocols' function "connection:willSendRequestForAuthenticationChallenge" This is used for adding the credentials to the request
  • Implement the protocols' function "connection:didReceiveResponse" This will check the http response status code

NSURLConnection Using iOS Swift

Check Below Codes :

1. SynchronousRequest

Swift 1.2

    let urlPath: String = "YOUR_URL_HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSURLRequest = NSURLRequest(URL: url)
    var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
    var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)!
    var err: NSError
    println(response)
    var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary
    println("Synchronous\(jsonResult)")

Swift 2.0 +

let urlPath: String = "YOUR_URL_HERE"
    let url: NSURL = NSURL(string: urlPath)!
    let request1: NSURLRequest = NSURLRequest(URL: url)
    let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil


    do{

        let dataVal = try NSURLConnection.sendSynchronousRequest(request1, returningResponse: response)

            print(response)
            do {
                if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {
                    print("Synchronous\(jsonResult)")
                }
            } catch let error as NSError {
                print(error.localizedDescription)
            }



    }catch let error as NSError
    {
         print(error.localizedDescription)
    }

2. AsynchonousRequest

Swift 1.2

let urlPath: String = "YOUR_URL_HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSURLRequest = NSURLRequest(URL: url)
    let queue:NSOperationQueue = NSOperationQueue()
    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        var err: NSError
        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println("Asynchronous\(jsonResult)")
       })

Swift 2.0 +

let urlPath: String = "YOUR_URL_HERE"
    let url: NSURL = NSURL(string: urlPath)!
    let request1: NSURLRequest = NSURLRequest(URL: url)
    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in

        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print("ASynchronous\(jsonResult)")
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }


    })

3. As usual URL connection

Swift 1.2

    var dataVal = NSMutableData()
    let urlPath: String = "YOUR URL HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request: NSURLRequest = NSURLRequest(URL: url)
    var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
    connection.start()

Then

 func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
    self.dataVal?.appendData(data)
}


func connectionDidFinishLoading(connection: NSURLConnection!)
{
    var error: NSErrorPointer=nil

    var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal!, options: NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary

    println(jsonResult)



}

Swift 2.0 +

   var dataVal = NSMutableData()
    let urlPath: String = "YOUR URL HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request: NSURLRequest = NSURLRequest(URL: url)
    var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
    connection.start()

Then

func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
    dataVal.appendData(data)
}


func connectionDidFinishLoading(connection: NSURLConnection!)
{

    do {
        if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {
            print(jsonResult)
        }
    } catch let error as NSError {
        print(error.localizedDescription)
    }

}

4. Asynchronous POST Request

Swift 1.2

    let urlPath: String = "YOUR URL HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "POST"
     var stringPost="deviceToken=123456" // Key and Value

    let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)

    request1.timeoutInterval = 60
    request1.HTTPBody=data
    request1.HTTPShouldHandleCookies=false

    let queue:NSOperationQueue = NSOperationQueue()

     NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in


        var err: NSError

        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println("AsSynchronous\(jsonResult)")


        })

Swift 2.0 +

let urlPath: String = "YOUR URL HERE"
    let url: NSURL = NSURL(string: urlPath)!
    let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "POST"
    let stringPost="deviceToken=123456" // Key and Value

    let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)

    request1.timeoutInterval = 60
    request1.HTTPBody=data
    request1.HTTPShouldHandleCookies=false

    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in

        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print("ASynchronous\(jsonResult)")
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }


    })

5. Asynchronous GET Request

Swift 1.2

    let urlPath: String = "YOUR URL HERE"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "GET"
    request1.timeoutInterval = 60
    let queue:NSOperationQueue = NSOperationQueue()

     NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in


        var err: NSError

        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        println("AsSynchronous\(jsonResult)")


        })

Swift 2.0 +

let urlPath: String = "YOUR URL HERE"
    let url: NSURL = NSURL(string: urlPath)!
    let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "GET"
    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in

        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print("ASynchronous\(jsonResult)")
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }


    })

6. Image(File) Upload

Swift 2.0 +

  let mainURL = "YOUR_URL_HERE"

    let url = NSURL(string: mainURL)
    let request = NSMutableURLRequest(URL: url!)
    let boundary = "78876565564454554547676"
    request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")


    request.HTTPMethod = "POST" // POST OR PUT What you want
    let session = NSURLSession(configuration:NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil)

    let imageData = UIImageJPEGRepresentation(UIImage(named: "Test.jpeg")!, 1)





    var body = NSMutableData()

    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    // Append your parameters

    body.appendData("Content-Disposition: form-data; name=\"name\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("PREMKUMAR\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    body.appendData("Content-Disposition: form-data; name=\"description\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("IOS_DEVELOPER\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)


    // Append your Image/File Data

    var imageNameval = "HELLO.jpg"

    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("Content-Disposition: form-data; name=\"profile_photo\"; filename=\"\(imageNameval)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(imageData!)
    body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    request.HTTPBody = body




    let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in

        if error != nil {

            //handle error


        }
        else {




            let outputString : NSString = NSString(data:data!, encoding:NSUTF8StringEncoding)!
            print("Response:\(outputString)")


        }
    }
    dataTask.resume()

7. GET,POST,Etc Swift 3.0 +

let request = NSMutableURLRequest(url: URL(string: "YOUR_URL_HERE" ,param: param))!,
    cachePolicy: .useProtocolCachePolicy,
    timeoutInterval:60)
request.httpMethod = "POST" // POST ,GET, PUT What you want 

let session = URLSession.shared



  let dataTask = session.dataTask(with: request as URLRequest) {data,response,error in

do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print("ASynchronous\(jsonResult)")
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }

    }
    dataTask.resume()

self.tableView.reloadData() not working in Swift

Try it: tableView.reloadSections(IndexSet(integersIn: 0...0), with: .automatic) It helped me

Sending intent to BroadcastReceiver from adb

Another thing to keep in mind: Android 8 limits the receivers that can be registered via manifest (e.g., statically)

https://developer.android.com/guide/components/broadcast-exceptions

Get SSID when WIFI is connected

In Android 8.1 it is must to turned Location on to get SSID, if not you can get connection state but not SSID

WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = null;
if (wifiManager != null) 
wifiInfo = wifiManager.getConnectionInfo();
 String ssid = null;
if (wifiInfo != null) 
ssid = wifiInfo.getSSID(); /*you will get SSID <unknown ssid> if location turned off*/

Import Google Play Services library in Android Studio

After hours of having the same problem, notice that if your jar is on the libs folder will cause problem once you set it upon the "Dependencies ", so i just comment the file tree dependencies and keep the one using

dependencies

//compile fileTree(dir: 'libs', include: ['*.jar'])  <-------- commented one 
compile 'com.google.android.gms:play-services:8.1.0'
compile 'com.android.support:appcompat-v7:22.2.1'

and the problem was solved.

Will iOS launch my app into the background if it was force-quit by the user?

The answer is YES, but shouldn't use 'Background Fetch' or 'Remote notification'. PushKit is the answer you desire.

In summary, PushKit, the new framework in ios 8, is the new push notification mechanism which can silently launch your app into the background with no visual alert prompt even your app was killed by swiping out from app switcher, amazingly you even cannot see it from app switcher.

PushKit reference from Apple:

The PushKit framework provides the classes for your iOS apps to receive pushes from remote servers. Pushes can be of one of two types: standard and VoIP. Standard pushes can deliver notifications just as in previous versions of iOS. VoIP pushes provide additional functionality on top of the standard push that is needed to VoIP apps to perform on-demand processing of the push before displaying a notification to the user.

To deploy this new feature, please refer to this tutorial: https://zeropush.com/guide/guide-to-pushkit-and-voip - I've tested it on my device and it works as expected.

IOException: read failed, socket might closed - Bluetooth on Android 4.3

I've had this problem and the solution was to use the special magic GUID.

            val id: UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB") // Any other GUID doesn't work.
            val device: BluetoothDevice = bta!!.bondedDevices.first { z -> z.name == deviceName }

            bts = device.createRfcommSocketToServiceRecord(id) // mPort is -1
            bts?.connect()
            // Start processing thread.

I suspect that these are the UUIDs that work:

var did: Array<ParcelUuid?> = device.uuids

However, I have not tried them all.

How to send email in ASP.NET C#

MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text);
mm.Subject = txtSubject.Text;
mm.Body = txtBody.Text;
if (fuAttachment.HasFile)//file upload select or not
{
    string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
    mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
}
mm.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
Response.write("Send Mail");

View Video: https://www.youtube.com/watch?v=bUUNv-19QAI

fix java.net.SocketTimeoutException: Read timed out

Here are few pointers/suggestions for investigation

  1. I see that every time you vote, you call vote method which creates a fresh HTTP connection.
  2. This might be a problem. I would suggest to use a single HttpClient instance to post to the server. This way it wont create too many connections from the client side.
  3. At the end of everything, HttpClient needs to be shut and hence call httpclient.getConnectionManager().shutdown(); to release the resources used by the connections.

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

In my case (I am using Xamarin Forms) this error was thrown due to a binding error - e.g. :

<Label Grid.Column="4" Grid.Row="1" VerticalTextAlignment="Start" HorizontalTextAlignment="Center"  VerticalOptions="Start" HorizontalOptions="Start" FontSize="10" TextColor="Pink" Text="{Binding }"></Label>

Basically I deleted the view model property by mistake. For Xamarin developers, if you have the same issue, check your bindings...

Fastest way to convert Image to Byte array

So is there any other method to achieve this goal?

No. In order to convert an image to a byte array you have to specify an image format - just as you have to specify an encoding when you convert text to a byte array.

If you're worried about compression artefacts, pick a lossless format. If you're worried about CPU resources, pick a format which doesn't bother compressing - just raw ARGB pixels, for example. But of course that will lead to a larger byte array.

Note that if you pick a format which does include compression, there's no point in then compressing the byte array afterwards - it's almost certain to have no beneficial effect.

How do I debug error ECONNRESET in Node.js?

I was facing the same issue but I mitigated it by placing:

server.timeout = 0;

before server.listen. server is an HTTP server here. The default timeout is 2 minutes as per the API documentation.

Email address validation using ASP.NET MVC data type attributes

[RegularExpression(@"^[A-Za-z0-9]+@([a-zA-Z]+\\.)+[a-zA-Z]{2,6}]&")]

Is it possible to play music during calls so that the partner can hear it ? Android

I think this is possible in one case

1.Some of the native music players in android device where handling this,they restrict the music when call is in TelephonyManager.EXTRA_STATE_OFFHOOK (OFFHOOK STATE) so there is no way of playing the background music using native players and some other players like "poweramp music palyer"

2.By using the MediaPlayer class also it is not possible(clearly mentioned in documentation)

3.It is possible only in one case if your developing custom music player(with out using MediaPlayer class) in that implements

AudioManager.OnAudioFocusChangeListener by using this you can get the state of the audiomanager in the below code "focusChange=AUDIOFOCUS_LOSS_TRANSIENT"(this state calls when music is playing in background any incoming call came) this state is completely in developers hand whether to play or pause the music. As according to your requriment as for question you asked if you want to play the music when call is in OFFHOOK STATE dont pause playing music in OFFHOOK STATE .And this is only possible when headset is disabled

AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
     
    OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
        public void onAudioFocusChange(int focusChange) {
            if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT
                // Pause playback (during incoming call) 
            } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                // Resume playback (incoming call ends)
            } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
                am.abandonAudioFocus(afChangeListener);
                // Stop playback (when any other app playing music  in that situation current app stop the audio)
            }
        }
    };

Sending an HTTP POST request on iOS

Using Swift 3 or 4 you can access these http request for sever communication.

// For POST data to request

 func postAction()  {
//declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid
let parameters = ["id": 13, "name": "jack"] as [String : Any]
//create the url with URL
let url = URL(string: "www.requestURL.php")! //change the url
//create the session object
let session = URLSession.shared
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
do {
    request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
    print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
    guard error == nil else {
        return
    }
    guard let data = data else {
        return
    }
    do {
        //create json object from data
        if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
            print(json)
            // handle json...
        }
    } catch let error {
        print(error.localizedDescription)
    }
})
task.resume() }

// For get the data from request

func GetRequest()  {
    let urlString = URL(string: "http://www.requestURL.php") //change the url

    if let url = urlString {
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error != nil {
                print(error ?? "")
            } else {
                if let responceData = data {
                    print(responceData) //JSONSerialization
                    do {
                        //create json object from data
                        if let json = try JSONSerialization.jsonObject(with:responceData, options: .mutableContainers) as? [String: Any] {
                            print(json)
                            // handle json...
                        }
                    } catch let error {
                        print(error.localizedDescription)
                    }
                }
            }
        }
        task.resume()
    }
}

// For get the download content like image or video from request

func downloadTask()  {
    // Create destination URL
    let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
    let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg")
    //Create URL to the source file you want to download
    let fileURL = URL(string: "http://placehold.it/120x120&text=image1")
    let sessionConfig = URLSessionConfiguration.default
    let session = URLSession(configuration: sessionConfig)
    let request = URLRequest(url:fileURL!)

    let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
        if let tempLocalUrl = tempLocalUrl, error == nil {
            // Success
            if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                print("Successfully downloaded. Status code: \(statusCode)")
            }

            do {
                try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
            } catch (let writeError) {
                print("Error creating a file \(destinationFileUrl) : \(writeError)")
            }

        } else {
            print("Error took place while downloading a file. Error description: %@", error?.localizedDescription ?? "");
        }
    }
    task.resume()

}

Broadcast receiver for checking internet connection in android app

manifest:

<receiver android:name=".your.namepackage.here.ConnectivityReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
    </intent-filter>
</receiver>

class for receiver:

public class ConnectivityReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        switch (action) {
            case ConnectivityManager.CONNECTIVITY_ACTION:
                DebugUtils.logDebug("BROADCAST", "network change");
                if(NetworkUtils.isConnect()){
                    //do action here
                }
            break;
        }
    }
}

and classs utils like example:

public class NetworkUtils {

    public static boolean isConnect() {
        ConnectivityManager connectivityManager = (ConnectivityManager) Application.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Network[] netArray = connectivityManager.getAllNetworks();
            NetworkInfo netInfo;
            for (Network net : netArray) {
                netInfo = connectivityManager.getNetworkInfo(net);
                if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) {
                    //if (netInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
                    Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName());
                    return true;
                }
            }
        } else {
            if (connectivityManager != null) {
                @SuppressWarnings("deprecation")
                NetworkInfo[] netInfoArray = connectivityManager.getAllNetworkInfo();
                if (netInfoArray != null) {
                    for (NetworkInfo netInfo : netInfoArray) {
                        if ((netInfo.getTypeName().equalsIgnoreCase("WIFI") || netInfo.getTypeName().equalsIgnoreCase("MOBILE")) && netInfo.isConnected() && netInfo.isAvailable()) {
                            //if (netInfo.getState() == NetworkInfo.State.CONNECTED) {
                            Log.d("Network", "NETWORKNAME: " + netInfo.getTypeName());
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }
}

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

Get push notification while App in foreground iOS

Here is the code to receive Push Notification when app in active state (foreground or open). UNUserNotificationCenter documentation

@available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void)
{
     completionHandler([UNNotificationPresentationOptions.Alert,UNNotificationPresentationOptions.Sound,UNNotificationPresentationOptions.Badge])
}

If you need to access userInfo of notification use code: notification.request.content.userInfo

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

SmsListenerClass

public class SmsListener extends BroadcastReceiver {

static final String ACTION =
        "android.provider.Telephony.SMS_RECEIVED";

@Override
public void onReceive(Context context, Intent intent) {

    Log.e("RECEIVED", ":-:-" + "SMS_ARRIVED");

    // TODO Auto-generated method stub
    if (intent.getAction().equals(ACTION)) {

        Log.e("RECEIVED", ":-" + "SMS_ARRIVED");

        StringBuilder buf = new StringBuilder();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {

            Object[] pdus = (Object[]) bundle.get("pdus");

            SmsMessage[] messages = new SmsMessage[pdus.length];
            SmsMessage message = null;

            for (int i = 0; i < messages.length; i++) {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    String format = bundle.getString("format");
                    messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
                } else {
                    messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                }

                message = messages[i];
                buf.append("Received SMS from  ");
                buf.append(message.getDisplayOriginatingAddress());
                buf.append(" - ");
                buf.append(message.getDisplayMessageBody());
            }

            MainActivity inst = MainActivity.instance();
            inst.updateList(message.getDisplayOriginatingAddress(),message.getDisplayMessageBody());

        }

        Log.e("RECEIVED:", ":" + buf.toString());

        Toast.makeText(context, "RECEIVED SMS FROM :" + buf.toString(), Toast.LENGTH_LONG).show();

    }
}

Activity

@Override
public void onStart() {
    super.onStart();
    inst = this;
}

public static MainActivity instance() {
    return inst;
}

public void updateList(final String msg_from, String msg_body) {

    tvMessage.setText(msg_from + " :- " + msg_body);

    sendSMSMessage(msg_from, msg_body);

}

protected void sendSMSMessage(String phoneNo, String message) {

    try {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phoneNo, null, message, null, null);
        Toast.makeText(getApplicationContext(), "SMS sent.", Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), "SMS faild, please try again.", Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }
}

Manifest

<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"/>

<receiver android:name=".SmsListener">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

Is Android using NTP to sync time?

Not an exact answer to your question, but a bit of information: if your device does use NTP for time (eg. if it is a tablet with no 3G or GPS capabilities), the server can be configured in /system/etc/gps.conf - obviously this file can only be edited with root access, but is viewable on non-rooted devices.

How to Lock/Unlock screen programmatically?

Edit:

As some folks needs help in Unlocking device after locking programmatically, I came through post Android screen lock/ unlock programatically, please have look, may help you.

Original Answer was:

You need to get Admin permission and you can lock phone screen

please check below simple tutorial to achive this one

Lock Phone Screen Programmtically

also here is the code example..

LockScreenActivity.java

public class LockScreenActivity extends Activity implements OnClickListener {  
 private Button lock;  
 private Button disable;  
 private Button enable;  
 static final int RESULT_ENABLE = 1;  

     DevicePolicyManager deviceManger;  
     ActivityManager activityManager;  
     ComponentName compName;  

    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  

        deviceManger = (DevicePolicyManager)getSystemService(  
          Context.DEVICE_POLICY_SERVICE);  
        activityManager = (ActivityManager)getSystemService(  
          Context.ACTIVITY_SERVICE);  
        compName = new ComponentName(this, MyAdmin.class);  

        setContentView(R.layout.main);  

        lock =(Button)findViewById(R.id.lock);  
        lock.setOnClickListener(this);  

        disable = (Button)findViewById(R.id.btnDisable);  
        enable =(Button)findViewById(R.id.btnEnable);  
        disable.setOnClickListener(this);  
        enable.setOnClickListener(this);  
    }  

 @Override  
 public void onClick(View v) {  

  if(v == lock){  
    boolean active = deviceManger.isAdminActive(compName);  
             if (active) {  
                 deviceManger.lockNow();  
             }  
  }  

  if(v == enable){  
   Intent intent = new Intent(DevicePolicyManager  
     .ACTION_ADD_DEVICE_ADMIN);  
            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,  
                    compName);  
            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,  
                    "Additional text explaining why this needs to be added.");  
            startActivityForResult(intent, RESULT_ENABLE);  
  }  

  if(v == disable){  
     deviceManger.removeActiveAdmin(compName);  
              updateButtonStates();  
  }    
 }  

 private void updateButtonStates() {  

        boolean active = deviceManger.isAdminActive(compName);  
        if (active) {  
            enable.setEnabled(false);  
            disable.setEnabled(true);  

        } else {  
            enable.setEnabled(true);  
            disable.setEnabled(false);  
        }      
 }  

  protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
         switch (requestCode) {  
             case RESULT_ENABLE:  
                 if (resultCode == Activity.RESULT_OK) {  
                     Log.i("DeviceAdminSample", "Admin enabled!");  
                 } else {  
                     Log.i("DeviceAdminSample", "Admin enable FAILED!");  
                 }  
                 return;  
         }  
         super.onActivityResult(requestCode, resultCode, data);  
     }  
}

MyAdmin.java

public class MyAdmin extends DeviceAdminReceiver{  


    static SharedPreferences getSamplePreferences(Context context) {  
        return context.getSharedPreferences(  
          DeviceAdminReceiver.class.getName(), 0);  
    }  

    static String PREF_PASSWORD_QUALITY = "password_quality";  
    static String PREF_PASSWORD_LENGTH = "password_length";  
    static String PREF_MAX_FAILED_PW = "max_failed_pw";  

    void showToast(Context context, CharSequence msg) {  
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();  
    }  

    @Override  
    public void onEnabled(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: enabled");  
    }  

    @Override  
    public CharSequence onDisableRequested(Context context, Intent intent) {  
        return "This is an optional message to warn the user about disabling.";  
    }  

    @Override  
    public void onDisabled(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: disabled");  
    }  

    @Override  
    public void onPasswordChanged(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: pw changed");  
    }  

    @Override  
    public void onPasswordFailed(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: pw failed");  
    }  

    @Override  
    public void onPasswordSucceeded(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: pw succeeded");  
    }  

}

Android + Pair devices via bluetooth programmatically

if you have the BluetoothDevice object you can create bond(pair) from api 19 onwards with bluetoothDevice.createBond() method.

Edit

for callback, if the request was accepted or denied you will have to create a BroadcastReceiver with BluetoothDevice.ACTION_BOND_STATE_CHANGED action

"The semaphore timeout period has expired" error for USB connection

Okay, I am now connecting without the semaphore timeout problem.

If anyone reading ever encounters the same thing, I hope that this procedure works for you; but no promises; hey, it's windows.

In my case this was Windows 7

I got a little hint from This page on eHow; not sure if that might help anyone or not.

So anyway, this was the simple twenty three step procedure that worked for me

  • Click on start button

  • Choose Control Panel

  • From Control Panel, choose Device Manger

  • From Device Manager, choose Universal Serial Bus Controllers

  • From Universal Serial Bus Controllers, click the little sideways triangle

  • I cannot predict what you'll see on your computer, but on mine I get a long drop-down list

  • Begin the investigation to figure out which one of these members of this list is the culprit...

    • On each member of the drop-down list, right-click on the name

    • A list will open, choose Properties

    • Guesswork time: using the various tabs near the top of the resulting window which opens, make a guess if this is the USB adapter driver which is choking your stuff with semaphore timeouts

  • Once you have made the proper guess, then close the USB Root Hub Properties window (but leave the Device Manager window open).

  • Physically disonnect anything and everything from that USB hub.

  • Unplug it.

  • Return your mouse pointer to that USB Root Hub in the list which you identified earlier.

  • Right click again

  • Choose Uninstall

  • Let Windows do its thing

  • Wait a little while

  • Power Down the whole computer if you have the time; some say this is required. I think I got away without it.

  • Plug the USB hub back into a USB connector on the PC

  • If the list in the device manager blinks and does a few flash-bulbs, it's okay.

  • Plug the BlueTooth connector back into the USB hub

  • Let windows do its thing some more

  • Within two minutes, I had a working COM port again, no semaphore timeouts.

Hope it works for anyone else who may be having a similar problem.

send mail to multiple receiver with HTML mailto

"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."

http://www.sightspecific.com/~mosh/www_faq/multrec.html

For a quick fix to your problem, change your ; to a comma , and eliminate the spaces between email addresses

<a href='mailto:[email protected],[email protected]'>Email Us</a>

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

I had a similar problem, and the solution for me was quite different from what the other users posted.

The problem with me was related to the project I was working last year, which required a certain proxy on maven settings (located at <path to maven folder>\maven\conf\settings.xml and C:\Users\<my user>\.m2\settings.xml). The proxy was blocking the download of required external packages.

The solution was to put back the original file (settings.xml) on those places. Once things were restored, I was able to download the packages and everything worked.

android - How to get view from context?

first use this:

LayoutInflater inflater = (LayoutInflater) Read_file.this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

Read file is current activity in which you want your context.

View layout = inflater.inflate(R.layout.your_layout_name,(ViewGroup)findViewById(R.id.layout_name_id));

then you can use this to find any element in layout.

ImageView myImage = (ImageView) layout.findViewById(R.id.my_image);

exec failed because the name not a valid identifier?

Try this instead in the end:

exec (@query)

If you do not have the brackets, SQL Server assumes the value of the variable to be a stored procedure name.

OR

EXECUTE sp_executesql @query

And it should not be because of FULL JOIN.
But I hope you have already created the temp tables: #TrafficFinal, #TrafficFinal2, #TrafficFinal3 before this.


Please note that there are performance considerations between using EXEC and sp_executesql. Because sp_executesql uses forced statement caching like an sp.
More details here.


On another note, is there a reason why you are using dynamic sql for this case, when you can use the query as is, considering you are not doing any query manipulations and executing it the way it is?

Get the current displaying UIViewController on the screen in AppDelegate.m

I always love solutions that involve categories as they are bolt on and can be easily reused.

So I created a category on UIWindow. You can now call visibleViewController on UIWindow and this will get you the visible view controller by searching down the controller hierarchy. This works if you are using navigation and/or tab bar controller. If you have another type of controller to suggest please let me know and I can add it.

UIWindow+PazLabs.h (header file)

#import <UIKit/UIKit.h>

@interface UIWindow (PazLabs)

- (UIViewController *) visibleViewController;

@end

UIWindow+PazLabs.m (implementation file)

#import "UIWindow+PazLabs.h"

@implementation UIWindow (PazLabs)

- (UIViewController *)visibleViewController {
    UIViewController *rootViewController = self.rootViewController;
    return [UIWindow getVisibleViewControllerFrom:rootViewController];
}

+ (UIViewController *) getVisibleViewControllerFrom:(UIViewController *) vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [UIWindow getVisibleViewControllerFrom:[((UINavigationController *) vc) visibleViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [UIWindow getVisibleViewControllerFrom:[((UITabBarController *) vc) selectedViewController]];
    } else {
        if (vc.presentedViewController) {
            return [UIWindow getVisibleViewControllerFrom:vc.presentedViewController];
        } else {
            return vc;
        }
    }
}

@end

Swift Version

public extension UIWindow {
    public var visibleViewController: UIViewController? {
        return UIWindow.getVisibleViewControllerFrom(self.rootViewController)
    }

    public static func getVisibleViewControllerFrom(_ vc: UIViewController?) -> UIViewController? {
        if let nc = vc as? UINavigationController {
            return UIWindow.getVisibleViewControllerFrom(nc.visibleViewController)
        } else if let tc = vc as? UITabBarController {
            return UIWindow.getVisibleViewControllerFrom(tc.selectedViewController)
        } else {
            if let pvc = vc?.presentedViewController {
                return UIWindow.getVisibleViewControllerFrom(pvc)
            } else {
                return vc
            }
        }
    }
}

What does it mean to bind a multicast (UDP) socket?

Correction for What does it mean to bind a multicast (udp) socket? as long as it partially true at the following quote:

The "bind" operation is basically saying, "use this local UDP port for sending and receiving data. In other words, it allocates that UDP port for exclusive use for your application

There is one exception. Multiple applications can share the same port for listening (usually it has practical value for multicast datagrams), if the SO_REUSEADDR option applied. For example

int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // create UDP socket somehow
...
int set_option_on = 1;
// it is important to do "reuse address" before bind, not after
int res = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*) &set_option_on, 
    sizeof(set_option_on));
res = bind(sock, src_addr, len);

If several processes did such "reuse binding", then every UDP datagram received on that shared port will be delivered to each of the processes (providing natural joint with multicasts traffic).

Here are further details regarding what happens in a few cases:

  1. attempt of any bind ("exclusive" or "reuse") to free port will be successful

  2. attempt to "exclusive binding" will fail if the port is already "reuse-binded"

  3. attempt to "reuse binding" will fail if some process keeps "exclusive binding"

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

How to POST JSON data with Python Requests?

Starting with Requests version 2.4.2, you can use the json= parameter (which takes a dictionary) instead of data= (which takes a string) in the call:

>>> import requests
>>> r = requests.post('http://httpbin.org/post', json={"key": "value"})
>>> r.status_code
200
>>> r.json()
{'args': {},
 'data': '{"key": "value"}',
 'files': {},
 'form': {},
 'headers': {'Accept': '*/*',
             'Accept-Encoding': 'gzip, deflate',
             'Connection': 'close',
             'Content-Length': '16',
             'Content-Type': 'application/json',
             'Host': 'httpbin.org',
             'User-Agent': 'python-requests/2.4.3 CPython/3.4.0',
             'X-Request-Id': 'xx-xx-xx'},
 'json': {'key': 'value'},
 'origin': 'x.x.x.x',
 'url': 'http://httpbin.org/post'}

support FragmentPagerAdapter holds reference to old fragments

I solved the problem by saving the fragments in SparceArray:

public abstract class SaveFragmentsPagerAdapter extends FragmentPagerAdapter {

    SparseArray<Fragment> fragments = new SparseArray<>();

    public SaveFragmentsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment fragment = (Fragment) super.instantiateItem(container, position);
        fragments.append(position, fragment);
        return fragment;
    }

    @Nullable
    public Fragment getFragmentByPosition(int position){
        return fragments.get(position);
    }

}

Broadcast Receiver within a Service

The better pattern is to create a standalone BroadcastReceiver. This insures that your app can respond to the broadcast, whether or not the Service is running. In fact, using this pattern may remove the need for a constant-running Service altogether.

Register the BroadcastReceiver in your Manifest, and create a separate class/file for it.

Eg:

<receiver android:name=".FooReceiver" >
    <intent-filter >
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

When the receiver runs, you simply pass an Intent (Bundle) to the Service, and respond to it in onStartCommand().

Eg:

public class FooReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // do your work quickly!
        // then call context.startService();
    }   
}

How to run an android app in background?

As apps run in the background anyway. I’m assuming what your really asking is how do you make apps do stuff in the background. The solution below will make your app do stuff in the background after opening the app and after the system has rebooted.

Below, I’ve added a link to a fully working example (in the form of an Android Studio Project)

This subject seems to be out of the scope of the Android docs, and there doesn’t seem to be any one comprehensive doc on this. The information is spread across a few docs.

The following docs tell you indirectly how to do this: https://developer.android.com/reference/android/app/Service.html

https://developer.android.com/reference/android/content/BroadcastReceiver.html

https://developer.android.com/guide/components/bound-services.html

In the interests of getting your usage requirements correct, the important part of this above doc to read carefully is: #Binder, #Messenger and the components link below:

https://developer.android.com/guide/components/aidl.html

Here is the link to a fully working example (in Android Studio format): http://developersfound.com/BackgroundServiceDemo.zip

This project will start an Activity which binds to a service; implementing the AIDL.

This project is also useful to re-factor for the purpose of IPC across different apps.

This project is also developed to start automatically when Android restarts (provided the app has been run at least one after installation and app is not installed on SD card)

When this app/project runs after reboot, it dynamically uses a transparent view to make it look like no app has started but the service of the associated app starts cleanly.

This code is written in such a way that it’s very easy to tweak to simulate a scheduled service.

This project is developed in accordance to the above docs and is subsequently a clean solution.

There is however a part of this project which is not clean being: I have not found a way to start a service on reboot without using an Activity. If any of you guys reading this post have a clean way to do this please post a comment.

receiver type *** for instance message is a forward declaration

That basically means that you need to import the .h file containing the declaration of States.

However, there is a lot of other stuff wrong with your code.

  • You're -init'ing an object without +alloc'ing it. That won't work
  • You're declaring an object as a non-pointer type, that won't work either
  • You're not calling [super init] in -init.
  • You've declared the class using @class in the header, but never imported the class.

How to use LocalBroadcastManager?

Kotlin version of using LocalBroadcastManager:

Please check the below code for registering, sending and receiving the broadcast message.

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // register broadcast manager
        val localBroadcastManager = LocalBroadcastManager.getInstance(this)
        localBroadcastManager.registerReceiver(receiver, IntentFilter("your_action"))
    }

    // broadcast receiver
    var receiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent != null) {
                val str = intent.getStringExtra("key")
                
            }
        }
    }

    /**
     * Send broadcast method
     */
    fun sendBroadcast() {
        val intent = Intent("your_action")
        intent.putExtra("key", "Your data")
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    override fun onDestroy() {
        // Unregister broadcast
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver)
        super.onDestroy()
    }

}

iOS application: how to clear notifications?

If you're coming here wondering the opposite (as I was), this post may be for you.

I couldn't figure out why my notifications were clearing when I cleared the badge...I manually increment the badge and then want to clear it when the user enters the app. That's no reason to clear out the notification center, though; they may still want to see or act on those notifications.

Negative 1 does the trick, luckily:

[UIApplication sharedApplication].applicationIconBadgeNumber = -1;

how to access downloads folder in android?

If you're using a shell, the filepath to the Download (no "s") folder is

/storage/emulated/0/Download

How to pass object with NSNotificationCenter

You'll have to use the "userInfo" variant and pass a NSDictionary object that contains the messageTotal integer:

NSDictionary* userInfo = @{@"total": @(messageTotal)};

NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"eRXReceived" object:self userInfo:userInfo];

On the receiving end you can access the userInfo dictionary as follows:

-(void) receiveTestNotification:(NSNotification*)notification
{
    if ([notification.name isEqualToString:@"TestNotification"])
    {
        NSDictionary* userInfo = notification.userInfo;
        NSNumber* total = (NSNumber*)userInfo[@"total"];
        NSLog (@"Successfully received test notification! %i", total.intValue);
    }
}

Android - Start service on boot

I've had success without the full package, do you know where the call chain is getting interrupted? If you debug with Log()'s, at what point does it no longer work?

I think it may be in your IntentService, this all looks fine.

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

MySQL implicitly closed the database connection because the connection has been inactive for too long (34,247,052 milliseconds ˜ 9.5 hours). If your program then fetches a bad connection from the connection-pool that causes the MySQLNonTransientConnectionException: No operations allowed after connection closed.

MySQL suggests:

You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property autoReconnect=true to avoid this problem.

Why is this rsync connection unexpectedly closed on Windows?

I had this problem, but only when I tried to rsync from a Linux (RH) server to a Solaris server. My fix was to make sure rsync had the same path on both boxes, and that the ownership of rsync was the same.

On the linux box, rsync path was /usr/bin, on Solaris box it was /usr/local/bin. So, on the Solaris box I did ln -s /usr/local/bin/rsync /usr/bin/rsync.

I still had the same problem, and noticed ownership differences. On linux it was root:root, on solaris it was bin:bin. Changing solaris to root:root fixed it.

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

This error may be about password characters. If your password contains special characters and also you add your password into Transport class methods;

For Example

Transport transport = session.getTransport("smtp");
transport.connect("user","passw@rd");

or

Transport.send(msg, "user", "passw%rd");

you may get that error. Because Transport class' methods may not handle special characters. If you add your username and password into your message using javax.mail.PasswordAuthentication class, i hope you will escape that error;

For Example

...
Session session = Session.getInstance(props, new javax.mail.Authenticator()
{
  protected PasswordAuthentication getPasswordAuthentication()
  {
    return new PasswordAuthentication("user", "pas$w@r|d");
  }
});

Message message = new MimeMessage(session);
...
Transport.send(message);

How do I programmatically "restart" an Android app?

There is a really nice trick. My problem was that some really old C++ jni library leaked resources. At some point, it stopped functioning. The user tried to exit the app and launch it again -- with no result, because finishing an activity is not the same as finishing (or killing) the process. (By the way, the user could go to the list of the running applications and stop it from there -- this would work, but the users just do not know how to terminate applications.)

If you want to observe the effect of this feature, add a static variable to your activity and increment it each, say, button press. If you exit the application activity and then invoke the application again, this static variable will keep its value. (If the application really was exited, the variable would be assigned the initial value.)

(And I have to comment on why I did not want to fix the bug instead. The library was written decades ago and leaked resources ever since. The management believes it always worked. The cost of providing a fix instead of a workaround... I think, you get the idea.)

Now, how could I reset a jni shared (a.k.a. dynamic, .so) library to the initial state? I chose to restart application as a new process.

The trick is that System.exit() closes the current activity and Android recreates the application with one activity less.

So the code is:

/** This activity shows nothing; instead, it restarts the android process */
public class MagicAppRestart extends Activity {
    // Do not forget to add it to AndroidManifest.xml
    // <activity android:name="your.package.name.MagicAppRestart"/>
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.exit(0);
    }
    public static void doRestart(Activity anyActivity) {
        anyActivity.startActivity(new Intent(anyActivity.getApplicationContext(), MagicAppRestart.class));
    }
}

The calling activity just executes the code MagicAppRestart.doRestart(this);, the calling activity's onPause() is executed, and then the process is re-created. And do not forget to mention this activity in AndroidManifest.xml

The advantage of this method is that there is no delays.

UPD: it worked in Android 2.x, but in Android 4 something has changed.

Get Context in a Service

Since Service is a Context, the variable context must be this:

DataBaseManager dbm = Utils.getDataManager(this);   

Receiver not registered exception error?

Declare receiver as null and then Put register and unregister methods in onResume() and onPause() of the activity respectively.

@Override
protected void onResume() {
    super.onResume();
    if (receiver == null) {
        filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
        filter.addCategory(Intent.CATEGORY_DEFAULT);
        receiver = new ResponseReceiver();
        registerReceiver(receiver, filter);
    }
}      

@Override
protected void onPause() {
    super.onPause();
    if (receiver != null) {
        unregisterReceiver(receiver);
        receiver = null;
    }
}

Submit form and stay on same page?

The easiest answer: jQuery. Do something like this:

$(document).ready(function(){
   var $form = $('form');
   $form.submit(function(){
      $.post($(this).attr('action'), $(this).serialize(), function(response){
            // do something here on success
      },'json');
      return false;
   });
});

If you want to add content dynamically and still need it to work, and also with more than one form, you can do this:

   $('form').live('submit', function(){
      $.post($(this).attr('action'), $(this).serialize(), function(response){
            // do something here on success
      },'json');
      return false;
   });

An item with the same key has already been added

I had the problem not in my C# model, but in the javascript object I was posting using AJAX. I'm using Angular for binding and had a capitalized Notes field on the page while my C# object was expecting lower-case notes. A more descriptive error would sure be nice.

C#:

class Post {
    public string notes { get; set; }
}

Angular/Javascript:

<input ng-model="post.Notes" type="text">

ContractFilter mismatch at the EndpointDispatcher exception

The error says that there is a mismatch, assuming that you have a common contract based on the same WSDL, then the mismatch is in the configuration.

For example that the client is using nettcpip and the server is set up to use basic http.

org.xml.sax.SAXParseException: Content is not allowed in prolog

What i have tried [Did not work]

In my case the web.xml in my application had extra space. Even after i deleted ; it did not work!.

I was playing with logging.properties and web.xml in my tomcat, but even after i reverted the error persists!.

Solution

To be specific i tried do adding

org.apache.catalina.filters.ExpiresFilter.level = FINE

Tomcat expire filter is not working correctly

extra space

Programmatically register a broadcast receiver

Define a broadcast receiver anywhere in Activity/Fragment like this:

mReceiver = new BroadcastReceiver() {
 @Override
 public void onReceive(Context context, Intent intent) {
     Log.d(TAG," onRecieve"); //do something with intent
   }
 };

Define IntentFilter in onCreate()

mIntentFilter=new IntentFilter("action_name");

Now register the BroadcastReciever in onResume() and Unregister it in onPause() [because there is no use of broadcast if the activity is paused].

@Override
protected void onResume() {
     super.onResume();
     registerReceiver(mReceiver, mIntentFilter);
}

@Override
protected void onPause() {
    if(mReceiver != null) {
            unregisterReceiver(mReceiver);
            mReceiver = null;
    }
    super.onPause();
}

For detail tutorial, have a look at broadcast receiver-two ways to implement.

Send message to specific client with socket.io and node.js

Well you have to grab the client for that (surprise), you can either go the simple way:

var io = io.listen(server);
io.clients[sessionID].send()

Which may break, I doubt it, but it's always a possibility that io.clients might get changed, so use the above with caution

Or you keep track of the clients yourself, therefore you add them to your own clients object in the connection listener and remove them in the disconnect listener.

I would use the latter one, since depending on your application you might want to have more state on the clients anyway, so something like clients[id] = {conn: clientConnect, data: {...}} might do the job.

Android Starting Service at Boot Time , How to restart service class after device Reboot?

Pls check JobScheduler for apis above 26

WakeLock was the best option for this but it is deprecated in api level 26 Pls check this link if you consider api levels above 26
https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html#startWakefulService(android.content.Context,%20android.content.Intent)

It says

As of Android O, background check restrictions make this class no longer generally useful. (It is generally not safe to start a service from the receipt of a broadcast, because you don't have any guarantees that your app is in the foreground at this point and thus allowed to do so.) Instead, developers should use android.app.job.JobScheduler to schedule a job, and this does not require that the app hold a wake lock while doing so (the system will take care of holding a wake lock for the job).

so as it says cosider JobScheduler
https://developer.android.com/reference/android/app/job/JobScheduler

if it is to do something than to start and to keep it you can receive the broadcast ACTION_BOOT_COMPLETED

If it isn't about foreground pls check if an Accessibility service could do

another option is to start an activity from broadcast receiver and finish it after starting the service within onCreate() , since newer android versions doesnot allows starting services from receivers

Android BroadcastReceiver within Activity

Extends the ToastDisplay class with BroadcastReceiver and register the receiver in the manifest file,and dont register your broadcast receiver in onResume() .

<application
  ....
  <receiver android:name=".ToastDisplay">
    <intent-filter>
      <action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"/>
    </intent-filter>
  </receiver>
</application>

if you want to register in activity then register in the onCreate() method e.g:

onCreate(){

    sentSmsBroadcastCome = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "SMS SENT!!", Toast.LENGTH_SHORT).show();
        }
    };
    IntentFilter filterSend = new IntentFilter();
    filterSend.addAction("m.sent");
    registerReceiver(sentSmsBroadcastCome, filterSend);
}

How to send json data in the Http request using NSURLRequest

Since my edit to Mike G's answer to modernize the code was rejected 3 to 2 as

This edit was intended to address the author of the post and makes no sense as an edit. It should have been written as a comment or an answer

I'm reposting my edit as a separate answer here. This edit removes the JSONRepresentation dependency with NSJSONSerialization as Rob's comment with 15 upvotes suggests.

    NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
      [[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"],     nil];
    NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
    NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

    NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];

    NSLog(@"jsonRequest is %@", jsonRequest);

    NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];


    NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil]; //TODO handle error

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody: requestData];

    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    if (connection) {
     receivedData = [[NSMutableData data] retain];
    }

The receivedData is then handled by:

NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSDictionary *question = [jsonDict objectForKey:@"question"];

Send file via cURL from form POST in PHP

For my the @ symbol did not work, so I do some research and found this way and it work for me, I hope this help you.

    $target_url = "http://server:port/xxxxx.php";           
    $fname = 'file.txt';   
    $cfile = new CURLFile(realpath($fname));

        $post = array (
                  'file' => $cfile
                  );    

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $target_url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");   
    curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: multipart/form-data'));
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);   
    curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);  
    curl_setopt($ch, CURLOPT_TIMEOUT, 100);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

    $result = curl_exec ($ch);

    if ($result === FALSE) {
        echo "Error sending" . $fname .  " " . curl_error($ch);
        curl_close ($ch);
    }else{
        curl_close ($ch);
        echo  "Result: " . $result;
    }   

How to use registerReceiver method?

Broadcast receivers receive events of a certain type. I don't think you can invoke them by class name.

First, your IntentFilter must contain an event.

static final String SOME_ACTION = "com.yourcompany.yourapp.SOME_ACTION";
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);

Second, when you send a broadcast, use this same action:

Intent i = new Intent(SOME_ACTION);
sendBroadcast(i);

Third, do you really need MyIntentService to be inline? Static? [EDIT] I discovered that MyIntentSerivce MUST be static if it is inline.

Fourth, is your service declared in the AndroidManifest.xml?

Sending Multipart File as POST parameters with RestTemplate requests

I recently struggled with this issue for 3 days. How the client is sending the request might not be the cause, the server might not be configured to handle multipart requests. This is what I had to do to get it working:

pom.xml - Added commons-fileupload dependency (download and add the jar to your project if you are not using dependency management such as maven)

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>${commons-version}</version>
</dependency>

web.xml - Add multipart filter and mapping

<filter>
  <filter-name>multipartFilter</filter-name>
  <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>multipartFilter</filter-name>
  <url-pattern>/springrest/*</url-pattern>
</filter-mapping>

app-context.xml - Add multipart resolver

<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <beans:property name="maxUploadSize">
        <beans:value>10000000</beans:value>
    </beans:property>
</beans:bean>

Your Controller

@RequestMapping(value=Constants.REQUEST_MAPPING_ADD_IMAGE, method = RequestMethod.POST, produces = { "application/json"})
public @ResponseBody boolean saveStationImage(
        @RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_FILE) MultipartFile file,
        @RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_URI) String imageUri, 
        @RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_TYPE) String imageType, 
        @RequestParam(value = Constants.MONGO_FIELD_STATION_ID) String stationId) {
    // Do something with file
    // Return results
}

Your client

public static Boolean updateStationImage(StationImage stationImage) {
    if(stationImage == null) {
        Log.w(TAG + ":updateStationImage", "Station Image object is null, returning.");
        return null;
    }

    Log.d(TAG, "Uploading: " + stationImage.getImageUri());
    try {
        RestTemplate restTemplate = new RestTemplate();
        FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
        formConverter.setCharset(Charset.forName("UTF8"));
        restTemplate.getMessageConverters().add(formConverter);
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setAccept(Collections.singletonList(MediaType.parseMediaType("application/json")));

        MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();

        parts.add(Constants.STATION_PROFILE_IMAGE_FILE, new FileSystemResource(stationImage.getImageFile()));
        parts.add(Constants.STATION_PROFILE_IMAGE_URI, stationImage.getImageUri());
        parts.add(Constants.STATION_PROFILE_IMAGE_TYPE, stationImage.getImageType());
        parts.add(Constants.FIELD_STATION_ID, stationImage.getStationId());

        return restTemplate.postForObject(Constants.REST_CLIENT_URL_ADD_IMAGE, parts, Boolean.class);
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));

        Log.e(TAG + ":addStationImage", sw.toString());
    }

    return false;
}

That should do the trick. I added as much information as possible because I spent days, piecing together bits and pieces of the full issue, I hope this will help.

Android - SMS Broadcast receiver

android.provider.Telephony.SMS_RECEIVED has a capital T, and yours in the manifest does not.

Please bear in mind that this Intent action is not documented.

Calling startActivity() from outside of an Activity?

if your android version is below Android - 6 then you need to add this line otherwise it will work above Android - 6.

...
Intent i = new Intent(this, Wakeup.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
...

Why do we use Base64?

Your first mistake is thinking that ASCII encoding and Base64 encoding are interchangeable. They are not. They are used for different purposes.

  • When you encode text in ASCII, you start with a text string and convert it to a sequence of bytes.
  • When you encode data in Base64, you start with a sequence of bytes and convert it to a text string.

To understand why Base64 was necessary in the first place we need a little history of computing.


Computers communicate in binary - 0s and 1s - but people typically want to communicate with more rich forms data such as text or images. In order to transfer this data between computers it first has to be encoded into 0s and 1s, sent, then decoded again. To take text as an example - there are many different ways to perform this encoding. It would be much simpler if we could all agree on a single encoding, but sadly this is not the case.

Originally a lot of different encodings were created (e.g. Baudot code) which used a different number of bits per character until eventually ASCII became a standard with 7 bits per character. However most computers store binary data in bytes consisting of 8 bits each so ASCII is unsuitable for tranferring this type of data. Some systems would even wipe the most significant bit. Furthermore the difference in line ending encodings across systems mean that the ASCII character 10 and 13 were also sometimes modified.

To solve these problems Base64 encoding was introduced. This allows you to encode arbitrary bytes to bytes which are known to be safe to send without getting corrupted (ASCII alphanumeric characters and a couple of symbols). The disadvantage is that encoding the message using Base64 increases its length - every 3 bytes of data is encoded to 4 ASCII characters.

To send text reliably you can first encode to bytes using a text encoding of your choice (for example UTF-8) and then afterwards Base64 encode the resulting binary data into a text string that is safe to send encoded as ASCII. The receiver will have to reverse this process to recover the original message. This of course requires that the receiver knows which encodings were used, and this information often needs to be sent separately.

Historically it has been used to encode binary data in email messages where the email server might modify line-endings. A more modern example is the use of Base64 encoding to embed image data directly in HTML source code. Here it is necessary to encode the data to avoid characters like '<' and '>' being interpreted as tags.


Here is a working example:

I wish to send a text message with two lines:

Hello
world!

If I send it as ASCII (or UTF-8) it will look like this:

72 101 108 108 111 10 119 111 114 108 100 33

The byte 10 is corrupted in some systems so we can base 64 encode these bytes as a Base64 string:

SGVsbG8Kd29ybGQh

Which when encoded using ASCII looks like this:

83 71 86 115 98 71 56 75 100 50 57 121 98 71 81 104

All the bytes here are known safe bytes, so there is very little chance that any system will corrupt this message. I can send this instead of my original message and let the receiver reverse the process to recover the original message.

Make an HTTP request with android

UPDATE

This is a very old answer. I definitely won't recommend Apache's client anymore. Instead use either:

Original Answer

First of all, request a permission to access network, add following to your manifest:

<uses-permission android:name="android.permission.INTERNET" />

Then the easiest way is to use Apache http client bundled with Android:

    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(new HttpGet(URL));
    StatusLine statusLine = response.getStatusLine();
    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        String responseString = out.toString();
        out.close();
        //..more logic
    } else{
        //Closes the connection.
        response.getEntity().getContent().close();
        throw new IOException(statusLine.getReasonPhrase());
    }

If you want it to run on separate thread I'd recommend extending AsyncTask:

class RequestTask extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                responseString = out.toString();
                out.close();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        }
        return responseString;
    }
    
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //Do anything with response..
    }
}

You then can make a request by:

   new RequestTask().execute("http://stackoverflow.com");

Constructor in an Interface?

See this question for the why (taken from the comments).

If you really need to do something like this, you may want an abstract base class rather than an interface.

Trying to start a service on boot on Android

I found out just now that it might be because of Fast Boot option in Settings > Power

When I have this option off, my application receives a this broadcast but not otherwise.

By the way, I have Android 2.3.3 on HTC Incredible S.

Hope it helps.

How to check if Receiver is registered in Android?

Just check NullPointerException. If receiver does not exist, then...

try{
    Intent i = new Intent();
    i.setAction("ir.sss.smsREC");
    context.sendBroadcast(i);
    Log.i("...","broadcast sent");
}
catch (NullPointerException e)
{
    e.getMessage();
}

How can I check the current status of the GPS receiver?

With LocationManager you can getLastKnownLocation() after you getBestProvider(). This gives you a Location object, which has the methods getAccuracy() in meters and getTime() in UTC milliseconds

Does this give you enough info?

Or perhaps you could iterate over the LocationProviders and find out if each one meetsCriteria( ACCURACY_COARSE )

How to kill a thread instantly in C#?

thread will be killed when it finish it's work, so if you are using loops or something else you should pass variable to the thread to stop the loop after that the thread will be finished.

Selectors in Objective-C?

Selectors are an efficient way to reference methods directly in compiled code - the compiler is what actually assigns the value to a SEL.

Other have already covered the second part of your q, the ':' at the end matches a different signature than what you're looking for (in this case that signature doesn't exist).

@class vs. #import

Forward declaration just to the prevent compiler from showing error.

the compiler will know that there is class with the name you've used in your header file to declare.

What causes a TCP/IP reset (RST) flag to be sent?

If there is a router doing NAT, especially a low end router with few resources, it will age the oldest TCP sessions first. To do this it sets the RST flag in the packet that effectively tells the receiving station to (very ungracefully) close the connection. this is done to save resources.

How do I format a String in an email so Outlook will print the line breaks?

I also had this issue with plain/text mail type. Earlier, I used "\n\n" but there was two line breaks. Then, I used "\t\n" and it worked. I was using StringBuffer in java to append content.
The content got printed in next line in Outlook 2010 mail.

How can I detect the encoding/codepage of a text file

Since it basically comes down to heuristics, it may help to use the encoding of previously received files from the same source as a first hint.

Most people (or applications) do stuff in pretty much the same order every time, often on the same machine, so its quite likely that when Bob creates a .csv file and sends it to Mary it'll always be using Windows-1252 or whatever his machine defaults to.

Where possible a bit of customer training never hurts either :-)

regular expression for anything but an empty string

You can do one of two things:

  • match against ^\s*$; a match means the string is "empty"
    • ^, $ are the beginning and end of string anchors respectively
    • \s is a whitespace character
    • * is zero-or-more repetition of
  • find a \S; an occurrence means the string is NOT "empty"
    • \S is the negated version of \s (note the case difference)
    • \S therefore matches any non-whitespace character

References

Related questions

How to make a transparent border using CSS?

Well if you want fully transparent than you can use

border: 5px solid transparent;

If you mean opaque/transparent, than you can use

border: 5px solid rgba(255, 255, 255, .5);

Here, a means alpha, which you can scale, 0-1.

Also some might suggest you to use opacity which does the same job as well, the only difference is it will result in child elements getting opaque too, yes, there are some work arounds but rgba seems better than using opacity.

For older browsers, always declare the background color using #(hex) just as a fall back, so that if old browsers doesn't recognize the rgba, they will apply the hex color to your element.

Demo

Demo 2 (With a background image for nested div)

Demo 3 (With an img tag instead of a background-image)

body {
    background: url(http://www.desktopas.com/files/2013/06/Images-1920x1200.jpg);   
}

div.wrap {
    border: 5px solid #fff; /* Fall back, not used in fiddle */
    border: 5px solid rgba(255, 255, 255, .5);
    height: 400px;
    width: 400px;
    margin: 50px;
    border-radius: 50%;
}

div.inner {
    background: #fff; /* Fall back, not used in fiddle */
    background: rgba(255, 255, 255, .5);
    height: 380px;
    width: 380px;
    border-radius: 50%; 
    margin: auto; /* Horizontal Center */
    margin-top: 10px; /* Vertical Center ... Yea I know, that's 
                         manually calculated*/
}

Note (For Demo 3): Image will be scaled according to the height and width provided so make sure it doesn't break the scaling ratio.

Create stacked barplot where each stack is scaled to sum to 100%

prop.table is a nice friendly way of obtaining proportions of tables.

m <- matrix(1:4,2)

 m
     [,1] [,2]
[1,]    1    3
[2,]    2    4

Leaving margin blank gives you proportions of the whole table

 prop.table(m, margin=NULL)
     [,1] [,2]
[1,]  0.1  0.3
[2,]  0.2  0.4

Giving it 1 gives you row proportions

 prop.table(m, 1)
      [,1]      [,2]
[1,] 0.2500000 0.7500000
[2,] 0.3333333 0.6666667

And 2 is column proportions

 prop.table(m, 2)
          [,1]      [,2]
[1,] 0.3333333 0.4285714
[2,] 0.6666667 0.5714286

How do I use a pipe to redirect the output of one command to the input of another?

Try this. Copy this into a batch file - such as send.bat - and then simply run send.bat to send the message from the temperature program to the prismcom program.

temperature.exe > msg.txt
set /p msg= < msg.txt
prismcom.exe usb "%msg%"

How to convert View Model into JSON object in ASP.NET MVC?

Andrew had a great response but I wanted to tweek it a little. The way this is different is that I like my ModelViews to not have overhead data in them. Just the data for the object. It seem that ViewData fits the bill for over head data, but of course I'm new at this. I suggest doing something like this.

Controller

virtual public ActionResult DisplaySomeWidget(int id)
{
    SomeModelView returnData = someDataMapper.getbyid(1);
    var serializer = new JavaScriptSerializer();
    ViewData["JSON"] = serializer.Serialize(returnData);
    return View(myview, returnData);
}

View

//create base js object;
var myWidget= new Widget(); //Widget is a class with a public member variable called data.
myWidget.data= <%= ViewData["JSON"] %>;

What This does for you is it gives you the same data in your JSON as in your ModelView so you can potentially return the JSON back to your controller and it would have all the parts. This is similar to just requesting it via a JSONRequest however it requires one less call so it saves you that overhead. BTW this is funky for Dates but that seems like another thread.

How to auto-reload files in Node.js?

For people using Vagrant and PHPStorm, file watcher is a faster approach

  • disable immediate sync of the files so you run the command only on save then create a scope for the *.js files and working directories and add this command

    vagrant ssh -c "/var/www/gadelkareem.com/forever.sh restart"

where forever.sh is like

#!/bin/bash

cd /var/www/gadelkareem.com/ && forever $1 -l /var/www/gadelkareem.com/.tmp/log/forever.log -a app.js

Compile/run assembler in Linux?

The GNU assembler is probably already installed on your system. Try man as to see full usage information. You can use as to compile individual files and ld to link if you really, really want to.

However, GCC makes a great front-end. It can assemble .s files for you. For example:

$ cat >hello.s <<"EOF"
.section .rodata             # read-only static data
.globl hello
hello:
  .string "Hello, world!"    # zero-terminated C string

.text
.global main
main:
    push    %rbp
    mov     %rsp,  %rbp                 # create a stack frame

    mov     $hello, %edi                # put the address of hello into RDI
    call    puts                        #  as the first arg for puts

    mov     $0,    %eax                 # return value = 0.  Normally xor %eax,%eax
    leave                               # tear down the stack frame
    ret                            # pop the return address off the stack into RIP
EOF
$ gcc hello.s -no-pie -o hello
$ ./hello
Hello, world!

The code above is x86-64. If you want to make a position-independent executable (PIE), you'd need lea hello(%rip), %rdi, and call puts@plt.

A non-PIE executable (position-dependent) can use 32-bit absolute addressing for static data, but a PIE should use RIP-relative LEA. (See also Difference between movq and movabsq in x86-64 neither movq nor movabsq are a good choice.)

If you wanted to write 32-bit code, the calling convention is different, and RIP-relative addressing isn't available. (So you'd push $hello before the call, and pop the stack args after.)


You can also compile C/C++ code directly to assembly if you're curious how something works:

$ cat >hello.c <<EOF
#include <stdio.h>
int main(void) {
    printf("Hello, world!\n");
    return 0;
}
EOF
$ gcc -S hello.c -o hello.s

See also How to remove "noise" from GCC/clang assembly output? for more about looking at compiler output, and writing useful small functions that will compile to interesting output.

ListView with Add and Delete Buttons in each Row in android

public class UserCustomAdapter extends ArrayAdapter<User> {
 Context context;
 int layoutResourceId;
 ArrayList<User> data = new ArrayList<User>();

 public UserCustomAdapter(Context context, int layoutResourceId,
   ArrayList<User> data) {
  super(context, layoutResourceId, data);
  this.layoutResourceId = layoutResourceId;
  this.context = context;
  this.data = data;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  View row = convertView;
  UserHolder holder = null;

  if (row == null) {
   LayoutInflater inflater = ((Activity) context).getLayoutInflater();
   row = inflater.inflate(layoutResourceId, parent, false);
   holder = new UserHolder();
   holder.textName = (TextView) row.findViewById(R.id.textView1);
   holder.textAddress = (TextView) row.findViewById(R.id.textView2);
   holder.textLocation = (TextView) row.findViewById(R.id.textView3);
   holder.btnEdit = (Button) row.findViewById(R.id.button1);
   holder.btnDelete = (Button) row.findViewById(R.id.button2);
   row.setTag(holder);
  } else {
   holder = (UserHolder) row.getTag();
  }
  User user = data.get(position);
  holder.textName.setText(user.getName());
  holder.textAddress.setText(user.getAddress());
  holder.textLocation.setText(user.getLocation());
  holder.btnEdit.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Edit Button Clicked", "**********");
    Toast.makeText(context, "Edit button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  holder.btnDelete.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Delete Button Clicked", "**********");
    Toast.makeText(context, "Delete button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  return row;

 }

 static class UserHolder {
  TextView textName;
  TextView textAddress;
  TextView textLocation;
  Button btnEdit;
  Button btnDelete;
 }
}

Hey Please have a look here-

I have same answer here on my blog ..

Disable browser 'Save Password' functionality

autocomplete="off" works for most modern browsers, but another method I used that worked successfully with Epiphany (a WebKit-powered browser for GNOME) is to store a randomly generated prefix in session state (or a hidden field, I happened to have a suitable variable in session state already), and use this to alter the name of the fields. Epiphany still wants to save the password, but when going back to the form it won't populate the fields.

How do I generate random numbers in Dart?

use this library http://dart.googlecode.com/svn/branches/bleeding_edge/dart/lib/math/random.dart provided a good random generator which i think will be included in the sdk soon hope it helps

Adding days to a date in Java

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, 5); // Adding 5 days
String output = sdf.format(c.getTime());
System.out.println(output);

Maven error :Perhaps you are running on a JRE rather than a JDK?

Just adding more details on where to setup. Main reason would be the JAVA_HOME setup in the environment variable should be pointing to correct JDK location.

  1. Check System -> Advance System Settings
  2. Click on Environment variable
  3. Add variable JAVA_HOME -> "C:\Program Files\Java\jdk1.8.0_141;"
  4. Edit "path" -> append %JAVA_HOME%; to the existing text.

Output ("echo") a variable to a text file

The simplest Hello World example...

$hello = "Hello World"
$hello | Out-File c:\debug.txt

How to sort mongodb with pymongo

Why python uses list of tuples instead dict?

In python, you cannot guarantee that the dictionary will be interpreted in the order you declared.

So, in mongo shell you could do .sort({'field1':1,'field2':1}) and the interpreter would sort field1 at first level and field 2 at second level.

If this syntax was used in python, there is a chance of sorting by field2 at first level. With tuple, there is no such risk.

.sort([("field1",pymongo.ASCENDING), ("field2",pymongo.DESCENDING)])

NameError: name 'python' is not defined

It looks like you are trying to start the Python interpreter by running the command python.

However the interpreter is already started. It is interpreting python as a name of a variable, and that name is not defined.

Try this instead and you should hopefully see that your Python installation is working as expected:

print("Hello world!")

Reading in double values with scanf in c

Using %lf will help you in solving this problem.

Use :

scanf("%lf",&doub)

Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

I tried it on XP and it doesn't work if the PC is set to International time yyyy-M-d. Place a breakpoint on the line and before it is processed change the date string to use '-' in place of the '/' and you'll find it works. It makes no difference whether you have the CultureInfo or not. Seems strange to be able specify an expercted format only to have the separator ignored.

What are the differences among grep, awk & sed?

Short definition:

grep: search for specific terms in a file

#usage
$ grep This file.txt
Every line containing "This"
Every line containing "This"
Every line containing "This"
Every line containing "This"

$ cat file.txt
Every line containing "This"
Every line containing "This"
Every line containing "That"
Every line containing "This"
Every line containing "This"

Now awk and sed are completly different than grep. awk and sed are text processors. Not only do they have the ability to find what you are looking for in text, they have the ability to remove, add and modify the text as well (and much more).

awk is mostly used for data extraction and reporting. sed is a stream editor
Each one of them has its own functionality and specialties.

Example
Sed

$ sed -i 's/cat/dog/' file.txt
# this will replace any occurrence of the characters 'cat' by 'dog'

Awk

$ awk '{print $2}' file.txt
# this will print the second column of file.txt

Basic awk usage:
Compute sum/average/max/min/etc. what ever you may need.

$ cat file.txt
A 10
B 20
C 60
$ awk 'BEGIN {sum=0; count=0; OFS="\t"} {sum+=$2; count++} END {print "Average:", sum/count}' file.txt
Average:    30

I recommend that you read this book: Sed & Awk: 2nd Ed.

It will help you become a proficient sed/awk user on any unix-like environment.

How to indent a few lines in Markdown markup?

I would use &emsp; is a lot cleaner in my opinion.

Word-wrap in an HTML table

The following works for me in Internet Explorer. Note the addition of the table-layout:fixed CSS attribute

_x000D_
_x000D_
td {_x000D_
  border: 1px solid;_x000D_
}
_x000D_
<table style="table-layout: fixed; width: 100%">_x000D_
  <tr>_x000D_
    <td style="word-wrap: break-word">_x000D_
      LongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongWord_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Java - Reading XML file

One of the possible implementations:

File file = new File("userdata.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
        .newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
String usr = document.getElementsByTagName("user").item(0).getTextContent();
String pwd = document.getElementsByTagName("password").item(0).getTextContent();

when used with the XML content:

<credentials>
    <user>testusr</user>
    <password>testpwd</password>
</credentials>

results in "testusr" and "testpwd" getting assigned to the usr and pwd references above.

What are the time complexities of various data structures?

Arrays

  • Set, Check element at a particular index: O(1)
  • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
  • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
  • Similarly, Insert for arrays is basically Set as mentioned in the beginning

ArrayList:

  • Add: Amortized O(1)
  • Remove: O(n)
  • Contains: O(n)
  • Size: O(1)

Linked List:

  • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Doubly-Linked List:

  • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Stack:

  • Push: O(1)
  • Pop: O(1)
  • Top: O(1)
  • Search (Something like lookup, as a special operation): O(n) (I guess so)

Queue/Deque/Circular Queue:

  • Insert: O(1)
  • Remove: O(1)
  • Size: O(1)

Binary Search Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

Red-Black Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

Heap/PriorityQueue (min/max):

  • Find Min/Find Max: O(1)
  • Insert: O(log n)
  • Delete Min/Delete Max: O(log n)
  • Extract Min/Extract Max: O(log n)
  • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST

HashMap/Hashtable/HashSet:

  • Insert/Delete: O(1) amortized
  • Re-size/hash: O(n)
  • Contains: O(1)

Transposing a 2D-array in JavaScript

You can do it in in-place by doing only one pass:

function transpose(arr,arrLen) {
  for (var i = 0; i < arrLen; i++) {
    for (var j = 0; j <i; j++) {
      //swap element[i,j] and element[j,i]
      var temp = arr[i][j];
      arr[i][j] = arr[j][i];
      arr[j][i] = temp;
    }
  }
}

Calling remove in foreach loop in Java

It's better to use an Iterator when you want to remove element from a list

because the source code of remove is

if (numMoved > 0)
    System.arraycopy(elementData, index+1, elementData, index,
             numMoved);
elementData[--size] = null;

so ,if you remove an element from the list, the list will be restructure ,the other element's index will be changed, this can result something that you want to happened.

How to make a div 100% height of the browser window

You can use vh in this case which is relative to 1% of the height of the viewport...

That means if you want to cover off the height, just simply use 100vh.

Look at the image below I draw for you here:

How to make a div 100% height of the browser window?

Try the snippet I created for you as below:

_x000D_
_x000D_
.left {_x000D_
  height: 100vh;_x000D_
  width: 50%;_x000D_
  background-color: grey;_x000D_
  float: left;_x000D_
}_x000D_
_x000D_
.right {_x000D_
  height: 100vh;_x000D_
  width: 50%;_x000D_
  background-color: red;_x000D_
  float: right;_x000D_
}
_x000D_
<div class="left"></div>_x000D_
<div class="right"></div>
_x000D_
_x000D_
_x000D_

How to detect pressing Enter on keyboard using jQuery?

There's a keypress() event method. The Enter key's ascii number is 13 and is not dependent on which browser is being used.

Check element CSS display with JavaScript

yes.

var displayValue = document.getElementById('yourid').style.display;

View JSON file in Browser

If there is a Content-Disposition: attachment reponse header, Firefox will ask you to save the file, even if you have JSONView installed to format JSON.

To bypass this problem, I removed the header ("Content-Disposition" : null) with moz-rewrite Firefox addon that allows you to modify request and response headers https://addons.mozilla.org/en-US/firefox/addon/moz-rewrite-js/

An example of JSON file served with this header is the Twitter API (it looks like they added it recently). If you want to try this JSON file, I have a script to access Twitter API in browser: https://gist.github.com/baptx/ffb268758cd4731784e3

wordpress contactform7 textarea cols and rows change in smaller screens

I was able to get this work. I added the following to my custom CSS:

.wpcf7-form textarea{ 
    width: 100% !important;
    height:50px;
}

ASP.NET - How to write some html in the page? With Response.Write?

You should really use the Literal ASP.NET control for that.

Initializing a struct to 0

If the data is a static or global variable, it is zero-filled by default, so just declare it myStruct _m;

If the data is a local variable or a heap-allocated zone, clear it with memset like:

memset(&m, 0, sizeof(myStruct));

Current compilers (e.g. recent versions of gcc) optimize that quite well in practice. This works only if all zero values (include null pointers and floating point zero) are represented as all zero bits, which is true on all platforms I know about (but the C standard permits implementations where this is false; I know no such implementation).

You could perhaps code myStruct m = {}; or myStruct m = {0}; (even if the first member of myStruct is not a scalar).

My feeling is that using memset for local structures is the best, and it conveys better the fact that at runtime, something has to be done (while usually, global and static data can be understood as initialized at compile time, without any cost at runtime).

What does it mean to have an index to scalar variable error? python

In my case, I was getting this error because I had an input named x and I was creating (without realizing it) a local variable called x. I thought I was trying to access an element of the input x (which was an array), while I was actually trying to access an element of the local variable x (which was a scalar).

How do I keep two side-by-side divs the same height?

This question was asked 6 years ago, but it's still worthy to give a simple answer with flexbox layout nowadays.

Just add the following CSS to the father <div>, it will work.

display: -webkit-flex;
display: flex;
flex-direction: row;
align-items: stretch;

The first two lines declare it will be displayed as flexbox. And flex-direction: row tells browsers that its children will be display in columns. And align-items: stretch will meet the requirement that all the children elements will stretch to the same height it one of them become higher.

When should I use Kruskal as opposed to Prim (and vice versa)?

Prim's is better for more dense graphs, and in this we also do not have to pay much attention to cycles by adding an edge, as we are primarily dealing with nodes. Prim's is faster than Kruskal's in the case of complex graphs.

Can I get "&&" or "-and" to work in PowerShell?

Very old question, but for the newcomers: maybe the PowerShell version (similar but not equivalent) that the question is looking for, is to use -and as follows:

(build_command) -and (run_tests_command)

mongodb: insert if not exists

As of MongoDB 2.4, you can use $setOnInsert (http://docs.mongodb.org/manual/reference/operator/setOnInsert/)

Set 'insertion_date' using $setOnInsert and 'last_update_date' using $set in your upsert command.

To turn your pseudocode into a working example:

now = datetime.utcnow()
for document in update:
    collection.update_one(
        {"_id": document["_id"]},
        {
            "$setOnInsert": {"insertion_date": now},
            "$set": {"last_update_date": now},
        },
        upsert=True,
    )

get the titles of all open windows

Something like this:

using System.Diagnostics;

Process[] processlist = Process.GetProcesses();

foreach (Process process in processlist)
{
    if (!String.IsNullOrEmpty(process.MainWindowTitle))
    {
        Console.WriteLine("Process: {0} ID: {1} Window title: {2}", process.ProcessName, process.Id, process.MainWindowTitle);
    }
}

Laravel Eloquent "WHERE NOT IN"

You can do following.

DB::table('book_mast') 
->selectRaw('book_name,dt_of_pub,pub_lang,no_page,book_price')  
->whereNotIn('book_price',[100,200]);

cout is not a member of std

add #include <iostream> to the start of io.cpp too.

The most efficient way to implement an integer based power function pow(int, int)

Note that exponentiation by squaring is not the most optimal method. It is probably the best you can do as a general method that works for all exponent values, but for a specific exponent value there might be a better sequence that needs fewer multiplications.

For instance, if you want to compute x^15, the method of exponentiation by squaring will give you:

x^15 = (x^7)*(x^7)*x 
x^7 = (x^3)*(x^3)*x 
x^3 = x*x*x

This is a total of 6 multiplications.

It turns out this can be done using "just" 5 multiplications via addition-chain exponentiation.

n*n = n^2
n^2*n = n^3
n^3*n^3 = n^6
n^6*n^6 = n^12
n^12*n^3 = n^15

There are no efficient algorithms to find this optimal sequence of multiplications. From Wikipedia:

The problem of finding the shortest addition chain cannot be solved by dynamic programming, because it does not satisfy the assumption of optimal substructure. That is, it is not sufficient to decompose the power into smaller powers, each of which is computed minimally, since the addition chains for the smaller powers may be related (to share computations). For example, in the shortest addition chain for a¹5 above, the subproblem for a6 must be computed as (a³)² since a³ is re-used (as opposed to, say, a6 = a²(a²)², which also requires three multiplies).

Looping through rows in a DataView

//You can convert DataView to Table. using DataView.ToTable();

foreach (DataRow drGroup in dtGroups.Rows)
{
    dtForms.DefaultView.RowFilter = "ParentFormID='" + drGroup["FormId"].ToString() + "'";

    if (dtForms.DefaultView.Count > 0)
    {
        foreach (DataRow drForm in dtForms.DefaultView.ToTable().Rows)
        {
            drNew = dtNew.NewRow();

            drNew["FormId"] = drForm["FormId"];
            drNew["FormCaption"] = drForm["FormCaption"];
            drNew["GroupName"] = drGroup["GroupName"];
            dtNew.Rows.Add(drNew);
        }
    }
}

// Or You Can Use

// 2.

dtForms.DefaultView.RowFilter = "ParentFormID='" + drGroup["FormId"].ToString() + "'";

DataTable DTFormFilter = dtForms.DefaultView.ToTable();

foreach (DataRow drFormFilter in DTFormFilter.Rows)
{ 
                            //Your logic goes here
}

How to auto-scroll to end of div when data is added?

var objDiv = document.getElementById("divExample");
objDiv.scrollTop = objDiv.scrollHeight;

Fragment onCreateView and onActivityCreated called twice

It looks to me like it's because you are instantiating your TabListener every time... so the system is recreating your fragment from the savedInstanceState and then you are doing it again in your onCreate.

You should wrap that in a if(savedInstanceState == null) so it only fires if there is no savedInstanceState.

How to get values from IGrouping

Since IGrouping<TKey, TElement> implements IEnumerable<TElement>, you can use SelectMany to put all the IEnumerables back into one IEnumerable all together:

List<smth> list = new List<smth>();
IEnumerable<IGrouping<int, smth>> groups = list.GroupBy(x => x.id);
IEnumerable<smth> smths = groups.SelectMany(group => group);
List<smth> newList = smths.ToList();

Here's an example that builds/runs: https://dotnetfiddle.net/DyuaaP

Video commentary of this solution: https://youtu.be/6BsU1n1KTdo

filter out multiple criteria using excel vba

I don't have found any solution on Internet, so I have implemented one.

The Autofilter code with criteria is then

iColNumber = 1
Dim aFilterValueArray() As Variant
Call ConstructFilterValueArray(aFilterValueArray, iColNumber, Array("A", "B", "C"))

ActiveSheet.range(sRange).AutoFilter Field:=iColNumber _
    , Criteria1:=aFilterValueArray _
    , Operator:=xlFilterValues

In fact, the ConstructFilterValueArray() method (not function) get all distinct values that it found in a specific column and remove all values present in last argument.

The VBA code of this method is

'************************************************************
'* ConstructFilterValueArray()
'************************************************************

Sub ConstructFilterValueArray(a() As Variant, iCol As Integer, aRemoveArray As Variant)

    Dim aValue As New Collection
    Call GetDistinctColumnValue(aValue, iCol)
    Call RemoveValueList(aValue, aRemoveArray)
    Call CollectionToArray(a, aValue)

End Sub

'************************************************************
'* GetDistinctColumnValue()
'************************************************************

Sub GetDistinctColumnValue(ByRef aValue As Collection, iCol As Integer)

    Dim sValue As String

    iEmptyValueCount = 0
    iLastRow = ActiveSheet.UsedRange.Rows.Count

    Dim oSheet: Set oSheet = Sheets("X")

    Sheets("Data")
        .range(Cells(1, iCol), Cells(iLastRow, iCol)) _
            .AdvancedFilter Action:=xlFilterCopy _
                          , CopyToRange:=oSheet.range("A1") _
                          , Unique:=True

    iRow = 2
    Do While True
        sValue = Trim(oSheet.Cells(iRow, 1))
        If sValue = "" Then
            If iEmptyValueCount > 0 Then
                Exit Do
            End If
            iEmptyValueCount = iEmptyValueCount + 1
        End If

        aValue.Add sValue
        iRow = iRow + 1
    Loop

End Sub

'************************************************************
'* RemoveValueList()
'************************************************************

Sub RemoveValueList(ByRef aValue As Collection, aRemoveArray As Variant)

    For i = LBound(aRemoveArray) To UBound(aRemoveArray)
        sValue = aRemoveArray(i)
        iMax = aValue.Count
        For j = iMax To 0 Step -1
            If aValue(j) = sValue Then
                aValue.Remove (j)
                Exit For
            End If
        Next j
     Next i

End Sub

'************************************************************
'* CollectionToArray()
'************************************************************

Sub CollectionToArray(a() As Variant, c As Collection)

    iSize = c.Count - 1
    ReDim a(iSize)

    For i = 0 To iSize
        a(i) = c.Item(i + 1)
    Next

End Sub

This code can certainly be improved in returning an Array of String but working with Array in VBA is not easy.

CAUTION: this code work only if you define a sheet named X because CopyToRange parameter used in AdvancedFilter() need an Excel Range !

It's a shame that Microfsoft doesn't have implemented this solution in adding simply a new enum as xlNotFilterValues ! ... or xlRegexMatch !

Using prepared statements with JDBCTemplate

Try the following:

PreparedStatementCreator creator = new PreparedStatementCreator() {
    @Override
    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
        PreparedStatement updateSales = con.prepareStatement(
        "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ? ");
        updateSales.setInt(1, 75); 
        updateSales.setString(2, "Colombian"); 
        return updateSales;
    }
};

Xcopy Command excluding files and folders

Just give full path to exclusion file: eg..

-- no - - - - -xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt

correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\list-of-excluded-files.txt

In this example the file would be located " C:\list-of-excluded-files.txt "

or...

correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\mybatch\list-of-excluded-files.txt

In this example the file would be located " C:\mybatch\list-of-excluded-files.txt "

Full path fixes syntax error.

What encoding/code page is cmd.exe using?

Yes, it’s frustrating—sometimes type and other programs print gibberish, and sometimes they do not.

First of all, Unicode characters will only display if the current console font contains the characters. So use a TrueType font like Lucida Console instead of the default Raster Font.

But if the console font doesn’t contain the character you’re trying to display, you’ll see question marks instead of gibberish. When you get gibberish, there’s more going on than just font settings.

When programs use standard C-library I/O functions like printf, the program’s output encoding must match the console’s output encoding, or you will get gibberish. chcp shows and sets the current codepage. All output using standard C-library I/O functions is treated as if it is in the codepage displayed by chcp.

Matching the program’s output encoding with the console’s output encoding can be accomplished in two different ways:

  • A program can get the console’s current codepage using chcp or GetConsoleOutputCP, and configure itself to output in that encoding, or

  • You or a program can set the console’s current codepage using chcp or SetConsoleOutputCP to match the default output encoding of the program.

However, programs that use Win32 APIs can write UTF-16LE strings directly to the console with WriteConsoleW. This is the only way to get correct output without setting codepages. And even when using that function, if a string is not in the UTF-16LE encoding to begin with, a Win32 program must pass the correct codepage to MultiByteToWideChar. Also, WriteConsoleW will not work if the program’s output is redirected; more fiddling is needed in that case.

type works some of the time because it checks the start of each file for a UTF-16LE Byte Order Mark (BOM), i.e. the bytes 0xFF 0xFE. If it finds such a mark, it displays the Unicode characters in the file using WriteConsoleW regardless of the current codepage. But when typeing any file without a UTF-16LE BOM, or for using non-ASCII characters with any command that doesn’t call WriteConsoleW—you will need to set the console codepage and program output encoding to match each other.


How can we find this out?

Here’s a test file containing Unicode characters:

ASCII     abcde xyz
German    äöü ÄÖÜ ß
Polish    aezznl
Russian   ??????? ???
CJK       ??

Here’s a Java program to print out the test file in a bunch of different Unicode encodings. It could be in any programming language; it only prints ASCII characters or encoded bytes to stdout.

import java.io.*;

public class Foo {

    private static final String BOM = "\ufeff";
    private static final String TEST_STRING
        = "ASCII     abcde xyz\n"
        + "German    äöü ÄÖÜ ß\n"
        + "Polish    aezznl\n"
        + "Russian   ??????? ???\n"
        + "CJK       ??\n";

    public static void main(String[] args)
        throws Exception
    {
        String[] encodings = new String[] {
            "UTF-8", "UTF-16LE", "UTF-16BE", "UTF-32LE", "UTF-32BE" };

        for (String encoding: encodings) {
            System.out.println("== " + encoding);

            for (boolean writeBom: new Boolean[] {false, true}) {
                System.out.println(writeBom ? "= bom" : "= no bom");

                String output = (writeBom ? BOM : "") + TEST_STRING;
                byte[] bytes = output.getBytes(encoding);
                System.out.write(bytes);
                FileOutputStream out = new FileOutputStream("uc-test-"
                    + encoding + (writeBom ? "-bom.txt" : "-nobom.txt"));
                out.write(bytes);
                out.close();
            }
        }
    }
}

The output in the default codepage? Total garbage!

Z:\andrew\projects\sx\1259084>chcp
Active code page: 850

Z:\andrew\projects\sx\1259084>java Foo
== UTF-8
= no bom
ASCII     abcde xyz
German    +ñ+Â++ +ä+û+£ +ƒ
Polish    -à-Ö+¦+++ä+é
Russian   ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK       õ¢áÕÑ¢
= bom
´++ASCII     abcde xyz
German    +ñ+Â++ +ä+û+£ +ƒ
Polish    -à-Ö+¦+++ä+é
Russian   ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK       õ¢áÕÑ¢
== UTF-16LE
= no bom
A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h         ????z?|?D?B?
 R u s s i a n       0?1?2?3?4?5?6?  M?N?O?
 C J K               `O}Y
 = bom
 ¦A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h         ????z?|?D?B?
 R u s s i a n       0?1?2?3?4?5?6?  M?N?O?
 C J K               `O}Y
 == UTF-16BE
= no bom
 A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h        ?????z?|?D?B
 R u s s i a n      ?0?1?2?3?4?5?6  ?M?N?O
 C J K              O`Y}
= bom
¦  A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h        ?????z?|?D?B
 R u s s i a n      ?0?1?2?3?4?5?6  ?M?N?O
 C J K              O`Y}
== UTF-32LE
= no bom
A   S   C   I   I                       a   b   c   d   e       x   y   z
   G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
   P   o   l   i   s   h                   ??  ??  z?  |?  D?  B?
   R   u   s   s   i   a   n               0?  1?  2?  3?  4?  5?  6?      M?  N
?  O?
   C   J   K                               `O  }Y
   = bom
 ¦  A   S   C   I   I                       a   b   c   d   e       x   y   z

   G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
   P   o   l   i   s   h                   ??  ??  z?  |?  D?  B?
   R   u   s   s   i   a   n               0?  1?  2?  3?  4?  5?  6?      M?  N
?  O?
   C   J   K                               `O  }Y
   == UTF-32BE
= no bom
   A   S   C   I   I                       a   b   c   d   e       x   y   z
   G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
   P   o   l   i   s   h                  ??  ??  ?z  ?|  ?D  ?B
   R   u   s   s   i   a   n              ?0  ?1  ?2  ?3  ?4  ?5  ?6      ?M  ?N
  ?O
   C   J   K                              O`  Y}
= bom
  ¦    A   S   C   I   I                       a   b   c   d   e       x   y   z

   G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
   P   o   l   i   s   h                  ??  ??  ?z  ?|  ?D  ?B
   R   u   s   s   i   a   n              ?0  ?1  ?2  ?3  ?4  ?5  ?6      ?M  ?N
  ?O
   C   J   K                              O`  Y}

However, what if we type the files that got saved? They contain the exact same bytes that were printed to the console.

Z:\andrew\projects\sx\1259084>type *.txt

uc-test-UTF-16BE-bom.txt


¦  A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h        ?????z?|?D?B
 R u s s i a n      ?0?1?2?3?4?5?6  ?M?N?O
 C J K              O`Y}

uc-test-UTF-16BE-nobom.txt


 A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h        ?????z?|?D?B
 R u s s i a n      ?0?1?2?3?4?5?6  ?M?N?O
 C J K              O`Y}

uc-test-UTF-16LE-bom.txt


ASCII     abcde xyz
German    äöü ÄÖÜ ß
Polish    aezznl
Russian   ??????? ???
CJK       ??

uc-test-UTF-16LE-nobom.txt


A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h         ????z?|?D?B?
 R u s s i a n       0?1?2?3?4?5?6?  M?N?O?
 C J K               `O}Y

uc-test-UTF-32BE-bom.txt


  ¦    A   S   C   I   I                       a   b   c   d   e       x   y   z

   G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
   P   o   l   i   s   h                  ??  ??  ?z  ?|  ?D  ?B
   R   u   s   s   i   a   n              ?0  ?1  ?2  ?3  ?4  ?5  ?6      ?M  ?N
  ?O
   C   J   K                              O`  Y}

uc-test-UTF-32BE-nobom.txt


   A   S   C   I   I                       a   b   c   d   e       x   y   z
   G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
   P   o   l   i   s   h                  ??  ??  ?z  ?|  ?D  ?B
   R   u   s   s   i   a   n              ?0  ?1  ?2  ?3  ?4  ?5  ?6      ?M  ?N
  ?O
   C   J   K                              O`  Y}

uc-test-UTF-32LE-bom.txt


 A S C I I           a b c d e   x y z
 G e r m a n         ä ö ü   Ä Ö Ü   ß
 P o l i s h         a e z z n l
 R u s s i a n       ? ? ? ? ? ? ?   ? ? ?
 C J K               ? ?

uc-test-UTF-32LE-nobom.txt


A   S   C   I   I                       a   b   c   d   e       x   y   z
   G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
   P   o   l   i   s   h                   ??  ??  z?  |?  D?  B?
   R   u   s   s   i   a   n               0?  1?  2?  3?  4?  5?  6?      M?  N
?  O?
   C   J   K                               `O  }Y

uc-test-UTF-8-bom.txt


´++ASCII     abcde xyz
German    +ñ+Â++ +ä+û+£ +ƒ
Polish    -à-Ö+¦+++ä+é
Russian   ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK       õ¢áÕÑ¢

uc-test-UTF-8-nobom.txt


ASCII     abcde xyz
German    +ñ+Â++ +ä+û+£ +ƒ
Polish    -à-Ö+¦+++ä+é
Russian   ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK       õ¢áÕÑ¢

The only thing that works is UTF-16LE file, with a BOM, printed to the console via type.

If we use anything other than type to print the file, we get garbage:

Z:\andrew\projects\sx\1259084>copy uc-test-UTF-16LE-bom.txt CON
 ¦A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h         ????z?|?D?B?
 R u s s i a n       0?1?2?3?4?5?6?  M?N?O?
 C J K               `O}Y
         1 file(s) copied.

From the fact that copy CON does not display Unicode correctly, we can conclude that the type command has logic to detect a UTF-16LE BOM at the start of the file, and use special Windows APIs to print it.

We can see this by opening cmd.exe in a debugger when it goes to type out a file:

enter image description here

After type opens a file, it checks for a BOM of 0xFEFF—i.e., the bytes 0xFF 0xFE in little-endian—and if there is such a BOM, type sets an internal fOutputUnicode flag. This flag is checked later to decide whether to call WriteConsoleW.

But that’s the only way to get type to output Unicode, and only for files that have BOMs and are in UTF-16LE. For all other files, and for programs that don’t have special code to handle console output, your files will be interpreted according to the current codepage, and will likely show up as gibberish.

You can emulate how type outputs Unicode to the console in your own programs like so:

#include <stdio.h>
#define UNICODE
#include <windows.h>

static LPCSTR lpcsTest =
    "ASCII     abcde xyz\n"
    "German    äöü ÄÖÜ ß\n"
    "Polish    aezznl\n"
    "Russian   ??????? ???\n"
    "CJK       ??\n";

int main() {
    int n;
    wchar_t buf[1024];

    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

    n = MultiByteToWideChar(CP_UTF8, 0,
            lpcsTest, strlen(lpcsTest),
            buf, sizeof(buf));

    WriteConsole(hConsole, buf, n, &n, NULL);

    return 0;
}

This program works for printing Unicode on the Windows console using the default codepage.


For the sample Java program, we can get a little bit of correct output by setting the codepage manually, though the output gets messed up in weird ways:

Z:\andrew\projects\sx\1259084>chcp 65001
Active code page: 65001

Z:\andrew\projects\sx\1259084>java Foo
== UTF-8
= no bom
ASCII     abcde xyz
German    äöü ÄÖÜ ß
Polish    aezznl
Russian   ??????? ???
CJK       ??
? ???
CJK       ??
 ??
?
?
= bom
ASCII     abcde xyz
German    äöü ÄÖÜ ß
Polish    aezznl
Russian   ??????? ???
CJK       ??
?? ???
CJK       ??
  ??
?
?
== UTF-16LE
= no bom
A S C I I           a b c d e   x y z
…

However, a C program that sets a Unicode UTF-8 codepage:

#include <stdio.h>
#include <windows.h>

int main() {
    int c, n;
    UINT oldCodePage;
    char buf[1024];

    oldCodePage = GetConsoleOutputCP();
    if (!SetConsoleOutputCP(65001)) {
        printf("error\n");
    }

    freopen("uc-test-UTF-8-nobom.txt", "rb", stdin);
    n = fread(buf, sizeof(buf[0]), sizeof(buf), stdin);
    fwrite(buf, sizeof(buf[0]), n, stdout);

    SetConsoleOutputCP(oldCodePage);

    return 0;
}

does have correct output:

Z:\andrew\projects\sx\1259084>.\test
ASCII     abcde xyz
German    äöü ÄÖÜ ß
Polish    aezznl
Russian   ??????? ???
CJK       ??

The moral of the story?

  • type can print UTF-16LE files with a BOM regardless of your current codepage
  • Win32 programs can be programmed to output Unicode to the console, using WriteConsoleW.
  • Other programs which set the codepage and adjust their output encoding accordingly can print Unicode on the console regardless of what the codepage was when the program started
  • For everything else you will have to mess around with chcp, and will probably still get weird output.

Deleting all files in a directory with Python

you can create a function. Add maxdepth as you like for traversing subdirectories.

def findNremove(path,pattern,maxdepth=1):
    cpath=path.count(os.sep)
    for r,d,f in os.walk(path):
        if r.count(os.sep) - cpath <maxdepth:
            for files in f:
                if files.endswith(pattern):
                    try:
                        print "Removing %s" % (os.path.join(r,files))
                        #os.remove(os.path.join(r,files))
                    except Exception,e:
                        print e
                    else:
                        print "%s removed" % (os.path.join(r,files))

path=os.path.join("/home","dir1","dir2")
findNremove(path,".bak")

How to extend a class in python?

class MyParent:

    def sayHi():
        print('Mamma says hi')
from path.to.MyParent import MyParent

class ChildClass(MyParent):
    pass

An instance of ChildClass will then inherit the sayHi() method.

Prevent text selection after double click

In plain javascript:

element.addEventListener('mousedown', function(e){ e.preventDefault(); }, false);

Or with jQuery:

jQuery(element).mousedown(function(e){ e.preventDefault(); });

Counting DISTINCT over multiple columns

I wish MS SQL could also do something like COUNT(DISTINCT A, B). But it can't.

At first JayTee's answer seemed like a solution to me bu after some tests CHECKSUM() failed to create unique values. A quick example is, both CHECKSUM(31,467,519) and CHECKSUM(69,1120,823) gives the same answer which is 55.

Then I made some research and found that Microsoft does NOT recommend using CHECKSUM for change detection purposes. In some forums some suggested using

SELECT COUNT(DISTINCT CHECKSUM(value1, value2, ..., valueN) + CHECKSUM(valueN, value(N-1), ..., value1))

but this is also not conforting.

You can use HASHBYTES() function as suggested in TSQL CHECKSUM conundrum. However this also has a small chance of not returning unique results.

I would suggest using

SELECT COUNT(DISTINCT CAST(DocumentId AS VARCHAR)+'-'+CAST(DocumentSessionId AS VARCHAR)) FROM DocumentOutputItems

Java - Using Accessor and Mutator methods

You need to remove the static from your accessor methods - these methods need to be instance methods and access the instance variables

public class IDCard {
    public String name, fileName;
    public int id;

    public IDCard(final String name, final String fileName, final int id) {
        this.name = name;
        this.fileName = fileName
        this.id = id;
    }

    public String getName() {
        return name;
    }
}

You can the create an IDCard and use the accessor like this:

final IDCard card = new IDCard();
card.getName();

Each time you call new a new instance of the IDCard will be created and it will have it's own copies of the 3 variables.

If you use the static keyword then those variables are common across every instance of IDCard.

A couple of things to bear in mind:

  1. don't add useless comments - they add code clutter and nothing else.
  2. conform to naming conventions, use lower case of variable names - name not Name.

Intellij idea subversion checkout error: `Cannot run program "svn"`

For me, on Debian GNU / Linux, installing the subversion package was the solution

# aptitude install subversion subversion-tool

Eclipse interface icons very small on high resolution screen in Windows 8.1

The best way is to edit the exe manifest with something like resource tuner and add

    <application xmlns="urn:schemas-microsoft-com:asm.v3"><windowsSettings><ms_windowsSettings:dpiAware xmlns:ms_windowsSettings="http://schemas.microsoft.com/SMI/2005/WindowsSettings" xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">false</ms_windowsSettings:dpiAware></windowsSettings></application>        

after dependency to set the exe as dpi unaware. This way the program will be a little pixelated but it will be in a confortable size.

I can't install python-ldap

To install python-ldap successfully with pip, following development libraries are needed (package names taken from ubuntu environment):

sudo apt-get install -y python-dev libldap2-dev libsasl2-dev libssl-dev

Git merge develop into feature branch outputs "Already up-to-date" while it's not

Initially my repo said "Already up to date."

MINGW64 (feature/Issue_123) 
$ git merge develop

Output:

Already up to date.

But the code is not up to date & it is showing some differences in some files.

MINGW64 (feature/Issue_123)
$ git diff develop

Output:

diff --git 
a/src/main/database/sql/additional/pkg_etl.sql 
b/src/main/database/sql/additional/pkg_etl.sql
index ba2a257..1c219bb 100644
--- a/src/main/database/sql/additional/pkg_etl.sql
+++ b/src/main/database/sql/additional/pkg_etl.sql

However, merging fixes it.

MINGW64 (feature/Issue_123)
$ git merge origin/develop

Output:

Updating c7c0ac9..09959e3
Fast-forward
3 files changed, 157 insertions(+), 92 deletions(-)

Again I have confirmed this by using diff command.

MINGW64 (feature/Issue_123)
$ git diff develop

No differences in the code now!

How to set timeout on python's socket recv method?

As mentioned both select.select() and socket.settimeout() will work.

Note you might need to call settimeout twice for your needs, e.g.

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("",0))
sock.listen(1)
# accept can throw socket.timeout
sock.settimeout(5.0)
conn, addr = sock.accept()

# recv can throw socket.timeout
conn.settimeout(5.0)
conn.recv(1024)

Docker official registry (Docker Hub) URL

You're able to get the current registry-url using docker info:

...
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Labels:
...

That's also the url you may use to run your self hosted-registry:

docker run -d -p 5000:5000 --name registry -e REGISTRY_PROXY_REMOTEURL=https://index.docker.io registry:2

Grep & use it right away:

$ echo $(docker info | grep -oP "(?<=Registry: ).*")
https://index.docker.io/v1/

What is REST call and how to send a REST call?

REST is just a software architecture style for exposing resources.

  • Use HTTP methods explicitly.
  • Be stateless.
  • Expose directory structure-like URIs.
  • Transfer XML, JavaScript Object Notation (JSON), or both.

A typical REST call to return information about customer 34456 could look like:

http://example.com/customer/34456

Have a look at the IBM tutorial for REST web services

Add column to SQL Server

Add new column to Table

ALTER TABLE [table]
ADD Column1 Datatype

E.g

ALTER TABLE [test]
ADD ID Int

If User wants to make it auto incremented then

ALTER TABLE [test]
ADD ID Int IDENTITY(1,1) NOT NULL

Regex to get string between curly braces

Here's a simple solution using javascript replace

var st = '{getThis}';

st = st.replace(/\{|\}/gi,''); // "getThis"

As the accepted answer above points out the original problem is easily solved with substring, but using replace can solve the more complicated use cases

If you have a string like "randomstring999[fieldname]" You use a slightly different pattern to get fieldname

var nameAttr = "randomstring999[fieldname]";

var justName = nameAttr.replace(/.*\[|\]/gi,''); // "fieldname"

Batch file to split .csv file

This will give you lines 1 to 20000 in newfile1.csv
and lines 20001 to the end in file newfile2.csv

It overcomes the 8K character limit per line too.

This uses a helper batch file called findrepl.bat from - https://www.dropbox.com/s/rfdldmcb6vwi9xc/findrepl.bat

Place findrepl.bat in the same folder as the batch file or on the path.

It's more robust than a plain batch file, and quicker too.

findrepl /o:1:20000 <file.csv >newfile1.csv
findrepl /o:20001   <file.csv >newfile2.csv

Difference between FetchType LAZY and EAGER in Java Persistence API?

Both FetchType.LAZY and FetchType.EAGER are used to define the default fetch plan.

Unfortunately, you can only override the default fetch plan for LAZY fetching. EAGER fetching is less flexible and can lead to many performance issues.

My advice is to restrain the urge of making your associations EAGER because fetching is a query-time responsibility. So all your queries should use the fetch directive to only retrieve what's necessary for the current business case.

Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (38)

In my case the solution was that I had mariadb installed, which was aliased to mysql. So all service commands relating to mysql were not recognised... I just needed:

service mariadb start

And for good measure:

chkconfig mariadb on

textarea character limit

... onkeydown="if(value.length>500)value=value.substr(0,500); if(value.length==500)return false;" ...

It ought to work.

Program to find largest and smallest among 5 numbers without using array

int findMin(int t1, int t2, int t3, int t4, int t5)
{
    int min1, min2, min3;

    min1 = std::min(t1, t2);
    min2 = std::min(t3, t4);
    min3 = std::min(min1, min2);
    return std::min(min3, t5);
}

int findMax(int t1, int t2, int t3, int t4, int t5)
{
    int max1, max2, max3;

    max1 = std::max(t1, t2);
    max2 = std::max(t3, t4);
    max3 = std::max(max1, max2);
    return std::max(max3, t5);
}

These functions are very messy but easy to follow and thus easy to remember and it only uses the simple min and max methods which work best for 2 values.

What's a good hex editor/viewer for the Mac?

One recommendation I've gotten is Hex Fiend.

Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on

I don't know if this is good enough but I made a static ThreadHelperClass class and implemented it as following .Now I can easily set text property of various controls without much coding .

public static class ThreadHelperClass
{
    delegate void SetTextCallback(Form f, Control ctrl, string text);
    /// <summary>
    /// Set text property of various controls
    /// </summary>
    /// <param name="form">The calling form</param>
    /// <param name="ctrl"></param>
    /// <param name="text"></param>
    public static void SetText(Form form, Control ctrl, string text)
    {
        // InvokeRequired required compares the thread ID of the 
        // calling thread to the thread ID of the creating thread. 
        // If these threads are different, it returns true. 
        if (ctrl.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(SetText);
            form.Invoke(d, new object[] { form, ctrl, text });
        }
        else
        {
            ctrl.Text = text;
        }
    }
}

Using the code:

 private void btnTestThread_Click(object sender, EventArgs e)
 {
    Thread demoThread =
       new Thread(new ThreadStart(this.ThreadProcSafe));
            demoThread.Start();
 }

 // This method is executed on the worker thread and makes 
 // a thread-safe call on the TextBox control. 
 private void ThreadProcSafe()
 {
     ThreadHelperClass.SetText(this, textBox1, "This text was set safely.");
     ThreadHelperClass.SetText(this, textBox2, "another text was set safely.");
 }

Angular/RxJs When should I unsubscribe from `Subscription`

You don't need to have bunch of subscriptions and unsubscribe manually. Use Subject and takeUntil combo to handle subscriptions like a boss:

import { Subject } from "rxjs"
import { takeUntil } from "rxjs/operators"

@Component({
  moduleId: __moduleName,
  selector: "my-view",
  templateUrl: "../views/view-route.view.html"
})
export class ViewRouteComponent implements OnInit, OnDestroy {
  componentDestroyed$: Subject<boolean> = new Subject()

  constructor(private titleService: TitleService) {}

  ngOnInit() {
    this.titleService.emitter1$
      .pipe(takeUntil(this.componentDestroyed$))
      .subscribe((data: any) => { /* ... do something 1 */ })

    this.titleService.emitter2$
      .pipe(takeUntil(this.componentDestroyed$))
      .subscribe((data: any) => { /* ... do something 2 */ })

    //...

    this.titleService.emitterN$
      .pipe(takeUntil(this.componentDestroyed$))
      .subscribe((data: any) => { /* ... do something N */ })
  }

  ngOnDestroy() {
    this.componentDestroyed$.next(true)
    this.componentDestroyed$.complete()
  }
}

Alternative approach, which was proposed by @acumartini in comments, uses takeWhile instead of takeUntil. You may prefer it, but mind that this way your Observable execution will not be cancelled on ngDestroy of your component (e.g. when you make time consuming calculations or wait for data from server). Method, which is based on takeUntil, doesn't have this drawback and leads to immediate cancellation of request. Thanks to @AlexChe for detailed explanation in comments.

So here is the code:

@Component({
  moduleId: __moduleName,
  selector: "my-view",
  templateUrl: "../views/view-route.view.html"
})
export class ViewRouteComponent implements OnInit, OnDestroy {
  alive: boolean = true

  constructor(private titleService: TitleService) {}

  ngOnInit() {
    this.titleService.emitter1$
      .pipe(takeWhile(() => this.alive))
      .subscribe((data: any) => { /* ... do something 1 */ })

    this.titleService.emitter2$
      .pipe(takeWhile(() => this.alive))
      .subscribe((data: any) => { /* ... do something 2 */ })

    // ...

    this.titleService.emitterN$
      .pipe(takeWhile(() => this.alive))
      .subscribe((data: any) => { /* ... do something N */ })
  }

  ngOnDestroy() {
    this.alive = false
  }
}

UILabel font size?

[label setFont:[UIFont systemFontOfSize:9]];

this works for me.

BAT file to map to network drive without running as admin

Save below in a test.bat and It'll work for you:

@echo off

net use Z: \\server\SharedFolderName password /user:domain\Username /persistent:yes

/persistent:yes flag will tell the computer to automatically reconnect this share on logon. Otherwise, you need to run the script again during each boot to map the drive.

For Example:

net use Z: \\WindowsServer123\g$ P@ssw0rd /user:Mynetdomain\Sysadmin /persistent:yes

async await return Task

You need to use the await keyword when use async and your function return type should be generic Here is an example with return value:

public async Task<object> MethodName()
{
    return await Task.FromResult<object>(null);
}

Here is an example with no return value:

public async Task MethodName()
{
    await Task.CompletedTask;
}

Read these:

TPL: http://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx and Tasks: http://msdn.microsoft.com/en-us/library/system.threading.tasks(v=vs.110).aspx

Async: http://msdn.microsoft.com/en-us/library/hh156513.aspx Await: http://msdn.microsoft.com/en-us/library/hh156528.aspx

What is the minimum I have to do to create an RPM file?

Easy way to build rpm package from binary (these steps were tested with Fedora 18):

1) First you have to install rpmdevtools, so run these commands (attention: run as normal user)

$ sudo yum install rpmdevtools rpmlint
$ rpmdev-setuptree

2) In the ~/rpmbuild/SPECS folder create new file: package_name.spec

3) Open it with an editor (like gedit) and write this:

Name:           package_name
Version:        1.0
Release:        1
Summary:        Short description (first char has to be uppercase)

License:        GPL
URL:            www. your_website/

BuildRequires:  package_required >= (or ==, or <=) 1.0.3 (for example)

%description
Description with almost 79 characters (first char has to be uppercase)

#This is a comment (just as example)

%files
/usr/bin/binary_file.bin
/usr/share/applications/package_name.desktop
/usr/share/pixmaps/package_name.png

%changelog
* date Packager's Name <packager's_email> version-revision
- Summary of changes

#For more details see: docs.fedoraproject.org/en-US/Fedora_Draft_Documentation/0.1/html/Packagers_Guide/sect-Packagers_Guide-Creating_a_Basic_Spec_File.html

4) Make ~/rpmbuild/BUILDROOT/package_name-version-release.i386 and reproduce the paths where the files will be placed So in this case for example create:

  • ~/rpmbuild/BUILDROOT/package_name-version-release.i386/usr/bin/
  • ~/rpmbuild/BUILDROOT/package_name-version-release.i386/usr/share/applications/
  • ~/rpmbuild/BUILDROOT/package_name-version-release.i386/usr/share/pixmaps/

5) Put in these folders the files that you want insert in the package:

  • ~/rpmbuild/BUILDROOT/package_name-version-release.i386/usr/bin/binary_file.bin
  • ~/rpmbuild/BUILDROOT/package_name-version-release.i386/usr/share/applications/package_name.desktop
  • ~/rpmbuild/BUILDROOT/package_name-version-release.i386/usr/share/pixmaps/package_name.png

usr/share/pixmaps/package_name.png is the icon of binary usr/share/applications/package_name.desktop are the rules to insert the program in the menu entries

6) package_name.desktop must be like this:

[Desktop Entry]
Encoding=UTF-8
Type=Application
Name=example
GenericName=Short description
Comment=Comment of the application
Exec=package_name
Icon=package_name
Terminal=false
Categories=System;

Categories are these: standards.freedesktop.org/menu-spec/latest/apa.html

7) Run $ rpmbuild -bb ~/rpmbuild/SPECS/package_name.spec

8) Your package was built into ~/rpmbuild/RPMS folder

if you install this package it's install:

  • /usr/bin/binary_file.bin
  • /usr/share/applications/package_name.desktop
  • /usr/share/pixmaps/package_name.png

Thanks to: losurs.org/docs/tips/redhat/binary-rpms

For more details to build rpm take a look at this link.

GUI java software to build rpm: https://sourceforge.net/projects/javarpmbuilder/

How do I directly modify a Google Chrome Extension File? (.CRX)

I searched it in Google and I found this:

The Google Chrome Extension file type is CRX. It is essentially a compression format. So if you want to see what is behind an extension, the scripts and the code, just change the file-type from “CRX” to “ZIP” .

Unzip the file and you will get all the info you need. This way you can see the guts, learn how to write an extension yourself, or modify it for your own needs.

Then you can pack it back up with Chrome’s internal tools which automatically create the file back into CRX. Installing it just requires a click.

Moment.js - how do I get the number of years since a date, not rounded up?

There appears to be a difference function that accepts time intervals to use as well as an option to not round the result. So, something like

Math.floor(moment(new Date()).diff(moment("02/26/1978","MM/DD/YYYY"),'years',true)))

I haven't tried this, and I'm not completely familiar with moment, but it seems like this should get what you want (without having to reset the month).

How do I get the coordinate position after using jQuery drag and drop?

I just made something like that (If I understand you correctly).

I use he function position() include in jQuery 1.3.2.

Just did a copy paste and a quick tweak... But should give you the idea.

// Make images draggable.
$(".item").draggable({

    // Find original position of dragged image.
    start: function(event, ui) {

        // Show start dragged position of image.
        var Startpos = $(this).position();
        $("div#start").text("START: \nLeft: "+ Startpos.left + "\nTop: " + Startpos.top);
    },

    // Find position where image is dropped.
    stop: function(event, ui) {

        // Show dropped position.
        var Stoppos = $(this).position();
        $("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top);
    }
});

<div id="container">
    <img id="productid_1" src="images/pic1.jpg" class="item" alt="" title="" />
    <img id="productid_2" src="images/pic2.jpg" class="item" alt="" title="" />
    <img id="productid_3" src="images/pic3.jpg" class="item" alt="" title="" />
</div>

<div id="start">Waiting for dragging the image get started...</div>
<div id="stop">Waiting image getting dropped...</div>

isolating a sub-string in a string before a symbol in SQL Server 2008

DECLARE @dd VARCHAR(200) = 'Net Operating Loss - 2007';

SELECT SUBSTRING(@dd, 1, CHARINDEX('-', @dd) -1) F1,
       SUBSTRING(@dd, CHARINDEX('-', @dd) +1, LEN(@dd)) F2

input[type='text'] CSS selector does not apply to default-type text inputs?

try this

 input[type='text']
 {
   background:red !important;
 }

Android selector & text color

And selector is the answer here as well.

Search for bright_text_dark_focused.xml in the sources, add to your project under res/color directory and then refer from the TextView as

android:textColor="@color/bright_text_dark_focused"

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

In addition to what TaskManager shows, if you use ProcessExplorer from Sysinternals, you can tell when you right-click on the process name and select Properties. In the Image tab, there is a field toward the bottom that says Image. It says 32-bit for a 32 bit application and 64 bit for the 64 bit application.

How to change a PG column to NULLABLE TRUE?

From the fine manual:

ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;

There's no need to specify the type when you're just changing the nullability.

PHPExcel auto size column width

If you need to do that on multiple sheets, and multiple columns in each sheet, here is how you can iterate through all of them:

// Auto size columns for each worksheet
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {

    $objPHPExcel->setActiveSheetIndex($objPHPExcel->getIndex($worksheet));

    $sheet = $objPHPExcel->getActiveSheet();
    $cellIterator = $sheet->getRowIterator()->current()->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(true);
    /** @var PHPExcel_Cell $cell */
    foreach ($cellIterator as $cell) {
        $sheet->getColumnDimension($cell->getColumn())->setAutoSize(true);
    }
}

Execute SQL script to create tables and rows

In the MySQL interactive client you can type:

source yourfile.sql

Alternatively you can pipe the data into mysql from the command line:

mysql < yourfile.sql

If the file doesn't specify a database then you will also need to add that:

mysql db_name < yourfile.sql

See the documentation for more details:

ORA-00979 not a group by expression

In addition to the other answers, this error can result if there's an inconsistency in an order by clause. For instance:

select 
    substr(year_month, 1, 4)
    ,count(*) as tot
from
    schema.tbl
group by
    substr(year_month, 1, 4)
order by
    year_month

Google Spreadsheet, Count IF contains a string

It will likely have been solved by now, but I ran accross this and figured to give my input

=COUNTIF(a2:a51;"*iPad*")

The important thing is that separating parameters in google docs is using a ; and not a ,

When to use MyISAM and InnoDB?

Read about Storage Engines.

MyISAM:

The MyISAM storage engine in MySQL.

  • Simpler to design and create, thus better for beginners. No worries about the foreign relationships between tables.
  • Faster than InnoDB on the whole as a result of the simpler structure thus much less costs of server resources. -- Mostly no longer true.
  • Full-text indexing. -- InnoDB has it now
  • Especially good for read-intensive (select) tables. -- Mostly no longer true.
  • Disk footprint is 2x-3x less than InnoDB's. -- As of Version 5.7, this is perhaps the only real advantage of MyISAM.

InnoDB:

The InnoDB storage engine in MySQL.

  • Support for transactions (giving you support for the ACID property).
  • Row-level locking. Having a more fine grained locking-mechanism gives you higher concurrency compared to, for instance, MyISAM.
  • Foreign key constraints. Allowing you to let the database ensure the integrity of the state of the database, and the relationships between tables.
  • InnoDB is more resistant to table corruption than MyISAM.
  • Support for large buffer pool for both data and indexes. MyISAM key buffer is only for indexes.
  • MyISAM is stagnant; all future enhancements will be in InnoDB. This was made abundantly clear with the roll out of Version 8.0.

MyISAM Limitations:

  • No foreign keys and cascading deletes/updates
  • No transactional integrity (ACID compliance)
  • No rollback abilities
  • 4,284,867,296 row limit (2^32) -- This is old default. The configurable limit (for many versions) has been 2**56 bytes.
  • Maximum of 64 indexes per table

InnoDB Limitations:

  • No full text indexing (Below-5.6 mysql version)
  • Cannot be compressed for fast, read-only (5.5.14 introduced ROW_FORMAT=COMPRESSED)
  • You cannot repair an InnoDB table

For brief understanding read below links:

  1. MySQL Engines: InnoDB vs. MyISAM – A Comparison of Pros and Cons
  2. MySQL Engines: MyISAM vs. InnoDB
  3. What are the main differences between InnoDB and MyISAM?
  4. MyISAM versus InnoDB
  5. What's the difference between MyISAM and InnoDB?
  6. MySql: MyISAM vs. Inno DB!

Modifying a subset of rows in a pandas dataframe

For a massive speed increase, use NumPy's where function.

Setup

Create a two-column DataFrame with 100,000 rows with some zeros.

df = pd.DataFrame(np.random.randint(0,3, (100000,2)), columns=list('ab'))

Fast solution with numpy.where

df['b'] = np.where(df.a.values == 0, np.nan, df.b.values)

Timings

%timeit df['b'] = np.where(df.a.values == 0, np.nan, df.b.values)
685 µs ± 6.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit df.loc[df['a'] == 0, 'b'] = np.nan
3.11 ms ± 17.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Numpy's where is about 4x faster

Converting a vector<int> to string

Maybe std::ostream_iterator and std::ostringstream:

#include <vector>
#include <string>
#include <algorithm>
#include <sstream>
#include <iterator>
#include <iostream>

int main()
{
  std::vector<int> vec;
  vec.push_back(1);
  vec.push_back(4);
  vec.push_back(7);
  vec.push_back(4);
  vec.push_back(9);
  vec.push_back(7);

  std::ostringstream oss;

  if (!vec.empty())
  {
    // Convert all but the last element to avoid a trailing ","
    std::copy(vec.begin(), vec.end()-1,
        std::ostream_iterator<int>(oss, ","));

    // Now add the last element with no delimiter
    oss << vec.back();
  }

  std::cout << oss.str() << std::endl;
}

How do I vertically align text in a paragraph?

Below styles will vertically center it for you.

p.event_desc {
 font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;
 line-height: 14px;
 height: 35px;
 display: table-cell;
 vertical-align: middle;
 margin: 0px;
}

Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

Basically, to make a cross domain AJAX requests, the requested server should allow the cross origin sharing of resources (CORS). You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/

In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/app server side code.

If you are using PHP Apache server, then you will need to add following in your .htaccess file:

Header set Access-Control-Allow-Origin "*"

How do I remove the top margin in a web page?

I have been having a similar issue. I wanted a percentage height and top-margin for my container div, but the body would take on the margin of the container div. I think I figured out a solution.

Here is my original (problem) code:

html {
    height:100%;
}

body {
    height:100%;                    
    margin-top:0%;
    padding:0%; 
}

#pageContainer {
    position:relative;
    width:96%;                  /* 100% - (margin * 2) */
    height:96%;                 /* 100% - (margin * 2) */           
    margin:2% auto 0% auto;
    padding:0%;
}

My solution was to set the height of the body the same as the height of the container.
html { height:100%; }

body {
    height:96%;     /* 100% * (pageContainer*2) */
    margin-top:0%;
    padding:0%; 
}

#pageContainer {
    position:relative;
    width:96%;                  /* 100% - (margin * 2) */
    height:96%;                 /* 100% - (margin * 2) */           
    margin:2% auto 0% auto;
    padding:0%;
}

I haven't tested it in every browser, but this seems to work.

How to Migrate to WKWebView?

WKWebView using Swift in iOS 8..

The whole ViewController.swift file now looks like this:

import UIKit
import WebKit

class ViewController: UIViewController {

    @IBOutlet var containerView : UIView! = nil
    var webView: WKWebView?

    override func loadView() {
        super.loadView()

        self.webView = WKWebView()
        self.view = self.webView!
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var url = NSURL(string:"http://www.kinderas.com/")
        var req = NSURLRequest(URL:url)
        self.webView!.loadRequest(req)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Deserialize JSON string to c# object

Use this code:

var result=JsonConvert.DeserializeObject<List<yourObj>>(jsonString);

Combine Regexp?

In my experience with regex you really need to focus on what EXACTLY you are trying to match, rather than what NOT to match.

for example

\d{2}

[1-9][0-9]

The first expression will match any 2 digits....and the second will match 1 digit from 1 to 9 and 1 digit - any digit. So if you type 07 the first expression will validate it, but the second one will not.

See this for advanced reference:

http://www.regular-expressions.info/refadv.html

EDITED:

^((?!my string).)*$ Is the regular expression for does not contain "my string".

Regex to match URL end-of-line or "/" character

To match either / or end of content, use (/|\z)

This only applies if you are not using multi-line matching (i.e. you're matching a single URL, not a newline-delimited list of URLs).


To put that with an updated version of what you had:

/(\S+?)/(\d{4}-\d{2}-\d{2})-(\d+)(/|\z)

Note that I've changed the start to be a non-greedy match for non-whitespace ( \S+? ) rather than matching anything and everything ( .* )

Align the form to the center in Bootstrap 4

You need to use the various Bootstrap 4 centering methods...

  • Use text-center for inline elements.
  • Use justify-content-center for flexbox elements (ie; form-inline)

https://codeply.com/go/Am5LvvjTxC

Also, to offset the column, the col-sm-* must be contained within a .row, and the .row must be in a container...

<section id="cover">
    <div id="cover-caption">
        <div id="container" class="container">
            <div class="row">
                <div class="col-sm-10 offset-sm-1 text-center">
                    <h1 class="display-3">Welcome to Bootstrap 4</h1>
                    <div class="info-form">
                        <form action="" class="form-inline justify-content-center">
                            <div class="form-group">
                                <label class="sr-only">Name</label>
                                <input type="text" class="form-control" placeholder="Jane Doe">
                            </div>
                            <div class="form-group">
                                <label class="sr-only">Email</label>
                                <input type="text" class="form-control" placeholder="[email protected]">
                            </div>
                            <button type="submit" class="btn btn-success ">okay, go!</button>
                        </form>
                    </div>
                    <br>

                    <a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">?</a>
                </div>
            </div>
        </div>
    </div>
</section>

Getting java.net.SocketTimeoutException: Connection timed out in android

I was facing this problem and the solution was to restart my modem (router). I could get connection for my app to internet after that.

I think the library I am using is not managing connections properly because it happeend just few times.

Where can I find documentation on formatting a date in JavaScript?

_x000D_
_x000D_
d = Date.now();_x000D_
d = new Date(d);_x000D_
d = (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear()+' '+(d.getHours() > 12 ? d.getHours() - 12 : d.getHours())+':'+d.getMinutes()+' '+(d.getHours() >= 12 ? "PM" : "AM");_x000D_
_x000D_
console.log(d);
_x000D_
_x000D_
_x000D_

How to implement drop down list in flutter?

Use this code.

class PlayerPreferences extends StatefulWidget {
  final int numPlayers;
  PlayerPreferences({this.numPlayers});

  @override
  _PlayerPreferencesState createState() => _PlayerPreferencesState();
}

class _PlayerPreferencesState extends State<PlayerPreferences> {
  int dropDownValue = 0;
  @override
  Widget build(BuildContext context) {
    return Container(
      child: DropdownButton(
        value: dropDownValue,
        onChanged: (int newVal){
          setState(() {
            dropDownValue = newVal;
          });
        },
        items: [
          DropdownMenuItem(
            value: 0,
            child: Text('Yellow'),
          ),
          DropdownMenuItem(
            value: 1,
            child: Text('Red'),
          ),
          DropdownMenuItem(
            value: 2,
            child: Text('Blue'),
          ),
          DropdownMenuItem(
            value: 3,
            child: Text('Green'),
          ),
        ],
      ),
    );
  }
}

and in the main body we call as

class ModeSelection extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Container(
          child: PlayerPreferences(),
        ) ,
      ),
    );
  }
}

AngularJS: How to make angular load script inside ng-include?

Short answer: AngularJS ("jqlite") doesn't support this. Include jQuery on your page (before including Angular), and it should work. See https://groups.google.com/d/topic/angular/H4haaMePJU0/discussion

What does if __name__ == "__main__": do?

The reason for

if __name__ == "__main__":
    main()

is primarily to avoid the import lock problems that would arise from having code directly imported. You want main() to run if your file was directly invoked (that's the __name__ == "__main__" case), but if your code was imported then the importer has to enter your code from the true main module to avoid import lock problems.

A side-effect is that you automatically sign on to a methodology that supports multiple entry points. You can run your program using main() as the entry point, but you don't have to. While setup.py expects main(), other tools use alternate entry points. For example, to run your file as a gunicorn process, you define an app() function instead of a main(). Just as with setup.py, gunicorn imports your code so you don't want it do do anything while it's being imported (because of the import lock issue).

How to use wget in php?

To run wget command in PHP you have to do following steps :

1) Allow apache server to use wget command by adding it in sudoers list.

2) Check "exec" function enabled or exist in your PHP config.

3) Run "exec" command as root user i.e. sudo user

Below code sample as per ubuntu machine

#Add apache in sudoers list to use wget command
~$ sudo nano /etc/sudoers
#add below line in the sudoers file
www-data ALL=(ALL) NOPASSWD: /usr/bin/wget


##Now in PHP file run wget command as 
exec("/usr/bin/sudo wget -P PATH_WHERE_WANT_TO_PLACE_FILE URL_OF_FILE");

`IF` statement with 3 possible answers each based on 3 different ranges

=IF(X2>=85,0.559,IF(X2>=80,0.327,IF(X2>=75,0.255,-1)))

Explanation:

=IF(X2>=85,                  'If the value is in the highest bracket
      0.559,                 'Use the appropriate number
      IF(X2>=80,             'Otherwise, if the number is in the next highest bracket
           0.327,            'Use the appropriate number
           IF(X2>=75,        'Otherwise, if the number is in the next highest bracket
              0.255,         'Use the appropriate number
              -1             'Otherwise, we're not in any of the ranges (Error)
             )
        )
   )

How to align content of a div to the bottom

I use these properties and it works!

#header {
  display: table-cell;
  vertical-align: bottom;
}

jquery live hover

This code works:

    $(".ui-button-text").live(
        'hover',
        function (ev) {
            if (ev.type == 'mouseover') {
                $(this).addClass("ui-state-hover");
            }

            if (ev.type == 'mouseout') {
                $(this).removeClass("ui-state-hover");
            }
        });

Trying to get Laravel 5 email to work

the problem will be solved by clearing cache

php artisan config:cache

How do I URL encode a string

In Swift 3, please try out below:

let stringURL = "YOUR URL TO BE ENCODE";
let encodedURLString = stringURL.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
print(encodedURLString)

Since, stringByAddingPercentEscapesUsingEncoding encodes non URL characters but leaves the reserved characters (like !*'();:@&=+$,/?%#[]), You can encode the url like the following code:

let stringURL = "YOUR URL TO BE ENCODE";
let characterSetTobeAllowed = (CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[] ").inverted)
if let encodedURLString = stringURL.addingPercentEncoding(withAllowedCharacters: characterSetTobeAllowed) {
    print(encodedURLString)
}

Difference between ref and out parameters in .NET

out and ref are exactly the same with the exception that out variables don't have to be initialized before sending it into the abyss. I'm not that smart, I cribbed that from the MSDN library :).

To be more explicit about their use, however, the meaning of the modifier is that if you change the reference of that variable in your code, out and ref will cause your calling variable to change reference as well. In the code below, the ceo variable will be a reference to the newGuy once it returns from the call to doStuff. If it weren't for ref (or out) the reference wouldn't be changed.

private void newEmployee()
{
    Person ceo = Person.FindCEO();
    doStuff(ref ceo);
}

private void doStuff(ref Person employee)
{
    Person newGuy = new Person();
    employee = newGuy;
}

How to change identity column values programmatically?

This can be done using a temporary table.

The idea

  • disable constraints (in case your id is referenced by a foreign key)
  • create a temp table with the new id
  • delete the table content
  • copy back data from the copied table to your original table
  • enable previsously disabled constraints

SQL Queries

Let's say your test table have two additional columns (column2 and column3) and that there are 2 tables having foreign keys referencing test called foreign_table1 and foreign_table2 (because real life issues are never simple).

alter table test nocheck constraint all;
alter table foreign_table1 nocheck constraint all;
alter table foreign_table2 nocheck constraint all;
set identity_insert test on;

select id + 1 as id, column2, column3 into test_copy from test v;
delete from test;
insert into test(id, column2, column3)
select id, column2, column3 from test_copy

alter table test check constraint all;
alter table foreign_table1 check constraint all;
alter table foreign_table2 check constraint all;
set identity_insert test off;
drop table test_copy;

That's it.

What is the best free SQL GUI for Linux for various DBMS systems

I use SQLite Database Browser for SQLite3 currently and it's pretty useful. Works across Windows/OS X/Linux and is lightweight and fast. Slightly unstable with executing SQL on the DB if it's incorrectly formatted.

Edit: I have recently discovered SQLite Manager, a plugin for Firefox. Obviously you need to run Firefox, but you can close all windows and just run it "standalone". It's very feature complete, amazingly stable and it remembers your databases! It has tonnes of features so I've moved away from SQLite Database Browser as the instability and lack of features is too much to bear.

Multiple github accounts on the same computer?

Simpler and Easy fix to avoid confusions..

For Windows users to use multiple or different git accounts for different projects.

Following steps: Go Control Panel and Search for Credential Manager. Then Go to Credential Manager -> Windows Credentials

Now remove the git:https//github.com node under Generic Credentials Heading

This will remove the current credentials. Now you can add any project through git pull it will ask for username and password.

When you face any issue with other account do the same process.

Thanks

refer to image

Aligning a float:left div to center?

use display:inline-block; instead of float

you can't centre floats, but inline-blocks centre as if they were text, so on the outer overall container of your "row" - you would set text-align: center; then for each image/caption container (it's those which would be inline-block;) you can re-align the text to left if you require

Aligning a button to the center

You should use something like this:

<div style="text-align:center">  
    <input type="submit" />  
</div>  

Or you could use something like this. By giving the element a width and specifying auto for the left and right margins the element will center itself in its parent.

<input type="submit" style="width: 300px; margin: 0 auto;" />

Export and import table dump (.sql) using pgAdmin

If you have Git bash installed, you can do something like this:

/c/Program\ Files\ \(x86\)/PostgreSQL/9.3/bin/psql -U <pg_role_name> -d <pg_database_name> < <path_to_your>.sql

Maven – Always download sources and javadocs

I am using Maven 3.3.3 and cannot get the default profile to work in a user or global settings.xml file.

As a workaround, you may also add an additional build plugin to your pom.xml file.

<properties>
    <maven-dependency-plugin.version>2.10</maven-dependency-plugin.version>
</properties>
<build>
    <plugins>
        <!-- Download Java source JARs. -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>${maven-dependency-plugin.version}</version>
            <executions>
                <execution>
                    <goals>
                        <goal>sources</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

string sanitizer for filename

SOLUTION 1 - simple and effective

$file_name = preg_replace( '/[^a-z0-9]+/', '-', strtolower( $url ) );

  • strtolower() guarantees the filename is lowercase (since case does not matter inside the URL, but in the NTFS filename)
  • [^a-z0-9]+ will ensure, the filename only keeps letters and numbers
  • Substitute invalid characters with '-' keeps the filename readable

Example:

URL:  http://stackoverflow.com/questions/2021624/string-sanitizer-for-filename
File: http-stackoverflow-com-questions-2021624-string-sanitizer-for-filename

SOLUTION 2 - for very long URLs

You want to cache the URL contents and just need to have unique filenames. I would use this function:

$file_name = md5( strtolower( $url ) )

this will create a filename with fixed length. The MD5 hash is in most cases unique enough for this kind of usage.

Example:

URL:  https://www.amazon.com/Interstellar-Matthew-McConaughey/dp/B00TU9UFTS/ref=s9_nwrsa_gw_g318_i10_r?_encoding=UTF8&fpl=fresh&pf_rd_m=ATVPDKIKX0DER&pf_rd_s=desktop-1&pf_rd_r=BS5M1H560SMAR2JDKYX3&pf_rd_r=BS5M1H560SMAR2JDKYX3&pf_rd_t=36701&pf_rd_p=6822bacc-d4f0-466d-83a8-2c5e1d703f8e&pf_rd_p=6822bacc-d4f0-466d-83a8-2c5e1d703f8e&pf_rd_i=desktop
File: 51301f3edb513f6543779c3a5433b01c

Should we @Override an interface's method implementation?

If the class that is implementing the interface is an abstract class, @Override is useful to ensure that the implementation is for an interface method; without the @Override an abstract class would just compile fine even if the implementation method signature does not match the method declared in the interface; the mismatched interface method would remain as unimplemented. The Java doc cited by @Zhao

The method does override or implement a method declared in a supertype

is clearly referring to an abstract super class; an interface can not be called the supertype. So, @Override is redundant and not sensible for interface method implementations in concrete classes.

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

Well, you're getting a java.lang.NoClassDefFoundError. In your pom.xml, hibernate-core version is 3.3.2.GA and declared after hibernate-entitymanager, so it prevails. You can remove that dependency, since will be inherited version 3.6.7.Final from hibernate-entitymanager.

You're using spring-boot as parent, so no need to declare version of some dependencies, since they are managed by spring-boot.

Also, hibernate-commons-annotations is inherited from hibernate-entitymanager and hibernate-annotations is an old version of hibernate-commons-annotations, you can remove both.

Finally, your pom.xml can look like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.elsys.internetprogramming.trafficspy.server</groupId>
    <artifactId>TrafficSpyService</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.3.RELEASE</version>
    </parent>

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cloud-connectors</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.7</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>

        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

Let me know if you have a problem.

Using python map and other functional tools

Here's the solution you're looking for:

>>> foos = [1.0, 2.0, 3.0, 4.0, 5.0]
>>> bars = [1, 2, 3]
>>> [(x, bars) for x in foos]
[(1.0, [1, 2, 3]), (2.0, [1, 2, 3]), (3.0, [1, 2, 3]), (4.0, [1, 2, 3]), (5.0, [
1, 2, 3])]

I'd recommend using a list comprehension (the [(x, bars) for x in foos] part) over using map as it avoids the overhead of a function call on every iteration (which can be very significant). If you're just going to use it in a for loop, you'll get better speeds by using a generator comprehension:

>>> y = ((x, bars) for x in foos)
>>> for z in y:
...     print z
...
(1.0, [1, 2, 3])
(2.0, [1, 2, 3])
(3.0, [1, 2, 3])
(4.0, [1, 2, 3])
(5.0, [1, 2, 3])

The difference is that the generator comprehension is lazily loaded.

UPDATE In response to this comment:

Of course you know, that you don't copy bars, all entries are the same bars list. So if you modify any one of them (including original bars), you modify all of them.

I suppose this is a valid point. There are two solutions to this that I can think of. The most efficient is probably something like this:

tbars = tuple(bars)
[(x, tbars) for x in foos]

Since tuples are immutable, this will prevent bars from being modified through the results of this list comprehension (or generator comprehension if you go that route). If you really need to modify each and every one of the results, you can do this:

from copy import copy
[(x, copy(bars)) for x in foos]

However, this can be a bit expensive both in terms of memory usage and in speed, so I'd recommend against it unless you really need to add to each one of them.

CSS3 Transition - Fade out effect

You forgot to add a position property to the .dummy-wrap class, and the top/left/bottom/right values don't apply to statically positioned elements (the default)

http://jsfiddle.net/dYBD2/2/

Get TimeZone offset value from TimeZone without TimeZone name

With java8 now, you can use

Integer offset  = ZonedDateTime.now().getOffset().getTotalSeconds();

to get the current system time offset from UTC. Then you can convert it to any format you want. Found it useful for my case. Example : https://docs.oracle.com/javase/tutorial/datetime/iso/timezones.html

How to keep footer at bottom of screen

What you’re looking for is the CSS Sticky Footer.

_x000D_
_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
html,_x000D_
body {_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
#wrap {_x000D_
  min-height: 100%;_x000D_
}_x000D_
_x000D_
#main {_x000D_
  overflow: auto;_x000D_
  padding-bottom: 180px;_x000D_
  /* must be same height as the footer */_x000D_
}_x000D_
_x000D_
#footer {_x000D_
  position: relative;_x000D_
  margin-top: -180px;_x000D_
  /* negative value of footer height */_x000D_
  height: 180px;_x000D_
  clear: both;_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* Opera Fix thanks to Maleika (Kohoutec) */_x000D_
_x000D_
body:before {_x000D_
  content: "";_x000D_
  height: 100%;_x000D_
  float: left;_x000D_
  width: 0;_x000D_
  margin-top: -32767px;_x000D_
  /* thank you Erik J - negate effect of float*/_x000D_
}
_x000D_
<div id="wrap">_x000D_
  <div id="main"></div>_x000D_
</div>_x000D_
_x000D_
<div id="footer"></div>
_x000D_
_x000D_
_x000D_

Setting Java heap space under Maven 2 on Windows

On windows:

Add an environmental variable (in both system and user's variables, I have some weird problem, that it gets the var from various places, so I add them in both of them).

Name it MAVEN_OPTS.

Value will be: -Xms1024m -Xmx3000m -XX:MaxPermSize=1024m -XX:+CMSClassUnloadingEnabled

The numbers can be different, make them relative to your mem size.

I had that problem and this fixed it, nothing else!

How to use http.client in Node.js if there is basic authorization

I came across this recently. Which among Proxy-Authorization and Authorization headers to set depends on the server the client is talking to. If it is a Webserver, you need to set Authorization and if it a proxy, you have to set the Proxy-Authorization header

What is the use of rt.jar file in java?

rt.jar contains all of the compiled class files for the base Java Runtime environment. You should not be messing with this jar file.

For MacOS it is called classes.jar and located under /System/Library/Frameworks/<java_version>/Classes . Same not messing with it rule applies there as well :).

http://javahowto.blogspot.com/2006/05/what-does-rtjar-stand-for-in.html

Convert a double to a QString

Check out the documentation

Quote:

QString provides many functions for converting numbers into strings and strings into numbers. See the arg() functions, the setNum() functions, the number() static functions, and the toInt(), toDouble(), and similar functions.

Can I use multiple versions of jQuery on the same page?

It is possible to load the second version of the jQuery use it and then restore to the original or keep the second version if there was no jQuery loaded before. Here is an example:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
    var jQueryTemp = jQuery.noConflict(true);
    var jQueryOriginal = jQuery || jQueryTemp;
    if (window.jQuery){
        console.log('Original jQuery: ', jQuery.fn.jquery);
        console.log('Second jQuery: ', jQueryTemp.fn.jquery);
    }
    window.jQuery = window.$ = jQueryTemp;
</script>
<script type="text/javascript">
    console.log('Script using second: ', jQuery.fn.jquery);
</script>
<script type="text/javascript">
    // Restore original jQuery:
    window.jQuery = window.$ = jQueryOriginal;
    console.log('Script using original or the only version: ', jQuery.fn.jquery);
</script>

Returning value that was passed into a method

The generic Returns<T> method can handle this situation nicely.

_mock.Setup(x => x.DoSomething(It.IsAny<string>())).Returns<string>(x => x);

Or if the method requires multiple inputs, specify them like so:

_mock.Setup(x => x.DoSomething(It.IsAny<string>(), It.IsAny<int>())).Returns((string x, int y) => x);

How can I edit a .jar file?

Here's what I did:

  • Extracted the files using WinRAR
  • Made my changes to the extracted files
  • Opened the original JAR file with WinRAR
  • Used the ADD button to replace the files that I modified

That's it. I have tested it with my Nokia and it's working for me.

How do I get list of methods in a Python class?

If you want to list only methods of a python class

import numpy as np
print(np.random.__all__)

How can I calculate the difference between two dates?

NSDate *date1 = [NSDate dateWithString:@"2010-01-01 00:00:00 +0000"];
NSDate *date2 = [NSDate dateWithString:@"2010-02-03 00:00:00 +0000"];

NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];

int numberOfDays = secondsBetween / 86400;

NSLog(@"There are %d days in between the two dates.", numberOfDays);

EDIT:

Remember, NSDate objects represent exact moments of time, they do not have any associated time-zone information. When you convert a string to a date using e.g. an NSDateFormatter, the NSDateFormatter converts the time from the configured timezone. Therefore, the number of seconds between two NSDate objects will always be time-zone-agnostic.

Furthermore, this documentation specifies that Cocoa's implementation of time does not account for leap seconds, so if you require such accuracy, you will need to roll your own implementation.

Show/hide 'div' using JavaScript

A simple example with a Button to scroll up. It will only scroll if the javascript is active, which is an event listening to the scroll type.

_x000D_
_x000D_
document.getElementById('btn').style.display='none'

window.addEventListener('scroll', (event) => {
    console.log(scrollY)
    document.getElementById('btn').style.display='inline'
})
_x000D_
a
long<br>
text<br>
comes<br>
long<br>
text<br>
again

<button id=btn class = 'btn btn-primary' onclick='window.scrollTo({top: 0, behavior: "smooth"});'>Scroll to Top</button>
_x000D_
_x000D_
_x000D_

Live in action here

Skip Git commit hooks

Maybe (from git commit man page):

git commit --no-verify

-n  
--no-verify

This option bypasses the pre-commit and commit-msg hooks. See also githooks(5).

As commented by Blaise, -n can have a different role for certain commands.
For instance, git push -n is actually a dry-run push.
Only git push --no-verify would skip the hook.


Note: Git 2.14.x/2.15 improves the --no-verify behavior:

See commit 680ee55 (14 Aug 2017) by Kevin Willford (``).
(Merged by Junio C Hamano -- gitster -- in commit c3e034f, 23 Aug 2017)

commit: skip discarding the index if there is no pre-commit hook

"git commit" used to discard the index and re-read from the filesystem just in case the pre-commit hook has updated it in the middle; this has been optimized out when we know we do not run the pre-commit hook.


Davi Lima points out in the comments the git cherry-pick does not support --no-verify.
So if a cherry-pick triggers a pre-commit hook, you might, as in this blog post, have to comment/disable somehow that hook in order for your git cherry-pick to proceed.
The same process would be necessary in case of a git rebase --continue, after a merge conflict resolution.

How to make Sonar ignore some classes for codeCoverage metric?

When using sonar-scanner for swift, use sonar.coverage.exclusions in your sonar-project.properties to exclude any file for only code coverage. If you want to exclude files from analysis as well, you can use sonar.exclusions. This has worked for me in swift

sonar.coverage.exclusions=**/*ViewController.swift,**/*Cell.swift,**/*View.swift

Android: Difference between onInterceptTouchEvent and dispatchTouchEvent?

Small answer:

onInterceptTouchEvent comes before setOnTouchListener.

Convert from MySQL datetime to another format with PHP

$valid_date = date( 'm/d/y g:i A', strtotime($date));

Reference: http://php.net/manual/en/function.date.php

How do I check if a string contains a specific word?

Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster. (http://in2.php.net/preg_match)

if (strpos($text, 'string_name') !== false){
   echo 'get the string';
}

How can I print out all possible letter combinations a given phone number can represent?

During a job interview I received this question regarding creating an array of and printing out all possible letter combinations of a phone number. During the interview I received a whisper from my interviewer about recursion and how it can't be done using loops. Very unnatural for me to receive input from another programmer, I trusted his advice instead of my own tuition and proceeded to write up a sloppy recursion mess. It didn't go so well. Before receiving input, as I had never received this problem before, my brain was calculating up the underlying replicable mathematical formula. Whispers under my breath, "can't just multiply by three, some of them are four" as my mind started racing against a short clock thinking about one answer while beginning to write another. It was not until the end of the week I received my call to let me know the sad news. It was later that night I decided to see if it really is a recursion problem. Turns out for me it isn't.

My solution below is coded in PHP, is non-recursive, works with any length of input and I've even included some comments to help describe what my variables mean. Its my official and unchanging final answer to this question. I hope this helps somebody else in the future, please feel free to translate this into other languages.

Me method involves calculating the total number of combinations and creating a buffer large enough to hold every byte. The length of my buffer is the same length you would expect to receive from a working recursive algorithm. I make an array that contains the groups of letters that represent each number. My method primarily works because your combo total will always be divisible by the number of letters in the current group. If you can imagine in your head a vertical list of the output of this algorithm, or see the list vertically as opposed to a horizontally written list of the combinations, my algorithm will begin to make sense. This algorithm allows us to loop through each byte vertically from top to bottom starting from the left instead of horizontally left to right, and populate each byte individually without requiring recursion. I use the buffer as though its a byte array to save time and energy.


NON-RECURSIVE, ITERATIVE PHP

<?php

// Display all possible combinations of letters for each number.

$input = '23456789';

// ====================

if(!isset($input[0]))
    die('Nothing to see here!');

$phone_letters = array(
    2 => array('a', 'b', 'c'),
    3 => array('d', 'e', 'f'),
    4 => array('g', 'h', 'i'),
    5 => array('j', 'k', 'l'),
    6 => array('m', 'n', 'o'),
    7 => array('p', 'q', 'r', 's'),
    8 => array('t', 'u', 'v'),
    9 => array('w', 'x', 'y', 'z')
);

$groups = array();
$combos_total = 1;
$l = strlen($input);
for($i = 0; $i < $l; ++$i) {
    $groups[] = $phone_letters[$input[$i]];
    $combos_total *= count($phone_letters[$input[$i]]);
}
$count = $combos_total / count($groups[0]);
$combos = array_fill(0, $combos_total, str_repeat(chr(0), strlen($input)));

for(
    $group = 0,                     // Index for the current group of letters.
    $groups_count = count($groups), // Total number of letter groups.
    $letters = count($groups[0]),   // Total number of letters in the current group.
    $width = $combos_total,         // Number of bytes to repeat the current letter.
    $repeat = 1;                    // Total number of times the group will repeat.
    ;
) {
    for($byte = 0, $width /= $letters, $r = 0; $r < $repeat; ++$r)
        for($l = 0; $l < $letters; ++$l)
            for($w = 0; $w < $width; ++$w)
                $combos[$byte++][$group] = $groups[$group][$l];

    if(++$group < $groups_count) {
        $repeat *= $letters;
        $letters = count($groups[$group]);
    }
    else
        break;
}

// ==================== 


if(is_array($combos)) {
    print_r($combos);
    echo 'Total combos:', count($combos), "\n";
}
else
    echo 'No combos.', "\n";
echo 'Expected combos: ', $combos_total, "\n";

NON-RECURSIVE, NON-ITERATIVE, NO-BUFFER, THREAD FRIENDLY, MATH ONLY + NON-RECURSIVE, ITERATIVE PHP OBJECT USING MULTI-BASE BIG ENDIAN

While I was working on the new house the other day, I had a realisation that I could use the mathematics from my first function coupled with my knowledge of base to treat all possible letter combinations of my input as a multi-dimensional number.

My object provides the functions necessary to store a prefered combination into a database, convert letters and numbers if it were required, pick out a combination from anywhere in the combination space using a prefered combination or byte and it all plays very well with multi-threading.

That being said, using my object I can provide a second answer that uses base, no buffer, no iterations and most importantly no recursion.

<?php
class phone {
    public static $letters = array(
        2 => array('a', 'b', 'c'),
        3 => array('d', 'e', 'f'),
        4 => array('g', 'h', 'i'),
        5 => array('j', 'k', 'l'),
        6 => array('m', 'n', 'o'),
        7 => array('p', 'q', 'r', 's'),
        8 => array('t', 'u', 'v'),
        9 => array('w', 'x', 'y', 'z')
    );

    // Convert a letter into its respective number.
    public static function letter_number($letter) {
        if(!isset($letter[0]) || isset($letter[1]))
            return false;

        for($i = 2; $i < 10; ++$i)
            if(in_array($letter, phone::$letters[$i], true))
                return $i;

        return false;
    }

    // Convert letters into their respective numbers.
    public static function letters_numbers($letters) {
        if(!isset($letters[0]))
            return false;

        $length = strlen($letters);
        $numbers = str_repeat(chr(0), $length);
        for($i = 0; $i < $length; ++$i) {
            for($j = 2; $j < 10; ++$j) {
                if(in_array($letters[$i], phone::$letters[$j], true)) {
                    $numbers[$i] = $j;
                    break;
                }
            }
        }
        return $numbers;
    }

    // Calculate the maximum number of combinations that could occur within a particular input size.
    public static function combination_size($groups) {
        return $groups <= 0 ? false : pow(4, $groups);
    }

    // Calculate the minimum bytes reqired to store a group using the current input.
    public static function combination_bytes($groups) {
        if($groups <= 0)
            return false;

        $size = $groups * 4;
        $bytes = 0;
        while($groups !== 0) {
            $groups >> 8;
            ++$bytes;
        }
        return $bytes;
    }

    public $input = '';
    public $input_len = 0;
    public $combinations_total = 0;
    public $combinations_length = 0;

    private $iterations = array();
    private $branches = array();

    function __construct($number) {
        if(!isset($number[0]))
            return false;

        $this->input = $number;
        $input_len = strlen($number);

        $combinations_total = 1;
        for($i = 0; $i < $input_len; ++$i) {
            $combinations_total *= count(phone::$letters[$number[$i]]);
        }

        $this->input_len = $input_len;
        $this->combinations_total = $combinations_total;
        $this->combinations_length = $combinations_total * $input_len;

        for($i = 0; $i < $input_len; ++$i) {
            $this->branches[] = $this->combination_branches($i);
            $this->iterations[] = $this->combination_iteration($i);
        }
    }

    // Calculate a particular combination in the combination space and return the details of that combination.
    public function combination($combination) {
        $position = $combination * $this->input_len;
        if($position < 0 || $position >= $this->combinations_length)
                return false;

        $group = $position % $this->input_len;
        $first = $position - $group;
        $last = $first + $this->input_len - 1;
        $combination = floor(($last + 1) / $this->input_len) - 1;

        $bytes = str_repeat(chr(0), $this->input_len);
        for($i = 0; $i < $this->input_len; ++$i)
            $bytes[$i] = phone::$letters[$this->input[$i]][($combination / $this->branches[$i]) % count(phone::$letters[$this->input[$i]])];

        return array(
            'combination' => $combination,
            'branches' => $this->branches[$group],
            'iterations' => $this->iterations[$group],
            'first' => $first,
            'last' => $last,
            'bytes' => $bytes
        );
    }

    // Calculate a particular byte in the combination space and return the details of that byte.
    public function combination_position($position) {
        if($position < 0 || $position >= $this->combinations_length)
                return false;

        $group = $position % $this->input_len;
        $group_count = count(phone::$letters[$this->input[$group]]);
        $first = $position - $group;
        $last = $first + $this->input_len - 1;
        $combination = floor(($last + 1) / $this->input_len) - 1;
        $index = ($combination / $this->branches[$group]) % $group_count;

        $bytes = str_repeat(chr(0), $this->input_len);
        for($i = 0; $i < $this->input_len; ++$i)
            $bytes[$i] = phone::$letters[$this->input[$i]][($combination / $this->branches[$i]) % count(phone::$letters[$this->input[$i]])];

        return array(
            'position' => $position,
            'combination' => $combination - 1,
            'group' => $group,
            'group_count' => $group_count,
            'group_index' => $index,
            'number' => $this->input[$group],
            'branches' => $this->branches[$group],
            'iterations' => $this->iterations[$group],
            'first' => $first,
            'last' => $last,
            'byte' => phone::$letters[$this->input[$group]][$index],
            'bytes' => $bytes
        );
    }

    // Convert letters into a combination number using Multi-Base Big Endian.
    public function combination_letters($letters) {
        if(!isset($letters[$this->input_len - 1]) || isset($letters[$this->input_len]))
            return false;

        $combination = 0;
        for($byte = 0; $byte < $this->input_len; ++$byte) {
            $base = count(phone::$letters[$this->input[$byte]]);
            $found = false;
            for($value = 0; $value < $base; ++$value) {
                if($letters[$byte] === phone::$letters[$this->input[$byte]][$value]) {
                    $combination += $value * $this->branches[$byte];
                    $found = true;
                    break;
                }
            }
            if($found === false)
                return false;
        }
        return $combination;
    }

    // Calculate the number of branches after a particular group.
    public function combination_branches($group) {
        if($group >= 0 && ++$group < $this->input_len) {
            $branches = 1;
            for($i = $group; $i < $this->input_len; ++$i)
                $branches *= count(phone::$letters[$this->input[$i]]);
            return $branches === 1 ? 1 : $branches;
        }
        elseif($group === $this->input_len)
            return 1;
        else
        return false;   
    }

    // Calculate the number of iterations before a particular group.
    public function combination_iteration($group) {
        if($group > 0 && $group < $this->input_len) {
            $iterations = 1;
            for($i = $group - 1; $i >= 0; --$i)
                $iterations *= count(phone::$letters[$this->input[$i]]);
            return $iterations;
        }
        elseif($group === 0)
            return 1;
        else
            return false;
    }

    // Iterations, Outputs array of all combinations using a buffer.
    public function combinations() {
        $count = $this->combinations_total / count(phone::$letters[$this->input[0]]);
        $combinations = array_fill(0, $this->combinations_total, str_repeat(chr(0), $this->input_len));
        for(
            $group = 0,                                         // Index for the current group of letters.
            $groups_count = $this->input_len,                   // Total number of letter groups.
            $letters = count(phone::$letters[$this->input[0]]), // Total number of letters in the current group.
            $width = $this->combinations_total,                         // Number of bytes to repeat the current letter.
            $repeat = 1;                                        // Total number of times the group will repeat.
            ;
        ) {
            for($byte = 0, $width /= $letters, $r = 0; $r < $repeat; ++$r)
                for($l = 0; $l < $letters; ++$l)
                    for($w = 0; $w < $width; ++$w)
                        $combinations[$byte++][$group] = phone::$letters[$this->input[$group]][$l];

            if(++$group < $groups_count) {
                $repeat *= $letters;
                $letters = count(phone::$letters[$this->input[$group]]);
            }
            else
                break;
        }
        return $combinations;
    }
}

// ====================

$phone = new phone('23456789');
print_r($phone);
//print_r($phone->combinations());
for($i = 0; $i < $phone->combinations_total; ++$i) {
    echo $i, ': ', $phone->combination($i)['bytes'], "\n";
}

How can I encode a string to Base64 in Swift?

SwiftyBase64 (full disclosure: I wrote it) is a native Swift Base64 encoding (no decoding library. With it, you can encode standard Base64:

let bytesToEncode : [UInt8] = [1,2,3]
let base64EncodedString = SwiftyBase64.EncodeString(bytesToEncode)

or URL and Filename Safe Base64:

let bytesToEncode : [UInt8] = [1,2,3]
let base64EncodedString = SwiftyBase64.EncodeString(bytesToEncode, alphabet:.URLAndFilenameSafe)

Detecting a redirect in ajax request?

While the other folks who answered this question are (sadly) correct that this information is hidden from us by the browser, I thought I'd post a workaround I came up with:

I configured my server app to set a custom response header (X-Response-Url) containing the url that was requested. Whenever my ajax code receives a response, it checks if xhr.getResponseHeader("x-response-url") is defined, in which case it compares it to the url that it originally requested via $.ajax(). If the strings differ, I know there was a redirect, and additionally, what url we actually arrived at.

This does have the drawback of requiring some server-side help, and also may break down if the url gets munged (due to quoting/encoding issues etc) during the round trip... but for 99% of cases, this seems to get the job done.


On the server side, my specific case was a python application using the Pyramid web framework, and I used the following snippet:

import pyramid.events

@pyramid.events.subscriber(pyramid.events.NewResponse)
def set_response_header(event):
    request = event.request
    if request.is_xhr:
        event.response.headers['X-Response-URL'] = request.url

How to jump back to NERDTree from file in tab?

Ctrl+ww cycle though all windows

Ctrl+wh takes you left a window

Ctrl+wj takes you down a window

Ctrl+wk takes you up a window

Ctrl+wl takes you right a window

Oracle row count of table by count(*) vs NUM_ROWS from DBA_TABLES

According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.

This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.

select num_rows from all_tables where table_name = 'MY_TABLE'

This query counts the current number of rows in MY_TABLE

select count(*) from my_table

By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.

  1. In the documentation there's an asterisk by the column name, which leads to this note:

    Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.

    This means that unless you have gathered statistics on the table then this column will not have any data.

  2. Statistics gathered in 11g+ with the default estimate_percent, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.

If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.

Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

I think this means that

  • You are using JDK9 or later
  • Your project uses maven-compiler-plugin with an old version which defaults to Java 5.

You have three options to solve this

  1. Downgrade to JDK7 or JDK8 (meh)
  2. Use maven-compiler-plugin version or later, because

    NOTE: Since 3.8.0 the default value has changed from 1.5 to 1.6 See https://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html#target

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
    </plugin>
    
  3. Indicate to the maven-compiler-plugin to use source level 6 and target 6 (or later).

    Best practice recommended by https://maven.apache.org/plugins/maven-compiler-plugin/

    Also note that at present the default source setting is 1.6 and the default target setting is 1.6, independently of the JDK you run Maven with. You are highly encouraged to change these defaults by setting source and target as described in Setting the -source and -target of the Java Compiler.

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <source>1.6</source>
            <target>1.6</target>
        </configuration>
    </plugin>
    

    or use

    <properties>
      <maven.compiler.source>1.6</maven.compiler.source>
      <maven.compiler.target>1.6</maven.compiler.target>
    </properties>
    

Express-js wildcard routing to cover everything under and including a path

I think you will have to have 2 routes. If you look at line 331 of the connect router the * in a path is replaced with .+ so will match 1 or more characters.

https://github.com/senchalabs/connect/blob/master/lib/middleware/router.js

If you have 2 routes that perform the same action you can do the following to keep it DRY.

var express = require("express"),
    app = express.createServer();

function fooRoute(req, res, next) {
  res.end("Foo Route\n");
}

app.get("/foo*", fooRoute);
app.get("/foo", fooRoute);

app.listen(3000);

Checking for Undefined In React

What you can do is check whether you props is defined initially or not by checking if nextProps.blog.content is undefined or not since your body is nested inside it like

componentWillReceiveProps(nextProps) {

    if(nextProps.blog.content !== undefined && nextProps.blog.title !== undefined) {
       console.log("new title is", nextProps.blog.title);
       console.log("new body content is", nextProps.blog.content["body"]);
       this.setState({
           title: nextProps.blog.title,
           body: nextProps.blog.content["body"]
       })
    }
}

You need not use type to check for undefined, just the strict operator !== which compares the value by their type as well as value

In order to check for undefined, you can also use the typeof operator like

typeof nextProps.blog.content != "undefined"

Numpy - add row to array

If no calculations are necessary after every row, it's much quicker to add rows in python, then convert to numpy. Here are timing tests using python 3.6 vs. numpy 1.14, adding 100 rows, one at a time:

import numpy as np 
from time import perf_counter, sleep

def time_it():
    # Compare performance of two methods for adding rows to numpy array
    py_array = [[0, 1, 2], [0, 2, 0]]
    py_row = [4, 5, 6]
    numpy_array = np.array(py_array)
    numpy_row = np.array([4,5,6])
    n_loops = 100

    start_clock = perf_counter()
    for count in range(0, n_loops):
       numpy_array = np.vstack([numpy_array, numpy_row]) # 5.8 micros
    duration = perf_counter() - start_clock
    print('numpy 1.14 takes {:.3f} micros per row'.format(duration * 1e6 / n_loops))

    start_clock = perf_counter()
    for count in range(0, n_loops):
        py_array.append(py_row) # .15 micros
    numpy_array = np.array(py_array) # 43.9 micros       
    duration = perf_counter() - start_clock
    print('python 3.6 takes {:.3f} micros per row'.format(duration * 1e6 / n_loops))
    sleep(15)

#time_it() prints:

numpy 1.14 takes 5.971 micros per row
python 3.6 takes 0.694 micros per row

So, the simple solution to the original question, from seven years ago, is to use vstack() to add a new row after converting the row to a numpy array. But a more realistic solution should consider vstack's poor performance under those circumstances. If you don't need to run data analysis on the array after every addition, it is better to buffer the new rows to a python list of rows (a list of lists, really), and add them as a group to the numpy array using vstack() before doing any data analysis.

How to find top three highest salary in emp table in oracle?

solution for to find top 5 salary in sq l server

select top(1) name, salary from salary where salary in(select distinct top(3) salary from salary order by salary disc)

Unable to simultaneously satisfy constraints, will attempt to recover by breaking constraint

swift 4

I just add this line in viewDidLoad and work fine with me.

view.removeConstraints(view.constraints)

Why cannot cast Integer to String in java?

You can't cast explicitly anything to a String that isn't a String. You should use either:

"" + myInt;

or:

Integer.toString(myInt);

or:

String.valueOf(myInt);

I prefer the second form, but I think it's personal choice.

Edit OK, here's why I prefer the second form. The first form, when compiled, could instantiate a StringBuffer (in Java 1.4) or a StringBuilder in 1.5; one more thing to be garbage collected. The compiler doesn't optimise this as far as I could tell. The second form also has an analogue, Integer.toString(myInt, radix) that lets you specify whether you want hex, octal, etc. If you want to be consistent in your code (purely aesthetically, I guess) the second form can be used in more places.

Edit 2 I assumed you meant that your integer was an int and not an Integer. If it's already an Integer, just use toString() on it and be done.

Explicitly select items from a list or tuple

Maybe a list comprehension is in order:

L = ['a', 'b', 'c', 'd', 'e', 'f']
print [ L[index] for index in [1,3,5] ]

Produces:

['b', 'd', 'f']

Is that what you are looking for?

How to get process ID of background process?

An even simpler way to kill all child process of a bash script:

pkill -P $$

The -P flag works the same way with pkill and pgrep - it gets child processes, only with pkill the child processes get killed and with pgrep child PIDs are printed to stdout.

How to delete Project from Google Developers Console

For me only way to delete project was switch language to English (UK) - from Polish and then button "DELETE" worked. If anyone have problem with not working or missing options in Google Cloud Platform I suggest switching to english after that everything works like charm...

Safely casting long to int in Java

With Google Guava's Ints class, your method can be changed to:

public static int safeLongToInt(long l) {
    return Ints.checkedCast(l);
}

From the linked docs:

checkedCast

public static int checkedCast(long value)

Returns the int value that is equal to value, if possible.

Parameters: value - any value in the range of the int type

Returns: the int value that equals value

Throws: IllegalArgumentException - if value is greater than Integer.MAX_VALUE or less than Integer.MIN_VALUE

Incidentally, you don't need the safeLongToInt wrapper, unless you want to leave it in place for changing out the functionality without extensive refactoring of course.

How to define the basic HTTP authentication using cURL correctly?

curl -u username:password http://
curl -u username http://

From the documentation page:

-u, --user <user:password>

Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.

If you simply specify the user name, curl will prompt for a password.

The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.

When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.

When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.

To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.

If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".

If this option is used several times, the last one will be used.

http://curl.haxx.se/docs/manpage.html#-u

Note that you do not need --basic flag as it is the default.

How to copy file from HDFS to the local file system

if you are using docker you have to do the following steps:

  1. copy the file from hdfs to namenode (hadoop fs -get output/part-r-00000 /out_text). "/out_text" will be stored on the namenode.

  2. copy the file from namenode to local disk by (docker cp namenode:/out_text output.txt)

  3. output.txt will be there on your current working directory

how to draw smooth curve through N points using javascript HTML5 canvas?

To add to K3N's cardinal splines method and perhaps address T. J. Crowder's concerns about curves 'dipping' in misleading places, I inserted the following code in the getCurvePoints() function, just before res.push(x);

if ((y < _pts[i+1] && y < _pts[i+3]) || (y > _pts[i+1] && y > _pts[i+3])) {
    y = (_pts[i+1] + _pts[i+3]) / 2;
}
if ((x < _pts[i] && x < _pts[i+2]) || (x > _pts[i] && x > _pts[i+2])) {
    x = (_pts[i] + _pts[i+2]) / 2;
}

This effectively creates a (invisible) bounding box between each pair of successive points and ensures the curve stays within this bounding box - ie. if a point on the curve is above/below/left/right of both points, it alters its position to be within the box. Here the midpoint is used, but this could be improved upon, perhaps using linear interpolation.

SQL Server : SUM() of multiple rows including where clauses

sounds like you want something like:

select PropertyID, SUM(Amount)
from MyTable
Where EndDate is null
Group by PropertyID

NameError: global name 'xrange' is not defined in Python 3

in python 2.x, xrange is used to return a generator while range is used to return a list. In python 3.x , xrange has been removed and range returns a generator just like xrange in python 2.x. Therefore, in python 3.x you need to use range rather than xrange.

Using a BOOL property

Apple recommends for stylistic purposes.If you write this code:

@property (nonatomic,assign) BOOL working;

Then you can not use [object isWorking].
It will show an error. But if you use below code means

@property (assign,getter=isWorking) BOOL working;

So you can use [object isWorking] .

OS X: equivalent of Linux's wget

You can either build wget on the mac machine or use MacPorts to install it directly.

sudo port install wget 

This would work like a charm, also you can update to the latest version as soon as it's available. Port is much more stable than brew, although has a lot less number of formula and ports.

You can install MacPorts from https://www.macports.org/install.php you can download the .pkg file and install it.

Java project in Eclipse: The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files

I got this error because I have installed "Eclipse IDE for Enterprise Java Developers", I uninstalled this and installed "Eclipse IDE for Java Developers". Problem solved for me.

What does void mean in C, C++, and C#?

Think of void as the "empty structure". Let me explain.

Every function takes a sequence of parameters, where each parameter has a type. In fact, we could package up the parameters into a structure, with the structure slots corresponding to the parameters. This makes every function have exactly one argument. Similarly, functions produce a result, which has a type. It could be a boolean, or it could be float, or it could be a structure, containing an arbitrary set of other typed values. If we want a languge that has multiple return values, it is easy to just insist they be packaged into a structure. In fact, we could always insist that a function returned a structure. Now every function takes exactly one argument, and produces exactly one value.

Now, what happens when I need a function that produces "no" value? Well, consider what I get when I form a struct with 3 slots: it holds 3 values. When I have 2 slots, it holds two values. When it has one slot, one value. And when it has zero slots, it holds... uh, zero values, or "no" value". So, I can think of a function returning void as returning a struct containing no values. You can even decide that "void" is just a synonym for the type represented by the empty structure, rather than a keyword in the language (maybe its just a predefined type :)

Similarly, I can think of a function requiring no values as accepting an empty structure, e.g., "void".

I can even implement my programming language this way. Passing a void value takes up zero bytes, so passing void values is just a special case of passing other values of arbitrary size. This makes it easy for the compiler to treat the "void" result or argument. You probably want a langauge feature that can throw a function result away; in C, if you call the non-void result function foo in the following statement: foo(...); the compiler knows that foo produces a result and simply ignores it. If void is a value, this works perfectly and now "procedures" (which are just an adjective for a function with void result) are just trivial special cases of general functions.

Void* is a bit funnier. I don't think the C designers thought of void in the above way; they just created a keyword. That keyword was available when somebody needed a point to an arbitrary type, thus void* as the idiom in C. It actually works pretty well if you interpret void as an empty structure. A void* pointer is the address of a place where that empty structure has been put.

Casts from void* to T* for other types T, also work out with this perspective. Pointer casts are a complete cheat that work on most common architectures to take advantage of the fact that if a compound type T has an element with subtype S placed physically at the beginning of T in its storage layout, then casting S* to T* and vice versa using the same physical machine address tends to work out, since most machine pointers have a single representation. Replacing the type S by the type void gives exactly the same effect, and thus casting to/from void* works out.

The PARLANSE programming language implements the above ideas pretty closely. We goofed in its design, and didn't pay close attention to "void" as a return type and thus have langauge keywords for procedure. Its mostly just a simple syntax change but its one of things you don't get around to once you get a large body working code in a language.

Find an element by class name, from a known parent element

var element = $("#parentDiv .myClassNameOfInterest")

Removing an activity from the history stack

I know I'm late on this (it's been two years since the question was asked) but I accomplished this by intercepting the back button press. Rather than checking for specific activities, I just look at the count and if it's less than 3 it simply sends the app to the back (pausing the app and returning the user to whatever was running before launch). I check for less than three because I only have one intro screen. Also, I check the count because my app allows the user to navigate back to the home screen through the menu, so this allows them to back up through other screens like normal if there are activities other than the intro screen on the stack.

//We want the home screen to behave like the bottom of the activity stack so we do not return to the initial screen
//unless the application has been killed. Users can toggle the session mode with a menu item at all other times.
@Override
public void onBackPressed() {
    //Check the activity stack and see if it's more than two deep (initial screen and home screen)
    //If it's more than two deep, then let the app proccess the press
    ActivityManager am = (ActivityManager)this.getSystemService(Activity.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = am.getRunningTasks(3); //3 because we have to give it something. This is an arbitrary number
    int activityCount = tasks.get(0).numActivities;

    if (activityCount < 3)
    {
        moveTaskToBack(true);
    }
    else
    {
        super.onBackPressed();
    }
}

Is there an API to get bank transaction and bank balance?

Just a helpful hint, there is a company called Yodlee.com who provides this data. They do charge for the API. Companies like Mint.com use this API to gather bank and financial account data.

Also, checkout https://plaid.com/, they are a similar company Yodlee.com and provide both authentication API for several banks and REST-based transaction fetching endpoints.

Hash and salt passwords in C#

Actually this is kind of strange, with the string conversions - which the membership provider does to put them into config files. Hashes and salts are binary blobs, you don't need to convert them to strings unless you want to put them into text files.

In my book, Beginning ASP.NET Security, (oh finally, an excuse to pimp the book) I do the following

static byte[] GenerateSaltedHash(byte[] plainText, byte[] salt)
{
  HashAlgorithm algorithm = new SHA256Managed();

  byte[] plainTextWithSaltBytes = 
    new byte[plainText.Length + salt.Length];

  for (int i = 0; i < plainText.Length; i++)
  {
    plainTextWithSaltBytes[i] = plainText[i];
  }
  for (int i = 0; i < salt.Length; i++)
  {
    plainTextWithSaltBytes[plainText.Length + i] = salt[i];
  }

  return algorithm.ComputeHash(plainTextWithSaltBytes);            
}

The salt generation is as the example in the question. You can convert text to byte arrays using Encoding.UTF8.GetBytes(string). If you must convert a hash to its string representation you can use Convert.ToBase64String and Convert.FromBase64String to convert it back.

You should note that you cannot use the equality operator on byte arrays, it checks references and so you should simply loop through both arrays checking each byte thus

public static bool CompareByteArrays(byte[] array1, byte[] array2)
{
  if (array1.Length != array2.Length)
  {
    return false;
  }

  for (int i = 0; i < array1.Length; i++)
  {
    if (array1[i] != array2[i])
    {
      return false;
    }
  }

  return true;
}

Always use a new salt per password. Salts do not have to be kept secret and can be stored alongside the hash itself.

Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

Behavior differences

Some differences on Bash 4.3.11:

  • POSIX vs Bash extension:

  • regular command vs magic

    • [ is just a regular command with a weird name.

      ] is just the last argument of [.

    Ubuntu 16.04 actually has an executable for it at /usr/bin/[ provided by coreutils, but the bash built-in version takes precedence.

    Nothing is altered in the way that Bash parses the command.

    In particular, < is redirection, && and || concatenate multiple commands, ( ) generates subshells unless escaped by \, and word expansion happens as usual.

    • [[ X ]] is a single construct that makes X be parsed magically. <, &&, || and () are treated specially, and word splitting rules are different.

      There are also further differences like = and =~.

    In Bashese: [ is a built-in command, and [[ is a keyword: https://askubuntu.com/questions/445749/whats-the-difference-between-shell-builtin-and-shell-keyword

  • <

  • && and ||

    • [[ a = a && b = b ]]: true, logical and
    • [ a = a && b = b ]: syntax error, && parsed as an AND command separator cmd1 && cmd2
    • [ a = a ] && [ b = b ]: POSIX reliable equivalent
    • [ a = a -a b = b ]: almost equivalent, but deprecated by POSIX because it is insane and fails for some values of a or b like ! or ( which would be interpreted as logical operations
  • (

    • [[ (a = a || a = b) && a = b ]]: false. Without ( ), would be true because [[ && ]] has greater precedence than [[ || ]]
    • [ ( a = a ) ]: syntax error, () is interpreted as a subshell
    • [ \( a = a -o a = b \) -a a = b ]: equivalent, but (), -a, and -o are deprecated by POSIX. Without \( \) would be true because -a has greater precedence than -o
    • { [ a = a ] || [ a = b ]; } && [ a = b ] non-deprecated POSIX equivalent. In this particular case however, we could have written just: [ a = a ] || [ a = b ] && [ a = b ] because the || and && shell operators have equal precedence unlike [[ || ]] and [[ && ]] and -o, -a and [
  • word splitting and filename generation upon expansions (split+glob)

    • x='a b'; [[ $x = 'a b' ]]: true, quotes not needed
    • x='a b'; [ $x = 'a b' ]: syntax error, expands to [ a b = 'a b' ]
    • x='*'; [ $x = 'a b' ]: syntax error if there's more than one file in the current directory.
    • x='a b'; [ "$x" = 'a b' ]: POSIX equivalent
  • =

    • [[ ab = a? ]]: true, because it does pattern matching (* ? [ are magic). Does not glob expand to files in current directory.
    • [ ab = a? ]: a? glob expands. So may be true or false depending on the files in the current directory.
    • [ ab = a\? ]: false, not glob expansion
    • = and == are the same in both [ and [[, but == is a Bash extension.
    • case ab in (a?) echo match; esac: POSIX equivalent
    • [[ ab =~ 'ab?' ]]: false, loses magic with '' in Bash 3.2 and above and provided compatibility to bash 3.1 is not enabled (like with BASH_COMPAT=3.1)
    • [[ ab? =~ 'ab?' ]]: true
  • =~

    • [[ ab =~ ab? ]]: true, POSIX extended regular expression match, ? does not glob expand
    • [ a =~ a ]: syntax error. No bash equivalent.
    • printf 'ab\n' | grep -Eq 'ab?': POSIX equivalent (single line data only)
    • awk 'BEGIN{exit !(ARGV[1] ~ ARGV[2])}' ab 'ab?': POSIX equivalent.

Recommendation: always use []

There are POSIX equivalents for every [[ ]] construct I've seen.

If you use [[ ]] you:

  • lose portability
  • force the reader to learn the intricacies of another bash extension. [ is just a regular command with a weird name, no special semantics are involved.

Thanks to Stéphane Chazelas for important corrections and additions.

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

Try with below code sample.it is working for me

var date_input_field = $('input[name="date"]');
    date_input_field .datepicker({
        dateFormat: '/dd/mm/yyyy',
        container: container,
        todayHighlight: true,
        autoclose: true,
    }).on('change', function(selected){
        alert("startDate..."+selected.timeStamp);
    });

Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0

keep using the id


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserVerification extends Model
{
    protected $table = 'user_verification';
    protected $fillable =   [
                            'id',
                            'email',
                            'verification_token'
                            ];
    //$timestamps = false;
    protected $primaryKey = 'verification_token';
}

and get the email :

$usr = User::find($id);
$token = $usr->verification_token;
$email = UserVerification::find($token);

Returning multiple values from a C++ function

Here, i am writing a program that is returning multiple values(more than two values) in c++. This program is executable in c++14 (G++4.9.2). program is like a calculator.

#  include <tuple>
# include <iostream>

using namespace std; 

tuple < int,int,int,int,int >   cal(int n1, int n2)
{
    return  make_tuple(n1/n2,n1%n2,n1+n2,n1-n2,n1*n2);
}

int main()
{
    int qut,rer,add,sub,mul,a,b;
    cin>>a>>b;
    tie(qut,rer,add,sub,mul)=cal(a,b);
    cout << "quotient= "<<qut<<endl;
    cout << "remainder= "<<rer<<endl;
    cout << "addition= "<<add<<endl;
    cout << "subtraction= "<<sub<<endl;
    cout << "multiplication= "<<mul<<endl;
    return 0;
}

So, you can clearly understand that in this way you can return multiple values from a function. using std::pair only 2 values can be returned while std::tuple can return more than two values.

Convert Mercurial project to Git

If you want to import your existing mercurial repository into a 'GitHub' repository, you can now simply use GitHub Importer available here [Login required]. No more messing around with fast-export etc. (although its a very good tool)

You will get all your commits, branches and tags intact. One more cool thing is that you can change the author's email-id as well. Check out below screenshots:

enter image description here

enter image description here

How can I list ALL DNS records?

When you query for ANY you will get a list of all records at that level but not below.

# try this
dig google.com any

This may return A records, TXT records, NS records, MX records, etc if the domain name is exactly "google.com". However, it will not return child records (e.g., www.google.com). More precisely, you MAY get these records if they exist. The name server does not have to return these records if it chooses not to do so (for example, to reduce the size of the response).

An AXFR is a zone transfer and is likely what you want. However, these are typically restricted and not available unless you control the zone. You'll usually conduct a zone transfer directly from the authoritative server (the @ns1.google.com below) and often from a name server that may not be published (a stealth name server).

# This will return "Transfer failed"
dig @ns1.google.com google.com axfr

If you have control of the zone, you can set it up to get transfers that are protected with a TSIG key. This is a shared secret the the client can send to the server to authorize the transfer.

Angular 4.3 - HttpClient set params

Couple of Easy Alternatives

Without using HttpParams Objects

let body = {
   params : {
    'email' : emailId,
    'password' : password
   }
}

this.http.post(url, body);

Using HttpParams Objects

let body = new HttpParams({
  fromObject : {
    'email' : emailId,
    'password' : password
  }
})

this.http.post(url, body);

Use String.split() with multiple delimiters

String[] token=s.split("[.-]");

Generating a random password in php

Generates a strong password of length 8 containing at least one lower case letter, one uppercase letter, one digit, and one special character. You can change the length in the code too.

function checkForCharacterCondition($string) {
    return (bool) preg_match('/(?=.*([A-Z]))(?=.*([a-z]))(?=.*([0-9]))(?=.*([~`\!@#\$%\^&\*\(\)_\{\}\[\]]))/', $string);
}

$j = 1;

function generate_pass() {
    global $j;
    $allowedCharacters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()_{}[]';
    $pass = '';
    $length = 8;
    $max = mb_strlen($allowedCharacters, '8bit') - 1;
    for ($i = 0; $i < $length; ++$i) {
        $pass .= $allowedCharacters[random_int(0, $max)];
    }

    if (checkForCharacterCondition($pass)){
        return '<br><strong>Selected password: </strong>'.$pass;
    }else{
        echo 'Iteration '.$j.':  <strong>'.$pass.'</strong>  Rejected<br>';
        $j++;
        return generate_pass();
    }

}

echo generate_pass();

How to run a program without an operating system?

I wrote a c++ program based on Win32 to write an assembly to the boot sector of a pen-drive. When the computer is booted from the pen-drive it executes the code successfully - have a look here C++ Program to write to the boot sector of a USB Pendrive

This program is a few lines that should be compiled on a compiler with windows compilation configured - such as a visual studio compiler - any available version.

How to change text and background color?

You can also use PDCurses library. (http://pdcurses.sourceforge.net/)

Elasticsearch query to return all records

Using Elasticsearch 7.5.1

http://${HOST}:9200/${INDEX}/_search?pretty=true&q=*:*&scroll=10m&size=5000

in case you can also specify the size of your array with &size=${number}

in case you don't know you index

http://${HOST}:9200/_cat/indices?v

difference between width auto and width 100 percent

It's about margins and border. If you use width: auto, then add border, your div won't become bigger than its container. On the other hand, if you use width: 100% and some border, the element's width will be 100% + border or margin. For more info see this.

Constructors in JavaScript objects

It seems to me most of you are giving example of getters and setters not a constructor, ie http://en.wikipedia.org/wiki/Constructor_(object-oriented_programming).

lunched-dan was closer but the example didn't work in jsFiddle.

This example creates a private constructor function that only runs during the creation of the object.

var color = 'black';

function Box()
{
   // private property
   var color = '';

   // private constructor 
   var __construct = function() {
       alert("Object Created.");
       color = 'green';
   }()

   // getter
   this.getColor = function() {
       return color;
   }

   // setter
   this.setColor = function(data) {
       color = data;
   }

}

var b = new Box();

alert(b.getColor()); // should be green

b.setColor('orange');

alert(b.getColor()); // should be orange

alert(color); // should be black

If you wanted to assign public properties then the constructor could be defined as such:

var color = 'black';

function Box()
{
   // public property
   this.color = '';

   // private constructor 
   var __construct = function(that) {
       alert("Object Created.");
       that.color = 'green';
   }(this)

   // getter
   this.getColor = function() {
       return this.color;
   }

   // setter
   this.setColor = function(color) {
       this.color = color;
   }

}

var b = new Box();

alert(b.getColor()); // should be green

b.setColor('orange'); 

alert(b.getColor()); // should be orange

alert(color); // should be black

Using HTML5/JavaScript to generate and save a file

Here is a tutorial to export files as ZIP:

Before getting started, there is a library to save files, the name of library is fileSaver.js, You can find this library here. Let's get started, Now, include the required libraries:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.4/jszip.min.js"  type="text/javascript"></script>
<script type="text/javascript" src="https://fastcdn.org/FileSaver.js/1.1.20151003/FileSaver.js" ></script>

Now copy this code and this code will download a zip file with a file hello.txt having content Hello World. If everything thing works fine, this will download a file.

<script type="text/javascript">
    var zip = new JSZip();
    zip.file("Hello.txt", "Hello World\n");
    zip.generateAsync({type:"blob"})
    .then(function(content) {
        // see FileSaver.js
        saveAs(content, "file.zip");
    });
</script>

This will download a file called file.zip. You can read more here: http://www.wapgee.com/story/248/guide-to-create-zip-files-using-javascript-by-using-jszip-library

How can I clone a JavaScript object except for one key?

If you're dealing with a huge variable, you don't want to copy it and then delete it, as this would be inefficient.

A simple for-loop with a hasOwnProperty check should work, and it is much more adaptable to future needs :

for(var key in someObject) {
        if(someObject.hasOwnProperty(key) && key != 'undesiredkey') {
                copyOfObject[key] = someObject[key];
        }
}

Show hide divs on click in HTML and CSS without jQuery

You can use a checkbox to simulate onClick with CSS:

input[type=checkbox]:checked + p {
    display: none;
}

JSFiddle

Adjacent sibling selectors

How do you concatenate Lists in C#?

targetList = list1.Concat(list2).ToList();

It's working fine I think so. As previously said, Concat returns a new sequence and while converting the result to List, it does the job perfectly.

use of entityManager.createNativeQuery(query,foo.class)

Here is a DB2 Stored Procidure that receive a parameter

SQL

CREATE PROCEDURE getStateByName (IN StateName VARCHAR(128))
DYNAMIC RESULT SETS 1
P1: BEGIN
    -- Declare cursor
    DECLARE State_Cursor CURSOR WITH RETURN for
    -- #######################################################################
    -- # Replace the SQL statement with your statement.
    -- # Note: Be sure to end statements with the terminator character (usually ';')
    -- #
    -- # The example SQL statement SELECT NAME FROM SYSIBM.SYSTABLES
    -- # returns all names from SYSIBM.SYSTABLES.
    -- ######################################################################
    SELECT * FROM COUNTRY.STATE
    WHERE PROVINCE_NAME LIKE UPPER(stateName);
    -- Cursor left open for client application
    OPEN Province_Cursor;
END P1

Java

//Country is a db2 scheme

//Now here is a java Entity bean Method

public List<Province> getStateByName(String stateName) throws Exception {

    EntityManager em = this.em;
    List<State> states= null;
    try {
        Query query = em.createNativeQuery("call NGB.getStateByName(?1)", Province.class);
        query.setParameter(1, provinceName);
        states= (List<Province>) query.getResultList();
    } catch (Exception ex) {
        throw ex;
    }

    return states;
}

How to pass data to all views in Laravel 5?

Laravel 5.6 method: https://laravel.com/docs/5.6/views#passing-data-to-views

Example, with sharing a model collection to all views (AppServiceProvider.php):

use Illuminate\Support\Facades\View;
use App\Product;

public function boot()
{
    $products = Product::all();
    View::share('products', $products);

}

read complete file without using loop in java

Java 7 one line solution

List<String> lines = Files.readAllLines(Paths.get("file"), StandardCharsets.UTF_8);

or

 String text = new String(Files.readAllBytes(Paths.get("file")), StandardCharsets.UTF_8);

Error: Unexpected value 'undefined' imported by the module

I had this issue, it is true that the error on the console ain't descriptive. But if you look at the angular-cli output:

You will see a WARNING, pointing to the circular dependency

WARNING in Circular dependency detected:
module1 -> module2
module2 -> module1

So the solution is to remove one import from one of the Modules.

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

After a fair amount of work, I was able to get it to build on Ubuntu 12.04 x86 and Debian 7.4 x86_64. I wrote up a guide below. Can you please try following it to see if it resolves the issue?

If not please let me know where you get stuck.

Install Common Dependencies

sudo apt-get install build-essential autoconf libtool pkg-config python-opengl python-imaging python-pyrex python-pyside.qtopengl idle-python2.7 qt4-dev-tools qt4-designer libqtgui4 libqtcore4 libqt4-xml libqt4-test libqt4-script libqt4-network libqt4-dbus python-qt4 python-qt4-gl libgle3 python-dev

Install NumArray 1.5.2

wget http://goo.gl/6gL0q3 -O numarray-1.5.2.tgz
tar xfvz numarray-1.5.2.tgz
cd numarray-1.5.2
sudo python setup.py install

Install Numeric 23.8

wget http://goo.gl/PxaHFW -O numeric-23.8.tgz
tar xfvz numeric-23.8.tgz
cd Numeric-23.8
sudo python setup.py install

Install HDF5 1.6.5

wget ftp://ftp.hdfgroup.org/HDF5/releases/hdf5-1.6/hdf5-1.6.5.tar.gz
tar xfvz hdf5-1.6.5.tar.gz
cd hdf5-1.6.5
./configure --prefix=/usr/local
sudo make 
sudo make install

Install Nanoengineer

git clone https://github.com/kanzure/nanoengineer.git
cd nanoengineer
./bootstrap
./configure
make
sudo make install

Troubleshooting

On Debian Jessie, you will receive the error message that cant pants mentioned. There seems to be an issue in the automake scripts. x86_64-linux-gnu-gcc is inserted in CFLAGS and gcc will interpret that as a name of one of the source files. As a workaround, let's create an empty file with that name. Empty so that it won't change the program and that very name so that compiler picks it up. From the cloned nanoengineer directory, run this command to make gcc happy (it is a hack yes, but it does work) ...

touch sim/src/x86_64-linux-gnu-gcc

If you receive an error message when attemping to compile HDF5 along the lines of: "error: call to ‘__open_missing_mode’ declared with attribute error: open with O_CREAT in second argument needs 3 arguments", then modify the file perform/zip_perf.c, line 548 to look like the following and then rerun make...

output = open(filename, O_RDWR | O_CREAT, S_IRUSR|S_IWUSR);

If you receive an error message about Numeric/arrayobject.h not being found when building Nanoengineer, try running

export CPPFLAGS=-I/usr/local/include/python2.7
./configure
make
sudo make install

If you receive an error message similar to "TRACE_PREFIX undeclared", modify the file sim/src/simhelp.c lines 38 to 41 to look like this and re-run make:

#ifdef DISTUTILS
static char tracePrefix[] = "";
#else
static char tracePrefix[] = "";

If you receive an error message when trying to launch NanoEngineer-1 that mentions something similar to "cannot import name GL_ARRAY_BUFFER_ARB", modify the lines in the following files

/usr/local/bin/NanoEngineer1_0.9.2.app/program/graphics/drawing/setup_draw.py
/usr/local/bin/NanoEngineer1_0.9.2.app/program/graphics/drawing/GLPrimitiveBuffer.py
/usr/local/bin/NanoEngineer1_0.9.2.app/program/prototype/test_drawing.py

that look like this:

from OpenGL.GL import GL_ARRAY_BUFFER_ARB
from OpenGL.GL import GL_ELEMENT_ARRAY_BUFFER_ARB

to look like this:

from OpenGL.GL.ARB.vertex_buffer_object import GL_ARRAY_BUFFER_AR
from OpenGL.GL.ARB.vertex_buffer_object import GL_ELEMENT_ARRAY_BUFFER_ARB

I also found an additional troubleshooting text file that has been removed, but you can find it here

How to check for null in a single statement in scala?

Try to avoid using null in Scala. It's really there only for interoperability with Java. In Scala, use Option for things that might be empty. If you're calling a Java API method that might return null, wrap it in an Option immediately.

def getObject : Option[QueueObject] = {
  // Wrap the Java result in an Option (this will become a Some or a None)
  Option(someJavaObject.getResponse)
}

Note: You don't need to put it in a val or use an explicit return statement in Scala; the result will be the value of the last expression in the block (in fact, since there's only one statement, you don't even need a block).

def getObject : Option[QueueObject] = Option(someJavaObject.getResponse)

Besides what the others have already shown (for example calling foreach on the Option, which might be slightly confusing), you could also call map on it (and ignore the result of the map operation if you don't need it):

getObject map QueueManager.add

This will do nothing if the Option is a None, and call QueueManager.add if it is a Some.

I find using a regular if however clearer and simpler than using any of these "tricks" just to avoid an indentation level. You could also just write it on one line:

if (getObject.isDefined) QueueManager.add(getObject.get)

or, if you want to deal with null instead of using Option:

if (getObject != null) QueueManager.add(getObject)

edit - Ben is right, be careful to not call getObject more than once if it has side-effects; better write it like this:

val result = getObject
if (result.isDefined) QueueManager.add(result.get)

or:

val result = getObject
if (result != null) QueueManager.add(result)

select2 changing items dynamically

I fix the lack of example's library here:

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js">

http://jsfiddle.net/bbAU9/328/

Disabling right click on images using jquery

what is your purpose of disabling the right click. problem with any technique is that there is always a way to go around them. the console for firefox (firebug) and chrome allow for unbinding of that event. or if you want the image to be protected one could always just take a look at their temporary cache for the images.

If you want to create your own contextual menu the preventDefault is fine. Just pick your battles here. not even a big JavaScript library like tnyMCE works on all browsers... and that is not because it's not possible ;-).

$(document).bind("contextmenu",function(e){
  e.preventDefault()
});

Personally I'm more in for an open internet. Native browser behavior should not be hindered by the pages interactions. I am sure that other ways can be found to interact that are not the right click.

How do I use arrays in cURL POST requests

You are just creating your array incorrectly. You could use http_build_query:

$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(
                 urlencode(base64_encode('image1')),
                 urlencode(base64_encode('image2'))
            )
        );
$fields_string = http_build_query($fields);

So, the entire code that you could use would be:

<?php
//extract data from the post
extract($_POST);

//set POST variables
$url = 'http://api.example.com/api';
$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(
                 urlencode(base64_encode('image1')),
                 urlencode(base64_encode('image2'))
            )
        );

//url-ify the data for the POST
$fields_string = http_build_query($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);
echo $result;

//close connection
curl_close($ch);
?>