Programs & Examples On #Android camera

The Android framework includes support for various cameras and camera features available on devices, allowing you to capture pictures and videos in your applications.

How to compress image size?

i resolve this problem in this way, later i will improve the code

protected Void doInBackground(byte[]... data) {
        FileOutputStream outStream = null;

        // Write to Internal Storage
        try {
            File dir = new File (context.getFilesDir());
            dir.mkdirs();

            String fileName ="image.jpg";
            File outFile = new File(dir, fileName);
            outFile.setExecutable(true, false);
            outFile.setWritable(true, false);
            outStream = new FileOutputStream(outFile);
            outStream.write(data[0]);
            outStream.flush();
            outStream.close();
            InputStream in = new FileInputStream(context.getFilesDir()+"image.jpg");
            Bitmap bm2 = BitmapFactory.decodeStream(in);
            OutputStream stream = new FileOutputStream(String.valueOf(context.getFilesDir()+pathImage+"/"+idPicture+".jpg"));
            bm2.compress(Bitmap.CompressFormat.JPEG, 50, stream);
            stream.close();
            in.close();

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

Allow user to select camera or gallery for image

You can try this :

To open Gallery :

private void browseImage() {

        try {
  Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  startActivityForResult(galleryIntent, GALLERY_IMAGE_PICK); //GALLERY_IMAGE_PICK it is a string
  } catch (Exception e) {}
     }

To open Camera :

 private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

    // start the image capture Intent

    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);

}

Android camera intent

Try the following I found Here's a link

If your app targets M and above and declares as using the CAMERA permission which is not granted, then attempting to use this action will result in a SecurityException.

EasyImage.openCamera(Activity activity, int type);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
        @Override
        public void onImagePickerError(Exception e, EasyImage.ImageSource source, int type) {
            //Some error handling
        }

        @Override
        public void onImagesPicked(List<File> imagesFiles, EasyImage.ImageSource source, int type) {
            //Handle the images
            onPhotosReturned(imagesFiles);
        }
    });
}

Android camera android.hardware.Camera deprecated

Now we have to use android.hardware.camera2 as android.hardware.Camera is deprecated which will only work on API >23 FlashLight

   public class MainActivity extends AppCompatActivity {

     Button button;

     Boolean light=true;

     CameraDevice cameraDevice;

     private CameraManager cameraManager;

     private CameraCharacteristics cameraCharacteristics;

     String cameraId;

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button)findViewById(R.id.button);
        cameraManager = (CameraManager) 
        getSystemService(Context.CAMERA_SERVICE);
        try {
          cameraId = cameraManager.getCameraIdList()[0];
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(light){
                    try {

                        cameraManager.setTorchMode(cameraId,true);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }

                    light=false;}
                    else {

                    try {

                      cameraManager.setTorchMode(cameraId,false);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }


                    light=true;
                    }


            }
        });
    }
}

How to measure height, width and distance of object using camera?

I think I know what you are asking for. Here is what you can do.

first get the height of the person say h meters.

sample image

if you can calculate the height of the camera from ground (using height if the person i.e. h) and get angles A and B using gyroscope or something from android then you can calculate the height of the object using the above formula.

Isn't this what you were looking for???

let me know if you need any explanation.

Android Camera : data intent returns null

Kotlin code that works for me:

 private fun takePhotoFromCamera() {
          val intent = Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE)
        startActivityForResult(intent, PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA)
      }

And get Result :

 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
 if (requestCode == PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA) {
         if (resultCode == Activity.RESULT_OK) {
           val photo: Bitmap? =  MediaStore.Images.Media.getBitmap(this.contentResolver, Uri.parse( data!!.dataString)   )
            // Do something here : set image to an ImageView or save it ..   
              imgV_pic.imageBitmap = photo 
        } else if (resultCode == Activity.RESULT_CANCELED) {
            Log.i(TAG, "Camera  , RESULT_CANCELED ")
        }

    }

}

and don't forget to declare request code:

companion object {
 const val PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA = 300
  }

How do I open the "front camera" on the Android platform?

private Camera openFrontFacingCameraGingerbread() {
    int cameraCount = 0;
    Camera cam = null;
    Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
    cameraCount = Camera.getNumberOfCameras();
    for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
        Camera.getCameraInfo(camIdx, cameraInfo);
        if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            try {
                cam = Camera.open(camIdx);
            } catch (RuntimeException e) {
                Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
            }
        }
    }

    return cam;
}

Add the following permissions in the AndroidManifest.xml file:

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.front" android:required="false" />

Note: This feature is available in Gingerbread(2.3) and Up Android Version.

Android open camera from button

public class camera_act extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_act);
         ImageView imageView = findViewById(R.id.image);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent,90);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode,resultCode,data);
       Bitmap bitmap = data.getExtras.get("imageKey");
       imageView.setBitmapImage(bitmap);
            
        }
    }
}

How to capture and save an image using custom camera in Android?

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

                // create intent with ACTION_IMAGE_CAPTURE action
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                /**
 Here REQUEST_IMAGE is the unique integer value you can pass it any integer
 **/
                // start camera activity
                startActivityForResult(intent, TAKE_PICTURE);
            }

            }

        );

then u can now give the image a file name as follows and then convert it into bitmap and later on to file

 private void createImageFile(Bitmap bitmap) throws IOException {
        // Create an image file name
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
        FileOutputStream stream = new FileOutputStream(image);
        stream.write(bytes.toByteArray());
        stream.close();
        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = "file:" + image.getAbsolutePath();
        fileUri = image.getAbsolutePath();
        Picasso.with(getActivity()).load(image).into(showbookimage);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {

        if (requestCode == TAKE_PICTURE && resultCode== Activity.RESULT_OK && intent != null){
            // get bundle
            Bundle extras = intent.getExtras();
            // get
            bitMap = (Bitmap) extras.get("data");
//            showbookimage.setImageBitmap(bitMap);
            try {
                createImageFile(bitMap);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

use picasso for images to display rather fast

Android Camera Preview Stretched

Just to make this thread more complete i am adding my version of answer:

What i wanted to achieve: The surface view shouldn't be stretched, and it should cover the whole screen, Moreover, there was only a landscape mode in my app.

Solution:

The solution is an extremely small extension to F1sher's solution:

=> First step is to integrate F1sher's solution.

=> Now, there might arise a scenario in F1sher's solution when the surface view doesn't covers the whole screen, The solution is to make the surface view greater than the screen dimensions so that it covers the whole screen, for that:

    size = getOptimalPreviewSize(mCamera.getParameters().getSupportedPreviewSizes(), screenWidth, screenHeight);

    Camera.Parameters parameters = mCamera.getParameters();
    parameters.setPreviewSize(size.width, size.height);


    mCamera.setParameters(parameters);      

    double screenRatio = (double) screenHeight / screenWidth;
    double previewRatio = (double) size.height / size.width;

    if (previewRatio > screenRatio)     /*if preview ratio is greater than screen ratio then we will have to recalculate the surface height while keeping the surface width equal to the screen width*/
    {
        RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(screenWidth, (int) (screenWidth * previewRatio));
        params1.addRule(RelativeLayout.CENTER_IN_PARENT);
        flPreview.setLayoutParams(params1);

        flPreview.setClipChildren(false);

        LayoutParams surfaceParams = new LayoutParams(screenWidth, (int) (screenWidth * previewRatio));
        surfaceParams.gravity = Gravity.CENTER;
        mPreview.setLayoutParams(surfaceParams);        
    }
    else     /*if preview ratio is smaller than screen ratio then we will have to recalculate the surface width while keeping the surface height equal to the screen height*/
    {
        RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams((int) ((double) screenHeight / previewRatio), screenHeight);
        params1.addRule(RelativeLayout.CENTER_IN_PARENT);
        flPreview.setLayoutParams(params1);
        flPreview.setClipChildren(false);

        LayoutParams surfaceParams = new LayoutParams((int) ((double) screenHeight / previewRatio), screenHeight);
        surfaceParams.gravity = Gravity.CENTER;
        mPreview.setLayoutParams(surfaceParams);

    }       

    flPreview.addView(mPreview); 

  /*  The TopMost layout used is the RelativeLayout, flPreview is the FrameLayout in which Surface View is added, mPreview is an instance of a class which extends SurfaceView  */

How to turn on front flash light programmatically in Android?

For this problem you should:

  1. Check whether the flashlight is available or not?

  2. If so then Turn Off/On

  3. If not then you can do whatever, according to your app needs.

For Checking availability of flash in the device:

You can use the following:

 context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

which will return true if a flash is available, false if not.

See:
http://developer.android.com/reference/android/content/pm/PackageManager.html for more information.

For turning on/off flashlight:

I googled out and got this about android.permission.FLASHLIGHT. Android manifests' permission looks promising:

 <!-- Allows access to the flashlight -->
 <permission android:name="android.permission.FLASHLIGHT"
             android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
             android:protectionLevel="normal"
             android:label="@string/permlab_flashlight"
             android:description="@string/permdesc_flashlight" />

Then make use of Camera and set Camera.Parameters. The main parameter used here is FLASH_MODE_TORCH.

eg.

Code Snippet to turn on camera flashlight.

Camera cam = Camera.open();     
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();

Code snippet to turn off camera led light.

  cam.stopPreview();
  cam.release();

I just found a project that uses this permission. Check quick-settings' src code. here http://code.google.com/p/quick-settings/ (Note: This link is now broken)

For Flashlight directly look http://code.google.com/p/quick-settings/source/browse/trunk/quick-settings/#quick-settings/src/com/bwx/bequick/flashlight (Note: This link is now broken)

Update6 You could also try to add a SurfaceView as described in this answer LED flashlight on Galaxy Nexus controllable by what API? This seems to be a solution that works on many phones.

Update 5 Major Update

I have found an alternative Link (for the broken links above): http://www.java2s.com/Open-Source/Android/Tools/quick-settings/com.bwx.bequick.flashlight.htm You can now use this link. [Update: 14/9/2012 This link is now broken]

Update 1

Another OpenSource Code : http://code.google.com/p/torch/source/browse/

Update 2

Example showing how to enable the LED on a Motorola Droid: http://code.google.com/p/droidled/

Another Open Source Code :

http://code.google.com/p/covedesigndev/
http://code.google.com/p/search-light/

Update 3 (Widget for turning on/off camera led)

If you want to develop a widget that turns on/off your camera led, then you must refer my answer Widget for turning on/off camera flashlight in android..

Update 4

If you want to set the intensity of light emerging from camera LED you can refer Can I change the LED intensity of an Android device? full post. Note that only rooted HTC devices support this feature.

** Issues:**

There are also some problems while turning On/Off flashlight. eg. for the devices not having FLASH_MODE_TORCH or even if it has, then flashlight does not turn ON etc.

Typically Samsung creates a lot of problems.

You can refer to problems in the given below list:

Use camera flashlight in Android

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

How to get file name from file path in android

Simple and easy way to get File name

File file = new File("/storage/sdcard0/DCIM/Camera/1414240995236.jpg"); 
String strFileName = file.getName();

After add this code and print strFileName you will get strFileName = 1414240995236.jpg

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

Bootstrap-select - how to fire event on change

Easiest implementation.

<script>
    $( ".selectpicker" ).change(function() {
        alert( "Handler for .change() called." );
    });
</script>

Determine the number of rows in a range

Function ListRowCount(ByVal FirstCellName as String) as Long
    With thisworkbook.Names(FirstCellName).RefersToRange
        If isempty(.Offset(1,0).value) Then 
            ListRowCount = 1
        Else
            ListRowCount = .End(xlDown).row - .row + 1
        End If
    End With
End Function

But if you are damn sure there's nothing around the list, then just thisworkbook.Names(FirstCellName).RefersToRange.CurrentRegion.rows.count

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

try to change this solved my issue, you may other graphics options, and change to a lower resolution model enter image description here

Error message "Forbidden You don't have permission to access / on this server"

I know this question has several answers already, but I think there is a very subtle aspect that, although mentioned, hasn't been highlighted enough in the previous answers.

Before checking the Apache configuration or your files' permissions, let's do a simpler check to make sure that each of the directories composing the full path to the file you want to access (e.g. the index.php file in your document's root) is not only readable but also executable by the web server user.

For example, let's say the path to your documents root is "/var/www/html". You have to make sure that all of the "var", "www" and "html" directories are (readable and) executable by the web server user. In my case (Ubuntu 16.04) I had mistakenly removed the "x" flag to the "others" group from the "html" directory so the permissions looked like this:

drwxr-xr-- 15 root root 4096 Jun 11 16:40 html

As you can see the web server user (to whom the "others" permissions apply in this case) didn't have execute access to the "html" directory, and this was exactly the root of the problem. After issuing a:

chmod o+x html

command, the problem got fixed!

Before resolving this way I had literally tried every other suggestion in this thread, and since the suggestion was buried in a comment that I found almost by chance, I think it may be helpful to highlight and expand on it here.

How do you get the cursor position in a textarea?

If there is no selection, you can use the properties .selectionStart or .selectionEnd (with no selection they're equal).

var cursorPosition = $('#myTextarea').prop("selectionStart");

Note that this is not supported in older browsers, most notably IE8-. There you'll have to work with text ranges, but it's a complete frustration.

I believe there is a library somewhere which is dedicated to getting and setting selections/cursor positions in input elements, though. I can't recall its name, but there seem to be dozens on articles about this subject.

How to get IP address of the device from code?

This is the easiest and simple way ever exist on the internet... First of all, add this permission to your manifest file...

  1. "INTERNET"

  2. "ACCESS_NETWORK_STATE"

add this in onCreate file of Activity..

    getPublicIP();

Now Add this function to your MainActivity.class.

_x000D_
_x000D_
    private void getPublicIP() {_x000D_
ArrayList<String> urls=new ArrayList<String>(); //to read each line_x000D_
_x000D_
        new Thread(new Runnable(){_x000D_
            public void run(){_x000D_
                //TextView t; //to show the result, please declare and find it inside onCreate()_x000D_
_x000D_
                try {_x000D_
                    // Create a URL for the desired page_x000D_
                    URL url = new URL("https://api.ipify.org/"); //My text file location_x000D_
                    //First open the connection_x000D_
                    HttpURLConnection conn=(HttpURLConnection) url.openConnection();_x000D_
                    conn.setConnectTimeout(60000); // timing out in a minute_x000D_
_x000D_
                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));_x000D_
_x000D_
                    //t=(TextView)findViewById(R.id.TextView1); // ideally do this in onCreate()_x000D_
                    String str;_x000D_
                    while ((str = in.readLine()) != null) {_x000D_
                        urls.add(str);_x000D_
                    }_x000D_
                    in.close();_x000D_
                } catch (Exception e) {_x000D_
                    Log.d("MyTag",e.toString());_x000D_
                }_x000D_
_x000D_
                //since we are in background thread, to post results we have to go back to ui thread. do the following for that_x000D_
_x000D_
                PermissionsActivity.this.runOnUiThread(new Runnable(){_x000D_
                    public void run(){_x000D_
                        try {_x000D_
                            Toast.makeText(PermissionsActivity.this, "Public IP:"+urls.get(0), Toast.LENGTH_SHORT).show();_x000D_
                        }_x000D_
                        catch (Exception e){_x000D_
                            Toast.makeText(PermissionsActivity.this, "TurnOn wiffi to get public ip", Toast.LENGTH_SHORT).show();_x000D_
                        }_x000D_
                    }_x000D_
                });_x000D_
_x000D_
            }_x000D_
        }).start();_x000D_
_x000D_
    }
_x000D_
_x000D_
_x000D_

LogisticRegression: Unknown label type: 'continuous' using sklearn in python

LogisticRegression is not for regression but classification !

The Y variable must be the classification class,

(for example 0 or 1)

And not a continuous variable,

that would be a regression problem.

Set cellpadding and cellspacing in CSS?

How about adding the style directly to the table itself? This is instead of using table in your CSS, which is a BAD approach if you have multiple tables on your page:

<table style="border-collapse: separate;border-spacing: 2px;">
    <tr>
        <td style="padding: 4px 4px;">Some Text</td>
    </tr>
</table>

Remove a specific character using awk or sed

Use sed's substitution: sed 's/"//g'

s/X/Y/ replaces X with Y.

g means all occurrences should be replaced, not just the first one.

How to get input text value on click in ReactJS

First of all, you can't pass to alert second argument, use concatenation instead

alert("Input is " + inputValue);

Example

However in order to get values from input better to use states like this

_x000D_
_x000D_
var MyComponent = React.createClass({_x000D_
  getInitialState: function () {_x000D_
    return { input: '' };_x000D_
  },_x000D_
_x000D_
  handleChange: function(e) {_x000D_
    this.setState({ input: e.target.value });_x000D_
  },_x000D_
_x000D_
  handleClick: function() {_x000D_
    console.log(this.state.input);_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <input type="text" onChange={ this.handleChange } />_x000D_
        <input_x000D_
          type="button"_x000D_
          value="Alert the text input"_x000D_
          onClick={this.handleClick}_x000D_
        />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
  <MyComponent />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

ggplot combining two plots from different data.frames

As Baptiste said, you need to specify the data argument at the geom level. Either

#df1 is the default dataset for all geoms
(plot1 <- ggplot(df1, aes(v, p)) + 
    geom_point() +
    geom_step(data = df2)
)

or

#No default; data explicitly specified for each geom
(plot2 <- ggplot(NULL, aes(v, p)) + 
      geom_point(data = df1) +
      geom_step(data = df2)
)

Python Socket Multiple Clients

#!/usr/bin/python
import sys
import os
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)         
port = 50000

try:
    s.bind((socket.gethostname() , port))
except socket.error as msg:
    print(str(msg))
s.listen(10)
conn, addr = s.accept()  
print 'Got connection from'+addr[0]+':'+str(addr[1]))
while 1:
        msg = s.recv(1024)
        print +addr[0]+, ' >> ', msg
        msg = raw_input('SERVER >>'),host
        s.send(msg)
s.close()

What is the C# version of VB.net's InputDialog?

There isn't one. If you really wanted to use the VB InputBox in C# you can. Just add reference to Microsoft.VisualBasic.dll and you'll find it there.

But I would suggest to not use it. It is ugly and outdated IMO.

Converting java.util.Properties to HashMap<String,String>

First thing,

Properties class is based on Hashtable and not Hashmap. Properties class basically extends Hashtable

There is no such constructor in HashMap class which takes a properties object and return you a hashmap object. So what you are doing is NOT correct. You should be able to cast the object of properties to hashtable reference.

Given final block not properly padded

This can also be a issue when you enter wrong password for your sign key.

How can I search sub-folders using glob.glob module?

To find files in immediate subdirectories:

configfiles = glob.glob(r'C:\Users\sam\Desktop\*\*.txt')

For a recursive version that traverse all subdirectories, you could use ** and pass recursive=True since Python 3.5:

configfiles = glob.glob(r'C:\Users\sam\Desktop\**\*.txt', recursive=True)

Both function calls return lists. You could use glob.iglob() to return paths one by one. Or use pathlib:

from pathlib import Path

path = Path(r'C:\Users\sam\Desktop')
txt_files_only_subdirs = path.glob('*/*.txt')
txt_files_all_recursively = path.rglob('*.txt') # including the current dir

Both methods return iterators (you can get paths one by one).

jQuery bind to Paste Event, how to get the content of the paste

I recently needed to accomplish something similar to this. I used the following design to access the paste element and value. jsFiddle demo

$('body').on('paste', 'input, textarea', function (e)
{
    setTimeout(function ()
    {
        //currentTarget added in jQuery 1.3
        alert($(e.currentTarget).val());
        //do stuff
    },0);
});

Oracle ORA-12154: TNS: Could not resolve service name Error?

I struggled to resolve this problem for hours until I found an Environment variable called TNS_ADMIN set in My Computer => Properties => Advanced => Environment Variables => look in System variables for an entry called TNS_ADMIN. TNS_ADMIN is added to change the default path for Tnsnames.ora entry. This is useful when its used in a network environment where a generic tnsnames.ora entry can be setup for all the network computers. To look at the default path of tnsnames.ora add the default path in TNS_ADMIN.

pySerial write() won't take my string

It turns out that the string needed to be turned into a bytearray and to do this I editted the code to

ser.write("%01#RDD0010000107**\r".encode())

This solved the problem

MySQL Trigger after update only if row has changed

BUT imagine a large table with changing columns. You have to compare every column and if the database changes you have to adjust the trigger. AND it doesn't "feel" good to compare every row hardcoded :)

Yeah, but that's the way to proceed.

As a side note, it's also good practice to pre-emptively check before updating:

UPDATE foo SET b = 3 WHERE a=3 and b <> 3;

In your example this would make it update (and thus overwrite) two rows instead of three.

MySQL query to select events between start/end date

If you would like to use INTERSECT option, the SQL is as follows

(SELECT id FROM events WHERE start BETWEEN '2013-06-13' AND '2013-07-22') 
INTERSECT
(SELECT id FROM events WHERE end BETWEEN '2013-06-13' AND '2013-07-22') 

AJAX Mailchimp signup form integration

In the other hand, there is some packages in AngularJS which are helpful (in AJAX WEB):

https://github.com/cgarnier/angular-mailchimp-subscribe

Git conflict markers

The line (or lines) between the lines beginning <<<<<<< and ====== here:

<<<<<<< HEAD:file.txt
Hello world
=======

... is what you already had locally - you can tell because HEAD points to your current branch or commit. The line (or lines) between the lines beginning ======= and >>>>>>>:

=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt

... is what was introduced by the other (pulled) commit, in this case 77976da35a11. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.

Nested routes with react router v4 / v5

Some thing like this.

_x000D_
_x000D_
import React from 'react';_x000D_
import {_x000D_
  BrowserRouter as Router, Route, NavLink, Switch, Link_x000D_
} from 'react-router-dom';_x000D_
_x000D_
import '../assets/styles/App.css';_x000D_
_x000D_
const Home = () =>_x000D_
  <NormalNavLinks>_x000D_
    <h1>HOME</h1>_x000D_
  </NormalNavLinks>;_x000D_
const About = () =>_x000D_
  <NormalNavLinks>_x000D_
    <h1>About</h1>_x000D_
  </NormalNavLinks>;_x000D_
const Help = () =>_x000D_
  <NormalNavLinks>_x000D_
    <h1>Help</h1>_x000D_
  </NormalNavLinks>;_x000D_
_x000D_
const AdminHome = () =>_x000D_
  <AdminNavLinks>_x000D_
    <h1>root</h1>_x000D_
  </AdminNavLinks>;_x000D_
_x000D_
const AdminAbout = () =>_x000D_
  <AdminNavLinks>_x000D_
    <h1>Admin about</h1>_x000D_
  </AdminNavLinks>;_x000D_
_x000D_
const AdminHelp = () =>_x000D_
  <AdminNavLinks>_x000D_
    <h1>Admin Help</h1>_x000D_
  </AdminNavLinks>;_x000D_
_x000D_
_x000D_
const AdminNavLinks = (props) => (_x000D_
  <div>_x000D_
    <h2>Admin Menu</h2>_x000D_
    <NavLink exact to="/admin">Admin Home</NavLink>_x000D_
    <NavLink to="/admin/help">Admin Help</NavLink>_x000D_
    <NavLink to="/admin/about">Admin About</NavLink>_x000D_
    <Link to="/">Home</Link>_x000D_
    {props.children}_x000D_
  </div>_x000D_
);_x000D_
_x000D_
const NormalNavLinks = (props) => (_x000D_
  <div>_x000D_
    <h2>Normal Menu</h2>_x000D_
    <NavLink exact to="/">Home</NavLink>_x000D_
    <NavLink to="/help">Help</NavLink>_x000D_
    <NavLink to="/about">About</NavLink>_x000D_
    <Link to="/admin">Admin</Link>_x000D_
    {props.children}_x000D_
  </div>_x000D_
);_x000D_
_x000D_
const App = () => (_x000D_
  <Router>_x000D_
    <div>_x000D_
      <Switch>_x000D_
        <Route exact path="/" component={Home}/>_x000D_
        <Route path="/help" component={Help}/>_x000D_
        <Route path="/about" component={About}/>_x000D_
_x000D_
        <Route exact path="/admin" component={AdminHome}/>_x000D_
        <Route path="/admin/help" component={AdminHelp}/>_x000D_
        <Route path="/admin/about" component={AdminAbout}/>_x000D_
      </Switch>_x000D_
_x000D_
    </div>_x000D_
  </Router>_x000D_
);_x000D_
_x000D_
_x000D_
export default App;
_x000D_
_x000D_
_x000D_

Play sound file in a web-page in the background

If you don't want to show controls then try this code

<audio  autoplay>
 <source src="song.ogg"  type="audio/ogg">
Your browser does not support the audio element.
</audio>

Required attribute HTML5

Just put the following below your form. Make sure your input fields are required.

<script>
    var forms = document.getElementsByTagName('form');
    for (var i = 0; i < forms.length; i++) {
        forms[i].noValidate = true;
        forms[i].addEventListener('submit', function(event) {
            if (!event.target.checkValidity()) {
                event.preventDefault();
                alert("Please complete all fields and accept the terms.");
            }
        }, false);
    }
</script>

Nesting await in Parallel.ForEach

Here is a simple generic implementation of a ForEachAsync method, based on an ActionBlock from the TPL Dataflow library, now embedded in the .NET 5 platform:

public static Task ForEachAsync<T>(this IEnumerable<T> source,
    Func<T, Task> action, int dop)
{
    // Arguments validation omitted
    var block = new ActionBlock<T>(action,
        new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = dop });
    try
    {
        foreach (var item in source) block.Post(item);
        block.Complete();
    }
    catch (Exception ex) { ((IDataflowBlock)block).Fault(ex); }
    return block.Completion;
}

This solution enumerates eagerly the supplied IEnumerable, and sends immediately all its elements to the ActionBlock. So it is not very suitable for enumerables with huge number of elements. Below is a more sophisticated approach, that enumerates the source lazily, and sends its elements to the ActionBlock one by one:

public static async Task ForEachAsync<T>(this IEnumerable<T> source,
    Func<T, Task> action, int dop)
{
    // Arguments validation omitted
    var block = new ActionBlock<T>(action, new ExecutionDataflowBlockOptions()
    { MaxDegreeOfParallelism = dop, BoundedCapacity = dop });
    try
    {
        foreach (var item in source)
            if (!await block.SendAsync(item).ConfigureAwait(false)) break;
        block.Complete();
    }
    catch (Exception ex) { ((IDataflowBlock)block).Fault(ex); }
    try { await block.Completion.ConfigureAwait(false); }
    catch { block.Completion.Wait(); } // Propagate AggregateException
}

These two methods have different behavior in case of exceptions. The first¹ propagates an AggregateException containing the exceptions directly in its InnerExceptions property. The second propagates an AggregateException that contains another AggregateException with the exceptions. Personally I find the behavior of the second method more convenient in practice, because awaiting it eliminates automatically a level of nesting, and so I can simply catch (AggregateException aex) and handle the aex.InnerExceptions inside the catch block. The first method requires to store the Task before awaiting it, so that I can gain access the task.Exception.InnerExceptions inside the catch block. For more info about propagating exceptions from async methods, look here or here.

Both implementations handle gracefully any errors that may occur during the enumeration of the source. The ForEachAsync method does not complete before all pending operations are completed. No tasks are left behind unobserved (in fire-and-forget fashion).

¹ The first implementation elides async and await.

batch/bat to copy folder and content at once

I suspect that the xcopy command is the magic bullet you're looking for.

It can copy files, directories, and even entire drives while preserving the original directory hierarchy. There are also a handful of additional options available, compared to the basic copy command.

Check out the documentation here.

If your batch file only needs to run on Windows Vista or later, you can use robocopy instead, which is an even more powerful tool than xcopy, and is now built into the operating system. It's documentation is available here.

Why is 22 the default port number for SFTP?

Ahem, because 22 is the port number for ssh and has been for ages?

SVN: Is there a way to mark a file as "do not commit"?

I don't believe there is a way to ignore a file in the repository. We often run into this with web.config and other configuration files.

Although not perfect, the solution I most often see and use is to have .default file and an nant task to create local copies.

For example, in the repo is a file called web.config.default that has default values. Then create a nant task that will rename all the web.config.default files to web.config that can then be customized to local values. This task should be called when a new working copy is retrieved or a build is run.

You'll also need to ignore the web.config file that is created so that it isn't committed to the repository.

Ruby, Difference between exec, system and %x() or Backticks

They do different things. exec replaces the current process with the new process and never returns. system invokes another process and returns its exit value to the current process. Using backticks invokes another process and returns the output of that process to the current process.

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

Changing the target framework from .NET Framework 4 Client Profile to .NET Framework 4 fixed this problem for me.

So in your example: set the target framework on MyWebProject1 to .NET Framework 4

OpenCV - Apply mask to a color image

Answer given by Abid Rahman K is not completely correct. I also tried it and found very helpful but got stuck.

This is how I copy image with a given mask.

x, y = np.where(mask!=0)
pts = zip(x, y)
# Assuming dst and src are of same sizes
for pt in pts:
   dst[pt] = src[pt]

This is a bit slow but gives correct results.

EDIT:

Pythonic way.

idx = (mask!=0)
dst[idx] = src[idx]

Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required

I had the same problem for an application deployed to Microsoft Azure.

SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.

First I approved all unknown devices (some ip-addresses originating from Ireland) on the following page (signed in as the gmail user): https://security.google.com/settings/u/1/security/secureaccount

I used the following settings for the client:

var client = new SmtpClient("smtp.gmail.com");
client.Port = 587;
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("[email protected]", "my_password"); 

It started working only after I set the following property on the smtp-client:

client.TargetName = "STARTTLS/smtp.gmail.com";

How to convert JTextField to String and String to JTextField?

// to string
String text = textField.getText();

// to JTextField
textField.setText(text);

You can also create a new text field: new JTextField(text)

Note that this is not conversion. You have two objects, where one has a property of the type of the other one, and you just set/get it.

Reference: javadocs of JTextField

How can I display a list view in an Android Alert Dialog?

You can actually create a simple Array with Alert Dialog like this.

 val sexArray = arrayOf("Male", "Female")
 val selectedPosition = 0

 AlertDialog.Builder(requireContext())
    .setSingleChoiceItems(sexArray, 0) { dialog, position ->
        val selectedSex = sexArray[position]
    }.show()

How to add a response header on nginx when using proxy_pass?

You could try this solution :

In your location block when you use proxy_pass do something like this:

location ... {

  add_header yourHeaderName yourValue;
  proxy_pass xxxx://xxx_my_proxy_addr_xxx;

  # Now use this solution:
  proxy_ignore_headers yourHeaderName // but set by proxy

  # Or if above didn't work maybe this:
  proxy_hide_header yourHeaderName // but set by proxy

}

I'm not sure would it be exactly what you need but try some manipulation of this method and maybe result will fit your problem.

Also you can use this combination:

proxy_hide_header headerSetByProxy;
set $sent_http_header_set_by_proxy yourValue;

ASP.NET MVC - passing parameters to the controller

The reason for the special treatment of "id" is that it is added to the default route mapping. To change this, go to Global.asax.cs, and you will find the following line:

routes.MapRoute ("Default", "{controller}/{action}/{id}", 
                 new { controller = "Home", action = "Index", id = "" });

Change it to:

routes.MapRoute ("Default", "{controller}/{action}", 
                 new { controller = "Home", action = "Index" });

Add zero-padding to a string

string strvalue="11".PadRight(4, '0');

output= 1100

string strvalue="301".PadRight(4, '0');

output= 3010

string strvalue="11".PadLeft(4, '0');

output= 0011

string strvalue="301".PadLeft(4, '0');

output= 0301

npm install gives error "can't find a package.json file"

Check this link for steps on how to install express.js for your application locally.

But, if for some reason you are installing express globally, make sure the directory you are in is the directory where Node is installed. On my Windows 10, package.json is located at

C:\Program Files\nodejs\node_modules\npm

Open command prompt as administrator and change your directory to the location where your package.json is located.

Then issue the install command.

Order Bars in ggplot2 bar graph

Since we are only looking at the distribution of a single variable ("Position") as opposed to looking at the relationship between two variables, then perhaps a histogram would be the more appropriate graph. ggplot has geom_histogram() that makes it easy:

ggplot(theTable, aes(x = Position)) + geom_histogram(stat="count")

enter image description here

Using geom_histogram():

I think geom_histogram() is a little quirky as it treats continuous and discrete data differently.

For continuous data, you can just use geom_histogram() with no parameters. For example, if we add in a numeric vector "Score"...

    Name   Position   Score  
1   James  Goalkeeper 10
2   Frank  Goalkeeper 20
3   Jean   Defense    10
4   Steve  Defense    10
5   John   Defense    20
6   Tim    Striker    50

and use geom_histogram() on the "Score" variable...

ggplot(theTable, aes(x = Score)) + geom_histogram()

enter image description here

For discrete data like "Position" we have to specify a calculated statistic computed by the aesthetic to give the y value for the height of the bars using stat = "count":

 ggplot(theTable, aes(x = Position)) + geom_histogram(stat = "count")

Note: Curiously and confusingly you can also use stat = "count" for continuous data as well and I think it provides a more aesthetically pleasing graph.

ggplot(theTable, aes(x = Score)) + geom_histogram(stat = "count")

enter image description here

Edits: Extended answer in response to DebanjanB's helpful suggestions.

jQuery scrollTop not working in Chrome but working in Firefox

Scroll body and check if it worked:

function getScrollableRoot() {
    var body = document.body;
    var prev = body.scrollTop;
    body.scrollTop++;
    if (body.scrollTop === prev) {
        return document.documentElement;
    } else {
        body.scrollTop--;
        return body;
    }
}


$(getScrollableRoot()).animate({ scrollTop: 0 }, "slow");

This is more efficient than $("html, body").animate because only one animation used, not two. Thus, only one callback fires, not two.

Enter key in textarea

My scenario is when the user strikes the enter key while typing in textarea i have to include a line break.I achieved this using the below code......Hope it may helps somebody......

function CheckLength()
{
    var keyCode = event.keyCode
    if (keyCode == 13)
    {
        document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value = document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value + "\n<br>";
    }
}

Fragment pressing back button

Solution for Pressing or handling back button in Fragment.

The way I solved my issue I am sure it will helps you too:

1.If you don't have any Edit Text-box in your fragment you can use below code

Here MainHomeFragment is main Fragment (When I press back button from second fragment it will take me too MainHomeFragment)

    @Override
    public void onResume() {

    super.onResume();

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){

                MainHomeFragment mainHomeFragment = new SupplierHomeFragment();
                android.support.v4.app.FragmentTransaction fragmentTransaction =
                        getActivity().getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.fragment_container, mainHomeFragment);
                fragmentTransaction.commit();

                return true;    
            }    
            return false;
        }
    }); }

2.If you have another fragment named as Somefragment and it has Edit text-box then you can do it by this way.

private EditText editText;

Then In,

onCreateView():    
editText = (EditText) view.findViewById(R.id.editText);

Then Override OnResume,

@Override
public void onResume() {
    super.onResume();

    editText.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                editTextOFS.clearFocus();
                getView().requestFocus();
            }
            return false;
        }
    });

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){

                MainHomeFragment mainHomeFragment = new SupplierHomeFragment();
                android.support.v4.app.FragmentTransaction fragmentTransaction =
                        getActivity().getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.fragment_container, mainHomeFragment);
                fragmentTransaction.commit();

                return true;

            }

            return false;
        }
    });

}

That's all folks (amitamie.com) :-) ;-)

Change div width live with jQuery

Got better solution:

$('#element').resizable({
    stop: function( event, ui ) {
        $('#element').height(ui.originalSize.height);
    }
});

C++ class forward declaration

In order for new T to compile, T must be a complete type. In your case, when you say new tile_tree_apple inside the definition of tile_tree::tick, tile_tree_apple is incomplete (it has been forward declared, but its definition is later in your file). Try moving the inline definitions of your functions to a separate source file, or at least move them after the class definitions.

Something like:

class A
{
    void f1();
    void f2();
};
class B
{
   void f3();
   void f4();
};

inline void A::f1() {...}
inline void A::f2() {...}
inline void B::f3() {...}
inline void B::f4() {...}

When you write your code this way, all references to A and B in these methods are guaranteed to refer to complete types, since there are no more forward references!

php foreach with multidimensional array

Wouldn't a normal foreach basically yield the same result as a mysql_fetch_assoc in your case?

when using foreach on that array, you would get an array containing those three keys: 'id','firstname' and 'lastname'.

That should be the same as mysql_fetch_assoc would give (in a loop) for each row.

deny directory listing with htaccess

Options -Indexes perfectly works for me ,

here is .htaccess file :

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes <---- This Works for Me :)
    </IfModule>


   ....etc stuff

</IfModule>

Before : enter image description here

After :

enter image description here

An implementation of the fast Fourier transform (FFT) in C#

http://www.exocortex.org/dsp/ is an open-source C# mathematics library with FFT algorithms.

jQuery load more data on scroll

Have you heard about the jQuery Waypoint plugin.

Below is the simple way of calling a waypoints plugin and having the page load more Content once you reaches the bottom on scroll :

$(document).ready(function() {
    var $loading = $("<div class='loading'><p>Loading more items&hellip;</p></div>"),
    $footer = $('footer'),
    opts = {
        offset: '100%'
    };

    $footer.waypoint(function(event, direction) {
        $footer.waypoint('remove');
        $('body').append($loading);
        $.get($('.more a').attr('href'), function(data) {
            var $data = $(data);
            $('#container').append($data.find('.article'));
            $loading.detach();
            $('.more').replaceWith($data.find('.more'));
            $footer.waypoint(opts);
        });
    }, opts);
});

java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

This is because your servlet is trying to access a request object which is no more exist.. A servlet's forward or include statement does not stop execution of method block. It continues to the end of method block or first return statement just like any other java method.

The best way to resolve this problem just set the page (where you suppose to forward the request) dynamically according your logic. That is:

protected void doPost(request , response){
String returnPage="default.jsp";
if(condition1){
 returnPage="page1.jsp";
}
if(condition2){
   returnPage="page2.jsp";
}
request.getRequestDispatcher(returnPage).forward(request,response); //at last line
}

and do the forward only once at last line...

you can also fix this problem using return statement after each forward() or put each forward() in if...else block

In SQL how to compare date values?

You could add the time component

WHERE mydate<='2008-11-25 23:59:59'

but that might fail on DST switchover dates if mydate is '2008-11-25 24:59:59', so it's probably safest to grab everything before the next date:

WHERE mydate < '2008-11-26 00:00:00'

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

LIKE operator in LINQ

You can also use the EF function tested in .net5

public async Task<IEnumerable<District>> SearchDistrict(string query, int stateId)
        {
            return await _dbContext
                .Districts
                .Include(s => s.State)
                .Where(s => s.StateId == stateId && EF.Functions.Like(s.Name, "$%{query}%"))
                .AsNoTracking()
                .ToListAsync();
        }

How to include route handlers in multiple files in Express?

One tweak to all of these answers:

var routes = fs.readdirSync('routes')
      .filter(function(v){
         return (/.js$/).test(v);
      });

Just use a regex to filter via testing each file in the array. It is not recursive, but it will filter out folders that don't end in .js

How to insert values in table with foreign key using MySQL?

Case 1

INSERT INTO tab_student (name_student, id_teacher_fk)
    VALUES ('dan red', 
           (SELECT id_teacher FROM tab_teacher WHERE name_teacher ='jason bourne')

it is advisable to store your values in lowercase to make retrieval easier and less error prone

Case 2

mysql docs

INSERT INTO tab_teacher (name_teacher) 
    VALUES ('tom stills')
INSERT INTO tab_student (name_student, id_teacher_fk)
    VALUES ('rich man', LAST_INSERT_ID())

Replace only some groups with Regex

I also had need for this and I created the following extension method for it:

public static class RegexExtensions
{
    public static string ReplaceGroup(
        this Regex regex, string input, string groupName, string replacement)
    {
        return regex.Replace(
            input,
            m =>
            {
                var group = m.Groups[groupName];
                var sb = new StringBuilder();
                var previousCaptureEnd = 0;
                foreach (var capture in group.Captures.Cast<Capture>())
                {
                    var currentCaptureEnd =
                        capture.Index + capture.Length - m.Index;
                    var currentCaptureLength =
                        capture.Index - m.Index - previousCaptureEnd;
                    sb.Append(
                        m.Value.Substring(
                            previousCaptureEnd, currentCaptureLength));
                    sb.Append(replacement);
                    previousCaptureEnd = currentCaptureEnd;
                }
                sb.Append(m.Value.Substring(previousCaptureEnd));

                return sb.ToString();
            });
    }
}

Usage:

var input = @"[assembly: AssemblyFileVersion(""2.0.3.0"")][assembly: AssemblyFileVersion(""2.0.3.0"")]";
var regex = new Regex(@"AssemblyFileVersion\(""(?<version>(\d+\.?){4})""\)");


var result = regex.ReplaceGroup(input , "version", "1.2.3");

Result:

[assembly: AssemblyFileVersion("1.2.3")][assembly: AssemblyFileVersion("1.2.3")]

In C - check if a char exists in a char array

Assuming your input is a standard null-terminated C string, you want to use strchr:

#include <string.h>

char* foo = "abcdefghijkl";
if (strchr(foo, 'a') != NULL)
{
  // do stuff
}

If on the other hand your array is not null-terminated (i.e. just raw data), you'll need to use memchr and provide a size:

#include <string.h>

char foo[] = { 'a', 'b', 'c', 'd', 'e' }; // note last element isn't '\0'
if (memchr(foo, 'a', sizeof(foo)))
{
  // do stuff
}

Use CSS3 transitions with gradient backgrounds

For what it's worth, here's a Sass mixin:

Usage:

@include gradientAnimation(red, blue, .6s);

Mixin:

@mixin gradientAnimation( $start, $end, $transTime ){
    background-size: 100%;
    background-image: linear-gradient($start, $end);
    position: relative;
    z-index: 100;
    &:before {
        background-image: linear-gradient($end, $start);
        content: "";
        display: block;
        height: 100%;
        position: absolute;
        top: 0; left: 0;
        opacity: 0;
        width: 100%;
        z-index: -100;
        transition: opacity $transTime;
    }
    &:hover {
        &:before {
            opacity: 1;
        }
    }
}

Taken from this awesome post on Medium from Dave Lunny: https://medium.com/@dave_lunny/animating-css-gradients-using-only-css-d2fd7671e759

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

I found a solution to this. It's bloody witchcraft, but it works.

When you install the client, open Control Panel > Network Connections.

You'll see a disabled network connection that was added by the TAP installer (Local Area Connection 3 or some such).

Right Click it, click Enable.

The device will not reset itself to enabled, but that's ok; try connecting w/ the client again. It'll work.

How do you print in Sublime Text 2

  1. Install the Package Control first and restart your editor. See: How to install plugins to Sublime Text 2 editor?
  2. Install Highlight plugin.
    1. Open the pallete, press ctrl+shift+p (Win, Linux) or cmd+shift+p (OS X).
    2. Type and confirm: Install Package
    3. Type and confirm: Highlight or Print

Also see related printing forum topic: Printing from sublime

Setting and getting localStorage with jQuery

Use setItem and getItem if you want to write simple strings to localStorage. Also you should be using text() if it's the text you're after as you say, else you will get the full HTML as a string.

Sample using .text()

// get the text
var text = $('#test').text();

// set the item in localStorage
localStorage.setItem('test', text);

// alert the value to check if we got it
alert(localStorage.getItem('test'));

JSFiddle: https://jsfiddle.net/f3zLa3zc/


Storing the HTML itself

// get html
var html = $('#test')[0].outerHTML;

// set localstorage
localStorage.setItem('htmltest', html);

// test if it works
alert(localStorage.getItem('htmltest'));

JSFiddle:
https://jsfiddle.net/psfL82q3/1/


Update on user comment

A user want to update the localStorage when the div's content changes. Since it's unclear how the div contents changes (ajax, other method?) contenteditable and blur() is used to change the contents of the div and overwrite the old localStorage entry.

// get the text
var text = $('#test').text();

// set the item in localStorage
localStorage.setItem('test', text);

// bind text to 'blur' event for div
$('#test').on('blur', function() {

    // check the new text
    var newText = $(this).text();

    // overwrite the old text
    localStorage.setItem('test', newText);

    // test if it works
    alert(localStorage.getItem('test'));

});

If we were using ajax we would instead trigger the function it via the function responsible for updating the contents.

JSFiddle:
https://jsfiddle.net/g1b8m1fc/

Streaming video from Android camera to server

Check Yasea library

Yasea is an Android streaming client. It encodes YUV and PCM data from camera and microphone to H.264/AAC, encapsulates in FLV and transmits over RTMP.

Feature:

  1. Android mini API 16.
  2. H.264/AAC hard encoding.
  3. H.264 soft encoding.
  4. RTMP streaming with state callback handler.
  5. Portrait and landscape dynamic orientation.
  6. Front and back cameras hot switch.
  7. Recording to MP4 while streaming.

Jquery: how to trigger click event on pressing enter key

Are you trying to mimic a click on a button when the enter key is pressed? If so you may need to use the trigger syntax.

Try changing

$('input[name = butAssignProd]').click();

to

$('input[name = butAssignProd]').trigger("click");

If this isn't the problem then try taking a second look at your key capture syntax by looking at the solutions in this post: jQuery Event Keypress: Which key was pressed?

What is the purpose of .PHONY in a Makefile?

Let's assume you have install target, which is a very common in makefiles. If you do not use .PHONY, and a file named install exists in the same directory as the Makefile, then make install will do nothing. This is because Make interprets the rule to mean "execute such-and-such recipe to create the file named install". Since the file is already there, and its dependencies didn't change, nothing will be done.

However if you make the install target PHONY, it will tell the make tool that the target is fictional, and that make should not expect it to create the actual file. Hence it will not check whether the install file exists, meaning: a) its behavior will not be altered if the file does exist and b) extra stat() will not be called.

Generally all targets in your Makefile which do not produce an output file with the same name as the target name should be PHONY. This typically includes all, install, clean, distclean, and so on.

\r\n, \r and \n what is the difference between them?

All 3 of them represent the end of a line. But...

  • \r (Carriage Return) → moves the cursor to the beginning of the line without advancing to the next line
  • \n (Line Feed) → moves the cursor down to the next line without returning to the beginning of the line — In a *nix environment \n moves to the beginning of the line.
  • \r\n (End Of Line) → a combination of \r and \n

Error You must specify a region when running command aws ecs list-container-instances

Just to add to answers by Mr. Dimitrov and Jason, if you are using a specific profile and you have put your region setting there,then for all the requests you need to add

"--profile" option.

For example:

Lets say you have AWS Playground profile, and the ~/.aws/config has [profile playground] which further has something like,

[profile playground] region=us-east-1

then, use something like below

aws ecs list-container-instances --cluster default --profile playground

"getaddrinfo failed", what does that mean?

Make sure you pass a proxy attribute in your command forexample - pip install --proxy=http://proxyhost:proxyport pixiedust

Use a proxy port which has direct connection (with / without password). Speak with your corporate IT administrator. Quick way is find out network settings used in eclipse which will have direct connection.

You will encouter this issue often if you work behind a corporate firewall. You will have to check your internet explorer - InternetOptions -LAN Connection - Settings

Uncheck - Use automatic configuration script Check - Use a proxy server for your LAN. Ensure you have given the right address and port.

Click Ok Come back to anaconda terminal and you can try install commands

“tag already exists in the remote" error after recreating the git tag

If you want to UPDATE a tag, let's say it 1.0.0

  1. git checkout 1.0.0
  2. make your changes
  3. git ci -am 'modify some content'
  4. git tag -f 1.0.0
  5. delete remote tag on github: git push origin --delete 1.0.0
  6. git push origin 1.0.0

DONE

ADB device list is empty

This helped me at the end:

Quick guide:

  • Download Google USB Driver

  • Connect your device with Android Debugging enabled to your PC

  • Open Device Manager of Windows from System Properties.

  • Your device should appear under Other devices listed as something like Android ADB Interface or 'Android Phone' or similar. Right-click that and click on Update Driver Software...

  • Select Browse my computer for driver software

  • Select Let me pick from a list of device drivers on my computer

  • Double-click Show all devices

  • Press the Have disk button

  • Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf

  • Select Android ADB Interface from the list of device types.

  • Press the Yes button

  • Press the Install button

  • Press the Close button

Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.

What is a serialVersionUID and why should I use it?

I can't pass up this opportunity to plug Josh Bloch's book Effective Java (2nd Edition). Chapter 11 is an indispensible resource on Java serialization.

Per Josh, the automatically-generated UID is generated based on a class name, implemented interfaces, and all public and protected members. Changing any of these in any way will change the serialVersionUID. So you don't need to mess with them only if you are certain that no more than one version of the class will ever be serialized (either across processes or retrieved from storage at a later time).

If you ignore them for now, and find later that you need to change the class in some way but maintain compatibility w/ old version of the class, you can use the JDK tool serialver to generate the serialVersionUID on the old class, and explicitly set that on the new class. (Depending on your changes you may need to also implement custom serialization by adding writeObject and readObject methods - see Serializable javadoc or aforementioned chapter 11.)

How to read Excel cell having Date with Apache POI?

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;


Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
if(cell.getCellTypeEnum() == CellType.NUMERIC||cell.getCellTypeEnum() == CellType.FORMULA)
   {
    

 String cellValue=String.valueOf(cell.getNumericCellValue());
     if(HSSFDateUtil.isCellDateFormatted(cell))
      {
          DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
          Date date = cell.getDateCellValue();
          cellValue = df.format(date);
       }
          System.out.println(cellValue);
    }

IPC performance: Named Pipe vs Socket

As often, numbers says more than feeling, here are some data: Pipe vs Unix Socket Performance (opendmx.net).

This benchmark shows a difference of about 12 to 15% faster speed for pipes.

Byte Array and Int conversion in Java

Instead of allocating space, et al, an approach using ByteBuffer from java.nio....

byte[] arr = { 0x01, 0x00, 0x00, 0x00, 0x48, 0x01};

// say we want to consider indices 1, 2, 3, 4 {0x00, 0x00, 0x00, 0x48};
ByteBuffer bf = ByteBuffer.wrap(arr, 1, 4); // big endian by default
int num = bf.getInt();    // 72

Now, to go the other way.

ByteBuffer newBuf = ByteBuffer.allocate(4);
newBuf.putInt(num);
byte[] bytes = newBuf.array();  // [0, 0, 0, 72] {0x48 = 72}

Function to calculate distance between two coordinates

Adding this for Node.JS users. You can use the haversine-distance module to do this so you won't need to handle the calculations on your own. See the npm page for more information.

To install:

npm install --save haversine-distance

You can use the module as follows:

var haversine = require("haversine-distance");

//First point in your haversine calculation
var point1 = { lat: 6.1754, lng: 106.8272 }

//Second point in your haversine calculation
var point2 = { lat: 6.1352, lng: 106.8133 }

var haversine_m = haversine(point1, point2); //Results in meters (default)
var haversine_km = haversine_m /1000; //Results in kilometers

console.log("distance (in meters): " + haversine_m + "m");
console.log("distance (in kilometers): " + haversine_km + "km");

How can I pass a class member function as a callback?

That doesn't work because a member function pointer cannot be handled like a normal function pointer, because it expects a "this" object argument.

Instead you can pass a static member function as follows, which are like normal non-member functions in this regard:

m_cRedundencyManager->Init(&CLoggersInfra::Callback, this);

The function can be defined as follows

static void Callback(int other_arg, void * this_pointer) {
    CLoggersInfra * self = static_cast<CLoggersInfra*>(this_pointer);
    self->RedundencyManagerCallBack(other_arg);
}

How to clone all remote branches in Git?

Why you only see "master"

git clone downloads all remote branches but still considers them "remote", even though the files are located in your new repository. There's one exception to this, which is that the cloning process creates a local branch called "master" from the remote branch called "master". By default, git branch only shows local branches, which is why you only see "master".

git branch -a shows all branches, including remote branches.


How to get local branches

If you actually want to work on a branch, you'll probably want a "local" version of it. To simply create local branches from remote branches (without checking them out and thereby changing the contents of your working directory), you can do that like this:

git branch branchone origin/branchone
git branch branchtwo origin/branchtwo
git branch branchthree origin/branchthree

In this example, branchone is the name of a local branch you're creating based on origin/branchone; if you instead want to create local branches with different names, you can do this:

git branch localbranchname origin/branchone

Once you've created a local branch, you can see it with git branch (remember, you don't need -a to see local branches).

How to change the minSdkVersion of a project?

This is what worked for me:

In the build.gradle file, setting the minSdkVersion under defaultConfig:

enter image description here

Good Luck...

Create autoincrement key in Java DB using NetBeans IDE

If you want to use Netbeans to define tables read this https://codezone4.wordpress.com/2012/06/19/java-database-application-using-javadb-part-1/ Simply define column as integer and create database, then grab structure to a temporary file, then delete table. Right clik to tables folder and select recreate table, select saved file and edit script for auto increment.

ES6 Map in Typescript

EDIT (Jun 5 2019): While the idea that "TypeScript supports Map natively" is still true, since version 2.1 TypeScript supports something called Record.

type MyMapLikeType = Record<string, IPerson>;
const peopleA: MyMapLikeType = {
    "a": { name: "joe" },
    "b": { name: "bart" },
};

Unfortunately the first generic parameter (key type) is still not fully respected: even with a string type, something like peopleA[0] (a number) is still valid.


EDIT (Apr 25 2016): The answer below is old and should not be considered the best answer. TypeScript does support Maps "natively" now, so it simply allows ES6 Maps to be used when the output is ES6. For ES5, it does not provide polyfills; you need to embed them yourself.

For more information, refer to mohamed hegazy's answer below for a more modern answer, or even this reddit comment for a short version.


As of 1.5.0 beta, TypeScript does not yet support Maps. It is not yet part of the roadmap, either.

The current best solution is an object with typed key and value (sometimes called a hashmap). For an object with keys of type string, and values of type number:

var arr : { [key:string]:number; } = {};

Some caveats, however:

  1. keys can only be of type string or number
  2. It actually doesn't matter what you use as the key type, since numbers/strings are still accepted interchangeably (only the value is enforced).

With the above example:

// OK:
arr["name"] = 1; // String key is fine
arr[0] = 0; // Number key is fine too

// Not OK:
arr[{ a: "a" }] = 2; // Invalid key
arr[3] = "name"; // Invalid value

How do I escape a reserved word in Oracle?

Oracle does use double-quotes, but you most likely need to place the object name in upper case, e.g. "TABLE". By default, if you create an object without double quotes, e.g.

CREATE TABLE table AS ...

Oracle would create the object as upper case. However, the referencing is not case sensitive unless you use double-quotes!

Python Tkinter clearing a frame

https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/universal.html

w.winfo_children()
Returns a list of all w's children, in their stacking order from lowest (bottom) to highest (top).

for widget in frame.winfo_children():
    widget.destroy()

Will destroy all the widget in your frame. No need for a second frame.

Android - Set text to TextView

In xml use this:

<TextView 
       android:id="@+id/textView"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"/>

In Activity define the view:

Textview textView=(TextView)findViewById(R.id.textView);
textView.setText(getResources().getString(R.string.txt_hello));

In string file:

<string name="txt_hello">Hello</string>

Output: Hello

Understanding ASP.NET Eval() and Bind()

The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval() and Bind(), taking advantage of the strongly-typed bindings.

*Note: this will only work if you're not using a SqlDataSource or an anonymous object. It requires a Strongly-typed object (from an EF model or any other class).

This code snippet shows how Eval and Bind would be used for a ListView control (InsertItem needs Bind, as explained by Darin Dimitrov above, and ItemTemplate is read-only (hence they're labels), so just needs an Eval):

<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
    <InsertItemTemplate>
        <li>
            Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />         
            Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />        
            <asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />        
        </li>
    </InsertItemTemplate>
    <ItemTemplate>
        <li>
            Title: <asp:Label ID="Title" runat="server" Text='<%#  Eval("Title") %>' /><br />
            Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />        
            <asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
        </li>
      </ItemTemplate>

From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType, which points to the type of object you're assigning to its data source.

<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>

Picture is the strongly type object (from EF model). We then replace:

Bind(property) -> BindItem.property
Eval(property) -> Item.property

So this:

<%# Bind("Title") %>      
<%# Bind("Description") %>         
<%#  Eval("Title") %> 
<%# Eval("Description") %>

Would become this:

<%# BindItem.Title %>         
<%# BindItem.Description %>
<%# Item.Title %>
<%# Item.Description %>

Advantages over Eval & Bind:

  • IntelliSense can find the correct property of the object your're working withenter image description here
  • If property is renamed/deleted, you will get an error before page is viewed in browser
  • External tools (requires full versions of VS) will correctly rename item in markup when you rename a property on your object

Source: from this excellent book

Java project in Eclipse: The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files

I had the similar problem. It was a maven project with the following snippet of pom.xml.

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.0</version>
            <configuration>
                <release>9</release>
            </configuration>
        </plugin>
        </plugins>
    </build>

I had to change the following.

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.0</version>
            <configuration>
                <release>11</release>
            </configuration>
        </plugin>
        </plugins>
    </build>

If you have already installed JDK 11 and working with java 9 or java 10 as maven compiler, eclipse can not detect. Hence change the release to 11 or the actual installed version of JDK.

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

At this point in your code the view controller's view has only been created but not added to any view hierarchy. If you want to present from that view controller as soon as possible you should do it in viewDidAppear to be safest.

Get 2 Digit Number For The Month

Function

FORMAT(date,'MM') 

will do the job with two digit.

Check table exist or not before create it in Oracle

-- checks for table in specfic schema:

declare n number(10);

begin
    Select count(*) into n  from SYS.All_All_Tables where owner = 'MYSCHEMA' and TABLE_NAME =  'EMPLOYEE';

   if (n = 0) then 
     execute immediate 
     'create table MYSCHEMA.EMPLOYEE ( ID NUMBER(3), NAME VARCHAR2(30) NOT NULL)';      
   end if;
end;

How to remove/ignore :hover css style on touch devices

According to Jason´s answer we can address only devices that doesn't support hover with pure css media queries. We can also address only devices that support hover, like moogal´s answer in a similar question, with @media not all and (hover: none). It looks weird but it works.

I made a Sass mixin out of this for easier use:

@mixin hover-supported {
    @media not all and (hover: none) {
        &:hover {
            @content;
        }
    }
}

Update 2019-05-15: I recommend this article from Medium that goes through all different devices that we can target with CSS. Basically it's a mix of these media rules, combine them for specific targets:

@media (hover: hover) {
    /* Device that can hover (desktops) */
}
@media (hover: none) {
    /* Device that can not hover with ease */
}
@media (pointer: coarse) {
    /* Device with limited pointing accuracy (touch) */
}
@media (pointer: fine) {
    /* Device with accurate pointing (desktop, stylus-based) */
}
@media (pointer: none) {
    /* Device with no pointing */
}

Example for specific targets:

@media (hover: none) and (pointer: coarse) {
    /* Smartphones and touchscreens */
}

@media (hover: hover) and (pointer: fine) {
    /* Desktops with mouse */
}

I love mixins, this is how I use my hover mixin to only target devices that supports it:

@mixin on-hover {
    @media (hover: hover) and (pointer: fine) {
        &:hover {
            @content;
        }
    }
}

button {
    @include on-hover {
        color: blue;
    }
}

Which tool to build a simple web front-end to my database

I think PHP is a good solution. It's simple to set up, free and there is plenty of documentation on how to create a database management app. Ruby on Rails is faster to code but a bit more difficult to set up.

How to sort an array based on the length of each element?

You can use Array.sort method to sort the array. A sorting function that considers the length of string as the sorting criteria can be used as follows:

arr.sort(function(a, b){
  // ASC  -> a.length - b.length
  // DESC -> b.length - a.length
  return b.length - a.length;
});

Note: sorting ["a", "b", "c"] by length of string is not guaranteed to return ["a", "b", "c"]. According to the specs:

The sort is not necessarily stable (that is, elements that compare equal do not necessarily remain in their original order).

If the objective is to sort by length then by dictionary order you must specify additional criteria:

["c", "a", "b"].sort(function(a, b) {
  return a.length - b.length || // sort by length, if equal then
         a.localeCompare(b);    // sort by dictionary order
});

Check the current number of connections to MongoDb

Sorry because this is an old post and currently there is more options than before.

db.getSiblingDB("admin").aggregate( [
   { $currentOp: { allUsers: true, idleConnections: true, idleSessions: true } }
  ,{$project:{
            "_id":0
           ,client:{$arrayElemAt:[ {$split:["$client",":"]}, 0 ] }
           ,curr_active:{$cond:[{$eq:["$active",true]},1,0]}
           ,curr_inactive:{$cond:[{$eq:["$active",false]},1,0]}
           }
   }
  ,{$match:{client:{$ne: null}}}
  ,{$group:{_id:"$client",curr_active:{$sum:"$curr_active"},curr_inactive:{$sum:"$curr_inactive"},total:{$sum:1}}}
  ,{$sort:{total:-1}}
] )

Output example:

{ "_id" : "xxx.xxx.xxx.78", "curr_active" : 0, "curr_inactive" : 1428, "total" : 1428 }
{ "_id" : "xxx.xxx.xxx.76", "curr_active" : 0, "curr_inactive" : 1428, "total" : 1428 }
{ "_id" : "xxx.xxx.xxx.73", "curr_active" : 0, "curr_inactive" : 1428, "total" : 1428 }
{ "_id" : "xxx.xxx.xxx.77", "curr_active" : 0, "curr_inactive" : 1428, "total" : 1428 }
{ "_id" : "xxx.xxx.xxx.74", "curr_active" : 0, "curr_inactive" : 1428, "total" : 1428 }
{ "_id" : "xxx.xxx.xxx.75", "curr_active" : 0, "curr_inactive" : 1428, "total" : 1428 }
{ "_id" : "xxx.xxx.xxx.58", "curr_active" : 0, "curr_inactive" : 510, "total" : 510 }
{ "_id" : "xxx.xxx.xxx.57", "curr_active" : 0, "curr_inactive" : 459, "total" : 459 }
{ "_id" : "xxx.xxx.xxx.55", "curr_active" : 0, "curr_inactive" : 459, "total" : 459 }
{ "_id" : "xxx.xxx.xxx.56", "curr_active" : 0, "curr_inactive" : 408, "total" : 408 }
{ "_id" : "xxx.xxx.xxx.47", "curr_active" : 1, "curr_inactive" : 11, "total" : 12 }
{ "_id" : "xxx.xxx.xxx.48", "curr_active" : 1, "curr_inactive" : 7, "total" : 8 }
{ "_id" : "xxx.xxx.xxx.51", "curr_active" : 0, "curr_inactive" : 8, "total" : 8 }
{ "_id" : "xxx.xxx.xxx.46", "curr_active" : 0, "curr_inactive" : 8, "total" : 8 }
{ "_id" : "xxx.xxx.xxx.52", "curr_active" : 0, "curr_inactive" : 6, "total" : 6 }
{ "_id" : "127.0.0.1", "curr_active" : 1, "curr_inactive" : 0, "total" : 1 }
{ "_id" : "xxx.xxx.xxx.3", "curr_active" : 0, "curr_inactive" : 1, "total" : 1 }

What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?

If you are looking for high performance matrix/linear algebra/optimization on Intel processors, I'd look at Intel's MKL library.

MKL is carefully optimized for fast run-time performance - much of it based on the very mature BLAS/LAPACK fortran standards. And its performance scales with the number of cores available. Hands-free scalability with available cores is the future of computing and I wouldn't use any math library for a new project doesn't support multi-core processors.

Very briefly, it includes:

  1. Basic vector-vector, vector-matrix, and matrix-matrix operations
  2. Matrix factorization (LU decomp, hermitian,sparse)
  3. Least squares fitting and eigenvalue problems
  4. Sparse linear system solvers
  5. Non-linear least squares solver (trust regions)
  6. Plus signal processing routines such as FFT and convolution
  7. Very fast random number generators (mersenne twist)
  8. Much more.... see: link text

A downside is that the MKL API can be quite complex depending on the routines that you need. You could also take a look at their IPP (Integrated Performance Primitives) library which is geared toward high performance image processing operations, but is nevertheless quite broad.

Paul

CenterSpace Software ,.NET Math libraries, centerspace.net

Install pip in docker

While T. Arboreus's answer might fix the issues with resolving 'archive.ubuntu.com', I think the last error you're getting says that it doesn't know about the packages php5-mcrypt and python-pip. Nevertheless, the reduced Dockerfile of you with just these two packages worked for me (using Debian 8.4 and Docker 1.11.0), but I'm not quite sure if that could be the case because my host system is different than yours.

FROM ubuntu:14.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    php5-mcrypt \
    python-pip

However, according to this answer you should think about installing the python3-pip package instead of the python-pip package when using Python 3.x.

Furthermore, to make the php5-mcrypt package installation working, you might want to add the universe repository like it's shown right here. I had trouble with the add-apt-repository command missing in the Ubuntu Docker image so I installed the package software-properties-common at first to make the command available.

Splitting up the statements and putting apt-get update and apt-get install into one RUN command is also recommended here.

Oh and by the way, you actually don't need the -y flag at apt-get update because there is nothing that has to be confirmed automatically.

Finally:

FROM ubuntu:14.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    software-properties-common
RUN add-apt-repository universe
RUN apt-get update && apt-get install -y \
    apache2 \
    curl \
    git \
    libapache2-mod-php5 \
    php5 \
    php5-mcrypt \
    php5-mysql \
    python3.4 \
    python3-pip

Remark: The used versions (e.g. of Ubuntu) might be outdated in the future.

Create a table without a header in Markdown

The following works well for me in GitHub. The first row is no longer bolded as it is not a header:

<table align="center">
    <tr>
        <td align="center"><img src="docs/img1.png?raw=true" alt="some text"></td>
        <td align="center">Some other text</td>
        <td align="center">More text</td>
    </tr>
    <tr>
        <td align="center"><img src="docs/img2.png?raw=true" alt="some text"></td>
        <td align="center">Some other text 2</td>
        <td align="center">More text 2</td>
    </tr>
</table>

Check a sample HTML table without a header here.

findAll() in yii

Try:

$id =101;
$comments = EmailArchive::model()->findAll(
array("condition"=>"email_id =  $id","order"=>"id"));

OR

$id =101;
$criteria = new CDbCriteria();
$criteria->addCondition("email_id=:email_id");
$criteria->params = array(':email_id' => $id);
$comments = EmailArchive::model()->findAll($criteria);

OR

$Criteria = new CDbCriteria();
$Criteria->condition = "email_id = $id";
$Products = Product::model()->findAll($Criteria);

How to manage a redirect request after a jQuery Ajax call

in the servlet you should put response.setStatus(response.SC_MOVED_PERMANENTLY); to send the '301' xmlHttp status you need for a redirection...

and in the $.ajax function you should not use the .toString() function..., just

if (xmlHttp.status == 301) { top.location.href = 'xxxx.jsp'; }

the problem is it is not very flexible, you can't decide where you want to redirect..

redirecting through the servlets should be the best way. but i still can not find the right way to do it.

How to call a .NET Webservice from Android using KSOAP2?

If more than one result is expected, then the getResponse() method will return a Vector containing the various responses.

In which case the offending code becomes:

Object result = envelope.getResponse();

// treat result as a vector
String resultText = null;
if (result instanceof Vector)
{
    SoapPrimitive element0 = (SoapPrimitive)((Vector) result).elementAt(0);
    resultText = element0.toString();
}

tv.setText(resultText);

Answer based on the ksoap2-android (mosabua fork)

How to delete all files older than 3 days when "Argument list too long"?

Another solution for the original question, esp. useful if you want to remove only SOME of the older files in a folder, would be smth like this:

find . -name "*.sess" -mtime +100 

and so on.. Quotes block shell wildcards, thus allowing you to "find" millions of files :)

Java ArrayList of Doubles

You can use Arrays.asList to get some list (not necessarily ArrayList) and then use addAll() to add it to an ArrayList:

new ArrayList<Double>().addAll(Arrays.asList(1.38L, 2.56L, 4.3L));

If you're using Java6 (or higher) you can also use the ArrayList constructor that takes another list:

new ArrayList<Double>(Arrays.asList(1.38L, 2.56L, 4.3L));

How to count lines of Java code using IntelliJ IDEA?

The Statistic plugin worked for me.

To install it from Intellij:

File - Settings - Plugins - Browse repositories... Find it on the list and double-click on it.

Access the 'statistic' toolbar via tabs in bottom left of project screen capture of statistic toolbar, bottom left

OLDER VERSIONS: Open statistics window from:

View -> Tool Windows -> Statistic

Link a photo with the cell in excel

Hold down the Alt key and drag the pictures to snap to the upper left corner of the cell.

Format the picture and in the Properties tab select "Move but don't size with cells"

Now you can sort the data table by any column and the pictures will stay with the respective data.

This post at SuperUser has a bit more background and screenshots: https://superuser.com/questions/712622/put-an-equation-object-in-an-excel-cell/712627#712627

Maven: How to change path to target directory from command line?

You should use profiles.

<profiles>
    <profile>
        <id>otherOutputDir</id>
        <build>
            <directory>yourDirectory</directory>
        </build>
    </profile>
</profiles>

And start maven with your profile

mvn compile -PotherOutputDir

If you really want to define your directory from the command line you could do something like this (NOT recommended at all) :

<properties>
    <buildDirectory>${project.basedir}/target</buildDirectory>
</properties>

<build>
    <directory>${buildDirectory}</directory>
</build>

And compile like this :

mvn compile -DbuildDirectory=test

That's because you can't change the target directory by using -Dproject.build.directory

Is Tomcat running?

Why grep ps, when the pid has been written to the $CATALINA_PID file?

I have a cron'd checker script which sends out an email when tomcat is down:

kill -0 `cat $CATALINA_PID` > /dev/null 2>&1
if [ $? -gt 0 ]
then
    echo "Check tomcat" | mailx -s "Tomcat not running" [email protected]
fi

I guess you could also use wget to check the health of your tomcat. If you have a diagnostics page with user load etc, you could fetch it periodically and parse it to determine if anything is going wrong.

How can I define an array of objects?

Array<T>

person: Array<{
  name: string;
  age: number;
}>

pandas three-way joining multiple dataframes on columns

This can also be done as follows for a list of dataframes df_list:

df = df_list[0]
for df_ in df_list[1:]:
    df = df.merge(df_, on='join_col_name')

or if the dataframes are in a generator object (e.g. to reduce memory consumption):

df = next(df_list)
for df_ in df_list:
    df = df.merge(df_, on='join_col_name')

How to get HTTP response code for a URL in Java?

This is the full static method, which you can adapt to set waiting time and error code when IOException happens:

  public static int getResponseCode(String address) {
    return getResponseCode(address, 404);
  }

  public static int getResponseCode(String address, int defaultValue) {
    try {
      //Logger.getLogger(WebOperations.class.getName()).info("Fetching response code at " + address);
      URL url = new URL(address);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setConnectTimeout(1000 * 5); //wait 5 seconds the most
      connection.setReadTimeout(1000 * 5);
      connection.setRequestProperty("User-Agent", "Your Robot Name");
      int responseCode = connection.getResponseCode();
      connection.disconnect();
      return responseCode;
    } catch (IOException ex) {
      Logger.getLogger(WebOperations.class.getName()).log(Level.INFO, "Exception at {0} {1}", new Object[]{address, ex.toString()});
      return defaultValue;
    }
  }

How to convert datatype:object to float64 in python?

You can convert most of the columns by just calling convert_objects:

In [36]:

df = df.convert_objects(convert_numeric=True)
df.dtypes
Out[36]:
Date         object
WD            int64
Manpower    float64
2nd          object
CTR          object
2ndU        float64
T1            int64
T2          int64
T3           int64
T4        float64
dtype: object

For column '2nd' and 'CTR' we can call the vectorised str methods to replace the thousands separator and remove the '%' sign and then astype to convert:

In [39]:

df['2nd'] = df['2nd'].str.replace(',','').astype(int)
df['CTR'] = df['CTR'].str.replace('%','').astype(np.float64)
df.dtypes
Out[39]:
Date         object
WD            int64
Manpower    float64
2nd           int32
CTR         float64
2ndU        float64
T1            int64
T2            int64
T3            int64
T4           object
dtype: object
In [40]:

df.head()
Out[40]:
        Date  WD  Manpower   2nd   CTR  2ndU   T1    T2   T3     T4
0   2013/4/6   6       NaN  2645  5.27  0.29  407   533  454    368
1   2013/4/7   7       NaN  2118  5.89  0.31  257   659  583    369
2  2013/4/13   6       NaN  2470  5.38  0.29  354   531  473    383
3  2013/4/14   7       NaN  2033  6.77  0.37  396   748  681    458
4  2013/4/20   6       NaN  2690  5.38  0.29  361   528  541    381

Or you can do the string handling operations above without the call to astype and then call convert_objects to convert everything in one go.

UPDATE

Since version 0.17.0 convert_objects is deprecated and there isn't a top-level function to do this so you need to do:

df.apply(lambda col:pd.to_numeric(col, errors='coerce'))

See the docs and this related question: pandas: to_numeric for multiple columns

A top-like utility for monitoring CUDA activity on a GPU

This may not be elegant, but you can try

while true; do sleep 2; nvidia-smi; done

I also tried the method by @Edric, which works, but I prefer the original layout of nvidia-smi.

How can I use Timer (formerly NSTimer) in Swift?

In Swift 3 something like this with @objc:

func startTimerForResendingCode() {
    let timerIntervalForResendingCode = TimeInterval(60)
    Timer.scheduledTimer(timeInterval: timerIntervalForResendingCode,
                         target: self,
                         selector: #selector(timerEndedUp),
                         userInfo: nil,
                         repeats: false)
}




@objc func timerEndedUp() {
    output?.timerHasFinishedAndCodeMayBeResended()
}

auto refresh for every 5 mins

Page should be refresh auto using meta tag

<meta http-equiv="Refresh" content="60"> 

content value in seconds.after one minute page should be refresh

CSS3 Fade Effect

You can't transition between two background images, as there's no way for the browser to know what you want to interpolate. As you've discovered, you can transition the background position. If you want the image to fade in on mouse over, I think the best way to do it with CSS transitions is to put the image on a containing element and then animate the background colour to transparent on the link itself:

span {
    background: url(button.png) no-repeat 0 0;
}
a {
    width: 32px;
    height: 32px;
    text-align: left;
    background: rgb(255,255,255);

    -webkit-transition: background 300ms ease-in 200ms; /* property duration timing-function delay */
    -moz-transition: background 300ms ease-in 200ms;
    -o-transition: background 300ms ease-in 200ms;
    transition: background 300ms ease-in 200ms;
    }
a:hover {
    background: rgba(255,255,255,0);
}

Get the current cell in Excel VB

Try this

Dim app As Excel.Application = Nothing
Dim Active_Cell As Excel.Range = Nothing

Try
            app = CType(Marshal.GetActiveObject("Excel.Application"), Excel.Application)
 Active_Cell = app.ActiveCell

Catch ex As Exception
            MsgBox(ex.Message)
            Exit Sub
        End Try

'             .address will return the cell reference :)

Maximum and minimum values in a textbox

Yes it can! You might consider first to set the value of maxlength to 3 and then write an event handler for the keyup-event.

The function can evaluate the user input using regex or parseInt to validate the user input and set it to any desired value, if the input is incorrect.

Multi-key dictionary in c#?

Here's a fleshed out example of a pair class which can be used as the key to a Dictionary.

public class Pair<T1, T2>
{
    public T1 Left { get; private set; }
    public T2 Right { get; private set; }

    public Pair(T1 t1, T2 t2)
    {
        Left = t1;
        Right = t2;
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != typeof(Pair<T1, T2>)) return false;
        return Equals((Pair<T1, T2>)obj);
    }

    public bool Equals(Pair<T1, T2> obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        return Equals(obj.Left, Left) && Equals(obj.Right, Right);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            return (Left.GetHashCode() * 397) ^ Right.GetHashCode();
        }
    }
}

Changing the interval of SetInterval while it's running

You can use a variable and change the variable instead.

````setInterval([the function], [the variable])```

How can I get the last character in a string?

You should look at charAt function and take length of the string.

var b = 'I am a JavaScript hacker.';
console.log(b.charAt(b.length-1));

Can we instantiate an abstract class directly?

No, you can never instantiate an abstract class. That's the purpose of an abstract class. The getProvider method you are referring to returns a specific implementation of the abstract class. This is the abstract factory pattern.

PHP check whether property exists in object or class

If you want to know if a property exists in an instance of a class that you have defined, simply combine property_exists() with isset().

public function hasProperty($property)
{
    return property_exists($this, $property) && isset($this->$property);
}

Disable scrolling in all mobile devices

The following works for me, although I did not test every single device there is to test :-)

$('body, html').css('overflow-y', 'hidden');
$('html, body').animate({
    scrollTop:0
}, 0);

Get string between two strings in a string

A working LINQ solution:

string str = "super example of string key : text I want to keep - end of my string";
string res = new string(str.SkipWhile(c => c != ':')
                           .Skip(1)
                           .TakeWhile(c => c != '-')
                           .ToArray()).Trim();
Console.WriteLine(res); // text I want to keep

How to get File Created Date and Modified Date

Use :

FileInfo fInfo = new FileInfo('FilePath');
var fFirstTime = fInfo.CreationTime;
var fLastTime = fInfo.LastWriteTime;

Conda activate not working?

Functions are not exported by default to be made available in subshells. I'd recommend you do:

source ~/anaconda3/etc/profile.d/conda.sh
conda activate my_env

In the commands above, replace ~/anaconda3/ with the path to your miniconda / anaconda installation.

Xcode iOS 8 Keyboard types not supported

I too had this problem after updating to the latest Xcode Beta. The settings on the simulator are refreshed, so the laptop (external) keyboard was being detected. If you simply press:

 iOS Simulator -> Hardware -> Keyboard -> Connect Hardware Keyboard

then the software keyboard will be displayed once again.

XSL xsl:template match="/"

It's worth noting, since it's confusing for people new to XML, that the root (or document node) of an XML document is not the top-level element. It's the parent of the top-level element. This is confusing because it doesn't seem like the top-level element can have a parent. Isn't it the top level?

But look at this, a well-formed XML document:

<?xml-stylesheet href="my_transform.xsl" type="text/xsl"?>
<!-- Comments and processing instructions are XML nodes too, remember. -->
<TopLevelElement/>

The root of this document has three children: a processing instruction, a comment, and an element.

So, for example, if you wanted to write a transform that got rid of that comment, but left in any comments appearing anywhere else in the document, you'd add this to the identity transform:

<xsl:template match="/comment()"/>

Even simpler (and more commonly useful), here's an XPath pattern that matches the document's top-level element irrespective of its name: /*.

How to execute a query in ms-access in VBA code?

How about something like this...

Dim rs As RecordSet
Set rs = Currentdb.OpenRecordSet("SELECT PictureLocation, ID FROM MyAccessTable;")

Do While Not rs.EOF
   Debug.Print rs("PictureLocation") & " - " & rs("ID")
   rs.MoveNext
Loop

How to find first element of array matching a boolean condition in JavaScript?

Summary:

  • For finding the first element in an array which matches a boolean condition we can use the ES6 find()
  • find() is located on Array.prototype so it can be used on every array.
  • find() takes a callback where a boolean condition is tested. The function returns the value (not the index!)

Example:

_x000D_
_x000D_
const array = [4, 33, 8, 56, 23];

const found = array.find(element => {
  return element > 50;
});

console.log(found);   //  56
_x000D_
_x000D_
_x000D_

Dealing with float precision in Javascript

You could do something like this:

> +(Math.floor(y/x)*x).toFixed(15);
1.2

How to speed up insertion performance in PostgreSQL

In addition to excellent Craig Ringer's post and depesz's blog post, if you would like to speed up your inserts through ODBC (psqlodbc) interface by using prepared-statement inserts inside a transaction, there are a few extra things you need to do to make it work fast:

  1. Set the level-of-rollback-on-errors to "Transaction" by specifying Protocol=-1 in the connection string. By default psqlodbc uses "Statement" level, which creates a SAVEPOINT for each statement rather than an entire transaction, making inserts slower.
  2. Use server-side prepared statements by specifying UseServerSidePrepare=1 in the connection string. Without this option the client sends the entire insert statement along with each row being inserted.
  3. Disable auto-commit on each statement using SQLSetConnectAttr(conn, SQL_ATTR_AUTOCOMMIT, reinterpret_cast<SQLPOINTER>(SQL_AUTOCOMMIT_OFF), 0);
  4. Once all rows have been inserted, commit the transaction using SQLEndTran(SQL_HANDLE_DBC, conn, SQL_COMMIT);. There is no need to explicitly open a transaction.

Unfortunately, psqlodbc "implements" SQLBulkOperations by issuing a series of unprepared insert statements, so that to achieve the fastest insert one needs to code up the above steps manually.

Removing MySQL 5.7 Completely

Run these commands in the terminal:

sudo apt-get remove --purge mysql-server mysql-client mysql-common

sudo apt-get autoremove

sudo apt-get autoclean

Run these commands separately as each command requires confirmation & if run as a block, the command below the one currently running will cancel the confirmation (leading to the command not being run).

Please refer to How do I uninstall Mysql?

Split column at delimiter in data frame

Combining @Ramnath and @Tommy's answers allowed me to find an approach that works in base R for one or more columns.

Basic usage:

> df = data.frame(
+   id=1:3, foo=c('a|b','b|c','c|d'), 
+   bar=c('p|q', 'r|s', 's|t'), stringsAsFactors=F)
> transform(df, test=do.call(rbind, strsplit(foo, '|', fixed=TRUE)), stringsAsFactors=F)
  id foo bar test.1 test.2
1  1 a|b p|q      a      b
2  2 b|c r|s      b      c
3  3 c|d s|t      c      d

Multiple columns:

> transform(df, lapply(list(foo,bar),
+ function(x)do.call(rbind, strsplit(x, '|', fixed=TRUE))), stringsAsFactors=F)
  id foo bar X1 X2 X1.1 X2.1
1  1 a|b p|q  a  b    p    q
2  2 b|c r|s  b  c    r    s
3  3 c|d s|t  c  d    s    t

Better naming of multiple split columns:

> transform(df, lapply({l<-list(foo,bar);names(l)=c('foo','bar');l}, 
+                          function(x)do.call(rbind, strsplit(x, '|', fixed=TRUE))), stringsAsFactors=F)
  id foo bar foo.1 foo.2 bar.1 bar.2
1  1 a|b p|q     a     b     p     q
2  2 b|c r|s     b     c     r     s
3  3 c|d s|t     c     d     s     t

Display curl output in readable JSON format in Unix shell script

python -m json.tool
Curl http://127.0.0.1:5000/people/api.json | python -m json.tool

can also help.

Apply CSS rules to a nested class inside a div

Use Css Selector for this, or learn more about Css Selector just go here https://www.w3schools.com/cssref/css_selectors.asp

#main_text > .title {
  /* Style goes here */
}

#main_text .title {
  /* Style goes here */
}

<img>: Unsafe value used in a resource URL context

Use Safe Pipe to fix it.

  • Create a safe pipe if u haven't any.

    ng g pipe safe

  • add Safe pipe in app.module.ts

    declarations: [SafePipe]

  • declare safe pipe in your ts

Import Dom Sanitizer and Safe Pipe to access url safely

import { Pipe, PipeTransform} from '@angular/core';
import { DomSanitizer } from "@angular/platform-browser";

@Pipe({ name: 'safe' })

export class SafePipe implements PipeTransform {

constructor(private sanitizer: DomSanitizer) { }
transform(url) {
 return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
}
  • Add safe with src url

    <img width="900" height="500" [src]="link | safe"/>

Changing text color of menu item in navigation drawer

Use app:itemIconTint in your NavigationView, ej:

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:itemTextColor="@color/customColor"
    app:itemIconTint="@color/customColor"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_home"
    app:menu="@menu/activity_home_drawer" />

Building and running app via Gradle and Android Studio is slower than via Eclipse

I'm far from being an expert on Gradle but my environment had the following line in .gradle/init.gradle

gradle.projectsLoaded {
    rootProject.allprojects {
        repositories {
            mavenRepo name: 'libs-repo', url: 'http://guest-vm/artifactory/repo'
        }
    }
}

Yet I have no idea why that line was there, but I try changing to

gradle.projectsLoaded {
    rootProject.allprojects {
        repositories {
            mavenCentral()
        }
    }
} 

and now I finally can work without swearing to Android Studio & Gradle buildind scheme.

Achieving white opacity effect in html/css

Try RGBA, e.g.

div { background-color: rgba(255, 255, 255, 0.5); }

As always, this won't work in every single browser ever written.

Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

Make sure that both the below jars are present in the build path:

  1. standard-1.1.2.jar
  2. jstl-api-1.2.jar

Maven Dependencies are:

<dependency>
    <groupId>javax.servlet.jsp.jstl</groupId>
    <artifactId>jstl-api</artifactId>
    <version>$1.2</version>
</dependency>

<dependency>
   <groupId>taglibs</groupId>
   <artifactId>standard</artifactId>
   <version>1.1.2</version>
</dependency

Twitter Bootstrap inline input with dropdown

As of Bootstrap 3.x, there's an example of this in the docs here: http://getbootstrap.com/components/#input-groups-buttons-dropdowns

<div class="input-group">
  <input type="text" class="form-control" aria-label="...">
  <div class="input-group-btn">
    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">Action <span class="caret"></span></button>
    <ul class="dropdown-menu dropdown-menu-right" role="menu">
      <li><a href="#">Action</a></li>
      <li><a href="#">Another action</a></li>
      <li><a href="#">Something else here</a></li>
      <li class="divider"></li>
      <li><a href="#">Separated link</a></li>
    </ul>
  </div><!-- /btn-group -->
</div><!-- /input-group -->

Select DISTINCT individual columns in django?

It's quite simple actually if you're using PostgreSQL, just use distinct(columns) (documentation).

Productorder.objects.all().distinct('category')

Note that this feature has been included in Django since 1.4

How to set editable true/false EditText in Android programmatically?

I did it in a easier way , setEditable and setFocusable false. but you should check this.

How to replicate android:editable="false" in code?

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

The command is date

To customise the output there are a myriad of options available, see date --help for a list.

For example, date '+%A %W %Y %X' gives Tuesday 34 2013 08:04:22 which is the name of the day of the week, the week number, the year and the time.

C# Return Different Types?

You could use external class, set the properties types as you wish, then use it in your function.

public class MultipleOpjects
{
    private List<string> _ObjectOne;
    public List<string> ObjectOne {
        get { return _ObjectOne; }
        set { _ObjectOne = value; }
    }
    private List<object> _ObjectTwo;
    public List<object> ObjectTwo {
        get { return _ObjectTwo; }
        set { _ObjectTwo = value; }
    }
    private object _ObjectThree;
    public object ObjectThree {
        get { return _ObjectThree; }
        set { _ObjectThree = value; }
    }
}
public MultipleOpjects GetAnything()
{
    MultipleOpjects Vrble = new MultipleOpjects();
    Vrble.ObjectOne  = SomeThing1;
    Vrble.ObjectTwo = SomeThing2;
    Vrble.ObjectThree = SomeThing3;

    return Vrble;      
}

HTML table with fixed headers?

This is not an exact solution to the fixed header row, but I have created a rather ingenious method of repeating the header row throughout the long table, yet still keeping the ability to sort.

This neat little option requires the jQuery tablesorter plugin. Here's how it works:

HTML

<table class="tablesorter boxlist" id="pmtable">
    <thead class="fixedheader">
        <tr class="boxheadrow">
            <th width="70px" class="header">Job Number</th>
            <th width="10px" class="header">Pri</th>
            <th width="70px" class="header">CLLI</th>
            <th width="35px" class="header">Market</th>
            <th width="35px" class="header">Job Status</th>
            <th width="65px" class="header">Technology</th>
            <th width="95px;" class="header headerSortDown">MEI</th>
            <th width="95px" class="header">TEO Writer</th>
            <th width="75px" class="header">Quote Due</th>
            <th width="100px" class="header">Engineer</th>
            <th width="75px" class="header">ML Due</th>
            <th width="75px" class="header">ML Complete</th>
            <th width="75px" class="header">SPEC Due</th>
            <th width="75px" class="header">SPEC Complete</th>
            <th width="100px" class="header">Install Supervisor</th>
            <th width="75px" class="header">MasTec OJD</th>
            <th width="75px" class="header">Install Start</th>
            <th width="30px" class="header">Install Hours</th>
            <th width="75px" class="header">Revised CRCD</th>
            <th width="75px" class="header">Latest Ship-To-Site</th>
            <th width="30px" class="header">Total Parts</th>
            <th width="30px" class="header">OEM Rcvd</th>
            <th width="30px" class="header">Minor Rcvd</th>
            <th width="30px" class="header">Total Received</th>
            <th width="30px" class="header">% On Site</th>
            <th width="60px" class="header">Actions</th>
        </tr>
    </thead>
        <tbody class="scrollable">
            <tr data-job_id="3548" data-ml_id="" class="odd">
                <td class="c black">FL-8-RG9UP</td>
                <td data-pri="2" class="priority c yellow">M</td>
                <td class="c">FTLDFLOV</td>
                <td class="c">SFL</td>
                <td class="c">NOI</td>
                <td class="c">TRANSPORT</td>
                <td class="c"></td>
                <td class="c">Chris Byrd</td>
                <td class="c">Apr 13, 2013</td>
                <td class="c">Kris Hall</td>
                <td class="c">May 20, 2013</td>
                <td class="c">May 20, 2013</td>
                <td class="c">Jun 5, 2013</td>
                <td class="c">Jun 7, 2013</td>
                <td class="c">Joseph Fitz</td>
                <td class="c">Jun 10, 2013</td>
                <td class="c">TBD</td>
                <td class="c">123</td>
                <td class="c revised_crcd"><input readonly="true" name="revised_crcd" value="Jul 26, 2013" type="text" size="12" class="smInput r_crcd c hasDatepicker" id="dp1377194058616"></td>
                <td class="c">TBD</td>
                <td class="c">N/A</td>
                <td class="c">N/A</td>
                <td class="c">N/A</td>
                <td class="c">N/A</td>
                <td class="c">N/A</td>
                <td class="actions"><span style="float:left;" class="ui-icon ui-icon-folder-open editJob" title="View this job" s="" details'=""></span></td>
            </tr>
            <tr data-job_id="4264" data-ml_id="2959" class="even">
                <td class="c black">MTS13009SF</td>
                <td data-pri="2" class="priority c yellow">M</td>
                <td class="c">OJUSFLTL</td>
                <td class="c">SFL</td>
                <td class="c">NOI</td>
                <td class="c">TRANSPORT</td>
                <td class="c"></td>
                <td class="c">DeMarcus Stewart</td>
                <td class="c">May 22, 2013</td>
                <td class="c">Ryan Alsobrook</td>
                <td class="c">Jun 19, 2013</td>
                <td class="c">Jun 27, 2013</td>
                <td class="c">Jun 19, 2013</td>
                <td class="c">Jul 4, 2013</td>
                <td class="c">Randy Williams</td>
                <td class="c">Jun 21, 2013</td>
                <td class="c">TBD</td>
                <td class="c">95</td>
                <td class="c revised_crcd"><input readonly="true" name="revised_crcd" value="Aug 9, 2013" type="text" size="12" class="smInput r_crcd c hasDatepicker" id="dp1377194058632"></td><td class="c">TBD</td>
                <td class="c">0</td>
                <td class="c">0.00%</td>
                <td class="c">0.00%</td>
                <td class="c">0.00%</td>
                <td class="c">0.00%</td>
                <td class="actions"><span style="float:left;" class="ui-icon ui-icon-folder-open editJob" title="View this job" s="" details'=""></span><input style="float:left;" type="hidden" name="req_ship" class="reqShip hasDatepicker" id="dp1377194058464"><span style="float:left;" class="ui-icon ui-icon-calendar requestShip" title="Schedule this job for shipping"></span><span class="ui-icon ui-icon-info viewOrderInfo" style="float:left;" title="Show material details for this order"></span></td>
            </tr>
            .
            .
            .
            .
            <tr class="boxheadrow repeated-header">
                <th width="70px" class="header">Job Number</th>
                <th width="10px" class="header">Pri</th>
                <th width="70px" class="header">CLLI</th>
                <th width="35px" class="header">Market</th>
                <th width="35px" class="header">Job Status</th>
                <th width="65px" class="header">Technology</th>
                <th width="95px;" class="header">MEI</th>
                <th width="95px" class="header">TEO Writer</th>
                <th width="75px" class="header">Quote Due</th>
                <th width="100px" class="header">Engineer</th>
                <th width="75px" class="header">ML Due</th>
                <th width="75px" class="header">ML Complete</th>
                <th width="75px" class="header">SPEC Due</th>
                <th width="75px" class="header">SPEC Complete</th>
                <th width="100px" class="header">Install Supervisor</th>
                <th width="75px" class="header">MasTec OJD</th>
                <th width="75px" class="header">Install Start</th>
                <th width="30px" class="header">Install Hours</th>
                <th width="75px" class="header">Revised CRCD</th>
                <th width="75px" class="header">Latest Ship-To-Site</th>
                <th width="30px" class="header">Total Parts</th>
                <th width="30px" class="header">OEM Rcvd</th>
                <th width="30px" class="header">Minor Rcvd</th>
                <th width="30px" class="header">Total Received</th>
                <th width="30px" class="header">% On Site</th>
                <th width="60px" class="header">Actions</th>
            </tr>

Obviously, my table has many more rows than this. 193 to be exact, but you can see where the header row repeats. The repeating header row is set up by this function:

jQuery

// Clone the original header row and add the "repeated-header" class
var tblHeader = $('tr.boxheadrow').clone().addClass('repeated-header');

// Add the cloned header with the new class every 34th row (or as you see fit)
$('tbody tr:odd:nth-of-type(17n)').after(tblHeader);

// On the 'sortStart' routine, remove all the inserted header rows
$('#pmtable').bind('sortStart', function() {
    $('.repeated-header').remove();
    // On the 'sortEnd' routine, add back all the header row lines.
}).bind('sortEnd', function() {
    $('tbody tr:odd:nth-of-type(17n)').after(tblHeader);
});

How to implement a simple scenario the OO way

The Chapter object should have reference to the book it came from so I would suggest something like chapter.getBook().getTitle();

Your database table structure should have a books table and a chapters table with columns like:

books

  • id
  • book specific info
  • etc

chapters

  • id
  • book_id
  • chapter specific info
  • etc

Then to reduce the number of queries use a join table in your search query.

How can I delete derived data in Xcode 8?

It may differ between versions of xcodes. Best approach is to go xcode preference page and from tab "Locations", directly open "Derived Data" directory.

Convert a String In C++ To Upper Case

ALL of these solutions on this page are harder than they need to be.

Do this

RegName = "SomE StRing That you wAnt ConvErTed";
NameLength = RegName.Size();
for (int forLoop = 0; forLoop < NameLength; ++forLoop)
{
     RegName[forLoop] = tolower(RegName[forLoop]);
}

RegName is your string. Get your string size don't use string.size() as your actual tester, very messy and can cause issues. then. the most basic for loop.

remember string size returns the delimiter too so use < and not <= in your loop test.

output will be: some string that you want converted

How can I clear the content of a file?

Try using something like

File.Create

Creates or overwrites a file in the specified path.

When is a language considered a scripting language?

In short Scripting languages have the following properties:

  1. Interpreter based.
  2. Easy syntax.Like access files of directory is very easy in python as compare to java.
  3. Generally used to write less line of codes.
  4. Convenient for writing automation codes.
  5. Very high level languages.

Eg.:Javascript,python,VBA.

Laravel: Auth::user()->id trying to get a property of a non-object

In Laravel 8.6, the following works for me in a controller:

$id = auth()->user()->id;

What is the MySQL VARCHAR max size?

Source

The max length of a varchar is subject to the max row size in MySQL, which is 64KB (not counting BLOBs):

VARCHAR(65535) However, note that the limit is lower if you use a multi-byte character set:

VARCHAR(21844) CHARACTER SET utf8

How to get featured image of a product in woocommerce

In WC 3.0+ versions the image can get by below code.

$image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $item->get_product_id() ), 'single-post-thumbnail' );
echo $image_url[0]

Decompile Python 2.7 .pyc

Decompyle++ (pycdc) appears to work for a range of python versions: https://github.com/zrax/pycdc

For example:

git clone https://github.com/zrax/pycdc   
cd pycdc
make  
./bin/pycdc Example.pyc > Example.py

Multiple commands on a single line in a Windows batch file

Use:

echo %time% & dir & echo %time%

This is, from memory, equivalent to the semi-colon separator in bash and other UNIXy shells.

There's also && (or ||) which only executes the second command if the first succeeded (or failed), but the single ampersand & is what you're looking for here.


That's likely to give you the same time however since environment variables tend to be evaluated on read rather than execute.

You can get round this by turning on delayed expansion:

pax> cmd /v:on /c "echo !time! & ping 127.0.0.1 >nul: & echo !time!"
15:23:36.77
15:23:39.85

That's needed from the command line. If you're doing this inside a script, you can just use setlocal:

@setlocal enableextensions enabledelayedexpansion
@echo off
echo !time! & ping 127.0.0.1 >nul: & echo !time!
endlocal

Http post and get request in angular 6

For reading full response in Angular you should add the observe option:

{ observe: 'response' }
    return this.http.get(`${environment.serverUrl}/api/posts/${postId}/comments/?page=${page}&size=${size}`, { observe: 'response' });

Writing Unicode text to a text file?

Preface: will your viewer work?

Make sure your viewer/editor/terminal (however you are interacting with your utf-8 encoded file) can read the file. This is frequently an issue on Windows, for example, Notepad.

Writing Unicode text to a text file?

In Python 2, use open from the io module (this is the same as the builtin open in Python 3):

import io

Best practice, in general, use UTF-8 for writing to files (we don't even have to worry about byte-order with utf-8).

encoding = 'utf-8'

utf-8 is the most modern and universally usable encoding - it works in all web browsers, most text-editors (see your settings if you have issues) and most terminals/shells.

On Windows, you might try utf-16le if you're limited to viewing output in Notepad (or another limited viewer).

encoding = 'utf-16le' # sorry, Windows users... :(

And just open it with the context manager and write your unicode characters out:

with io.open(filename, 'w', encoding=encoding) as f:
    f.write(unicode_object)

Example using many Unicode characters

Here's an example that attempts to map every possible character up to three bits wide (4 is the max, but that would be going a bit far) from the digital representation (in integers) to an encoded printable output, along with its name, if possible (put this into a file called uni.py):

from __future__ import print_function
import io
from unicodedata import name, category
from curses.ascii import controlnames
from collections import Counter

try: # use these if Python 2
    unicode_chr, range = unichr, xrange
except NameError: # Python 3
    unicode_chr = chr

exclude_categories = set(('Co', 'Cn'))
counts = Counter()
control_names = dict(enumerate(controlnames))
with io.open('unidata', 'w', encoding='utf-8') as f:
    for x in range((2**8)**3): 
        try:
            char = unicode_chr(x)
        except ValueError:
            continue # can't map to unicode, try next x
        cat = category(char)
        counts.update((cat,))
        if cat in exclude_categories:
            continue # get rid of noise & greatly shorten result file
        try:
            uname = name(char)
        except ValueError: # probably control character, don't use actual
            uname = control_names.get(x, '')
            f.write(u'{0:>6x} {1}    {2}\n'.format(x, cat, uname))
        else:
            f.write(u'{0:>6x} {1}  {2}  {3}\n'.format(x, cat, char, uname))
# may as well describe the types we logged.
for cat, count in counts.items():
    print('{0} chars of category, {1}'.format(count, cat))

This should run in the order of about a minute, and you can view the data file, and if your file viewer can display unicode, you'll see it. Information about the categories can be found here. Based on the counts, we can probably improve our results by excluding the Cn and Co categories, which have no symbols associated with them.

$ python uni.py

It will display the hexadecimal mapping, category, symbol (unless can't get the name, so probably a control character), and the name of the symbol. e.g.

I recommend less on Unix or Cygwin (don't print/cat the entire file to your output):

$ less unidata

e.g. will display similar to the following lines which I sampled from it using Python 2 (unicode 5.2):

     0 Cc NUL
    20 Zs     SPACE
    21 Po  !  EXCLAMATION MARK
    b6 So  ¶  PILCROW SIGN
    d0 Lu  Ð  LATIN CAPITAL LETTER ETH
   e59 Nd  ?  THAI DIGIT NINE
  2887 So  ?  BRAILLE PATTERN DOTS-1238
  bc13 Lo  ?  HANGUL SYLLABLE MIH
  ffeb Sm  ?  HALFWIDTH RIGHTWARDS ARROW

My Python 3.5 from Anaconda has unicode 8.0, I would presume most 3's would.

RuntimeError on windows trying python multiprocessing

As @Ofer said, when you are using another libraries or modules, you should import all of them inside the if __name__ == '__main__':

So, in my case, ended like this:

if __name__ == '__main__':       
    import librosa
    import os
    import pandas as pd
    run_my_program()

Remove Datepicker Function dynamically

Well I had the same issue and tried "destroy" but that not worked for me. Then I found following work around My HTML was:

<input placeholder="Select Date" id="MyControlId" class="form-control datepicker" type="text" />

Jquery That work for me:

$('#MyControlId').data('datepicker').remove();

Using "margin: 0 auto;" in Internet Explorer 8

Add <!doctype html> at the top of your HTML output.

PHP find difference between two datetimes

You can simply use datetime diff and format for calculating difference.

<?php
$datetime1 = new DateTime('2009-10-11 12:12:00');
$datetime2 = new DateTime('2009-10-13 10:12:00');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%Y-%m-%d %H:%i:%s');
?>

For more information OF DATETIME format, refer: here
You can change the interval format in the way,you want.

Here is the working example

P.S. These features( diff() and format()) work with >=PHP 5.3.0 only

How do I use the conditional operator (? :) in Ruby?

Easiest way:

param_a = 1
param_b = 2

result = param_a === param_b ? 'Same!' : 'Not same!'

since param_a is not equal to param_b then the result's value will be Not same!

Django Template Variables and Javascript

I use this way in Django 2.1 and work for me and this way is secure (reference):

Django side:

def age(request):
    mydata = {'age':12}
    return render(request, 'test.html', context={"mydata_json": json.dumps(mydata)})

Html side:

<script type='text/javascript'>
     const  mydata = {{ mydata_json|safe }};
console.log(mydata)
 </script>

How to create custom spinner like border around the spinner with down triangle on the right side?

Spinner

<Spinner
    android:id="@+id/To_Units"
    style="@style/spinner_style" />

style.xml

    <style name="spinner_style">
          <item name="android:layout_width">match_parent</item>
          <item name="android:layout_height">wrap_content</item>
          <item name="android:background">@drawable/gradient_spinner</item>
          <item name="android:layout_margin">10dp</item>
          <item name="android:paddingLeft">8dp</item>
          <item name="android:paddingRight">20dp</item>
          <item name="android:paddingTop">5dp</item>
          <item name="android:paddingBottom">5dp</item>
          <item name="android:popupBackground">#DFFFFFFF</item>
     </style>

gradient_spinner.xml (in drawable folder)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item><layer-list>
            <item><shape>
                    <gradient android:angle="90" android:endColor="#B3BBCC" android:startColor="#E8EBEF" android:type="linear" />

                    <stroke android:width="1dp" android:color="#000000" />

                    <corners android:radius="4dp" />

                    <padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp" />
                </shape></item>
            <item ><bitmap android:gravity="bottom|right" android:src="@drawable/spinner_arrow" />
            </item>
        </layer-list></item>

</selector>  

@drawable/spinner_arrow is your bottom right corner image

Create a simple Login page using eclipse and mysql

use this code it is working

// index.jsp or login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>
</form>

</body>
</html>

// authentication servlet class

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class auth extends HttpServlet {
        private static final long serialVersionUID = 1L;

        public auth() {
            super();
        }
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {

        }

        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {

            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            String username = request.getParameter("username");
            String pass = request.getParameter("pass");

            String sql = "select * from reg where username='" + username + "'";
            Connection conn = null;

            try {
                conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
                        "root", "");
                Statement s = conn.createStatement();

                java.sql.ResultSet rs = s.executeQuery(sql);
                String un = null;
                String pw = null;
                String name = null;

            /* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */   

            PrintWriter prwr1 = response.getWriter();               
            if(!rs.isBeforeFirst()){
                prwr1.write("<h1> No Such User in Database<h1>");
            } else {

/* Conditions to be executed after at least one row is returned by query execution */ 
                while (rs.next()) {
                    un = rs.getString("username");
                    pw = rs.getString("password");
                    name = rs.getString("name");
                }

                PrintWriter pww = response.getWriter();

                if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
                                // use this or create request dispatcher 
                    response.setContentType("text/html");
                    pww.write("<h1>Welcome, " + name + "</h1>");
                } else {
                    pww.write("wrong username or password\n");
                }
              }

            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

    }

Proper way to use **kwargs in Python

@AbhinavGupta and @Steef suggested using update(), which I found very helpful for processing large argument lists:

args.update(kwargs)

What if we want to check that the user hasn't passed any spurious/unsupported arguments? @VinaySajip pointed out that pop() can be used to iteratively process the list of arguments. Then, any leftover arguments are spurious. Nice.

Here's another possible way to do this, which keeps the simple syntax of using update():

# kwargs = dictionary of user-supplied arguments
# args = dictionary containing default arguments

# Check that user hasn't given spurious arguments
unknown_args = user_args.keys() - default_args.keys()
if unknown_args:
    raise TypeError('Unknown arguments: {}'.format(unknown_args))

# Update args to contain user-supplied arguments
args.update(kwargs)

unknown_args is a set containing the names of arguments that don't occur in the defaults.

There isn't anything to compare. Nothing to compare, branches are entirely different commit histories

I solve my issue using these commands

git checkout [BRANCH]   
git branch master [BRANCH] -f   
git checkout master   
git push origin master -f

Git undo changes in some files

Why can't you simply mark what changes you want to have in a commit using "git add <file>" (or even "git add --interactive", or "git gui" which has option for interactive comitting), and then use "git commit" instead of "git commit -a"?

In your situation (for your example) it would be:

prompt> git add B
prompt> git commit

Only changes to file B would be comitted, and file A would be left "dirty", i.e. with those print statements in the working area version. When you want to remove those print statements, it would be enought to use

prompt> git reset A

or

prompt> git checkout HEAD -- A

to revert to comitted version (version from HEAD, i.e. "git show HEAD:A" version).

How to run a shell script in OS X by double-clicking?

You can also set defaults by file extension using RCDefaultApp:

http://www.rubicode.com/Software/RCDefaultApp/

potentially you could set .sh to open in iTerm/Terminal etc. it would need user execute permissions, eg

chmod u+x filename.sh

RCDefaultApp pref pane

What's the best way to trim std::string?

It seems I'm really late to the party - I can't believe this was asked 7 years ago!

Here's my take on the problem. I'm working on a project and I didn't want to go through the trouble of using Boost right now.

std::string trim(std::string str) {
    if(str.length() == 0) return str;

    int beg = 0, end = str.length() - 1;
    while (str[beg] == ' ') {
        beg++;
    }

    while (str[end] == ' ') {
        end--;
    }

    return str.substr(beg, end - beg + 1);
}

This solution will trim from the left and the right.

How can I make a button redirect my page to another page?

This is here:

 <button onClick="window.location='page_name.php';" value="click here" />

How do I mock a class without an interface?

I faced something like that in one of the old and legacy projects that i worked in that not contains any interfaces or best practice and also it's too hard to enforce them build things again or refactoring the code due to the maturity of the project business, So in my UnitTest project i used to create a Wrapper over the classes that I want to mock and that wrapper implement interface which contains all my needed methods that I want to setup and work with, Now I can mock the wrapper instead of the real class.

For Example:

Service you want to test which not contains virtual methods or implement interface

public class ServiceA{

public void A(){}

public String B(){}

}

Wrapper to moq

public class ServiceAWrapper : IServiceAWrapper{

public void A(){}

public String B(){}

}

The Wrapper Interface

public interface IServiceAWrapper{

void A();

String B();

}

In the unit test you can now mock the wrapper:

    public void A_Run_ChangeStateOfX()
    {
    var moq = new Mock<IServiceAWrapper>();
    moq.Setup(...);
    }

This might be not the best practice, but if your project rules force you in this way, do it. Also Put all your Wrappers inside your Unit Test project or Helper project specified only for the unit tests in order to not overload the project with unneeded wrappers or adaptors.

Update: This answer from more than a year but in this year i faced a lot of similar scenarios with different solutions. For example it's so easy to use Microsoft Fake Framework to create mocks, fakes and stubs and even test private and protected methods without any interfaces. You can read: https://docs.microsoft.com/en-us/visualstudio/test/isolating-code-under-test-with-microsoft-fakes?view=vs-2017

Is there a conditional ternary operator in VB.NET?

Just for the record, here is the difference between If and IIf:

IIf(condition, true-part, false-part):

  • This is the old VB6/VBA Function
  • The function always returns an Object type, so if you want to use the methods or properties of the chosen object, you have to re-cast it with DirectCast or CType or the Convert.* Functions to its original type
  • Because of this, if true-part and false-part are of different types there is no matter, the result is just an object anyway

If(condition, true-part, false-part):

  • This is the new VB.NET Function
  • The result type is the type of the chosen part, true-part or false-part
  • This doesn't work, if Strict Mode is switched on and the two parts are of different types. In Strict Mode they have to be of the same type, otherwise you will get an Exception
  • If you really need to have two parts of different types, switch off Strict Mode (or use IIf)
  • I didn't try so far if Strict Mode allows objects of different type but inherited from the same base or implementing the same Interface. The Microsoft documentation isn't quite helpful about this issue. Maybe somebody here knows it.

SQLite equivalent to ISNULL(), NVL(), IFNULL() or COALESCE()

Try this

ifnull(X,Y)  

e.g

select ifnull(InfoDetail,'') InfoDetail; -- this will replace null with ''
select ifnull(NULL,'THIS IS NULL');-- More clearly....

The ifnull() function returns a copy of its first non-NULL argument, or NULL if both arguments are NULL. Ifnull() must have exactly 2 arguments. The ifnull() function is equivalent to coalesce() with two arguments.

How to change checkbox's border style in CSS?

put it in a div and add border to the div

Android TextView padding between lines

Adding android:lineSpacingMultiplier="0.8" can make the line spacing to 80%.

How do I push amended commit to the remote Git repository?

Short answer: Don't push amended commits to a public repo.

Long answer: A few Git commands, like git commit --amend and git rebase, actually rewrite the history graph. This is fine as long as you haven't published your changes, but once you do, you really shouldn't be mucking around with the history, because if someone already got your changes, then when they try to pull again, it might fail. Instead of amending a commit, you should just make a new commit with the changes.

However, if you really, really want to push an amended commit, you can do so like this:

$ git push origin +master:master

The leading + sign will force the push to occur, even if it doesn't result in a "fast-forward" commit. (A fast-forward commit occurs when the changes you are pushing are a direct descendant of the changes already in the public repo.)

Correctly ignore all files recursively under a specific folder except for a specific file type

Either I'm doing it wrongly, or the accepted answer does not work anymore with the current git.

I have actually found the proper solution and posted it under almost the same question here. For more details head there.

Solution:

# Ignore everything inside Resources/ directory
/Resources/**
# Except for subdirectories(won't be committed anyway if there is no committed file inside)
!/Resources/**/
# And except for *.foo files
!*.foo

How to find the nearest parent of a Git branch?

A solution

The solution based on git show-branch did not quite work for me (see below), so I've combined it with the one based on git log and ended up with this:

git log --decorate --simplify-by-decoration --oneline \ # selects only commits with a branch or tag
      | grep -v "(HEAD" \                               # removes current head (and branch)
      | head -n1 \                                      # selects only the closest decoration
      | sed 's/.* (\(.*\)) .*/\1/' \                    # filters out everything but decorations
      | sed 's/\(.*\), .*/\1/' \                        # picks only the first decoration
      | sed 's/origin\///'                              # strips "origin/" from the decoration

Limitations and Caveats

  • HEAD can be detached (many CI tools do so to ensure they build correct commit in a given branch), but origin branch and local branch have to be both at par or "above" the current HEAD.
  • There must be no tags in the way (I presume; I have not tested the script on commits with a tag between child and parent branch)
  • the script relies on the fact "HEAD" is always listed as the first decoration by the log command
  • running the script on master and develop results (mostly) in <SHA> Initial commit

The results

 A---B---D---E---F <-origin/master, master
      \      \
       \      \
        \      G---H---I <- origin/hotfix, hotfix
         \
          \
           J---K---L <-origin/develop, develop
                \
                 \
                  M---N---O <-origin/feature/a, feature/a
                       \   \
                        \   \
                         \   P---Q---R <-origin/feature/b, feature/b
                          \
                           \
                            S---T---U <-origin/feature/c, feature/c

Despite local branch existence (e.g. only origin/topic is present since the commit O was checked-out by directly by its SHA), the script should print as follows:

  • For commits G, H, I (branch hotfix) ? master
  • For commits M, N, O (branch feature/a) ? develop
  • For commits S, T, U (branch feature/c) ? develop
  • For commits P, Q, R (branch feature/b) ? feature/a
  • For commits J, K, L (branch develop) ? <sha> Initial commit*
  • For commits B, D, E, F (branch master) ? <sha> Initial commit

* - or master if develop's commits were on top of master's HEAD (~ the master would be fast-forwardable to develop)


Why did not show-branch work for me

The solution based on git show-branch proved unreliable for me in the following situations:

  • detached HEAD – including detached head case means replacing grep '\*' \ for `grep '!' \ – and that is just the beginning of all the troubles
  • running the script on master and develop results in develop and `` respectively
  • branches on master branch (hotfix/ branches) end up with the develop as a parent since their closest master branch parent was marked with ! instead of * for a reason.

How to export SQL Server database to MySQL?

if you have a MSSQL compatible SQL dump you can convert it to MySQL queries one by one using this online tool

http://burrist.com/mstomy.php

Hope it saved your time

How to set a class attribute to a Symfony2 form input

You can add it in the options of your form class:

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\MyEntity',
        'attr' => array(
            'class' => 'form-horizontal'
        )
    ));
}

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

It is used to find the how many rows contain data in a worksheet that contains data in the column "A". The full usage is

 lastRowIndex = ws.Cells(ws.Rows.Count, "A").End(xlUp).row

Where ws is a Worksheet object. In the questions example it was implied that the statement was inside a With block

With ws
    lastRowIndex = .Cells(.Rows.Count, "A").End(xlUp).row
End With
  1. ws.Rows.Count returns the total count of rows in the worksheet (1048576 in Excel 2010).
  2. .Cells(.Rows.Count, "A") returns the bottom most cell in column "A" in the worksheet

Then there is the End method. The documentation is ambiguous as to what it does.

Returns a Range object that represents the cell at the end of the region that contains the source range

Particularly it doesn't define what a "region" is. My understanding is a region is a contiguous range of non-empty cells. So the expected usage is to start from a cell in a region and find the last cell in that region in that direction from the original cell. However there are multiple exceptions for when you don't use it like that:

  • If the range is multiple cells, it will use the region of rng.cells(1,1).
  • If the range isn't in a region, or the range is already at the end of the region, then it will travel along the direction until it enters a region and return the first encountered cell in that region.
  • If it encounters the edge of the worksheet it will return the cell on the edge of that worksheet.

So Range.End is not a trivial function.

  1. .row returns the row index of that cell.

Remove char at specific index - python

Another option, using list comprehension and join:

''.join([_str[i] for i in xrange(len(_str)) if i  != 4])

Microsoft.WebApplication.targets was not found, on the build server. What's your solution?

Based on this post here you can simply download the Microsoft Visual Studio 2010 Shell (Integrated) Redistributable Package and the targets are installed.

This avoids the need to install Visual Studio on the build server.

I have just tried this out now, and can verify that it works:

Before:

error MSB4019: The imported project "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" was not found. Confirm that the path in the declaration is correct, and that the file exists on disk.

After the install:

[Builds correctly]

This is a far better solution than installing Visual Studio on a build server, obviously.

HTML img align="middle" doesn't align an image

You don't need align="center" and float:left. Remove both of these. margin: 0 auto is sufficient.

convert a JavaScript string variable to decimal/money

This works:

var num = parseFloat(document.getElementById(amtid4).innerHTML, 10).toFixed(2);

How to convert JSON data into a Python object

Use the json module (new in Python 2.6) or the simplejson module which is almost always installed.

When should I use uuid.uuid1() vs. uuid.uuid4() in python?

Perhaps something that's not been mentioned is that of locality.

A MAC address or time-based ordering (UUID1) can afford increased database performance, since it's less work to sort numbers closer-together than those distributed randomly (UUID4) (see here).

A second related issue, is that using UUID1 can be useful in debugging, even if origin data is lost or not explicitly stored (this is obviously in conflict with the privacy issue mentioned by the OP).

Tensorflow r1.0 : could not a find a version that satisfies the requirement tensorflow

I was in same problem.

Below command solved my problem

pip3 install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.0.0-py3-none-any.whl

to find the list of all the urls based on the python version and CPU or GPU only refer to: https://www.tensorflow.org/install/pip

How to disable JavaScript in Chrome Developer Tools?

Paste it: chrome://settings/content

Go to "Javascript" section and disable it.

Select NOT IN multiple columns

I'm not sure whether you think about:

select * from friend f
where not exists (
    select 1 from likes l where f.id1 = l.id and f.id2 = l.id2
)

it works only if id1 is related with id1 and id2 with id2 not both.

C# How to change font of a label

Font.Name, Font.XYZProperty, etc are readonly as Font is an immutable object, so you need to specify a new Font object to replace it:

mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);

Check the constructor of the Font class for further options.

Connecting to smtp.gmail.com via command line

gmail uses an encrypted connection. So, even after you establish a connection, you wont be able to send any email. The encryption is a little complex to manage. Try using openssl instead.

The thread below should help-

How to send email using simple SMTP commands via Gmail?

Min/Max-value validators in asp.net mvc

A complete example of how this could be done. To avoid having to write client-side validation scripts, the existing ValidationType = "range" has been used.

public class MinValueAttribute : ValidationAttribute, IClientValidatable
{
    private readonly double _minValue;

    public MinValueAttribute(double minValue)
    {
        _minValue = minValue;
        ErrorMessage = "Enter a value greater than or equal to " + _minValue;  
    }

    public MinValueAttribute(int minValue)
    {
        _minValue = minValue;
        ErrorMessage = "Enter a value greater than or equal to " + _minValue;
    }

    public override bool IsValid(object value)
    {
        return Convert.ToDouble(value) >= _minValue;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule();
        rule.ErrorMessage = ErrorMessage;
        rule.ValidationParameters.Add("min", _minValue);
        rule.ValidationParameters.Add("max", Double.MaxValue);
        rule.ValidationType = "range";
        yield return rule;
    }

}

Pass a simple string from controller to a view MVC3

If you are trying to simply return a string to a View, try this:

public string Test()
{
     return "test";
}

This will return a view with the word test in it. You can insert some html in the string.

You can also try this:

public ActionResult Index()
{
    return Content("<html><b>test</b></html>");
}

Getting the count of unique values in a column in bash

Ruby(1.9+)

#!/usr/bin/env ruby
Dir["*"].each do |file|
    h=Hash.new(0)
    open(file).each do |row|
        row.chomp.split("\t").each do |w|
            h[ w ] += 1
        end
    end
    h.sort{|a,b| b[1]<=>a[1] }.each{|x,y| print "#{x}:#{y}\n" }
end

E11000 duplicate key error index in mongodb mongoose

Change the collection name if it already exists in the database, it will show an error. And if you given any property as unique the same error will occur.