Programs & Examples On #Working set

Options for embedding Chromium instead of IE WebBrowser control with WPF/C#

UPDATE 2018 MAY:

Alternatively, you can embed Edge browser, but only targetting windows 10.

Here is the solution.

Creating a chart in Excel that ignores #N/A or blank cells

This is what I found as I was plotting only 3 cells from each 4 columns lumped together. My chart has a merged cell with the date which is my x axis. The problem: BC26-BE27 are plotting as ZERO on my chart. enter image description here

I click on the filter on the side of the chart and found where it is showing all the columns for which the data points are charted. I unchecked the boxes that do not have values. enter image description here

It worked for me.

Build fails with "Command failed with a nonzero exit code"

I encountered this error when I was upgrading my project from Swift 4 to 5. I first updated all my pods to their latest versions. When I built, some pods showed this error.

The following steps resolved this issue for me:

  1. Removed all pods from Podfile
  2. Executed pod install to remove all installed pods
  3. Executed pod deintegrate to remove support for CocoaPods
  4. Deleted Podfile.lock and .xcworkspace from my project so no CocoaPods anymore
  5. Now my project is a pure Xcode project
  6. Opened my project from the regular .xcodeproj file
  7. Changed Swift Version of my project to Swift 5
  8. Cleaned the project (cmd+shift+K)
  9. Quitted Xcode
  10. Restored all pods to my Podfile
  11. Executed pod install to reintegrate CocoaPods and add my pods
  12. Opened the project from the .xcworkspace file
  13. Cleaned and rebuilt
  14. Some old pods that were still using Swift 4.0 (SlideMenuControllerSwift in my case) were set to Swift 5.0, caused many build errors in their code. I corrected it back to Swift 4.0 by opening the Pods project and selecting its target.
  15. Cleaned again, rebuilt.

Now I have only errors in my own project code related with difference in Swift version I made. My job now is to fix them.

Append values to query string

Note you can add the Microsoft.AspNetCore.WebUtilities nuget package from Microsoft and then use this to append values to query string:

QueryHelpers.AddQueryString(longurl, "action", "login1")
QueryHelpers.AddQueryString(longurl, new Dictionary<string, string> { { "action", "login1" }, { "attempts", "11" } });

Get property value from C# dynamic object by string (reflection?)

Use the following code to get Name and Value of a dynamic object's property.

dynamic d = new { Property1= "Value1", Property2= "Value2"};

var properties = d.GetType().GetProperties();
foreach (var property in properties)
{
    var PropertyName=property.Name; 
//You get "Property1" as a result

  var PropetyValue=d.GetType().GetProperty(property.Name).GetValue(d, null); 
//You get "Value1" as a result

// you can use the PropertyName and Value here
 }

Rails: How to run `rails generate scaffold` when the model already exists?

In Rails 5, you can still run

$rails generate scaffold movie --skip

to create all the missing scaffold files or

rails generate scaffold_controller Movie

to create the controller and view only.

For a better explanation check out rails scaffold

How to redirect from one URL to another URL?

location.href = "Pagename.html";

Drop multiple columns in pandas

You don't need to wrap it in a list with [..], just provide the subselection of the columns index:

df.drop(df.columns[[1, 69]], axis=1, inplace=True)

as the index object is already regarded as list-like.

Trim Cells using VBA in Excel

Only thing that worked for me is this function:

Sub DoTrim()
Dim cell As Range
Dim str As String
For Each cell In Selection.Cells
    If cell.HasFormula = False Then
        str = Left(cell.Value, 1) 'space
        While str = " " Or str = Chr(160)
            cell.Value = Right(cell.Value, Len(cell.Value) - 1)
            str = Left(cell.Value, 1) 'space
        Wend
        str = Right(cell.Value, 1) 'space
        While str = " " Or str = Chr(160)
            cell.Value = Left(cell.Value, Len(cell.Value) - 1)
            str = Right(cell.Value, 1) 'space
        Wend
    End If
Next cell
End Sub

Return multiple values from a function, sub or type?

I always approach returning more than one result from a function by always returning an ArrayList. By using an ArrayList I can return only one item, consisting of many multiple values, mixing between Strings and Integers.

Once I have the ArrayList returned in my main sub, I simply use ArrayList.Item(i).ToString where i is the index of the value I want to return from the ArrayList

An example:

 Public Function Set_Database_Path()
        Dim Result As ArrayList = New ArrayList
        Dim fd As OpenFileDialog = New OpenFileDialog()


        fd.Title = "Open File Dialog"
        fd.InitialDirectory = "C:\"
        fd.RestoreDirectory = True
        fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
        fd.FilterIndex = 2
        fd.Multiselect = False


        If fd.ShowDialog() = DialogResult.OK Then

            Dim Database_Location = Path.GetFullPath(fd.FileName)

            Dim Database_Connection_Var = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""" & Database_Location & """"

            Result.Add(Database_Connection_Var)
            Result.Add(Database_Location)

            Return (Result)

        Else

            Return (Nothing)

        End If
    End Function

And then call the Function like this:

Private Sub Main_Load()
  Dim PathArray As ArrayList

            PathArray = Set_Database_Path()
            My.Settings.Database_Connection_String = PathArray.Item(0).ToString
            My.Settings.FilePath = PathArray.Item(1).ToString
            My.Settings.Save()
End Sub

Filtering a list of strings based on contents

This simple filtering can be achieved in many ways with Python. The best approach is to use "list comprehensions" as follows:

>>> lst = ['a', 'ab', 'abc', 'bac']
>>> [k for k in lst if 'ab' in k]
['ab', 'abc']

Another way is to use the filter function. In Python 2:

>>> filter(lambda k: 'ab' in k, lst)
['ab', 'abc']

In Python 3, it returns an iterator instead of a list, but you can cast it:

>>> list(filter(lambda k: 'ab' in k, lst))
['ab', 'abc']

Though it's better practice to use a comprehension.

Restricting JTextField input to Integers

Here's one approach that uses a keylistener,but uses the keyChar (instead of the keyCode):

http://edenti.deis.unibo.it/utils/Java-tips/Validating%20numerical%20input%20in%20a%20JTextField.txt

 keyText.addKeyListener(new KeyAdapter() {
    public void keyTyped(KeyEvent e) {
      char c = e.getKeyChar();
      if (!((c >= '0') && (c <= '9') ||
         (c == KeyEvent.VK_BACK_SPACE) ||
         (c == KeyEvent.VK_DELETE))) {
        getToolkit().beep();
        e.consume();
      }
    }
  });

Another approach (which personally I find almost as over-complicated as Swing's JTree model) is to use Formatted Text Fields:

http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html

How do I find out what version of Sybase is running

There are two ways to know the about Sybase version,

1) Using this System procedure to get the information about Sybase version

> sp_version
> go

2) Using this command to get Sybase version

> select @@version
> go

UTF-8 in Windows 7 CMD

This question has been already answered in Unicode characters in Windows command line - how?

You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.

No server in Eclipse; trying to install Tomcat

  1. In {workspace-directory}/.metadata/.plugins/org.eclipse.core.runtime/.settings delete the following two files:

    • org.eclipse.wst.server.core.prefs
    • org.eclipse.jst.server.tomcat.core.prefs
  2. Restart Eclipse

How to get Month Name from Calendar?

DateFormat date =  new SimpleDateFormat("dd/MMM/yyyy");
Date date1 = new Date();
System.out.println(date.format(date1));

Get a list of all git commits, including the 'lost' ones

We'll git log sometimes is not good to get all commits detail, so to view this...

For Mac: Get into you git project and type:

$ nano .git/logs/HEAD

to view you all commits in that, or:

$ gedit .git/logs/HEAD

to view you all commits in that,

then you can edit in any of your favourite browser.

jQuery.ajax returns 400 Bad Request

I was getting the 400 Bad Request error, even after setting:

contentType: "application/json",
dataType: "json"

The issue was with the type of a property passed in the json object, for the data property in the ajax request object.
To figure out the issue, I added an error handler and then logged the error to the console. Console log will clearly show validation errors for the properties if any.

This was my initial code:

var data = {
    "TestId": testId,
    "PlayerId": parseInt(playerId),
    "Result": result
};

var url = document.location.protocol + "//" + document.location.host + "/api/tests"
$.ajax({
    url: url,
    method: "POST",
    contentType: "application/json",
    data: JSON.stringify(data), // issue with a property type in the data object
    dataType: "json",
    error: function (e) {
        console.log(e); // logging the error object to console
    },
    success: function () {
        console.log('Success saving test result');
    }
});

Now after making the request, I checked the console tab in the browser development tool.
It looked like this: enter image description here

responseJSON.errors[0] clearly shows a validation error: The JSON value could not be converted to System.String. Path: $.TestId, which means I have to convert TestId to a string in the data object, before making the request.

Changing the data object creation like below fixed the issue for me:

var data = {
        "TestId": String(testId), //converting testId to a string
        "PlayerId": parseInt(playerId),
        "Result": result
};

I assume other possible errors could also be identified by logging and inspecting the error object.

Check whether a string is not null and not empty

In case you need to validate your method parameters you can use follow simple method

public class StringUtils {

    static boolean anyEmptyString(String ... strings) {
        return Stream.of(strings).anyMatch(s -> s == null || s.isEmpty());
    }

}

Example:

public String concatenate(String firstName, String lastName) {
    if(StringUtils.anyBlankString(firstName, lastName)) {
        throw new IllegalArgumentException("Empty field found");
    }
    return firstName + " " + lastName;
}

Mailto: Body formatting

From the first result on Google:

mailto:[email protected]_t?subject=Header&body=This%20is...%20the%20first%20line%0D%0AThis%20is%20the%20second

How to copy data to clipboard in C#

There are two classes that lives in different assemblies and different namespaces.

  • WinForms: use following namespace declaration, make sure Main is marked with [STAThread] attribute:

    using System.Windows.Forms;
    
  • WPF: use following namespace declaration

    using System.Windows;
    
  • console: add reference to System.Windows.Forms, use following namespace declaration, make sure Main is marked with [STAThread] attribute. Step-by-step guide in another answer

    using System.Windows.Forms;
    

To copy an exact string (literal in this case):

Clipboard.SetText("Hello, clipboard");

To copy the contents of a textbox either use TextBox.Copy() or get text first and then set clipboard value:

Clipboard.SetText(txtClipboard.Text);

See here for an example. Or... Official MSDN documentation or Here for WPF.


Remarks:

Programmatically set image to UIImageView with Xcode 6.1/Swift

If you want to do it the way you showed in your question, this is a way to do it inline

class YourClass: UIViewController{

  @IBOutlet weak var tableView: UITableView!
  //other IBOutlets

  //THIS is how you declare a UIImageView inline
  let placeholderImage : UIImageView = {
        let placeholderImage = UIImageView(image: UIImage(named: "nophoto"))
        placeholderImage.contentMode = .scaleAspectFill
        return placeholderImage
    }()

   var someVariable: String!
   var someOtherVariable: Int!

   func someMethod(){
      //method code
   }

   //and so on
}

Java - No enclosing instance of type Foo is accessible

Lets understand it with the following simple example. This happens because this is NON-STATIC INNER CLASS. You should need the instance of outer class.

 public class PQ {

    public static void main(String[] args) {

        // create dog object here
        Dog dog = new PQ().new Dog();
        //OR
        PQ pq = new PQ();
        Dog dog1 = pq.new Dog();
    }

    abstract class Animal {
        abstract void checkup();
    }

    class Dog extends Animal {
        @Override
        void checkup() {
            System.out.println("Dog checkup");

        }
    }

    class Cat extends Animal {
        @Override
        void checkup() {
            System.out.println("Cat Checkup");

        }
    }
}

Scanner is never closed

According to the Javadoc of Scanner, it closes the stream when you call it's close method. Generally speaking, the code that creates a resource is also responsible for closing it. System.in was not instantiated by by your code, but by the VM. So in this case it's safe to not close the Scanner, ignore the warning and add a comment why you ignore it. The VM will take care of closing it if needed.

(Offtopic: instead of "amount", the word "number" would be more appropriate to use for a number of players. English is not my native language (I'm Dutch) and I used to make exactly the same mistake.)

Maintain/Save/Restore scroll position when returning to a ListView

My answer is for Firebase and position 0 is a workaround

Parcelable state;

DatabaseReference everybody = db.getReference("Everybody Room List");
    everybody.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            state = listView.onSaveInstanceState(); // Save
            progressBar.setVisibility(View.GONE);
            arrayList.clear();
            for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
                Messages messagesSpacecraft = messageSnapshot.getValue(Messages.class);
                arrayList.add(messagesSpacecraft);
            }
            listView.setAdapter(convertView);
            listView.onRestoreInstanceState(state); // Restore
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
        }
    });

and convertView

position 0 a add a blank item that you are not using

public class Chat_ConvertView_List_Room extends BaseAdapter {

private ArrayList<Messages> spacecrafts;
private Context context;

@SuppressLint("CommitPrefEdits")
Chat_ConvertView_List_Room(Context context, ArrayList<Messages> spacecrafts) {
    this.context = context;
    this.spacecrafts = spacecrafts;
}

@Override
public int getCount() {
    return spacecrafts.size();
}

@Override
public Object getItem(int position) {
    return spacecrafts.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@SuppressLint({"SetTextI18n", "SimpleDateFormat"})
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = LayoutInflater.from(context).inflate(R.layout.message_model_list_room, parent, false);
    }

    final Messages s = (Messages) this.getItem(position);

    if (position == 0) {
        convertView.getLayoutParams().height = 1; // 0 does not work
    } else {
        convertView.getLayoutParams().height = RelativeLayout.LayoutParams.WRAP_CONTENT;
    }

    return convertView;
}
}

I have seen this work temporarily without disturbing the user, I hope it works for you

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

css absolute position won't work with margin-left:auto margin-right: auto

If the element is position absolutely, then it isn't relative, or in reference to any object - including the page itself. So margin: auto; can't decide where the middle is.

Its waiting to be told explicitly, using left and top where to position itself.

You can still center it programatically, using javascript or somesuch.

How to create a notification with NotificationCompat.Builder?

Use this code

            Intent intent = new Intent(getApplicationContext(), SomeActvity.class);
            PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(),
                    (int) System.currentTimeMillis(), intent, 0);

            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(getApplicationContext())
                            .setSmallIcon(R.drawable.your_notification_icon)
                            .setContentTitle("Notification title")
                            .setContentText("Notification message!")
                            .setContentIntent(pIntent);

            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, mBuilder.build());

How do I raise the same Exception with a custom message in Python?

This only works with Python 3. You can modify the exception's original arguments and add your own arguments.

An exception remembers the args it was created with. I presume this is so that you can modify the exception.

In the function reraise we prepend the exception's original arguments with any new arguments that we want (like a message). Finally we re-raise the exception while preserving the trace-back history.

def reraise(e, *args):
  '''re-raise an exception with extra arguments
  :param e: The exception to reraise
  :param args: Extra args to add to the exception
  '''

  # e.args is a tuple of arguments that the exception with instantiated with.
  #
  e.args = args + e.args

  # Recreate the expection and preserve the traceback info so thta we can see 
  # where this exception originated.
  #
  raise e.with_traceback(e.__traceback__)   


def bad():
  raise ValueError('bad')

def very():
  try:
    bad()
  except Exception as e:
    reraise(e, 'very')

def very_very():
  try:
    very()
  except Exception as e:
    reraise(e, 'very')

very_very()

output

Traceback (most recent call last):
  File "main.py", line 35, in <module>
    very_very()
  File "main.py", line 30, in very_very
    reraise(e, 'very')
  File "main.py", line 15, in reraise
    raise e.with_traceback(e.__traceback__)
  File "main.py", line 28, in very_very
    very()
  File "main.py", line 24, in very
    reraise(e, 'very')
  File "main.py", line 15, in reraise
    raise e.with_traceback(e.__traceback__)
  File "main.py", line 22, in very
    bad()
  File "main.py", line 18, in bad
    raise ValueError('bad')
ValueError: ('very', 'very', 'bad')

How to remove elements from a generic list while iterating over it?

foreach(var item in list.ToList())

{

if(item.Delete) list.Remove(item);

}

Simply create an entirely new list from the first one. I say "Easy" rather than "Right" as creating an entirely new list probably comes at a performance premium over the previous method (I haven't bothered with any benchmarking.) I generally prefer this pattern, it can also be useful in overcoming Linq-To-Entities limitations.

for(i = list.Count()-1;i>=0;i--)

{

item=list[i];

if (item.Delete) list.Remove(item);

}

This way cycles through the list backwards with a plain old For loop. Doing this forwards could be problematic if the size of the collection changes, but backwards should always be safe.

Get generic type of java.util.List

At runtime, no, you can't.

However via reflection the type parameters are accessible. Try

for(Field field : this.getDeclaredFields()) {
    System.out.println(field.getGenericType())
}

The method getGenericType() returns a Type object. In this case, it will be an instance of ParametrizedType, which in turn has methods getRawType() (which will contain List.class, in this case) and getActualTypeArguments(), which will return an array (in this case, of length one, containing either String.class or Integer.class).

Is it possible to save HTML page as PDF using JavaScript or jquery?

Here is how I would do it, its an idea not bulletproof design, you need to modify it

  • The user clicks the save as PDF button
  • The server is sent a call using ajax
  • The server responds with a URL for PDF generated using HTML, I have used Apache FOP very succssfully
  • The js handling the ajax response does a location.href to point the URL send by JS and as soon as that URL loads, it sends the file using content disposition header as attachment forcing user to download the file.

How to check if a particular service is running on Ubuntu

There is a simple way to verify if a service is running

systemctl status service_name

Try PostgreSQL:

systemctl status postgresql

Set custom HTML5 required field validation message

Just need to get the element and use the method setCustomValidity.

Example

var foo = document.getElementById('foo');
foo.setCustomValidity(' An error occurred');

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

Typing the Enter/Return key using Python and Selenium

If you are in this specific situation:

a) want to just press the key, but you not have a specific webElement to click on

b) you are using Selenium 2 (WebDriver)

Then the solution is:

    Actions builder = new Actions(webDriverInstance);
    builder.sendKeys(Keys.RETURN).perform();

Updating PartialView mvc 4

Controller :

public ActionResult Refresh(string ID)
    {
        DetailsViewModel vm = new DetailsViewModel();  // Model
        vm.productDetails = _product.GetproductDetails(ID); 
        /* "productDetails " is a property in "DetailsViewModel"
        "GetProductDetails" is a method in "Product" class
        "_product" is an interface of "Product" class */

        return PartialView("_Details", vm); // Details is a partial view
    }

In yore index page you should to have refresh link :

     <a href="#" id="refreshItem">Refresh</a>

This Script should be also in your index page:

<script type="text/javascript">

    $(function () {
    $('a[id=refreshItem]:last').click(function (e) {
        e.preventDefault();

        var url = MVC.Url.action('Refresh', 'MyController', { itemId: '@(Model.itemProp.itemId )' }); // Refresh is an Action in controller, MyController is a controller name

        $.ajax({
            type: 'GET',
            url: url,
            cache: false,
            success: function (grid) {
                $('#tabItemDetails').html(grid);
                clientBehaviors.applyPlugins($("#tabProductDetails")); // "tabProductDetails" is an id of div in your "Details partial view"
            }
        });
    });
});

Android: How to change CheckBox size?

You can try the following solution to change the size of custom checkbox by setting the following properties to Checkbox in your layout file. Worked for me

android:scaleX="0.8" android:scaleY="0.8"

android:button="@null"
android:scaleX="0.8"
android:scaleY="0.8"
android:background="@drawable/custom_checkbox"

add following lines to drawable file

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_checked="false"
      android:drawable="@drawable/unchecked_img" />
<item android:state_checked="true"
      android:drawable="@drawable/checked_img" />
</selector>

CAST DECIMAL to INT

your can try this :

SELECT columnName1, CAST(columnName2 AS  SIGNED ) FROM tableName 

Converting HTML to PDF using PHP?

If you wish to create a pdf from php, pdflib will help you (as some others suggested).

Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.

So, the options I know are:

DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.

HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.

Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:

wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.

htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.

Method to Add new or update existing item in Dictionary

There's no problem. I would even remove the CreateNewOrUpdateExisting from the source and use map[key] = value directly in your code, because this this is much more readable, because developers would usually know what map[key] = value means.

NSURLConnection Using iOS Swift

Swift 3.0

AsynchonousRequest

let urlString = "http://heyhttp.org/me.json"
var request = URLRequest(url: URL(string: urlString)!)
let session = URLSession.shared

session.dataTask(with: request) {data, response, error in
  if error != nil {
    print(error!.localizedDescription)
    return
  }

  do {
    let jsonResult: NSDictionary? = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
    print("Synchronous\(jsonResult)")
  } catch {
    print(error.localizedDescription)
  }
}.resume()

How to upload multiple files using PHP, jQuery and AJAX

HTML

<form enctype="multipart/form-data" action="upload.php" method="post">
    <input name="file[]" type="file" />
    <button class="add_more">Add More Files</button>
    <input type="button" value="Upload File" id="upload"/>
</form>

Javascript

 $(document).ready(function(){
    $('.add_more').click(function(e){
        e.preventDefault();
        $(this).before("<input name='file[]' type='file'/>");
    });
});

for ajax upload

$('#upload').click(function() {
    var filedata = document.getElementsByName("file"),
            formdata = false;
    if (window.FormData) {
        formdata = new FormData();
    }
    var i = 0, len = filedata.files.length, img, reader, file;

    for (; i < len; i++) {
        file = filedata.files[i];

        if (window.FileReader) {
            reader = new FileReader();
            reader.onloadend = function(e) {
                showUploadedItem(e.target.result, file.fileName);
            };
            reader.readAsDataURL(file);
        }
        if (formdata) {
            formdata.append("file", file);
        }
    }
    if (formdata) {
        $.ajax({
            url: "/path to upload/",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success: function(res) {

            },       
            error: function(res) {

             }       
             });
            }
        });

PHP

for($i=0; $i<count($_FILES['file']['name']); $i++){
    $target_path = "uploads/";
    $ext = explode('.', basename( $_FILES['file']['name'][$i]));
    $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1]; 

    if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
        echo "The file has been uploaded successfully <br />";
    } else{
        echo "There was an error uploading the file, please try again! <br />";
    }
}

/** 
    Edit: $target_path variable need to be reinitialized and should 
    be inside for loop to avoid appending previous file name to new one. 
*/

Please use the script above script for ajax upload. It will work

Nginx location "not equal to" regex

i was looking for the same. and found this solution.

Use negative regex assertion:

location ~ ^/(?!(favicon\.ico|resources|robots\.txt)) { 
.... # your stuff 
} 

Source Negated Regular Expressions in location

Explanation of Regex :

If URL does not match any of the following path

example.com/favicon.ico
example.com/resources
example.com/robots.txt

Then it will go inside that location block and will process it.

Manually adding a Userscript to Google Chrome

This parameter is is working for me:

--enable-easy-off-store-extension-install

Do the following:

  1. Right click on your "Chrome" icon.
  2. Choose properties
  3. At the end of your target line, place these parameters: --enable-easy-off-store-extension-install
  4. It should look like: chrome.exe --enable-easy-off-store-extension-install
  5. Start Chrome by double-clicking on the icon

Java ArrayList - how can I tell if two lists are equal, order not mattering?

One-line method :)

  1. Collection's items NOT implement the interface Comparable<? super T>

     static boolean isEqualCollection(Collection<?> a, Collection<?> b) {
         return a == b || (a != null && b != null && a.size() == b.size()
             && a.stream().collect(Collectors.toMap(Function.identity(), s -> 1L, Long::sum)).equals(b.stream().collect(Collectors.toMap(Function.identity(), s -> 1L, Long::sum))));
     }
    
  2. Collection's items implement the interface Comparable<? super T>

     static <T extends Comparable<? super T>> boolean  isEqualCollection2(Collection<T> a, Collection<T> b) {
       return a == b || (a != null && b != null && a.size() == b.size() && a.stream().sorted().collect(Collectors.toList()).equals(b.stream().sorted().collect(Collectors.toList())));
     }
    
  3. support Android5 & Android6 via https://github.com/retrostreams/android-retrostreams

    static boolean isEqualCollection(Collection<?> a, Collection<?> b) {
     return a == b || (a != null && b != null && a.size() == b.size()
             && StreamSupport.stream(a).collect(Collectors.toMap(Function.identity(), s->1L, Longs::sum)).equals(StreamSupport.stream(b).collect(Collectors.toMap(Function.identity(), s->1L, Longs::sum))));
    }
    

////Test case

    boolean isEquals1 = isEqualCollection(null, null); //true
    boolean isEquals2 = isEqualCollection(null, Arrays.asList("1", "2")); //false
    boolean isEquals3 = isEqualCollection(Arrays.asList("1", "2"), null); //false
    boolean isEquals4 = isEqualCollection(Arrays.asList("1", "2", "2"), Arrays.asList("1", "1", "2")); //false
    boolean isEquals5 = isEqualCollection(Arrays.asList("1", "2"), Arrays.asList("2", "1")); //true
    boolean isEquals6 = isEqualCollection(Arrays.asList("1", 2.0), Arrays.asList(2.0, "1")); //true
    boolean isEquals7 = isEqualCollection(Arrays.asList("1", 2.0, 100L), Arrays.asList(2.0, 100L, "1")); //true
    boolean isEquals8 = isEqualCollection(Arrays.asList("1", null, 2.0, 100L), Arrays.asList(2.0, null, 100L, "1")); //true

Align image to left of text on same line - Twitter Bootstrap3

I would use Bootstrap's grid to achieve the desired result. The class="img-responsive" works nicely. Something like:

    <div class="container-fluid">
        <div class="row">
            <div class="col-md-3"><img src="./pictures/placeholder.jpg" class="img-responsive" alt="Some picture" width="410" height="307"></div>
            <div class="col-md-9"><h1>Heading</h1><p>Your Information.</p></div>
        </div>
    </div>

Git for beginners: The definitive practical guide

How do you compare two revisions of a file, or your current file and a previous revision?

Compare command is git diff.

To compare 2 revisions of a file:

$ git diff <commit1> <commit2> <file_name>

That diffs commit1 against commit2; if you change order then files are diffed the other way round, which may not be what you expect...

To compare current staged file against the repository:

$ git diff --staged <file_name>

To compare current unstaged file against the repository:

$ git diff <file_name>

Selecting only numeric columns from a data frame

Another way could be as follows:-

#extracting numeric columns from iris datset
(iris[sapply(iris, is.numeric)])

Task<> does not contain a definition for 'GetAwaiter'

The Problem Occur Because the application I was using and the dll i added to my application both have different Versions.

Add this Package- Install-Package Microsoft.Bcl.Async -Version 1.0.168

ADDING THIS PACKAGE async Code becomes Compatible in version 4.0 as well, because Async only work on applications whose Versions are more than or equal to 4.5

Show git diff on file in staging area

You can show changes that have been staged with the --cached flag:

$ git diff --cached

In more recent versions of git, you can also use the --staged flag (--staged is a synonym for --cached):

$ git diff --staged

Put Excel-VBA code in module or sheet?

I would suggest separating your code based on the functionality and purpose specific to each sheet or module. In this manner, you would only put code relative to a sheet's UI inside the sheet's module and only put code related to modules in respective modules. Also, use separate modules to encapsulate code that is shared or reused among several different sheets.

For example, let's say you multiple sheets that are responsible for displaying data from a database in a special way. What kinds of functionality do we have in this situation? We have functionality related to each specific sheet, tasks related to getting data from the database, and tasks related to populating a sheet with data. In this case, I might start with a module for the data access, a module for populating a sheet with data, and within each sheet I'd have code for accessing code in those modules.

It might be laid out like this.

Module: DataAccess:

Function GetData(strTableName As String, strCondition1 As String) As Recordset
    'Code Related to getting data from the database'
End Function

Module: PopulateSheet:

Sub PopulateASheet(wsSheet As Worksheet, rs As Recordset)
    'Code to populate a worksheet '
End Function

Sheet: Sheet1 Code:

Sub GetDataAndPopulate()
    'Sample Code'
     Dim rs As New Recordset
     Dim ws As Worksheet
     Dim strParam As String
     Set ws = ActiveSheet
     strParam = ws.Range("A1").Value

     Set rs = GetData("Orders",strParam)

     PopulateASheet ws, rs
End Sub

Sub Button1_Click()
    Call GetDataAndPopulate
End Sub

remove item from stored array in angular 2

I think the Angular 2 way of doing this is the filter method:

this.data = this.data.filter(item => item !== data_item);

where data_item is the item that should be deleted

How to use HTTP_X_FORWARDED_FOR properly?

You can also solve this problem via Apache configuration using mod_remoteip, by adding the following to a conf.d file:

RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy 172.16.0.0/12
LogFormat "%a %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

outline on only one border

You can use box-shadow to create an outline on one side. Like outline, box-shadow does not change the size of the box model.

This puts a line on top:

box-shadow: 0 -1px 0 #000;

I made a jsFiddle where you can check it out in action.


INSET

For an inset border, use the inset keyword. This puts an inset line on top:

box-shadow: 0 1px 0 #000 inset;

Multiple lines can be added using comma-separated statements. This puts an inset line on the top and the left:

box-shadow: 0 1px 0 #000 inset,
            1px 0 0 #000 inset;

For more details on how box-shadow works, check out the MDN page.

How to preview a part of a large pandas DataFrame, in iPython notebook?

In this case, where the DataFrame is long but not too wide, you can simply slice it:

>>> df = pd.DataFrame({"A": range(1000), "B": range(1000)})
>>> df
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1000 entries, 0 to 999
Data columns:
A    1000  non-null values
B    1000  non-null values
dtypes: int64(2)
>>> df[:5]
   A  B
0  0  0
1  1  1
2  2  2
3  3  3
4  4  4

ix is deprecated.

If it's both wide and long, I tend to use .ix:

>>> df = pd.DataFrame({i: range(1000) for i in range(100)})
>>> df.ix[:5, :10]
   0   1   2   3   4   5   6   7   8   9   10
0   0   0   0   0   0   0   0   0   0   0   0
1   1   1   1   1   1   1   1   1   1   1   1
2   2   2   2   2   2   2   2   2   2   2   2
3   3   3   3   3   3   3   3   3   3   3   3
4   4   4   4   4   4   4   4   4   4   4   4
5   5   5   5   5   5   5   5   5   5   5   5

Sequelize, convert entity to plain object

you can use the query options {raw: true} to return the raw result. Your query should like follows:

db.Sensors.findAll({
  where: {
    nodeid: node.nodeid
  },
  raw: true,
})

also if you have associations with include that gets flattened. So, we can use another parameter nest:true

db.Sensors.findAll({
  where: {
    nodeid: node.nodeid
  },
  raw: true,
  nest: true,
})

Detecting Windows or Linux?

I think It's a best approach to use Apache lang dependency to decide which OS you're running programmatically through Java

import org.apache.commons.lang3.SystemUtils;

public class App {
    public static void main( String[] args ) {
        if(SystemUtils.IS_OS_WINDOWS_7)
            System.out.println("It's a Windows 7 OS");
        if(SystemUtils.IS_OS_WINDOWS_8)
            System.out.println("It's a Windows 8 OS");
        if(SystemUtils.IS_OS_LINUX)
            System.out.println("It's a Linux OS");
        if(SystemUtils.IS_OS_MAC)
            System.out.println("It's a MAC OS");
    }
}

How can I check if an array contains a specific value in php?

See in_array

<?php
    $arr = array(0 => "kitchen", 1 => "bedroom", 2 => "living_room", 3 => "dining_room");    
    if (in_array("kitchen", $arr))
    {
        echo sprintf("'kitchen' is in '%s'", implode(', ', $arr));
    }
?>

Convert from lowercase to uppercase all values in all character variables in dataframe

Alternatively, if you just want to convert one particular row to uppercase, use the code below:

df[[1]] <- toupper(df[[1]])

How to reference image resources in XAML?

If you've got an image in the Icons folder of your project and its build action is "Resource", you can refer to it like this:

<Image Source="/Icons/play_small.png" />

That's the simplest way to do it. This is the only way I could figure doing it purely from the resource standpoint and no project files:

var resourceManager = new ResourceManager(typeof (Resources));
var bitmap = resourceManager.GetObject("Search") as System.Drawing.Bitmap;

var memoryStream = new MemoryStream();
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
memoryStream.Position = 0;

var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();

this.image1.Source = bitmapImage;

how to pass command line arguments to main method dynamically

go to Run Configuration and in argument tab you can write your argument

SQLRecoverableException: I/O Exception: Connection reset

Solution
Change the setup for your application, so you this parameter[-Djava.security.egd=file:/dev/../dev/urandom] next to the java command:

java -Djava.security.egd=file:/dev/../dev/urandom [your command]

Ref :- https://community.oracle.com/thread/943911

What are the differences between a multidimensional array and an array of arrays in C#?

Array of arrays (jagged arrays) are faster than multi-dimensional arrays and can be used more effectively. Multidimensional arrays have nicer syntax.

If you write some simple code using jagged and multidimensional arrays and then inspect the compiled assembly with an IL disassembler you will see that the storage and retrieval from jagged (or single dimensional) arrays are simple IL instructions while the same operations for multidimensional arrays are method invocations which are always slower.

Consider the following methods:

static void SetElementAt(int[][] array, int i, int j, int value)
{
    array[i][j] = value;
}

static void SetElementAt(int[,] array, int i, int j, int value)
{
    array[i, j] = value;
}

Their IL will be the following:

.method private hidebysig static void  SetElementAt(int32[][] 'array',
                                                    int32 i,
                                                    int32 j,
                                                    int32 'value') cil managed
{
  // Code size       7 (0x7)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldarg.1
  IL_0002:  ldelem.ref
  IL_0003:  ldarg.2
  IL_0004:  ldarg.3
  IL_0005:  stelem.i4
  IL_0006:  ret
} // end of method Program::SetElementAt

.method private hidebysig static void  SetElementAt(int32[0...,0...] 'array',
                                                    int32 i,
                                                    int32 j,
                                                    int32 'value') cil managed
{
  // Code size       10 (0xa)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldarg.1
  IL_0002:  ldarg.2
  IL_0003:  ldarg.3
  IL_0004:  call       instance void int32[0...,0...]::Set(int32,
                                                           int32,
                                                           int32)
  IL_0009:  ret
} // end of method Program::SetElementAt

When using jagged arrays you can easily perform such operations as row swap and row resize. Maybe in some cases usage of multidimensional arrays will be more safe, but even Microsoft FxCop tells that jagged arrays should be used instead of multidimensional when you use it to analyse your projects.

Use images instead of radio buttons

  • Wrap radio and image in <label>
  • Hide radio button (Don't use display:none or visibility:hidden since such will impact accessibility)
  • Target the image next to the hidden radio using Adjacent sibling selector +

_x000D_
_x000D_
/* HIDE RADIO */
[type=radio] { 
  position: absolute;
  opacity: 0;
  width: 0;
  height: 0;
}

/* IMAGE STYLES */
[type=radio] + img {
  cursor: pointer;
}

/* CHECKED STYLES */
[type=radio]:checked + img {
  outline: 2px solid #f00;
}
_x000D_
<label>
  <input type="radio" name="test" value="small" checked>
  <img src="http://placehold.it/40x60/0bf/fff&text=A">
</label>

<label>
  <input type="radio" name="test" value="big">
  <img src="http://placehold.it/40x60/b0f/fff&text=B">
</label>
_x000D_
_x000D_
_x000D_

Don't forget to add a class to your labels and in CSS use that class instead.


Custom styles and animations

Here's an advanced version using the <i> element and the :after pseudo:

CSS custom radio and checkbox

_x000D_
_x000D_
body{color:#444;font:100%/1.4 sans-serif;}


/* CUSTOM RADIO & CHECKBOXES
   http://stackoverflow.com/a/17541916/383904 */
.rad,
.ckb{
  cursor: pointer;
  user-select: none;
  -webkit-user-select: none;
  -webkit-touch-callout: none;
}
.rad > input,
.ckb > input{ /* HIDE ORG RADIO & CHECKBOX */
  position: absolute;
  opacity: 0;
  width: 0;
  height: 0;
}
/* RADIO & CHECKBOX STYLES */
/* DEFAULT <i> STYLE */
.rad > i,
.ckb > i{ 
  display: inline-block;
  vertical-align: middle;
  width:  16px;
  height: 16px;
  border-radius: 50%;
  transition: 0.2s;
  box-shadow: inset 0 0 0 8px #fff;
  border: 1px solid gray;
  background: gray;
}
/* CHECKBOX OVERWRITE STYLES */
.ckb > i {
  width: 25px;
  border-radius: 3px;
}
.rad:hover > i{ /* HOVER <i> STYLE */
  box-shadow: inset 0 0 0 3px #fff;
  background: gray;
}
.rad > input:checked + i{ /* (RADIO CHECKED) <i> STYLE */
  box-shadow: inset 0 0 0 3px #fff;
  background: orange;
}
/* CHECKBOX */
.ckb > input + i:after{
  content: "";
  display: block;
  height: 12px;
  width:  12px;
  margin: 2px;
  border-radius: inherit;
  transition: inherit;
  background: gray;
}
.ckb > input:checked + i:after{ /* (RADIO CHECKED) <i> STYLE */
  margin-left: 11px;
  background:  orange;
}
_x000D_
<label class="rad">
  <input type="radio" name="rad1" value="a">
  <i></i> Radio 1
</label>
<label class="rad">
  <input type="radio" name="rad1" value="b" checked>
  <i></i> Radio 2
</label>

<br>

<label class="ckb">
  <input type="checkbox" name="ckb1" value="a" checked>
  <i></i> Checkbox 1
</label>
<label class="ckb">
  <input type="checkbox" name="ckb2" value="b">
  <i></i> Checkbox 2
</label>
_x000D_
_x000D_
_x000D_

Detecting negative numbers

You could use a ternary operator like this one, to make it a one liner.

echo ($profitloss < 0) ? 'false' : 'true';

Go to beginning of line without opening new line in VI

You can use ^ or 0 (Zero) in normal mode to move to the beginning of a line.

^ moves the cursor to the first non-blank character of a line
0 always moves the cursor to the "first column"

You can also use Shifti to move and switch to Insert mode.

Deny direct access to all .php files except index.php

Are you sure, you want to do that? Even css and js files and images and ...?

OK, first check if mod_access in installed to apache, then add the following to your .htaccess:

Order Deny,Allow
Deny from all
Allow from 127.0.0.1

<Files /index.php>
    Order Allow,Deny
    Allow from all
</Files>

The first directive forbids access to any files except from localhost, because of Order Deny,Allow, Allow gets applied later, the second directive only affects index.php.

Caveat: No space after the comma in the Order line.

To allow access to files matching *.css or *.js use this directive:

<FilesMatch ".*\.(css|js)$">
    Order Allow,Deny
    Allow from all
</FilesMatch>

You cannot use directives for <Location> or <Directory> inside .htaccess files, though.

Your option would be to use <FilesMatch ".*\.php$"> around the first allow,deny group and then explicitely allow access to index.php.

Update for Apache 2.4: This answer is correct for Apache 2.2. In Apache 2.4 the access control paradigm has changed, and the correct syntax is to use Require all denied.

How do you develop Java Servlets using Eclipse?

You need to install a plugin, There is a free one from the eclipse foundation called the Web Tools Platform. It has all the development functionality that you'll need.

You can get the Java EE Edition of eclipse with has it pre-installed.

To create and run your first servlet:

  1. New... Project... Dynamic Web Project.
  2. Right click the project... New Servlet.
  3. Write some code in the doGet() method.
  4. Find the servers view in the Java EE perspective, it's usually one of the tabs at the bottom.
  5. Right click in there and select new Server.
  6. Select Tomcat X.X and a wizard will point you to finding the installation.
  7. Right click the server you just created and select Add and Remove... and add your created web project.
  8. Right click your servlet and select Run > Run on Server...

That should do it for you. You can use ant to build here if that's what you'd like but eclipse will actually do the build and automatically deploy the changes to the server. With Tomcat you might have to restart it every now and again depending on the change.

*ngIf and *ngFor on same element causing error

You can not use more than one Structural Directive in Angular on the same element, it makes a bad confusion and structure, so you need to apply them in 2 separate nested elements(or you can use ng-container), read this statement from Angular team:

One structural directive per host element

Someday you'll want to repeat a block of HTML but only when a particular condition is true. You'll try to put both an *ngFor and an *ngIf on the same host element. Angular won't let you. You may apply only one structural directive to an element.

The reason is simplicity. Structural directives can do complex things with the host element and its descendents. When two directives lay claim to the same host element, which one takes precedence? Which should go first, the NgIf or the NgFor? Can the NgIf cancel the effect of the NgFor? If so (and it seems like it should be so), how should Angular generalize the ability to cancel for other structural directives?

There are no easy answers to these questions. Prohibiting multiple structural directives makes them moot. There's an easy solution for this use case: put the *ngIf on a container element that wraps the *ngFor element. One or both elements can be an ng-container so you don't have to introduce extra levels of HTML.

So you can use ng-container (Angular4) as the wrapper (will be deleted from the dom) or a div or span if you have class or some other attributes as below:

<div class="right" *ngIf="show">
  <div *ngFor="let thing of stuff">
    {{log(thing)}}
    <span>{{thing.name}}</span>
  </div>
</div>

How to check string length with JavaScript

 var myString = 'sample String';   var length = myString.length ;

first you need to defined a keypressed handler or some kind of a event trigger to listen , btw , getting the length is really simple like mentioned above

Access XAMPP Localhost from Internet

I guess you can do this in 5 minute without any further IP/port forwarding, for presenting your local websites temporary.

All you need to do it, go to http://ngrok.com Download small tool extract and run that tool as administrator enter image description here

Enter command
ngrok http 80

You will see it will connect to server and will create a temporary URL for you which you can share to your friend and let him browse localhost or any of its folder.

You can see detailed process here.
How do I access/share xampp or localhost website from another computer

How can I replace a newline (\n) using sed?

gnu sed has an option -z for null separated records (lines). You can just call:

sed -z 's/\n/ /g'

iOS Simulator to test website on Mac

You could also download Xcode to your mac and use iPhone simulator.

Excel Looping through rows and copy cell values to another worksheet

Private Sub CommandButton1_Click() 

Dim Z As Long 
Dim Cellidx As Range 
Dim NextRow As Long 
Dim Rng As Range 
Dim SrcWks As Worksheet 
Dim DataWks As Worksheet 
Z = 1 
Set SrcWks = Worksheets("Sheet1") 
Set DataWks = Worksheets("Sheet2") 
Set Rng = EntryWks.Range("B6:ad6") 

NextRow = DataWks.UsedRange.Rows.Count 
NextRow = IIf(NextRow = 1, 1, NextRow + 1) 

For Each RA In Rng.Areas 
    For Each Cellidx In RA 
        Z = Z + 1 
        DataWks.Cells(NextRow, Z) = Cellidx 
    Next Cellidx 
Next RA 
End Sub

Alternatively

Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10") 

This is a CopynPaste - Method

Sub CopyDataToPlan()

Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean

On Error GoTo Err_Execute

'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value

Sheets("Plan").Select

'Start at column B
LColumn = 2
LFound = False

While LFound = False

  'Encountered blank cell in row 2, terminate search
  If Len(Cells(2, LColumn)) = 0 Then
     MsgBox "No matching date was found."
     Exit Sub

  'Found match in row 2
  ElseIf Cells(2, LColumn) = LDate Then

     'Select values to copy from "Rolling Plan" sheet
     Sheets("Rolling Plan").Select
     Range("B5:H6").Select
     Selection.Copy

     'Paste onto "Plan" sheet
     Sheets("Plan").Select
     Cells(3, LColumn).Select
     Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
     False, Transpose:=False

     LFound = True
     MsgBox "The data has been successfully copied."

     'Continue searching
      Else
         LColumn = LColumn + 1
      End If

   Wend

   Exit Sub

Err_Execute:
  MsgBox "An error occurred."

End Sub

And there might be some methods doing that in Excel.

Git submodule push

Note that since git1.7.11 ([ANNOUNCE] Git 1.7.11.rc1 and release note, June 2012) mentions:

"git push --recurse-submodules" learned to optionally look into the histories of submodules bound to the superproject and push them out.

Probably done after this patch and the --on-demand option:

recurse-submodules=<check|on-demand>::

Make sure all submodule commits used by the revisions to be pushed are available on a remote tracking branch.

  • If check is used, it will be checked that all submodule commits that changed in the revisions to be pushed are available on a remote.
    Otherwise the push will be aborted and exit with non-zero status.
  • If on-demand is used, all submodules that changed in the revisions to be pushed will be pushed.
    If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status.

So you could push everything in one go with (from the parent repo) a:

git push --recurse-submodules=on-demand

This option only works for one level of nesting. Changes to the submodule inside of another submodule will not be pushed.


With git 2.7 (January 2016), a simple git push will be enough to push the parent repo... and all its submodules.

See commit d34141c, commit f5c7cd9 (03 Dec 2015), commit f5c7cd9 (03 Dec 2015), and commit b33a15b (17 Nov 2015) by Mike Crowe (mikecrowe).
(Merged by Junio C Hamano -- gitster -- in commit 5d35d72, 21 Dec 2015)

push: add recurseSubmodules config option

The --recurse-submodules command line parameter has existed for some time but it has no config file equivalent.

Following the style of the corresponding parameter for git fetch, let's invent push.recurseSubmodules to provide a default for this parameter.
This also requires the addition of --recurse-submodules=no to allow the configuration to be overridden on the command line when required.

The most straightforward way to implement this appears to be to make push use code in submodule-config in a similar way to fetch.

The git config doc now include:

push.recurseSubmodules:

Make sure all submodule commits used by the revisions to be pushed are available on a remote-tracking branch.

  • If the value is 'check', then Git will verify that all submodule commits that changed in the revisions to be pushed are available on at least one remote of the submodule. If any commits are missing, the push will be aborted and exit with non-zero status.
  • If the value is 'on-demand' then all submodules that changed in the revisions to be pushed will be pushed. If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status. -
  • If the value is 'no' then default behavior of ignoring submodules when pushing is retained.

You may override this configuration at time of push by specifying '--recurse-submodules=check|on-demand|no'.

So:

git config push.recurseSubmodules on-demand
git push

Git 2.12 (Q1 2017)

git push --dry-run --recurse-submodules=on-demand will actually work.

See commit 0301c82, commit 1aa7365 (17 Nov 2016) by Brandon Williams (mbrandonw).
(Merged by Junio C Hamano -- gitster -- in commit 12cf113, 16 Dec 2016)

push run with --dry-run doesn't actually (Git 2.11 Dec. 2016 and lower/before) perform a dry-run when push is configured to push submodules on-demand.
Instead all submodules which need to be pushed are actually pushed to their remotes while any updates for the superproject are performed as a dry-run.
This is a bug and not the intended behaviour of a dry-run.

Teach push to respect the --dry-run option when configured to recursively push submodules 'on-demand'.
This is done by passing the --dry-run flag to the child process which performs a push for a submodules when performing a dry-run.


And still in Git 2.12, you now havea "--recurse-submodules=only" option to push submodules out without pushing the top-level superproject.

See commit 225e8bf, commit 6c656c3, commit 14c01bd (19 Dec 2016) by Brandon Williams (mbrandonw).
(Merged by Junio C Hamano -- gitster -- in commit 792e22e, 31 Jan 2017)

String comparison technique used by Python

Python string comparison is lexicographic:

From Python Docs: http://docs.python.org/reference/expressions.html

Strings are compared lexicographically using the numeric equivalents (the result of the built-in function ord()) of their characters. Unicode and 8-bit strings are fully interoperable in this behavior.

Hence in your example, 'abc' < 'bac', 'a' comes before (less-than) 'b' numerically (in ASCII and Unicode representations), so the comparison ends right there.

jQuery selector regular expressions

James Padolsey created a wonderful filter that allows regex to be used for selection.

Say you have the following div:

<div class="asdf">

Padolsey's :regex filter can select it like so:

$("div:regex(class, .*sd.*)")

Also, check the official documentation on selectors.

UPDATE: : syntax Deprecation JQuery 3.0

Since jQuery.expr[':'] used in Padolsey's implementation is already deprecated and will render a syntax error in the latest version of jQuery, here is his code adapted to jQuery 3+ syntax:

jQuery.expr.pseudos.regex = jQuery.expr.createPseudo(function (expression) {
    return function (elem) {
        var matchParams = expression.split(','),
            validLabels = /^(data|css):/,
            attr = {
                method: matchParams[0].match(validLabels) ?
                    matchParams[0].split(':')[0] : 'attr',
                property: matchParams.shift().replace(validLabels, '')
            },
            regexFlags = 'ig',
            regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g, ''), regexFlags);
        return regex.test(jQuery(elem)[attr.method](attr.property));
    }
});

fitting data with numpy

Note that you can use the Polynomial class directly to do the fitting and return a Polynomial instance.

from numpy.polynomial import Polynomial

p = Polynomial.fit(x, y, 4)
plt.plot(*p.linspace())

p uses scaled and shifted x values for numerical stability. If you need the usual form of the coefficients, you will need to follow with

pnormal = p.convert(domain=(-1, 1))

How to install Guest addition in Mac OS as guest and Windows machine as host

You can use SSH and SFTP as suggested here.

  1. In the Guest OS (Mac OS X), open System Preferences > Sharing, then activate Remote Login; note the ip address specified in the Remote Login instructions, e.g. ssh [email protected]
  2. In VirtualBox, open Devices > Network > Network Settings > Advanced > Port Forwarding and specify Host IP = 127.0.0.1, Host Port 2222, Guest IP 10.0.2.15, Guest Port 22
  3. On the Host OS, run the following command sftp -P 2222 [email protected]; if you prefer a graphical interface, you can use FileZilla

Replace user and 10.0.2.15 with the appropriate values relevant to your configuration.

Get Selected Item Using Checkbox in Listview

[Custom ListView with CheckBox]

If customlayout use checkbox, you must set checkbox focusable = false

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <TextView android:id="@+id/rowTextView" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:textSize="16sp" >
  </TextView>

  <CheckBox android:id="@+id/CheckBox01" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:padding="10dp"
    android:layout_alignParentRight="true" 
    android:layout_marginRight="6sp"
    android:focusable="false">           // <---important
  </CheckBox>

</RelativeLayout>

Readmore : A ListView with Checkboxes (Without Using ListActivity)

Hot deploy on JBoss - how do I make JBoss "see" the change?

Hot deployment is stable only for changes on static parts of the application (jsf, xhtml, etc.).

Here is a working solution, according to JBoss AS 7.1.1.Final:

  • Build your project.
  • Navigate to [JBOSS_HOME]/standalone/tmp/vfs.
  • Open the most recently modified folder named "deployment[some_alphanumeric_values]", i.e. "deployment344b1c870c8edbd".
  • Navigate to the specific view that you want to edit (usually, this is included into the packaged .war folder) and open it with a text editor (i.e. Notepad++).
  • Make the changes you want and save the file.
  • Refresh the respective page on your browser. The changes should be visible now.
  • When finished, don't forget to copy these changes to your actual development environment, rebuild and redeploy.

    Set a border around a StackPanel.

    What about this one :

    <DockPanel Margin="8">
        <Border CornerRadius="6" BorderBrush="Gray" Background="LightGray" BorderThickness="2" DockPanel.Dock="Top">
            <StackPanel Orientation="Horizontal">
                <TextBlock FontSize="14" Padding="0 0 8 0" HorizontalAlignment="Center" VerticalAlignment="Center">Search:</TextBlock>
                <TextBox x:Name="txtSearchTerm" HorizontalAlignment="Center" VerticalAlignment="Center" />
                <Image Source="lock.png" Width="32" Height="32" HorizontalAlignment="Center" VerticalAlignment="Center" />            
            </StackPanel>
        </Border>
        <StackPanel Orientation="Horizontal" DockPanel.Dock="Bottom" Height="25" />
    </DockPanel>
    

    How to find serial number of Android device?

    There are problems with all the above approaches. At Google i/o Reto Meier released a robust answer to how to approach this which should meet most developers needs to track users across installations.

    This approach will give you an anonymous, secure user ID which will be persistent for the user across different devices (including tablets, based on primary Google account) and across installs on the same device. The basic approach is to generate a random user ID and to store this in the apps shared preferences. You then use Google's backup agent to store the shared preferences linked to the Google account in the cloud.

    Lets go through the full approach. First we need to create a backup for our SharedPreferences using the Android Backup Service. Start by registering your app via this link: http://developer.android.com/google/backup/signup.html

    Google will give you a backup service key which you need to add to the manifest. You also need to tell the application to use the BackupAgent as follows:

    <application android:label="MyApplication"
             android:backupAgent="MyBackupAgent">
        ...
        <meta-data android:name="com.google.android.backup.api_key"
            android:value="your_backup_service_key" />
    </application>
    

    Then you need to create the backup agent and tell it to use the helper agent for sharedpreferences:

    public class MyBackupAgent extends BackupAgentHelper {
        // The name of the SharedPreferences file
        static final String PREFS = "user_preferences";
    
        // A key to uniquely identify the set of backup data
        static final String PREFS_BACKUP_KEY = "prefs";
    
        // Allocate a helper and add it to the backup agent
        @Override
        public void onCreate() {
            SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this,          PREFS);
            addHelper(PREFS_BACKUP_KEY, helper);
        }
    }
    

    To complete the backup you need to create an instance of BackupManager in your main Activity:

    BackupManager backupManager = new BackupManager(context);
    

    Finally create a user ID, if it doesn't already exist, and store it in the SharedPreferences:

      public static String getUserID(Context context) {
                private static String uniqueID = null;
            private static final String PREF_UNIQUE_ID = "PREF_UNIQUE_ID";
        if (uniqueID == null) {
            SharedPreferences sharedPrefs = context.getSharedPreferences(
                    MyBackupAgent.PREFS, Context.MODE_PRIVATE);
            uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
            if (uniqueID == null) {
                uniqueID = UUID.randomUUID().toString();
                Editor editor = sharedPrefs.edit();
                editor.putString(PREF_UNIQUE_ID, uniqueID);
                editor.commit();
    
                //backup the changes
                BackupManager mBackupManager = new BackupManager(context);
                mBackupManager.dataChanged();
            }
        }
    
        return uniqueID;
    }
    

    This User_ID will now be persistent across installations, even if the user switches devices.

    For more information on this approach see Reto's talk here http://www.google.com/events/io/2011/sessions/android-protips-advanced-topics-for-expert-android-app-developers.html

    And for full details of how to implement the backup agent see the developer site here: http://developer.android.com/guide/topics/data/backup.html I particularly recommend the section at the bottom on testing as the backup does not happen instantaneously and so to test you have to force the backup.

    Maximum number of rows in an MS Access database engine table?

    It's been some years since I last worked with Access but larger database files always used to have more problems and be more prone to corruption than smaller files.

    Unless the database file is only being accessed by one person or stored on a robust network you may find this is a problem before the 2GB database size limit is reached.

    Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

    DevOps is a combination of 3C's - continuous, communication, collaboration and this lead to prime focus in various industries.

    In an IoT connected devices world, multiple scrum features like product owner, web, mobile and QA working in an agile manner in a scrum of scrum cycle to deliver a product to end customer.

    Continuous integration: Multiple scrum feature working simultanrouly in multiple endpoints

    Continuous delivery: With integration and deployment, delivery of product to multiple customers to be handled at the same time.

    Continuous deployment: multiple products deployed to multiple customers at multiple platform.

    Watch this to know how DevOps enabling IoT connected world: https://youtu.be/nAfZt2t4HqA

    Java Enum return Int

    If you need to get the int value, just have a getter for the value in your ENUM:

    private enum DownloadType {
        AUDIO(1), VIDEO(2), AUDIO_AND_VIDEO(3);
        private final int value;
    
        private DownloadType(int value) {
            this.value = value;
        }
    
        public int getValue() {
            return value;
        }
    }
    
    public static void main(String[] args) {
        System.out.println(DownloadType.AUDIO.getValue());           //returns 1
        System.out.println(DownloadType.VIDEO.getValue());           //returns 2
        System.out.println(DownloadType.AUDIO_AND_VIDEO.getValue()); //returns 3
    }
    

    Or you could simple use the ordinal() method, which would return the position of the enum constant in the enum.

    private enum DownloadType {
        AUDIO(0), VIDEO(1), AUDIO_AND_VIDEO(2);
        //rest of the code
    }
    
    System.out.println(DownloadType.AUDIO.ordinal());            //returns 0
    System.out.println(DownloadType.VIDEO.ordinal());            //returns 1
    System.out.println(DownloadType.AUDIO_AND_VIDEO.ordinal()); //returns 2
    

    T-SQL: Opposite to string concatenation - how to split string into multiple records

    SELECT substring(commaSeparatedTags,0,charindex(',',commaSeparatedTags))
    

    will give you the first tag. You can proceed similarly to get the second one and so on by combining substring and charindex one layer deeper each time. That's an immediate solution but it works only with very few tags as the query grows very quickly in size and becomes unreadable. Move on to functions then, as outlined in other, more sophisticated answers to this post.

    MySQL show current connection info

    There are MYSQL functions you can use. Like this one that resolves the user:

    SELECT USER();
    

    This will return something like root@localhost so you get the host and the user.

    To get the current database run this statement:

    SELECT DATABASE();
    

    Other useful functions can be found here: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html

    Is there a git-merge --dry-run option?

    I use git log to see what has changed on a feature branch from master branch

    git log does_this_branch..contain_this_branch_changes
    

    e.g. - to see what commits are in a feature branch that has/not been merged to master:

    git log master..feature_branch
    

    Using XPATH to search text containing &nbsp;

    Bear in mind that a standards-compliant XML processor will have replaced any entity references other than XML's five standard ones (&amp;, &gt;, &lt;, &apos;, &quot;) with the corresponding character in the target encoding by the time XPath expressions are evaluated. Given that behavior, PhiLho's and jsulak's suggestions are the way to go if you want to work with XML tools. When you enter &#160; in the XPath expression, it should be converted to the corresponding byte sequence before the XPath expression is applied.

    How to copy java.util.list Collection

    You may create a new list with an input of a previous list like so:

    List one = new ArrayList()
    //... add data, sort, etc
    List two = new ArrayList(one);
    

    This will allow you to modify the order or what elemtents are contained independent of the first list.

    Keep in mind that the two lists will contain the same objects though, so if you modify an object in List two, the same object will be modified in list one.

    example:

    MyObject value1 = one.get(0);
    MyObject value2 = two.get(0);
    value1 == value2 //true
    value1.setName("hello");
    value2.getName(); //returns "hello"
    

    Edit

    To avoid this you need a deep copy of each element in the list like so:

    List<Torero> one = new ArrayList<Torero>();
    //add elements
    
    List<Torero> two = new Arraylist<Torero>();
    for(Torero t : one){
        Torero copy = deepCopy(t);
        two.add(copy);
    }
    

    with copy like the following:

    public Torero deepCopy(Torero input){
        Torero copy = new Torero();
        copy.setValue(input.getValue());//.. copy primitives, deep copy objects again
    
        return copy;
    }
    

    How do I return a char array from a function?

    When you create local variables inside a function that are created on the stack, they most likely get overwritten in memory when exiting the function.

    So code like this in most C++ implementations will not work:

    char[] populateChar()
    {
        char* ch = "wonet return me";
        return ch;
    }
    

    A fix is to create the variable that want to be populated outside the function or where you want to use it, and then pass it as a parameter and manipulate the function, example:

    void populateChar(char* ch){
        strcpy(ch, "fill me, Will. This will stay", size); // This will work as long as it won't overflow it.
    }
    
    int main(){
        char ch[100]; // Reserve memory on the stack outside the function
        populateChar(ch); // Populate the array
    }
    

    A C++11 solution using std::move(ch) to cast lvalues to rvalues:

    void populateChar(char* && fillme){
        fillme = new char[20];
        strcpy(fillme, "this worked for me");
    }
    
    int main(){
        char* ch;
        populateChar(std::move(ch));
        return 0;
    }
    

    Or this option in C++11:

    char* populateChar(){
        char* ch = "test char";
        // Will change from lvalue to r value
        return std::move(ch);
    }
    
    int main(){
        char* ch = populateChar();
        return 0;
    }
    

    Why is a div with "display: table-cell;" not affected by margin?

    Table cells don't respect margin, but you could use transparent borders instead:

    div {
      display: table-cell;
      border: 5px solid transparent;
    }
    

    Note: you can't use percentages here... :(

    How can I read a large text file line by line using Java?

    Look at this blog:

    The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

    // Open the file
    FileInputStream fstream = new FileInputStream("textfile.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
    
    String strLine;
    
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
      System.out.println (strLine);
    }
    
    //Close the input stream
    fstream.close();
    

    Angular2 RC6: '<component> is not a known element'

    I was facing this issue on Angular 7 and the problem was after creating the module, I did not perform ng build. So I performed -

    • ng build
    • ng serve

    and it worked.

    How to allow only numbers in textbox in mvc4 razor

    This worked for me :

    <input type="text" class="numericOnly" placeholder="Search" id="txtSearch">
    

    Javacript:

    //Allow users to enter numbers only
    $(".numericOnly").bind('keypress', function (e) {
        if (e.keyCode == '9' || e.keyCode == '16') {
            return;
        }
        var code;
        if (e.keyCode) code = e.keyCode;
        else if (e.which) code = e.which;
        if (e.which == 46)
            return false;
        if (code == 8 || code == 46)
            return true;
        if (code < 48 || code > 57)
            return false;
    });
    
    //Disable paste
    $(".numericOnly").bind("paste", function (e) {
        e.preventDefault();
    });
    
    $(".numericOnly").bind('mouseenter', function (e) {
        var val = $(this).val();
        if (val != '0') {
            val = val.replace(/[^0-9]+/g, "")
            $(this).val(val);
        }
    });
    

    api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

    While the answer from alireza is correct, it has one gotcha:

    You can't install Microsoft Visual C++ 2015 redist (runtime) unless you have Windows Update KB2999226 installed (at least on Windows 7 64-bit SP1).

    List All Google Map Marker Images

    var pinIcon = new google.maps.MarkerImage(
        "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
        null, /* size is determined at runtime */
        null, /* origin is 0,0 */
        null, /* anchor is bottom center of the scaled image */
        new google.maps.Size(12, 18)
    );
    

    How can I sort one set of data to match another set of data in Excel?

    You could also use INDEX MATCH, which is more "powerful" than vlookup. This would give you exactly what you are looking for:

    enter image description here

    Multiple inputs on one line

    Yes, you can.

    From cplusplus.com:

    Because these functions are operator overloading functions, the usual way in which they are called is:

       strm >> variable;
    

    Where strm is the identifier of a istream object and variable is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:

       strm >> variable1 >> variable2 >> variable3; //...
    

    which is the same as performing successive extractions from the same object strm.

    Just replace strm with cin.

    MySQL: determine which database is selected?

    SELECT DATABASE();
    

    p.s. I didn't want to take the liberty of modifying @cwallenpoole's answer to reflect the fact that this is a MySQL question and not an Oracle question and doesn't need DUAL.

    javac error: Class names are only accepted if annotation processing is explicitly requested

    I learned that you also can get this error by storing the source file in a folder named Java

    Draw a curve with css

    You could use an asymmetrical border to make curves with CSS.

    border-radius: 50%/100px 100px 0 0;

    VIEW DEMO

    _x000D_
    _x000D_
    .box {_x000D_
      width: 500px; _x000D_
      height: 100px;  _x000D_
      border: solid 5px #000;_x000D_
      border-color: #000 transparent transparent transparent;_x000D_
      border-radius: 50%/100px 100px 0 0;_x000D_
    }
    _x000D_
    <div class="box"></div>
    _x000D_
    _x000D_
    _x000D_

    SyntaxError: import declarations may only appear at top level of a module

    I got this on Firefox (FF58). I fixed this with:

    1. It is still experimental on Firefox (from v54): You have to set to true the variable dom.moduleScripts.enabled in about:config

    Source: Import page on mozilla (See Browser compatibility)

    1. Add type="module" to your script tag where you import the js file

    <script type="module" src="appthatimports.js"></script>

    1. Import files have to be prefixed (./, /, ../ or http:// before)

    import * from "./mylib.js"

    For more examples, this blog post is good.

    How can you remove all documents from a collection with Mongoose?

    MongoDB shell version v4.2.6
    Node v14.2.0

    Assuming you have a Tour Model: tourModel.js

    const mongoose = require('mongoose');
    
    const tourSchema = new mongoose.Schema({
      name: {
        type: String,
        required: [true, 'A tour must have a name'],
        unique: true,
        trim: true,
      },
      createdAt: {
        type: Date,
        default: Date.now(),
      },
    });
    const Tour = mongoose.model('Tour', tourSchema);
    
    module.exports = Tour;
    

    Now you want to delete all tours at once from your MongoDB, I also providing connection code to connect with the remote cluster. I used deleteMany(), if you do not pass any args to deleteMany(), then it will delete all the documents in Tour collection.

    const mongoose = require('mongoose');
    const Tour = require('./../../models/tourModel');
    const conStr = 'mongodb+srv://lord:<PASSWORD>@cluster0-eeev8.mongodb.net/tour-guide?retryWrites=true&w=majority';
    const DB = conStr.replace('<PASSWORD>','ADUSsaZEKESKZX');
    mongoose.connect(DB, {
        useNewUrlParser: true,
        useCreateIndex: true,
        useFindAndModify: false,
        useUnifiedTopology: true,
      })
      .then((con) => {
        console.log(`DB connection successful ${con.path}`);
      });
    
    const deleteAllData = async () => {
      try {
        await Tour.deleteMany();
        console.log('All Data successfully deleted');
      } catch (err) {
        console.log(err);
      }
    };
    

    When to use MongoDB or other document oriented database systems?

    Like said previously, you can choose between a lot of choices, take a look at all those choices: http://kkovacs.eu/cassandra-vs-mongodb-vs-couchdb-vs-redis

    What I suggest is to find your best combination: MySQL + Memcache is really great if you need ACID and you want to join some tables MongoDB + Redis is perfect for document store Neo4J is perfect for graph database

    What i do: I start with MySQl + Memcache because I'm use to, then I start using others database framework. In a single project, you can combine MySQL and MongoDB for instance !

    Load external css file like scripts in jquery which is compatible in ie also

    Based on your comment under @Raul's answer, I can think of two ways to include a callback:

    1. Have getScript call the file that loads the css.
    2. Load the contents of the css file with AJAX, and append to <style>. Your callback would be the callback from $.get or whatever you use to load the css file contents.

    Check whether a table contains rows or not sql server 2005

    For what purpose?

    • Quickest for an IF would be IF EXISTS (SELECT * FROM Table)...
    • For a result set, SELECT TOP 1 1 FROM Table returns either zero or one rows
    • For exactly one row with a count (0 or non-zero), SELECT COUNT(*) FROM Table

    Is there an equivalent to background-size: cover and contain for image elements?

    What you could do is use the 'style' attribute to add the background image to the element, that way you will still be calling the image in the HTML but you will still be able to use the background-size: cover css behaviour:

    HTML:

        <div class="image-div" style="background-image:url(yourimage.jpg)">
        </div>
    

    CSS:

        .image-div{
        background-size: cover;
        }
    

    This is how I add the background-size: cover behaviour to elements that I need to dynamically load into HTML. You can then use awesome css classes like background-position: center. boom

    Good Hash Function for Strings

    here's a link that explains many different hash functions, for now I prefer the ELF hash function for your particular problem. It takes as input a string of arbitrary length.

    TypeError: list indices must be integers or slices, not str

    I had same error and the mistake was that I had added list and dictionary into the same list (object) and when I used to iterate over the list of dictionaries and use to hit a list (type) object then I used to get this error.

    Its was a code error and made sure that I only added dictionary objects to that list and list typed object into the list, this solved my issue as well.

    Proper use of mutexes in Python

    I don't know why you're using the Window's Mutex instead of Python's. Using the Python methods, this is pretty simple:

    from threading import Thread, Lock
    
    mutex = Lock()
    
    def processData(data):
        mutex.acquire()
        try:
            print('Do some stuff')
        finally:
            mutex.release()
    
    while True:
        t = Thread(target = processData, args = (some_data,))
        t.start()
    

    But note, because of the architecture of CPython (namely the Global Interpreter Lock) you'll effectively only have one thread running at a time anyway--this is fine if a number of them are I/O bound, although you'll want to release the lock as much as possible so the I/O bound thread doesn't block other threads from running.

    An alternative, for Python 2.6 and later, is to use Python's multiprocessing package. It mirrors the threading package, but will create entirely new processes which can run simultaneously. It's trivial to update your example:

    from multiprocessing import Process, Lock
    
    mutex = Lock()
    
    def processData(data):
        with mutex:
            print('Do some stuff')
    
    if __name__ == '__main__':
        while True:
            p = Process(target = processData, args = (some_data,))
            p.start()
    

    Number of regex matches

    If you know you will want all the matches, you could use the re.findall function. It will return a list of all the matches. Then you can just do len(result) for the number of matches.

    html/css buttons that scroll down to different div sections on a webpage

    try this:

    <input type="button" onClick="document.getElementById('middle').scrollIntoView();" />
    

    How to create a multiline UITextfield?

    If you must have a UITextField with 2 lines of text, one option is to add a UILabel as a subview of the UITextField for the second line of text. I have a UITextField in my app that users often do not realize is editable by tapping, and I wanted to add some small subtitle text that says "Tap to Edit" to the UITextField.

    CGFloat tapLlblHeight = 10;
    UILabel *tapEditLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, textField.frame.size.height - tapLlblHeight - 2, 70, tapLlblHeight)];
    tapEditLbl.backgroundColor = [UIColor clearColor];
    tapEditLbl.textColor = [UIColor whiteColor];
    tapEditLbl.text = @"Tap to Edit";
    
    [textField addSubview:tapEditLbl];
    

    Why is document.body null in my javascript?

    Add your code to the onload event. The accepted answer shows this correctly, however that answer as well as all the others at the time of writing also suggest putting the script tag after the closing body tag, .

    This is not valid html. However it will cause your code to work, because browsers are too kind ;)

    See this answer for more info Is it wrong to place the <script> tag after the </body> tag?

    Downvoted other answers for this reason.

    Seeking useful Eclipse Java code templates

    I like a generated class comment like this:

    /**
     * I... 
     * 
     * $Id$
     */
    

    The "I..." immediately encourages the developer to describe what the class does. I does seem to improve the problem of undocumented classes.

    And of course the $Id$ is a useful CVS keyword.

    Difference between Eclipse Europa, Helios, Galileo

    In Galileo and Helios Provisioning Platform were introduced, and non-update-site plugins now should be placed in "dropins" subfolder ("eclipse/dropins/plugin_name/features", "eclipse/dropins/plugin_name/plugins") instead of Eclipse's folder ("eclipse/features" and "eclipse/plugins").

    Also for programming needs the best Eclipse is the latest Eclipse. It has too many bugs for now, and all the Eclipse team is now doing is fixing the bugs. There are very few interface enhancements since Europa. IMHO.

    phpmyadmin logs out after 1440 secs

    You will then get another warning: “Your PHP parameter session.gc_maxlifetime is lower that cookie validity configured in phpMyAdmin, because of this, your login will expire sooner than configured in phpMyAdmin.“. That makes sense because php’s session will time out first anyways. So we will need to change /etc/php.ini .

    session.gc_maxlifetime = 43200
    That’s 12 hours in seconds. 
    

    Restart your apache server and you are done!

    source: http://birdchan.com/home/2011/06/06/phpmyadmin-timeout-after-1440-seconds/

    this works for me! :)

    Error: Cannot Start Container: stat /bin/sh: no such file or directory"

    You have no shell at /bin/sh? Have you tried docker run -it pensu/busybox /usr/bin/sh ?

    Check if null Boolean is true results in exception

    If you don't like extra null checks:

    if (Boolean.TRUE.equals(value)) {...}
    

    Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

    By converting the matrix to array by using

    n12 = np.squeeze(np.asarray(n2))
    
    X12 = np.squeeze(np.asarray(x1))
    

    solved the issue.

    Storing image in database directly or as base64 data?

    I came across this really great talk by Facebook engineers about the Efficient Storage of Billions of Photos in a database

    XPath: Get parent node from child node

    Just as an alternative, you can use ancestor.

    //*[title="50"]/ancestor::store
    

    It's more powerful than parent since it can get even the grandparent or great great grandparent

    Listening for variable changes in JavaScript

    Not directly: you need a pair getter/setter with an "addListener/removeListener" interface of some sort... or an NPAPI plugin (but that's another story altogether).

    How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

    the below lines would also work

    !python script.py
    

    PostgreSQL wildcard LIKE for any of a list of words

    Actually there is an operator for that in PostgreSQL:

    SELECT *
    FROM table
    WHERE lower(value) ~~ ANY('{%foo%,%bar%,%baz%}');
    

    Log to the base 2 in python

    >>> def log2( x ):
    ...     return math.log( x ) / math.log( 2 )
    ... 
    >>> log2( 2 )
    1.0
    >>> log2( 4 )
    2.0
    >>> log2( 8 )
    3.0
    >>> log2( 2.4 )
    1.2630344058337937
    >>> 
    

    Is there a way to delete all the data from a topic or delete the topic before every run?

    For brew users

    If you're using brew like me and wasted a lot of time searching for the infamous kafka-logs folder, fear no more. (and please do let me know if that works for you and multiple different versions of Homebrew, Kafka etc :) )

    You're probably going to find it under:

    Location:

    /usr/local/var/lib/kafka-logs


    How to actually find that path

    (this is also helpful for basically every app you install through brew)

    1) brew services list

    kafka started matbhz /Users/matbhz/Library/LaunchAgents/homebrew.mxcl.kafka.plist

    2) Open and read that plist you found above

    3) Find the line defining server.properties location open it, in my case:

    • /usr/local/etc/kafka/server.properties

    4) Look for the log.dirs line:

    log.dirs=/usr/local/var/lib/kafka-logs

    5) Go to that location and delete the logs for the topics you wish

    6) Restart Kafka with brew services restart kafka

    Combining INSERT INTO and WITH/CTE

    You need to put the CTE first and then combine the INSERT INTO with your select statement. Also, the "AS" keyword following the CTE's name is not optional:

    WITH tab AS (
        bla bla
    )
    INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos (
    BatchID,
    AccountNo,
    APartyNo,
    SourceRowID
    )  
    SELECT * FROM tab
    

    Please note that the code assumes that the CTE will return exactly four fields and that those fields are matching in order and type with those specified in the INSERT statement. If that is not the case, just replace the "SELECT *" with a specific select of the fields that you require.

    As for your question on using a function, I would say "it depends". If you are putting the data in a table just because of performance reasons, and the speed is acceptable when using it through a function, then I'd consider function to be an option. On the other hand, if you need to use the result of the CTE in several different queries, and speed is already an issue, I'd go for a table (either regular, or temp).

    WITH common_table_expression (Transact-SQL)

    Bootstrap 3 Carousel Not Working

    For me, the carousel wasn't working in the DreamWeaver CC provided the code in the "template" page I am playing with. I needed to add the data-ride="carousel" attribute to the carousel div in order for it to start working. Thanks to Adarsh for his code snippet which highlighted the missing attribute.

    How does one make random number between range for arc4random_uniform()?

    The answer is just 1 line code:

    let randomNumber = arc4random_uniform(8999) + 1000 //for 4 digit random number
    let randomNumber = arc4random_uniform(899999999) + 100000000 //for 9 digit random number
    let randomNumber = arc4random_uniform(89) + 10    //for 2 digit random number
    let randomNumber = arc4random_uniform(899) + 100  //for 3 digit random number
    

    The alternate solution is:

        func generateRandomNumber(numDigits: Int) -> Int{
        var place = 1
        var finalNumber = 0;
        var finanum = 0;
        for var i in 0 ..< numDigits {
            place *= 10
            let randomNumber = arc4random_uniform(10)         
            finalNumber += Int(randomNumber) * place
            finanum = finalNumber / 10
               i += 1
        }
        return finanum
    }
    

    Although the drawback is that number cannot start from 0.

    How is the AND/OR operator represented as in Regular Expressions?

    Not an expert in regex, but you can do ^((part1|part2)|(part1, part2))$. In words: "part 1 or part2 or both"

    T-SQL STOP or ABORT command in SQL Server

    Why not simply add the following to the beginning of the script

    PRINT 'INACTIVE SCRIPT'
    RETURN
    

    How to properly make a http web GET request

    var request = (HttpWebRequest)WebRequest.Create("sendrequesturl");
    var response = (HttpWebResponse)request.GetResponse();
    string responseString;
    using (var stream = response.GetResponseStream())
    {
        using (var reader = new StreamReader(stream))
        {
            responseString = reader.ReadToEnd();
        }
    }
    

    Explain ggplot2 warning: "Removed k rows containing missing values"

    Just for the shake of completing the answer given by eipi10.

    I was facing the same problem, without using scale_y_continuous nor coord_cartesian.

    The conflict was coming from the x axis, where I defined limits = c(1, 30). It seems such limits do not provide enough space if you want to "dodge" your bars, so R still throws the error

    Removed 8 rows containing missing values (geom_bar)

    Adjusting the limits of the x axis to limits = c(0, 31) solved the problem.

    In conclusion, even if you are not putting limits to your y axis, check out your x axis' behavior to ensure you have enough space

    sqlalchemy filter multiple columns

    You can use SQLAlchemy's or_ function to search in more than one column (the underscore is necessary to distinguish it from Python's own or).

    Here's an example:

    from sqlalchemy import or_
    query = meta.Session.query(User).filter(or_(User.firstname.like(searchVar),
                                                User.lastname.like(searchVar)))
    

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

    I had this problem as well on two different Windows computers when communicating with a Arduino Leonardo. The reliable solution was:

    • Find the COM port in device manager and open the device properties.
    • Open the "Port Settings" tab, and click the advanced button.
    • There, uncheck the box "Use FIFO buffers (required 16550 compatible UART), and press OK.

    Unfortunately, I don't know what this feature does, or how it affects this issue. After several PC restarts and a dozen device connection cycles, this is the only thing that reliably fixed the issue.

    What does <? php echo ("<pre>"); ..... echo("</pre>"); ?> mean?

    I think you're talking about <pre></pre>. element is displayed in a fixed-width font, and it preserves both spaces and line breaks.

    try printing an array with a **<pre>** and whitout **<pre>**

    $arr = array(1, 2, 3);
    
    echo '<pre>';
    print_r($arr);
    echo '</pre>';
    
    print_r($arr); 
    

    How to start IDLE (Python editor) without using the shortcut on Windows Vista?

    there is a .bat script to start it (python 2.7).

    c:\Python27\Lib\idlelib\idle.bat
    

    How do I convert an array object to a string in PowerShell?

    You could specify type like this:

    [string[]] $a = "This", "Is", "a", "cat"
    

    Checking the type:

    $a.GetType()
    

    Confirms:

        IsPublic IsSerial Name                                     BaseType
        -------- -------- ----                                     --------
        True     True     String[]                                 System.Array
    

    Outputting $a:

    PS C:\> $a 
    This 
    Is 
    a 
    cat
    

    Upgrade python without breaking yum

    I recommend, instead, updating the path in the associated script(s) (such as /usr/bin/yum) to point at your previous Python as the interpreter.

    Ideally, you want to upgrade yum and its associated scripts so that they are supported by the default Python installed.

    If that is not possible, the above is entirely workable and tested.

    Change:

    #!/usr/bin/python
    

    to whatever the path is of your old version until you can make the above yum improvement.

    Cases where you couldn't do the above are if you have an isolated machine, don't have the time to upgrade rpm manually or can't connect temporarily or permanently to a standard yum repository.

    Why use String.Format?

    I can see a number of reasons:

    Readability

    string s = string.Format("Hey, {0} it is the {1}st day of {2}.  I feel {3}!", _name, _day, _month, _feeling);
    

    vs:

    string s = "Hey," + _name + " it is the " + _day + "st day of " + _month + ".  I feel " + feeling + "!";
    

    Format Specifiers (and this includes the fact you can write custom formatters)

    string s = string.Format("Invoice number: {0:0000}", _invoiceNum);
    

    vs:

    string s = "Invoice Number = " + ("0000" + _invoiceNum).Substr(..... /*can't even be bothered to type it*/)
    

    String Template Persistence

    What if I want to store string templates in the database? With string formatting:

    _id         _translation
      1         Welcome {0} to {1}.  Today is {2}.
      2         You have {0} products in your basket.
      3         Thank-you for your order.  Your {0} will arrive in {1} working days.
    

    vs:

    _id         _translation
      1         Welcome
      2         to
      3         .  Today is
      4         . 
      5         You have
      6         products in your basket.
      7         Someone
      8         just shoot
      9         the developer.
    

    how to get file path from sd card in android

    maybe you are having the same problem i had, my tablet has a SD card on it, in /mnt/sdcard and the sd card external was in /mnt/extcard, you can look it on the android file manager, going to your sd card and see the path to it.

    Hope it helps.

    org.hibernate.MappingException: Unknown entity

    I encountered the same problem when I switched to AnnotationSessionFactoryBean. I was using entity.hbm.xml before.

    I found that My class was missing following annotation which resolved the issue in my case:

    @Entity
    @Table(name = "MyTestEntity")
    @XmlRootElement
    

    How do I format a number to a dollar amount in PHP

    i tried money_format() but it didn't work for me at all. then i tried the following one. it worked perfect for me. hopefully it will work in right way for you too.. :)

    you should use this one

    number_format($money, 2,'.', ',')
    

    it will show money number in terms of money format up to 2 decimal.

    Remove the last three characters from a string

    read last 3 characters from string [Initially asked question]

    You can use string.Substring and give it the starting index and it will get the substring starting from given index till end.

    myString.Substring(myString.Length-3)
    

    Retrieves a substring from this instance. The substring starts at a specified character position. MSDN

    Edit, for updated post

    Remove last 3 characters from string [Updated question]

    To remove the last three characters from the string you can use string.Substring(Int32, Int32) and give it the starting index 0 and end index three less than the string length. It will get the substring before last three characters.

    myString = myString.Substring(0, myString.Length-3);
    

    String.Substring Method (Int32, Int32)

    Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.

    You can also using String.Remove(Int32) method to remove the last three characters by passing start index as length - 3, it will remove from this point to end of string.

    myString = myString.Remove(myString.Length-3)
    

    String.Remove Method (Int32)

    Returns a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted

    Error in launching AVD with AMD processor

    For AMD processors:

    You don't need Genymotion, just create a new Virtual Device and while selecting the system Image select the ABI as armeabi instead of the default x86 one.

    enter image description here

    What does the clearfix class do in css?

    When an element, such as a div is floated, its parent container no longer considers its height, i.e.

    <div id="main">
      <div id="child" style="float:left;height:40px;"> Hi</div>
    </div>
    

    The parent container will not be be 40 pixels tall by default. This causes a lot of weird little quirks if you're using these containers to structure layout.

    So the clearfix class that various frameworks use fixes this problem by making the parent container "acknowledge" the contained elements.

    Day to day, I normally just use frameworks such as 960gs, Twitter Bootstrap for laying out and not bothering with the exact mechanics.

    Can read more here

    http://www.webtoolkit.info/css-clearfix.html

    How to prepare a Unity project for git?

    Since Unity 4.3 you also have to enable External option from preferences, so full setup process looks like:

    1. Enable External option in Unity ? Preferences ? Packages ? Repository
    2. Switch to Hidden Meta Files in Editor ? Project Settings ? Editor ? Version Control Mode
    3. Switch to Force Text in Editor ? Project Settings ? Editor ? Asset Serialization Mode
    4. Save scene and project from File menu

    Note that the only folders you need to keep under source control are Assets and ProjectSettigns.

    More information about keeping Unity Project under source control you can find in this post.

    Check if Cell value exists in Column, and then get the value of the NEXT Cell

    How about this?

    =IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", INDIRECT(ADDRESS(MATCH(A1,B:B, 0), 3)))
    

    The "3" at the end means for column C.

    C++ multiline string literal

    In C++11 you have raw string literals. Sort of like here-text in shells and script languages like Python and Perl and Ruby.

    const char * vogon_poem = R"V0G0N(
                 O freddled gruntbuggly thy micturations are to me
                     As plured gabbleblochits on a lurgid bee.
                  Groop, I implore thee my foonting turlingdromes.   
               And hooptiously drangle me with crinkly bindlewurdles,
    Or I will rend thee in the gobberwarts with my blurlecruncheon, see if I don't.
    
                    (by Prostetnic Vogon Jeltz; see p. 56/57)
    )V0G0N";
    

    All the spaces and indentation and the newlines in the string are preserved.

    These can also be utf-8|16|32 or wchar_t (with the usual prefixes).

    I should point out that the escape sequence, V0G0N, is not actually needed here. Its presence would allow putting )" inside the string. In other words, I could have put

                    "(by Prostetnic Vogon Jeltz; see p. 56/57)"
    

    (note extra quotes) and the string above would still be correct. Otherwise I could just as well have used

    const char * vogon_poem = R"( ... )";
    

    The parens just inside the quotes are still needed.

    PL/pgSQL checking if a row exists

    Simpler, shorter, faster: EXISTS.

    IF EXISTS (SELECT 1 FROM people p WHERE p.person_id = my_person_id) THEN
      -- do something
    END IF;
    

    The query planner can stop at the first row found - as opposed to count(), which will scan all matching rows regardless. Makes a difference with big tables. Hardly matters with a condition on a unique column - only one row qualifies anyway (and there is an index to look it up quickly).

    Improved with input from @a_horse_with_no_name in the comments below.

    You could even use an empty SELECT list:

    IF EXISTS (SELECT FROM people p WHERE p.person_id = my_person_id) THEN ...
    

    Since the SELECT list is not relevant to the outcome of EXISTS. Only the existence of at least one qualifying row matters.

    Creating an empty list in Python

    Here is how you can test which piece of code is faster:

    % python -mtimeit  "l=[]"
    10000000 loops, best of 3: 0.0711 usec per loop
    
    % python -mtimeit  "l=list()"
    1000000 loops, best of 3: 0.297 usec per loop
    

    However, in practice, this initialization is most likely an extremely small part of your program, so worrying about this is probably wrong-headed.

    Readability is very subjective. I prefer [], but some very knowledgable people, like Alex Martelli, prefer list() because it is pronounceable.

    How do you easily create empty matrices javascript?

    With ES6 spread operator: Array(9).fill([...Array(9)])

    How to choose the right bean scope?

    Introduction

    It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.


    @Request/View/Flow/Session/ApplicationScoped

    A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

    Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

    Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

    Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

    See also:


    @CustomScoped/NoneScoped/Dependent

    It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

    The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

    See also:


    Flash scope

    As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

    This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

    See also:

    What is output buffering?

    Output Buffering for Web Developers, a Beginner’s Guide:

    Without output buffering (the default), your HTML is sent to the browser in pieces as PHP processes through your script. With output buffering, your HTML is stored in a variable and sent to the browser as one piece at the end of your script.

    Advantages of output buffering for Web developers

    • Turning on output buffering alone decreases the amount of time it takes to download and render our HTML because it's not being sent to the browser in pieces as PHP processes the HTML.
    • All the fancy stuff we can do with PHP strings, we can now do with our whole HTML page as one variable.
    • If you've ever encountered the message "Warning: Cannot modify header information - headers already sent by (output)" while setting cookies, you'll be happy to know that output buffering is your answer.

    Git Push Error: insufficient permission for adding an object to repository database

    Solved for me... just this:

    sudo chmod 777 -R .git/objects
    

    How to do case insensitive search in Vim

    put this command in your vimrc file

    set ic 
    

    always do case insensitive search

    What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

    It's easy, just add if (e.AddedItems.Count == 0) return; in the beggining of function like:

            private  void ComboBox_Symbols_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count == 0) 
            return;
            //Some Other Codes
        }
    

    Gradient of n colors ranging from color 1 and color 2

    colorRampPalette could be your friend here:

    colfunc <- colorRampPalette(c("black", "white"))
    colfunc(10)
    # [1] "#000000" "#1C1C1C" "#383838" "#555555" "#717171" "#8D8D8D" "#AAAAAA"
    # [8] "#C6C6C6" "#E2E2E2" "#FFFFFF"
    

    And just to show it works:

    plot(rep(1,10),col=colfunc(10),pch=19,cex=3)
    

    enter image description here

    How to use the DropDownList's SelectedIndexChanged event

    You should add AutoPostBack="true" to DropDownList1

                    <asp:DropDownList ID="ddmanu" runat="server" AutoPostBack="true"
                        DataSourceID="Sql_fur_model_manu"    
                        DataTextField="manufacturer" DataValueField="manufacturer" 
                        onselectedindexchanged="ddmanu_SelectedIndexChanged">
                    </asp:DropDownList>
    

    sending mail from Batch file

    You can also use a Power Shell script:

    $smtp = new-object Net.Mail.SmtpClient("mail.example.com")
    
    if( $Env:SmtpUseCredentials -eq "true" ) {
        $credentials = new-object Net.NetworkCredential("username","password")
        $smtp.Credentials = $credentials
    }
    $objMailMessage = New-Object System.Net.Mail.MailMessage
    $objMailMessage.From = "[email protected]"
    $objMailMessage.To.Add("[email protected]")
    $objMailMessage.Subject = "eMail subject Notification"
    $objMailMessage.Body = "Hello world!"
    
    $smtp.send($objMailMessage)
    

    How to merge a specific commit in Git

    'git cherry-pick' should be your answer here.

    Apply the change introduced by an existing commit.

    Do not forget to read bdonlan's answer about the consequence of cherry-picking in this post:
    "Pull all commits from a branch, push specified commits to another", where:

    A-----B------C
     \
      \
       D
    

    becomes:

    A-----B------C
     \
      \
       D-----C'
    

    The problem with this commit is that git considers commits to include all history before them

    Where C' has a different SHA-1 ID.
    Likewise, cherry picking a commit from one branch to another basically involves generating a patch, then applying it, thus losing history that way as well.

    This changing of commit IDs breaks git's merging functionality among other things (though if used sparingly there are heuristics that will paper over this).
    More importantly though, it ignores functional dependencies - if C actually used a function defined in B, you'll never know.

    How to format a float in javascript?

    /** don't spend 5 minutes, use my code **/
    function prettyFloat(x,nbDec) { 
        if (!nbDec) nbDec = 100;
        var a = Math.abs(x);
        var e = Math.floor(a);
        var d = Math.round((a-e)*nbDec); if (d == nbDec) { d=0; e++; }
        var signStr = (x<0) ? "-" : " ";
        var decStr = d.toString(); var tmp = 10; while(tmp<nbDec && d*tmp < nbDec) {decStr = "0"+decStr; tmp*=10;}
        var eStr = e.toString();
        return signStr+eStr+"."+decStr;
    }
    
    prettyFloat(0);      //  "0.00"
    prettyFloat(-1);     // "-1.00"
    prettyFloat(-0.999); // "-1.00"
    prettyFloat(0.5);    //  "0.50"
    

    SpringApplication.run main method

    One more way is to extend the application (as my application was to inherit and customize the parent). It invokes the parent and its commandlinerunner automatically.

    @SpringBootApplication
    public class ChildApplication extends ParentApplication{
        public static void main(String[] args) {
            SpringApplication.run(ChildApplication.class, args);
        }
    }
    

    Properties file with a list as the value for an individual key

    Try writing the properties as a comma separated list, then split the value after the properties file is loaded. For example

    a=one,two,three
    b=nine,ten,fourteen
    

    You can also use org.apache.commons.configuration and change the value delimiter using the AbstractConfiguration.setListDelimiter(char) method if you're using comma in your values.

    Mismatched anonymous define() module

    Per the docs:

    If you manually code a script tag in HTML to load a script with an anonymous define() call, this error can occur.

    Also seen if you manually code a script tag in HTML to load a script that has a few named modules, but then try to load an anonymous module that ends up having the same name as one of the named modules in the script loaded by the manually coded script tag.

    Finally, if you use the loader plugins or anonymous modules (modules that call define() with no string ID) but do not use the RequireJS optimizer to combine files together, this error can occur. The optimizer knows how to name anonymous modules correctly so that they can be combined with other modules in an optimized file.

    To avoid the error:

    • Be sure to load all scripts that call define() via the RequireJS API. Do not manually code script tags in HTML to load scripts that have define() calls in them.

    • If you manually code an HTML script tag, be sure it only includes named modules, and that an anonymous module that will have the same name as one of the modules in that file is not loaded.

    • If the problem is the use of loader plugins or anonymous modules but the RequireJS optimizer is not used for file bundling, use the RequireJS optimizer.

    Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

    If you chain the events together I believe it eliminates the need to use .one as suggested elsewhere in this thread.

    Example:

    $('input.your_element').focus( function () {
        $(this).select().mouseup( function (e) {
            e.preventDefault();
        });
    });
    

    AJAX Mailchimp signup form integration

    As for this date (February 2017), it seems that mailchimp has integrated something similar to what gbinflames suggests into their own javascript generated form.

    You don't need any further intervention now as mailchimp will convert the form to an ajax submitted one when javascript is enabled.

    All you need to do now is just paste the generated form from the embed menu into your html page and NOT modify or add any other code.

    This simply works. Thanks MailChimp!

    remove all variables except functions

    I wrote this to remove all objects apart from functions from the current environment (Programming language used is R with IDE R-Studio):

        remove_list=c()                             # create a vector
    
          for(i in 1:NROW(ls())){                   # repeat over all objects in environment
            if(class(get(ls()[i]))!="function"){    # if object is *not* a function
             remove_list=c(remove_list,ls()[i])     # ..add to vector remove_list
             }    
          }
    
        rm(list=remove_list)                        # remove all objects named in remove_list
    

    Notes-

    The argument "list" in rm(list=) must be a character vector.

    The name of an object in position i of the current environment is returned from ls()[i] and the object itself from get(ls()[i]). Therefore the class of an object is returned from class(get(ls()[i]))

    SQL Server dynamic PIVOT query?

    The below code provides the results which replaces NULL to zero in the output.

    Table creation and data insertion:

    create table test_table
     (
     date nvarchar(10),
     category char(3),
     amount money
     )
    
     insert into test_table values ('1/1/2012','ABC',1000.00)
     insert into test_table values ('2/1/2012','DEF',500.00)
     insert into test_table values ('2/1/2012','GHI',800.00)
     insert into test_table values ('2/10/2012','DEF',700.00)
     insert into test_table values ('3/1/2012','ABC',1100.00)
    

    Query to generate the exact results which also replaces NULL with zeros:

    DECLARE @DynamicPivotQuery AS NVARCHAR(MAX),
    @PivotColumnNames AS NVARCHAR(MAX),
    @PivotSelectColumnNames AS NVARCHAR(MAX)
    
    --Get distinct values of the PIVOT Column
    SELECT @PivotColumnNames= ISNULL(@PivotColumnNames + ',','')
    + QUOTENAME(category)
    FROM (SELECT DISTINCT category FROM test_table) AS cat
    
    --Get distinct values of the PIVOT Column with isnull
    SELECT @PivotSelectColumnNames 
    = ISNULL(@PivotSelectColumnNames + ',','')
    + 'ISNULL(' + QUOTENAME(category) + ', 0) AS '
    + QUOTENAME(category)
    FROM (SELECT DISTINCT category FROM test_table) AS cat
    
    --Prepare the PIVOT query using the dynamic 
    SET @DynamicPivotQuery = 
    N'SELECT date, ' + @PivotSelectColumnNames + '
    FROM test_table
    pivot(sum(amount) for category in (' + @PivotColumnNames + ')) as pvt';
    
    --Execute the Dynamic Pivot Query
    EXEC sp_executesql @DynamicPivotQuery
    

    OUTPUT :

    enter image description here

    Is it possible to hide the cursor in a webpage using CSS or Javascript?

    If you want to do it in CSS:

    #ID { cursor: none !important; }
    

    Inline IF Statement in C#

    The literal answer is:

    return (value == 1 ? Periods.VariablePeriods : Periods.FixedPeriods);
    

    Note that the inline if statement, just like an if statement, only checks for true or false. If (value == 1) evaluates to false, it might not necessarily mean that value == 2. Therefore it would be safer like this:

    return (value == 1
        ? Periods.VariablePeriods
        : (value == 2
            ? Periods.FixedPeriods
            : Periods.Unknown));
    

    If you add more values an inline if will become unreadable and a switch would be preferred:

    switch (value)
    {
    case 1:
        return Periods.VariablePeriods;
    case 2:
        return Periods.FixedPeriods;
    }
    

    The good thing about enums is that they have a value, so you can use the values for the mapping, as user854301 suggested. This way you can prevent unnecessary branches thus making the code more readable and extensible.

    Round to 2 decimal places

    Try:

    float number mkm = (((((amountdrug/fluidvol)*1000f)/60f)*infrate)/ptwt)*1000f;
    int newNum = (int) mkm;
    mkm = newNum/1000f; // Will return 3 decimal places
    

    Python - Get Yesterday's date as a string in YYYY-MM-DD format

    You Just need to subtract one day from today's date. In Python datetime.timedelta object lets you create specific spans of time as a timedelta object.

    datetime.timedelta(1) gives you the duration of "one day" and is subtractable from a datetime object. After you subtracted the objects you can use datetime.strftime in order to convert the result --which is a date object-- to string format based on your format of choice:

    >>> from datetime import datetime, timedelta
    >>> yesterday = datetime.now() - timedelta(1)
    
    >>> type(yesterday)                                                                                                                                                                                    
    >>> datetime.datetime    
    
    >>> datetime.strftime(yesterday, '%Y-%m-%d')
    '2015-05-26'
    

    Note that instead of calling the datetime.strftime function, you can also directly use strftime method of datetime objects:

    >>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
    '2015-05-26'
    

    As a function:

    def yesterday(string=False):
        yesterday = datetime.now() - timedelta(1)
        if string:
            return yesterday.strftime('%Y-%m-%d')
        return yesterday
    

    How to hide a div with jQuery?

    $('#myDiv').hide(); hide function is used to edit content and show function is used to show again.

    For more please click on this link.

    How can I get the current network interface throughput statistics on Linux/UNIX?

    iftop does for network usage what top(1) does for CPU usage -- http://www.ex-parrot.com/~pdw/iftop/

    I don't know how "standard" iftop is, but I was able to install it with yum install iftop on Fedora.

    Align div with fixed position on the right side

    make a parent div, in css make it float:right then make the child div's position fixed this will make the div stay in its position at all times and on the right

    'DataFrame' object has no attribute 'sort'

    sort() was deprecated for DataFrames in favor of either:

    sort() was deprecated (but still available) in Pandas with release 0.17 (2015-10-09) with the introduction of sort_values() and sort_index(). It was removed from Pandas with release 0.20 (2017-05-05).

    How do I download a tarball from GitHub using cURL?

    with a specific dir:

    cd your_dir && curl -L https://download.calibre-ebook.com/3.19.0/calibre-3.19.0-x86_64.txz | tar zx
    

    How can you dynamically create variables via a while loop?

    Stuffing things into the global and/or local namespaces is not a good idea. Using a dict is so some-other-language-ish ... d['constant-key'] = value just looks awkward. Python is OO. In the words of a master: """Namespaces are one honking great idea -- let's do more of those!"""

    Like this:

    >>> class Record(object):
    ...     pass
    ...
    >>> r = Record()
    >>> r.foo = 'oof'
    >>> setattr(r, 'bar', 'rab')
    >>> r.foo
    'oof'
    >>> r.bar
    'rab'
    >>> names = 'id description price'.split()
    >>> values = [666, 'duct tape', 3.45]
    >>> s = Record()
    >>> for name, value in zip(names, values):
    ...     setattr(s, name, value)
    ...
    >>> s.__dict__ # If you are suffering from dict withdrawal symptoms
    {'price': 3.45, 'id': 666, 'description': 'duct tape'}
    >>>
    

    UITableview: How to Disable Selection for Some Rows but Not Others

    Use this to make the cell look like it is disabled and non-selectable:

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    

    Important: note that this is only a styling property, and does not actually disable the cell. In order to do that, you have to check for selectionStylein your didSelectRowAtIndexPath: delegate implementation:

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if(cell.selectionStyle == UITableViewCellSelectionStyleNone) {
            return;
        }
    
        // do your cell selection handling here
    }
    

    How can I force Python's file.write() to use the same newline format in Windows as in Linux ("\r\n" vs. "\n")?

    You need to open the file in binary mode i.e. wb instead of w. If you don't, the end of line characters are auto-converted to OS specific ones.

    Here is an excerpt from Python reference about open().

    The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading.

    How to directly execute SQL query in C#?

    IMPORTANT NOTE: You should not concatenate SQL queries unless you trust the user completely. Query concatenation involves risk of SQL Injection being used to take over the world, ...khem, your database.

    If you don't want to go into details how to execute query using SqlCommand then you could call the same command line like this:

    string userInput = "Brian";
    var process = new Process();
    var startInfo = new ProcessStartInfo();
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    startInfo.FileName = "cmd.exe";
    startInfo.Arguments = string.Format(@"sqlcmd.exe -S .\PDATA_SQLEXPRESS -U sa -P 2BeChanged! -d PDATA_SQLEXPRESS  
         -s ; -W -w 100 -Q "" SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName,
         tPatDBirthday  FROM  [dbo].[TPatientRaw] WHERE tPatSName = '{0}' """, userInput);
    
    process.StartInfo = startInfo;
    process.Start();
    

    Just ensure that you escape each double quote " with ""

    Retrieving JSON Object Literal from HttpServletRequest

    The easiest way is to populate your bean would be from a Reader object, this can be done in a single call:

    BufferedReader reader = request.getReader();
    Gson gson = new Gson();
    
    MyBean myBean = gson.fromJson(reader, MyBean.class);
    

    how to define variable in jquery

    In jquery, u can delcare variable two styles.

    One is,

    $.name = 'anirudha';
    alert($.name);
    

    Second is,

    var hText = $("#head1").text();
    

    Second is used when you read data from textbox, label, etc.

    Convert and format a Date in JSP

    In JSP, you'd normally like to use JSTL <fmt:formatDate> for this. You can of course also throw in a scriptlet with SimpleDateFormat, but scriptlets are strongly discouraged since 2003.

    Assuming that ${bean.date} returns java.util.Date, here's how you can use it:

    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    ...
    <fmt:formatDate value="${bean.date}" pattern="yyyy-MM-dd HH:mm:ss" />
    

    If you're actually using a java.util.Calendar, then you can invoke its getTime() method to get a java.util.Date out of it that <fmt:formatDate> accepts:

    <fmt:formatDate value="${bean.calendar.time}" pattern="yyyy-MM-dd HH:mm:ss" />
    

    Or, if you're actually holding the date in a java.lang.String (this indicates a serious design mistake in the model; you should really fix your model to store dates as java.util.Date instead of as java.lang.String!), here's how you can convert from one date string format e.g. MM/dd/yyyy to another date string format e.g. yyyy-MM-dd with help of JSTL <fmt:parseDate>.

    <fmt:parseDate pattern="MM/dd/yyyy" value="${bean.dateString}" var="parsedDate" />
    <fmt:formatDate value="${parsedDate}" pattern="yyyy-MM-dd" />
    

    Adding Apostrophe in every field in particular column for excel

    The way I'd do this is:

    • In Cell L2, enter the formula ="'"&K2
    • Use the fill handle or Ctrl+D to fill it down to the length of Column K's values.
    • Select the whole of Column L's values and copy them to the clipboard
    • Select the same range in Column K, right-click to select 'Paste Special' and choose 'Values'

    href="javascript:" vs. href="javascript:void(0)"

    Why have all the click events as a href links?

    If instead you use span tags with :hover CSS and the appropriate onclick events, this will get around the issue completely.

    Getting the ID of the element that fired an event

    The source element as a jQuery object should be obtained via

    var $el = $(event.target);
    

    This gets you the source of the click, rather than the element that the click function was assigned too. Can be useful when the click event is on a parent object EG.a click event on a table row, and you need the cell that was clicked

    $("tr").click(function(event){
        var $td = $(event.target);
    });
    

    How to get the current time in milliseconds from C in Linux?

    Use gettimeofday() to get the time in seconds and microseconds. Combining and rounding to milliseconds is left as an exercise.

    Eclipse C++ : "Program "g++" not found in PATH"

    I had the same problem: Eclipse couldn't find (g++) and (gcc) in PATH even they were accessible from command-line. I was also sure they are pointed by PATH correctly.

    I have just deleted the (.metadata) folder from Eclipse's Workspace as a mean to reset it and this worked for me.

    Re-run Spring Boot Configuration Annotation Processor to update generated metadata

    None of these options worked for me. I've found that the auto detection of annotation processors to be pretty flaky. I ended up creating a plugin section in the pom.xml file that explicitly sets the annotation processors that are used for the project. The advantage of this is that you don't need to rely on any IDE settings.

    <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <compilerVersion>1.8</compilerVersion>
                    <source>1.8</source>
                    <target>1.8</target>
                    <annotationProcessors>
                        <annotationProcessor>org.springframework.boot.configurationprocessor.ConfigurationMetadataAnnotationProcessor</annotationProcessor>
                        <annotationProcessor>lombok.launch.AnnotationProcessorHider$AnnotationProcessor</annotationProcessor>
                        <annotationProcessor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</annotationProcessor>
                    </annotationProcessors>
                </configuration>
            </plugin>
    

    C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

    Since your content-type is application/x-www-form-urlencoded you'll need to encode the POST body, especially if it contains characters like & which have special meaning in a form.

    Try passing your string through HttpUtility.UrlEncode before writing it to the request stream.

    Here are a couple links for reference.

    How to figure out the SMTP server host?

    this really is a question for Serverfault.

    Windows:

    1. Open up a command prompt (CMD.exe)
    2. Type nslookup and hit enter
    3. Type set type=MX and hit enter
    4. Type the domain name and hit enter, for example: google.com
    5. The results will be a list of host names that are set up for SMTP

    Linux:

    1. Open a command prompt
    2. Type dig domain.name MX and hit enter where domain.name is the domain you are trying to find out the smtp server for.

    If you do not get any answers back from your dns server, there is a good chance that there isn't any SMTP Servers set up for that domain. If this is the case, do like other's have suggested and call the hosting companies tech support.