Programs & Examples On #Bitflags

the use of individual bits in a byte (or a set of bytes) to represent boolean values.

How to create PDF files in Python

It depends on what format your image files are in, but for a project here at work I used the tiff2pdf tool in LibTIFF from RemoteSensing.org. Basically just used subprocess to call tiff2pdf.exe with the appropriate argument to read the kind of tiff I had and output the kind of pdf I wanted. If they aren't tiffs you could probably convert them to tiffs using PIL, or maybe find a tool more specific to your image type (or more generic if the images will be diverse) like ReportLab mentioned above.

How do I split a multi-line string into multiple lines?

I wish comments had proper code text formatting, because I think @1_CR 's answer needs more bumps, and I would like to augment his answer. Anyway, He led me to the following technique; it will use cStringIO if available (BUT NOTE: cStringIO and StringIO are not the same, because you cannot subclass cStringIO... it is a built-in... but for basic operations the syntax will be identical, so you can do this):

try:
    import cStringIO
    StringIO = cStringIO
except ImportError:
    import StringIO

for line in StringIO.StringIO(variable_with_multiline_string):
    pass
print line.strip()

How to change dot size in gnuplot

The pointsize command scales the size of points, but does not affect the size of dots.

In other words, plot ... with points ps 2 will generate points of twice the normal size, but for plot ... with dots ps 2 the "ps 2" part is ignored.

You could use circular points (pt 7), which look just like dots.

notifyDataSetChange not working from custom adapter

If adapter is set to AutoCompleteTextView then notifyDataSetChanged() doesn't work.

Need this to update adapter:

myAutoCompleteAdapter = new ArrayAdapter<String>(MainActivity.this, 
        android.R.layout.simple_dropdown_item_1line, myList);

myAutoComplete.setAdapter(myAutoCompleteAdapter);

Refer: http://android-er.blogspot.in/2012/10/autocompletetextview-with-dynamic.html

Aliases in Windows command prompt

First, you could create a file named np.cmd and put it in the folder which in PATH search list. Then, edit the np.cmd file as below:

@echo off
notepad++.exe

How do I check whether a file exists without exceptions?

You can use the following open method to check if a file exists + readable:

file = open(inputFile, 'r')
file.close()

Ruby replace string with captured regex pattern

Try '\1' for the replacement (single quotes are important, otherwise you need to escape the \):

"foo".gsub(/(o+)/, '\1\1\1')
#=> "foooooo"

But since you only seem to be interested in the capture group, note that you can index a string with a regex:

"foo"[/oo/]
#=> "oo"
"Z_123: foobar"[/^Z_.*(?=:)/]
#=> "Z_123"

How to convert a byte array to Stream

I am using as what John Rasch said:

Stream streamContent = taxformUpload.FileContent;

How to get the selected item of a combo box to a string variable in c#

Test this

  var selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
  MessageBox.Show(selected);

Slide div left/right using jQuery

_x000D_
_x000D_
$(document).ready(function(){_x000D_
$("#left").on('click', function (e) {_x000D_
        e.stopPropagation();_x000D_
        e.preventDefault();_x000D_
        $('#left').hide("slide", { direction: "left" }, 500, function () {_x000D_
            $('#right').show("slide", { direction: "right" }, 500);_x000D_
        });_x000D_
    });_x000D_
    $("#right").on('click', function (e) {_x000D_
        e.stopPropagation();_x000D_
        e.preventDefault();_x000D_
        $('#right').hide("slide", { direction: "right" }, 500, function () {_x000D_
            $('#left').show("slide", { direction: "left" }, 500);_x000D_
        });_x000D_
    });_x000D_
_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
_x000D_
<div style="height:100%;width:100%;background:cyan" id="left">_x000D_
<h1>Hello im going left to hide and will comeback from left to show</h1>_x000D_
</div>_x000D_
<div style="height:100%;width:100%;background:blue;display:none" id="right">_x000D_
<h1>Hello im coming from right to sho and will go back to right to hide</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

$("#btnOpenEditing").off('click');
$("#btnOpenEditing").on('click', function (e) {
    e.stopPropagation();
    e.preventDefault();
    $('#mappingModel').hide("slide", { direction: "right" }, 500, function () {
        $('#fsEditWindow').show("slide", { direction: "left" }, 500);
    });
});

It will work like charm take a look at the demo.

how does unix handle full path name with space and arguments?

You can quote if you like, or you can escape the spaces with a preceding \, but most UNIX paths (Mac OS X aside) don't have spaces in them.

/Applications/Image\ Capture.app/Contents/MacOS/Image\ Capture

"/Applications/Image Capture.app/Contents/MacOS/Image Capture"

/Applications/"Image Capture.app"/Contents/MacOS/"Image Capture"

All refer to the same executable under Mac OS X.

I'm not sure what you mean about recognizing a path - if any of the above paths are passed as a parameter to a program the shell will put the entire string in one variable - you don't have to parse multiple arguments to get the entire path.

bash script use cut command at variable and store result at another variable

You can avoid the loop and cut etc by using:

awk -F ':' '{system("ping " $1);}' config.txt

However it would be better if you post a snippet of your config.txt

How to implement a Boolean search with multiple columns in pandas

All the considerations made by @EdChum in 2014 are still valid, but the pandas.Dataframe.ix method is deprecated from the version 0.0.20 of pandas. Directly from the docs:

Warning: Starting in 0.20.0, the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

In subsequent versions of pandas, this method has been replaced by new indexing methods pandas.Dataframe.loc and pandas.Dataframe.iloc.

If you want to learn more, in this post you can find comparisons between the methods mentioned above.

Ultimately, to date (and there does not seem to be any change in the upcoming versions of pandas from this point of view), the answer to this question is as follows:

foo = df.loc[(df['column1']==value) | (df['columns2'] == 'b') | (df['column3'] == 'c')]

Add CSS to <head> with JavaScript?

A simple non-jQuery solution, albeit with a bit of a hack for IE:

var css = ".lightbox { width: 400px; height: 400px; border: 1px solid #333}";

var htmlDiv = document.createElement('div');
htmlDiv.innerHTML = '<p>foo</p><style>' + css + '</style>';
document.getElementsByTagName('head')[0].appendChild(htmlDiv.childNodes[1]);

It seems IE does not allow setting innerText, innerHTML or using appendChild on style elements. Here is a bug report which demonstrates this, although I think it identifies the problem incorrectly. The workaround above is from the comments on the bug report and has been tested in IE6 and IE9.

Whether you use this, document.write or a more complex solution will really depend on your situation.

matplotlib: how to draw a rectangle on image

You need use patches.

import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig2 = plt.figure()
ax2 = fig2.add_subplot(111, aspect='equal')

ax2.add_patch(
     patches.Rectangle(
        (0.1, 0.1),
        0.5,
        0.5,
        fill=False      # remove background
     ) ) 
fig2.savefig('rect2.png', dpi=90, bbox_inches='tight')

ZIP Code (US Postal Code) validation

Suggest you have a look at the USPS Address Information APIs. You can validate a zip and obtain standard formatted addresses. https://www.usps.com/business/web-tools-apis/address-information.htm

Cannot enqueue Handshake after invoking quit

If you using the node-mysql module, just remove the .connect and .end. Just solved the problem myself. Apparently they pushed in unnecessary code in their last iteration that is also bugged. You don't need to connect if you have already ran the createConnection call

Running multiple AsyncTasks at the same time -- not possible?

Making @sulai suggestion more generic :

@TargetApi(Build.VERSION_CODES.HONEYCOMB) // API 11
public static <T> void executeAsyncTask(AsyncTask<T, ?, ?> asyncTask, T... params) {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
    else
        asyncTask.execute(params);
}   

AngularJS $http, CORS and http authentication

For making a CORS request one must add headers to the request along with the same he needs to check of mode_header is enabled in Apache.

For enabling headers in Ubuntu:

sudo a2enmod headers

For php server to accept request from different origin use:

Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

How to call a button click event from another method

A simple way to call it from anywhere is just use "null" and "RoutedEventArgs.Empty", like this:

SubGraphButton_Click(null, RoutedEventArgs.Empty);

How do you get the cursor position in a textarea?

Here's a cross browser function I have in my standard library:

function getCursorPos(input) {
    if ("selectionStart" in input && document.activeElement == input) {
        return {
            start: input.selectionStart,
            end: input.selectionEnd
        };
    }
    else if (input.createTextRange) {
        var sel = document.selection.createRange();
        if (sel.parentElement() === input) {
            var rng = input.createTextRange();
            rng.moveToBookmark(sel.getBookmark());
            for (var len = 0;
                     rng.compareEndPoints("EndToStart", rng) > 0;
                     rng.moveEnd("character", -1)) {
                len++;
            }
            rng.setEndPoint("StartToStart", input.createTextRange());
            for (var pos = { start: 0, end: len };
                     rng.compareEndPoints("EndToStart", rng) > 0;
                     rng.moveEnd("character", -1)) {
                pos.start++;
                pos.end++;
            }
            return pos;
        }
    }
    return -1;
}

Use it in your code like this:

var cursorPosition = getCursorPos($('#myTextarea')[0])

Here's its complementary function:

function setCursorPos(input, start, end) {
    if (arguments.length < 3) end = start;
    if ("selectionStart" in input) {
        setTimeout(function() {
            input.selectionStart = start;
            input.selectionEnd = end;
        }, 1);
    }
    else if (input.createTextRange) {
        var rng = input.createTextRange();
        rng.moveStart("character", start);
        rng.collapse();
        rng.moveEnd("character", end - start);
        rng.select();
    }
}

http://jsfiddle.net/gilly3/6SUN8/

Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version

I also have this problem.

But I change my mongodb version to "^2.2.33" and no longer have the problem.

You shoud npm rm your old mongodb package on global or local and install this version.

If anyone don't want to have any side-effect on changing the direction name could try this method.

Query to list all users of a certain group

For Active Directory users, an alternative way to do this would be -- assuming all your groups are stored in OU=Groups,DC=CorpDir,DC=QA,DC=CorpName -- to use the query (&(objectCategory=group)(CN=GroupCN)). This will work well for all groups with less than 1500 members. If you want to list all members of a large AD group, the same query will work, but you'll have to use ranged retrieval to fetch all the members, 1500 records at a time.

The key to performing ranged retrievals is to specify the range in the attributes using this syntax: attribute;range=low-high. So to fetch all members of an AD Group with 3000 members, first run the above query asking for the member;range=0-1499 attribute to be returned, then for the member;range=1500-2999 attribute.

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

The value you have passed as the file descriptor is not valid. It is either negative or does not represent a currently open file or socket.

So you have either closed the socket before calling write() or you have corrupted the value of 'sockfd' somewhere in your code.

It would be useful to trace all calls to close(), and the value of 'sockfd' prior to the write() calls.

Your technique of only printing error messages in debug mode seems to me complete madness, and in any case calling another function between a system call and perror() is invalid, as it may disturb the value of errno. Indeed it may have done so in this case, and the real underlying error may be different.

How to remove entry from $PATH on mac

If you're removing the path for Python 3 specifically, I found it in ~/.zprofile and ~/.zshrc.

Swift 2: Call can throw, but it is not marked with 'try' and the error is not handled

You have to catch the error just as you're already doing for your save() call and since you're handling multiple errors here, you can try multiple calls sequentially in a single do-catch block, like so:

func deleteAccountDetail() {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()
    request.entity = entityDescription

    do {
        let fetchedEntities = try self.Context!.executeFetchRequest(request) as! [AccountDetail]

        for entity in fetchedEntities {
            self.Context!.deleteObject(entity)
        }

        try self.Context!.save()
    } catch {
        print(error)
    }
}

Or as @bames53 pointed out in the comments below, it is often better practice not to catch the error where it was thrown. You can mark the method as throws then try to call the method. For example:

func deleteAccountDetail() throws {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()

    request.entity = entityDescription

    let fetchedEntities = try Context.executeFetchRequest(request) as! [AccountDetail]

    for entity in fetchedEntities {
        self.Context!.deleteObject(entity)
    }

    try self.Context!.save()
}

How do I kill a process using Vb.NET or C#?

It's better practise, safer and more polite to detect if the process is running and tell the user to close it manually. Of course you could also add a timeout and kill the process if they've gone away...

Swift: print() vs println() vs NSLog()

There's another method called dump() which can also be used for logging:

func dump<T>(T, name: String?, indent: Int, maxDepth: Int, maxItems: Int)

Dumps an object’s contents using its mirror to standard output.

From Swift Standard Library Functions

How to do SQL Like % in Linq?

Contains is used in Linq ,Just like Like is used in SQL .

string _search="/12/";

. . .

.Where(s => s.Hierarchy.Contains(_search))

You can write your SQL script in Linq as Following :

 var result= Organizations.Join(OrganizationsHierarchy.Where(s=>s.Hierarchy.Contains("/12/")),s=>s.Id,s=>s.OrganizationsId,(org,orgH)=>new {org,orgH});

Where do I get servlet-api.jar from?

You can find a recent servlet-api.jar in Tomcat 6 or 7 lib directory. If you don't have Tomcat on your machine, download the binary distribution of version 6 or 7 from http://tomcat.apache.org/download-70.cgi

C# string does not contain possible?

So you can utilize short-circuiting:

bool containsBoth = compareString.Contains(firstString) && 
                    compareString.Contains(secondString);

How do I change the number of open files limit in Linux?

If some of your services are balking into ulimits, it's sometimes easier to put appropriate commands into service's init-script. For example, when Apache is reporting

[alert] (11)Resource temporarily unavailable: apr_thread_create: unable to create worker thread

Try to put ulimit -s unlimited into /etc/init.d/httpd. This does not require a server reboot.

How to set min-height for bootstrap container

Usually, if you are using bootstrap you can do this to set a min-height of 100%.

 <div class="container-fluid min-vh-100"></div>

this will also solve the footer not sticking at the bottom.

you can also do this from CSS with the following class

.stickDamnFooter{min-height: 100vh;}

if this class does not stick your footer just add position: fixed; to that same css class and you will not have this issue in a lifetime. Cheers.

Difference between static class and singleton pattern?

Well a singleton is just a normal class that IS instantiated but just once and indirectly from the client code. Static class is not instantiated. As far as I know static methods (static class must have static methods) are faster than non-static.

Edit:
FxCop Performance rule description: "Methods which do not access instance data or call instance methods can be marked as static (Shared in VB). After doing so, the compiler will emit non-virtual call sites to these members which will prevent a check at runtime for each call that insures the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue."
I don't actually know if this applies also to static methods in static classes.

jQuery datepicker years shown

 $("#DateOfBirth").datepicker({
        yearRange: "-100:+0",
        changeMonth: true,
        changeYear: true,
    });

yearRange: '1950:2013', // specifying a hard coded year range or this way

yearRange: "-100:+0", // last hundred years

It will help to show drop down for year and month selection.

Errors in pom.xml with dependencies (Missing artifact...)

This is a very late answer,but this might help.I went to this link and searched for ojdbc8(I was trying to add jdbc oracle driver) When clicked on the result , a note was displayed like this:

enter image description here

I clicked the link in the note and the correct dependency was mentioned like below enter image description here

How to append to New Line in Node.js

Use the os.EOL constant instead.

var os = require("os");

function processInput ( text ) 
{     
  fs.open('H://log.txt', 'a', 666, function( e, id ) {
   fs.write( id, text + os.EOL, null, 'utf8', function(){
    fs.close(id, function(){
     console.log('file is updated');
    });
   });
  });
 }

Check whether specific radio button is checked

You should remove the '@' before 'name'; it's not needed anymore (for current jQuery versions).

You're want to return all checked elements with name 'test2', but you don't have any elements with that name, you're using an id of 'test2'.

If you're going to use IDs, just try:

return $('#test2').attr('checked');

Why can I not switch branches?

I got this message when updating new files from remote and index got out of whack. Tried to fix the index, but resolving via Xcode 4.5, GitHub.app (103), and GitX.app (0.7.1) failed. So, I did this:

git commit -a -m "your commit message here"

which worked in bypassing the git index.

Two blog posts that helped me understand about Git and Xcode are:

  • Ray Wenderlich on Xcode 4.5 and
  • Oliver Steele from 2008

  • Draggable div without jQuery UI

    What I saw above is complicate.....

    Here is some code can refer to.

    $("#box").on({
                    mousedown:function(e)
                    {
                      dragging = true;
                      dragX = e.clientX - $(this).position().left;
                      //To calculate the distance between the cursor pointer and box 
                      dragY = e.clientY - $(this).position().top;
                    },
                    mouseup:function(){dragging = false;},
                      //If not set this on/off,the move will continue forever
                    mousemove:function(e)
                    {
                      if(dragging)
                      $(this).offset({top:e.clientY-dragY,left:e.clientX-dragX});
    
                    }
                })
    

    dragging,dragX,dragY may place as the global variable.

    It's a simple show about this issue,but there is some bug about this method.

    If it's your need now,here's the Example here.

    Configure Log4net to write to multiple files

    These answers were helpful, but I wanted to share my answer with both the app.config part and the c# code part, so there is less guessing for the next person.

    <log4net>
      <appender name="SomeName" type="log4net.Appender.RollingFileAppender">
        <file value="c:/Console.txt" />
        <appendToFile value="true" />
        <rollingStyle value="Composite" />
        <datePattern value="yyyyMMdd" />
        <maxSizeRollBackups value="10" />
        <maximumFileSize value="1MB" />
      </appender>
      <appender name="Summary" type="log4net.Appender.FileAppender">
        <file value="SummaryFile.log" />
        <appendToFile value="true" />
      </appender>
      <root>
        <level value="ALL" />
        <appender-ref ref="SomeName" />
      </root>
      <logger additivity="false" name="Summary">
        <level value="DEBUG"/>
        <appender-ref ref="Summary" />
      </logger>
    </log4net>
    

    Then in code:

    ILog Log = LogManager.GetLogger("SomeName");
    ILog SummaryLog = LogManager.GetLogger("Summary");
    Log.DebugFormat("Processing");
    SummaryLog.DebugFormat("Processing2"));
    

    Here c:/Console.txt will contain "Processing" ... and \SummaryFile.log will contain "Processing2"

    How to POST request using RestSharp

    As of 2017 I post to a rest service and getting the results from it like that:

            var loginModel = new LoginModel();
            loginModel.DatabaseName = "TestDB";
            loginModel.UserGroupCode = "G1";
            loginModel.UserName = "test1";
            loginModel.Password = "123";
    
            var client = new RestClient(BaseUrl);
    
            var request = new RestRequest("/Connect?", Method.POST);
            request.RequestFormat = DataFormat.Json;
            request.AddBody(loginModel);
    
            var response = client.Execute(request);
    
            var obj = JObject.Parse(response.Content);
    
            LoginResult result = new LoginResult
            {
                Status = obj["Status"].ToString(),
                Authority = response.ResponseUri.Authority,
                SessionID = obj["SessionID"].ToString()
            };
    

    Find stored procedure by name

    Option 1: In SSMS go to View > Object Explorer Details or press F7. Use the Search box. Finally in the displayed list right click and select Synchronize to find the object in the Object Explorer tree.

    Object Explorer Details

    Option 2: Install an Add-On like dbForge Search. Right click on the displayed list and select Find in Object Explorer.

    enter image description here

    Difference between chr(13) and chr(10)

    Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

    You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


    Historically, Line Feed would move down a line but not return to column 1:

    This  
        is  
            a  
                test.
    

    Similarly Carriage Return would return to column 1 but not move down a line:

    This  
    is  
    a  
    test.
    

    Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

    dll missing in JDBC

    Set java.library.path to a directory containing this DLL which Java uses to find native libraries. Specify -D switch on the command line

    java -Djava.library.path=C:\Java\native\libs YourProgram

    C:\Java\native\libs should contain sqljdbc_auth.dll

    Look at this SO post if you are using Eclipse or at this blog if you want to set programatically.

    Adding rows dynamically with jQuery

    Building on the other answers, I simplified things a bit. By cloning the last element, we get the "add new" button for free (you have to change the ID to a class because of the cloning) and also reduce DOM operations. I had to use filter() instead of find() to get only the last element.

    $('.js-addNew').on('click', function(e) {
       e.preventDefault();
       var $rows   = $('.person'),
           $last   = $rows.filter(':last'),
           $newRow = $last.clone().insertAfter($last);
    
       $last.find($('.js-addNew')).remove(); // remove old button
       $newRow.hide().find('input').val('');
       $newRow.slideDown(500);
    });
    

    How to dock "Tool Options" to "Toolbox"?

    In the detached 'Tool Options' window, click on the red 'X' in the upper right corner to get rid of the window. Then on the main Gimp screen, click on 'Windows,' then 'Dockable Dialogs.' The first entry on its list will be 'Tool Options,' so click on that. Then, Tool Options will appear as a tab in the window on the right side of the screen, along with layers and undo history. Click and drag that tab over to the toolbox window on hte left and drop it inside. The tool options will again be docked in the toolbox.

    Easiest way to convert a Blob into a byte array

    the mySql blob class has the following function :

    blob.getBytes

    use it like this:

    //(assuming you have a ResultSet named RS)
    Blob blob = rs.getBlob("SomeDatabaseField");
    
    int blobLength = (int) blob.length();  
    byte[] blobAsBytes = blob.getBytes(1, blobLength);
    
    //release the blob and free up memory. (since JDBC 4.0)
    blob.free();
    

    How to prepare a Unity project for git?

    On the Unity Editor open your project and:

    1. Enable External option in Unity ? Preferences ? Packages ? Repository (only if Unity ver < 4.5)
    2. Switch to Visible Meta Files in Edit ? Project Settings ? Editor ? Version Control Mode
    3. Switch to Force Text in Edit ? Project Settings ? Editor ? Asset Serialization Mode
    4. Save Scene and Project from File menu.
    5. Quit Unity and then you can delete the Library and Temp directory in the project directory. You can delete everything but keep the Assets and ProjectSettings directory.

    If you already created your empty git repo on-line (eg. github.com) now it's time to upload your code. Open a command prompt and follow the next steps:

    cd to/your/unity/project/folder
    
    git init
    
    git add *
    
    git commit -m "First commit"
    
    git remote add origin [email protected]:username/project.git
    
    git push -u origin master
    

    You should now open your Unity project while holding down the Option or the Left Alt key. This will force Unity to recreate the Library directory (this step might not be necessary since I've seen Unity recreating the Library directory even if you don't hold down any key).

    Finally have git ignore the Library and Temp directories so that they won’t be pushed to the server. Add them to the .gitignore file and push the ignore to the server. Remember that you'll only commit the Assets and ProjectSettings directories.

    And here's my own .gitignore recipe for my Unity projects:

    # =============== #
    # Unity generated #
    # =============== #
    Temp/
    Obj/
    UnityGenerated/
    Library/
    Assets/AssetStoreTools*
    
    # ===================================== #
    # Visual Studio / MonoDevelop generated #
    # ===================================== #
    ExportedObj/
    *.svd
    *.userprefs
    *.csproj
    *.pidb
    *.suo
    *.sln
    *.user
    *.unityproj
    *.booproj
    
    # ============ #
    # OS generated #
    # ============ #
    .DS_Store
    .DS_Store?
    ._*
    .Spotlight-V100
    .Trashes
    Icon?
    ehthumbs.db
    Thumbs.db
    

    Find html label associated with a given input

    It is actually far easier to add an id to the label in the form itself, for example:

    <label for="firstName" id="firstNameLabel">FirstName:</label>
    
    <input type="text" id="firstName" name="firstName" class="input_Field" 
           pattern="^[a-zA-Z\s\-]{2,25}$" maxlength="25"
           title="Alphabetic, Space, Dash Only, 2-25 Characters Long" 
           autocomplete="on" required
    />
    

    Then, you can simply use something like this:

    if (myvariableforpagelang == 'es') {
       // set field label to spanish
       document.getElementById("firstNameLabel").innerHTML = "Primer Nombre:";
       // set field tooltip (title to spanish
       document.getElementById("firstName").title = "Alfabética, espacio, guión Sólo, 2-25 caracteres de longitud";
    }
    

    The javascript does have to be in a body onload function to work.

    Just a thought, works beautifully for me.

    How to get anchor text/href on click using jQuery?

    Edited to reflect update to question

    $(document).ready(function() {
        $(".res a").click(function() {
            alert($(this).attr("href"));
        });
    });
    

    How can I get around MySQL Errcode 13 with SELECT INTO OUTFILE?

    I just ran into this same problem. My issue was the directory that I was trying to dump into didn't have write permission for the mysqld process. The initial sql dump would write out but the write of the csv/txt file would fail. Looks like the sql dump runs as the current user and the conversion to csv/txt is run as the user that is running mysqld. So the directory needs write permissions for both users.

    Is it possible to make an HTML anchor tag not clickable/linkable using CSS?

    A more un-obtrusive way (assuming you use jQuery):

    HTML:

    <a id="my-link" href="page.html">page link</a>

    Javascript:

    $('#my-link').click(function(e)
    {
        e.preventDefault();
    });
    

    The advantage of this is the clean separation between logic and presentation. If one day you decide that this link would do something else, you don't have to mess with the markup, just the JS.

    C# Break out of foreach loop after X number of items

    int processed = 0;
    foreach(ListViewItem lvi in listView.Items)
    {
       //do stuff
       if (++processed == 50) break;
    }
    

    or use LINQ

    foreach( ListViewItem lvi in listView.Items.Cast<ListViewItem>().Take(50))
    {
        //do stuff
    }
    

    or just use a regular for loop (as suggested by @sgriffinusa and @Eric J.)

    for(int i = 0; i < 50 && i < listView.Items.Count; i++)
    {
        ListViewItem lvi = listView.Items[i];
    }
    

    Setting max-height for table cell contents

    We finally found an answer of sorts. First, the problem: the table always sizes itself around the content, rather than forcing the content to fit in the table. That limits your options.

    We did it by setting the content div to display:none, letting the table size itself, and then in javascript setting the height and width of the content div to the inner height and width of the enclosing td tag. Show the content div. Repeat the process when the window is resized.

    Is there a way to get the XPath in Google Chrome?

    All above answers are correct here is another way with screenshot too.

    From Chrome :

    1. Right click "inspect" on the item you are trying to find the xpath
    2. Right click on the highlighted area on the console.
    3. Go to Copy xpath

    enter image description here

    How do I execute a PowerShell script automatically using Windows task scheduler?

    You can use the Unblock-File cmdlet to unblock the execution of this specific script. This prevents you doing any permanent policy changes which you may not want due to security concerns.

    Unblock-File path_to_your_script
    

    Source: Unblock-File

    Search for string and get count in vi editor

    You need the n flag. To count words use:

    :%s/\i\+/&/gn   
    

    and a particular word:

    :%s/the/&/gn        
    

    See count-items documentation section.

    If you simply type in:

    %s/pattern/pattern/g
    

    then the status line will give you the number of matches in vi as well.

    Android: failed to convert @drawable/picture into a drawable

    I think I found a way to have it work without restarting Eclipse, or without closing project (it worked for me):

    • rename image file name under res/ in Eclipse -> choose file and press F2 (for me it res/drawable-mdpi/bush-landscape.jpg -> changed to bush.jpg)

    • Build Project (it will still show error)

    • change image where you used it (I changed in Graphical Layout. For me the place was LinearLayout/Background/bush-landscape -> changed "bush-landscape" to "bush")

    • Build Project

    Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

    I have got the same error, but in my case I wrote class names for carousel item as .carousel-item the bootstrap.css is referring .item. SO ERROR solved. carosel-item is renamed to item

    <div class="carousel-item active"></div>
    

    RENAMED To the following:

    <div class="item active"></div>
    

    Change the jquery show()/hide() animation?

    Use slidedown():

    $("test").slideDown("slow");
    

    'profile name is not valid' error when executing the sp_send_dbmail command

    I got the same problem also. Here's what I did:

    If you're already done granting the user/group the rights to use the profile name.

    1. Go to the configuration Wizard of Database Mail
    2. Tick Manage profile security
    3. On public profiles tab, check your profile name
    4. On private profiles tab, select NT AUTHORITY\NETWORK SERVICE for user name and check your profile name
    5. Do #4 this time for NT AUTHORITY\SYSTEM user name
    6. Click Next until Finish.

    What is the main purpose of setTag() getTag() methods of View?

    Let's say you generate a bunch of views that are similar. You could set an OnClickListener for each view individually:

    button1.setOnClickListener(new OnClickListener ... );
    button2.setOnClickListener(new OnClickListener ... );
     ...
    

    Then you have to create a unique onClick method for each view even if they do the similar things, like:

    public void onClick(View v) {
        doAction(1); // 1 for button1, 2 for button2, etc.
    }
    

    This is because onClick has only one parameter, a View, and it has to get other information from instance variables or final local variables in enclosing scopes. What we really want is to get information from the views themselves.

    Enter getTag/setTag:

    button1.setTag(1);
    button2.setTag(2);
    

    Now we can use the same OnClickListener for every button:

    listener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            doAction(v.getTag());
        }
    };
    

    It's basically a way for views to have memories.

    Timestamp to human readable format

    use Date.prototype.toLocaleTimeString() as documented here

    please note the locale example en-US in the url.

    How to return images in flask response?

    You use something like

    from flask import send_file
    
    @app.route('/get_image')
    def get_image():
        if request.args.get('type') == '1':
           filename = 'ok.gif'
        else:
           filename = 'error.gif'
        return send_file(filename, mimetype='image/gif')
    

    to send back ok.gif or error.gif, depending on the type query parameter. See the documentation for the send_file function and the request object for more information.

    How do I create HTML table using jQuery dynamically?

    You may use two options:

    1. createElement
    2. InnerHTML

    Create Element is the fastest way (check here.):

    $(document.createElement('table'));
    

    InnerHTML is another popular approach:

    $("#foo").append("<div>hello world</div>"); // Check similar for table too.
    

    Check a real example on How to create a new table with rows using jQuery and wrap it inside div.

    There may be other approaches as well. Please use this as a starting point and not as a copy-paste solution.

    Edit:

    Check Dynamic creation of table with DOM

    Edit 2:

    IMHO, you are mixing object and inner HTML. Let's try with a pure inner html approach:

    function createProviderFormFields(id, labelText, tooltip, regex) {
        var tr = '<tr>' ;
             // create a new textInputBox  
               var textInputBox = '<input type="text" id="' + id + '" name="' + id + '" title="' + tooltip + '" />';  
            // create a new Label Text
                tr += '<td>' + labelText  + '</td>';
                tr += '<td>' + textInputBox + '</td>';  
        tr +='</tr>';
        return tr;
    }
    

    How to run html file on localhost?

    You can install Xampp and run apache serve and place your file to www folder and access your file at localhost/{file name} or simply at localhost if your file is named index.html

    Event for Handling the Focus of the EditText

    Here is the focus listener example.

    editText.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean hasFocus) {
            if (hasFocus) {
                Toast.makeText(getApplicationContext(), "Got the focus", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), "Lost the focus", Toast.LENGTH_LONG).show();
            }
        }
    });
    

    Fitting a density curve to a histogram in R

    Dirk has explained how to plot the density function over the histogram. But sometimes you might want to go with the stronger assumption of a skewed normal distribution and plot that instead of density. You can estimate the parameters of the distribution and plot it using the sn package:

    > sn.mle(y=c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4)))
    $call
    sn.mle(y = c(rep(65, times = 5), rep(25, times = 5), rep(35, 
        times = 10), rep(45, times = 4)))
    
    $cp
        mean     s.d. skewness 
    41.46228 12.47892  0.99527 
    

    Skew-normal distributed data plot

    This probably works better on data that is more skew-normal:

    Another skew-normal plot

    How to set the environmental variable LD_LIBRARY_PATH in linux

    You should add more details about your distribution, for example under Ubuntu the right way to do this is to add a custom .conf file to /etc/ld.so.conf.d, for example

    sudo gedit /etc/ld.so.conf.d/randomLibs.conf
    

    inside the file you are supposed to write the complete path to the directory that contains all the libraries that you wish to add to the system, for example

    /home/linux/myLocalLibs
    

    remember to add only the path to the dir, not the full path for the file, all the libs inside that path will be automatically indexed.

    Save and run sudo ldconfig to update the system with this libs.

    How to stop java process gracefully?

    Here is a bit tricky, but portable solution:

    • In your application implement a shutdown hook
    • When you want to shut down your JVM gracefully, install a Java Agent that calls System.exit() using the Attach API.

    I implemented the Java Agent. It is available on Github: https://github.com/everit-org/javaagent-shutdown

    Detailed description about the solution is available here: https://everitorg.wordpress.com/2016/06/15/shutting-down-a-jvm-process/

    How to print variable addresses in C?

    You want to use %p to print a pointer. From the spec:

    p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

    And don't forget the cast, e.g.

    printf("%p\n",(void*)&a);
    

    Execute a shell function with timeout

    function foo(){
        for i in {1..100};
        do 
            echo $i;  
            sleep 1;
        done;
    }
    
    cat <( foo ) # Will work 
    timeout 3 cat <( foo ) # Will Work 
    timeout 3 cat <( foo ) | sort # Wont work, As sort will fail 
    cat <( timeout 3 cat <( foo ) ) | sort -r # Will Work 
    

    How can I get the current directory name in Javascript?

    An interesting approach to get the dirname of the current URL is to make use of your browser's built-in path resolution. You can do that by:

    1. Create a link to ., i.e. the current directory
    2. Use the HTMLAnchorElement interface of the link to get the resolved URL or path equivalent to ..

    Here's one line of code that does just that:

    Object.assign(document.createElement('a'), {href: '.'}).pathname
    

    In contrast to some of the other solutions presented here, the result of this method will always have a trailing slash. E.g. running it on this page will yield /questions/3151436/, running it on https://stackoverflow.com/ will yield /.

    It's also easy to get the full URL instead of the path. Just read the href property instead of pathname.

    Finally, this approach should work in even the most ancient browsers if you don't use Object.assign:

    function getCurrentDir () {
        var link = document.createElement('a');
        link.href = '.';
        return link.pathname;
    }
    

    appending array to FormData and send via AJAX

    add all type inputs to FormData

    const formData = new FormData();
    for (let key in form) {
        Array.isArray(form[key])
            ? form[key].forEach(value => formData.append(key + '[]', value))
            : formData.append(key, form[key]) ;
    }
    

    How to get the number of characters in a std::string?

    It might be the easiest way to input a string and find its length.

    // Finding length of a string in C++ 
    #include<iostream>
    #include<string>
    using namespace std;
    
    int count(string);
    
    int main()
    {
    string str;
    cout << "Enter a string: ";
    getline(cin,str);
    cout << "\nString: " << str << endl;
    cout << count(str) << endl;
    
    return 0;
    
    }
    
    int count(string s){
    if(s == "")
      return 0;
    if(s.length() == 1)
      return 1;
    else
        return (s.length());
    
    }
    

    Does reading an entire file leave the file handle open?

    You can use pathlib.

    For Python 3.5 and above:

    from pathlib import Path
    contents = Path(file_path).read_text()
    

    For older versions of Python use pathlib2:

    $ pip install pathlib2
    

    Then:

    from pathlib2 import Path
    contents = Path(file_path).read_text()
    

    This is the actual read_text implementation:

    def read_text(self, encoding=None, errors=None):
        """
        Open the file in text mode, read it, and close the file.
        """
        with self.open(mode='r', encoding=encoding, errors=errors) as f:
            return f.read()
    

    How to find the installed pandas version

    Run:

    pip  list
    

    You should get a list of packages (including panda) and their versions, e.g.:

    beautifulsoup4 (4.5.1)
    cycler (0.10.0)
    jdcal (1.3)
    matplotlib (1.5.3)
    numpy (1.11.1)
    openpyxl (2.2.0b1)
    pandas (0.18.1)
    pip (8.1.2)
    pyparsing (2.1.9)
    python-dateutil (2.2)
    python-nmap (0.6.1)
    pytz (2016.6.1)
    requests (2.11.1)
    setuptools (20.10.1)
    six (1.10.0)
    SQLAlchemy (1.0.15)
    xlrd (1.0.0)
    

    NSString property: copy or retain?

    Through this example copy and retain can be explained like:

    NSMutableString *someName = [NSMutableString stringWithString:@"Chris"];
    
    Person *p = [[[Person alloc] init] autorelease];
    p.name = someName;
    
    [someName setString:@"Debajit"];
    

    if the property is of type copy then ,

    a new copy will be created for the [Person name] string that will hold the contents of someName string. Now any operation on someName string will have no effect on [Person name].

    [Person name] and someName strings will have different memory addresses.

    But in case of retain,

    both the [Person name] will hold the same memory address as of somename string, just the retain count of somename string will be incremented by 1.

    So any change in somename string will be reflected in [Person name] string.

    HTML: can I display button text in multiple lines?

    Yes, you can have it on multiple lines using the white-space css property :)

    _x000D_
    _x000D_
    input[type="submit"] {_x000D_
        white-space: normal;_x000D_
        width: 100px;_x000D_
    }
    _x000D_
    <input type="submit" value="Some long text that won't fit." />
    _x000D_
    _x000D_
    _x000D_

    add this to your element

     white-space: normal;
     width: 100px;
    

    How to match letters only using java regex, matches method?

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.regex.*;
    
    /* Write an application that prompts the user for a String that contains at least
     * five letters and at least five digits. Continuously re-prompt the user until a
     * valid String is entered. Display a message indicating whether the user was
     * successful or did not enter enough digits, letters, or both.
     */
    public class FiveLettersAndDigits {
    
      private static String readIn() { // read input from stdin
        StringBuilder sb = new StringBuilder();
        int c = 0;
        try { // do not use try-with-resources. We don't want to close the stdin stream
          BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
          while ((c = reader.read()) != 0) { // read all characters until null
            // We don't want new lines, although we must consume them.
            if (c != 13 && c != 10) {
              sb.append((char) c);
            } else {
              break; // break on new line (or else the loop won't terminate)
            }
          }
          // reader.readLine(); // get the trailing new line
        } catch (IOException ex) {
          System.err.println("Failed to read user input!");
          ex.printStackTrace(System.err);
        }
    
        return sb.toString().trim();
      }
    
      /**
       * Check the given input against a pattern
       *
       * @return the number of matches
       */
      private static int getitemCount(String input, String pattern) {
        int count = 0;
    
        try {
          Pattern p = Pattern.compile(pattern);
          Matcher m = p.matcher(input);
          while (m.find()) { // count the number of times the pattern matches
            count++;
          }
        } catch (PatternSyntaxException ex) {
          System.err.println("Failed to test input String \"" + input + "\" for matches to pattern \"" + pattern + "\"!");
          ex.printStackTrace(System.err);
        }
    
        return count;
      }
    
      private static String reprompt() {
        System.out.print("Entered input is invalid! Please enter five letters and five digits in any order: ");
    
        String in = readIn();
    
        return in;
      }
    
      public static void main(String[] args) {
        int letters = 0, digits = 0;
        String in = null;
        System.out.print("Please enter five letters and five digits in any order: ");
        in = readIn();
        while (letters < 5 || digits < 5) { // will keep occuring until the user enters sufficient input
          if (null != in && in.length() > 9) { // must be at least 10 chars long in order to contain both
            // count the letters and numbers. If there are enough, this loop won't happen again.
            letters = getitemCount(in, "[A-Za-z]");
            digits = getitemCount(in, "[0-9]");
    
            if (letters < 5 || digits < 5) {
              in = reprompt(); // reset in case we need to go around again.
            }
          } else {
            in = reprompt();
          }
        }
      }
    
    }
    

    Auto Resize Image in CSS FlexBox Layout and keeping Aspect Ratio?

    You might want to try the very new and simple CSS3 feature:

    img { 
      object-fit: contain;
    }
    

    It preserves the picture ratio (as when you use the background-picture trick), and in my case worked nicely for the same issue.

    Be careful though, it is not supported by IE (see support details here).

    twitter bootstrap autocomplete dropdown / combobox with Knockoutjs

    Does the basic HTML5 datalist work? It's clean and you don't have to play around with the messy third party code. W3SCHOOL tutorial

    The MDN Documentation is very eloquent and features examples.

    Two Divs on the same row and center align both of them

    Align to the center, using display: inline-block and text-align: center.

    _x000D_
    _x000D_
    .outerdiv_x000D_
    {_x000D_
        height:100px;_x000D_
        width:500px;_x000D_
        background: red;_x000D_
        margin: 0 auto;_x000D_
        text-align: center;_x000D_
    }_x000D_
    _x000D_
    .innerdiv_x000D_
    {_x000D_
        height:40px;_x000D_
        width: 100px;_x000D_
        margin: 2px;_x000D_
        box-sizing: border-box;_x000D_
        background: green;_x000D_
        display: inline-block;_x000D_
    }
    _x000D_
    <div class="outerdiv">_x000D_
        <div class="innerdiv"></div>_x000D_
        <div class="innerdiv"></div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Align to the center using display: flex and justify-content: center

    _x000D_
    _x000D_
    .outerdiv_x000D_
    {_x000D_
        height:100px;_x000D_
        width:500px;_x000D_
        background: red;_x000D_
        display: flex;_x000D_
        flex-direction: row;_x000D_
        justify-content: center;_x000D_
    }_x000D_
    _x000D_
    .innerdiv_x000D_
    {_x000D_
        height:40px;_x000D_
        width: 100px;_x000D_
        margin: 2px;_x000D_
        box-sizing: border-box;_x000D_
        background: green;_x000D_
    }
    _x000D_
    <div class="outerdiv">_x000D_
        <div class="innerdiv"></div>_x000D_
        <div class="innerdiv"></div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Align to the center vertically and horizontally using display: flex, justify-content: center and align-items:center.

    _x000D_
    _x000D_
    .outerdiv_x000D_
    {_x000D_
        height:100px;_x000D_
        width:500px;_x000D_
        background: red;_x000D_
        display: flex;_x000D_
        flex-direction: row;_x000D_
        justify-content: center;_x000D_
        align-items:center;_x000D_
    }_x000D_
    _x000D_
    .innerdiv_x000D_
    {_x000D_
        height:40px;_x000D_
        width: 100px;_x000D_
        margin: 2px;_x000D_
        box-sizing: border-box;_x000D_
        background: green;_x000D_
    }
    _x000D_
    <div class="outerdiv">_x000D_
        <div class="innerdiv"></div>_x000D_
        <div class="innerdiv"></div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Onclick on bootstrap button

    <a class="btn btn-large btn-success" id="fire" href="http://twitter.github.io/bootstrap/examples/marketing-narrow.html#">Send Email</a>
    
    $('#fire').on('click', function (e) {
    
         //your awesome code here
    
    })
    

    Which regular expression operator means 'Don't' match this character?

    You can use negated character classes to exclude certain characters: for example [^abcde] will match anything but a,b,c,d,e characters.

    Instead of specifying all the characters literally, you can use shorthands inside character classes: [\w] (lowercase) will match any "word character" (letter, numbers and underscore), [\W] (uppercase) will match anything but word characters; similarly, [\d] will match the 0-9 digits while [\D] matches anything but the 0-9 digits, and so on.

    If you use PHP you can take a look at the regex character classes documentation.

    How to prevent Browser cache for php site

    try this

    <?php
    
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    ?>
    

    Intellij reformat on file save

    If you're developing in Flutter, there's a new experimental option as of 5/1/2018 that allows you to format code on save. Settings

    HTML5 Video autoplay on iPhone

    Does playsinline attribute help?

    Here's what I have:

    <video autoplay loop muted playsinline class="video-background ">
      <source src="videos/intro-video3.mp4" type="video/mp4">
    </video>
    

    See the comment on playsinline here: https://webkit.org/blog/6784/new-video-policies-for-ios/

    How to disable HTML button using JavaScript?

    It is an attribute, but a boolean one (so it doesn't need a name, just a value -- I know, it's weird). You can set the property equivalent in Javascript:

    document.getElementsByName("myButton")[0].disabled = true;
    

    Adding gif image in an ImageView in android

    I faced problem to use

    compile 'pl.droidsonroids.gif:android-gif-drawable:1.1.+'
    

    And also I could not find the jar file to add to my project. So, in order to show gif, I use WebView like this:

    WebView webView = (WebView) this.findViewById(R.id.webView);
    webView.loadDataWithBaseURL(null, "<html><body><center><img style='align:center;width:250px; height:250px; border-radius:50%' src='file:///android_asset/loading.gif'/></center></body></html>", "text/html", "UTF-8", "");
    webView.setBackgroundColor(Color.TRANSPARENT);
    

    Is there a way to iterate over a dictionary?

    The block approach avoids running the lookup algorithm for every key:

    [dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL* stop) {
      NSLog(@"%@ => %@", key, value);
    }];
    

    Even though NSDictionary is implemented as a hashtable (which means that the cost of looking up an element is O(1)), lookups still slow down your iteration by a constant factor.

    My measurements show that for a dictionary d of numbers ...

    NSMutableDictionary* dict = [NSMutableDictionary dictionary];
    for (int i = 0; i < 5000000; ++i) {
      NSNumber* value = @(i);
      dict[value.stringValue] = value;
    }
    

    ... summing up the numbers with the block approach ...

    __block int sum = 0;
    [dict enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSNumber* value, BOOL* stop) {
      sum += value.intValue;
    }];
    

    ... rather than the loop approach ...

    int sum = 0;
    for (NSString* key in dict)
      sum += [dict[key] intValue];
    

    ... is about 40% faster.

    EDIT: The new SDK (6.1+) appears to optimise loop iteration, so the loop approach is now about 20% faster than the block approach, at least for the simple case above.

    No grammar constraints (DTD or XML schema) detected for the document

    Add DOCTYPE tag ...

    In this case:

    <!DOCTYPE xml>
    

    Add after:

    <?xml version="1.0" encoding="UTF-8"?>
    

    So:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE xml>
    

    RESTful API methods; HEAD & OPTIONS

    OPTIONS tells you things such as "What methods are allowed for this resource".

    HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned. The availability is only a small part of it.

    plotting different colors in matplotlib

    @tcaswell already answered, but I was in the middle of typing my answer up, so I'll go ahead and post it...

    There are a number of different ways you could do this. To begin with, matplotlib will automatically cycle through colors. By default, it cycles through blue, green, red, cyan, magenta, yellow, black:

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.linspace(0, 1, 10)
    for i in range(1, 6):
        plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))
    plt.legend(loc='best')
    plt.show()
    

    enter image description here

    If you want to control which colors matplotlib cycles through, use ax.set_color_cycle:

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.linspace(0, 1, 10)
    fig, ax = plt.subplots()
    ax.set_color_cycle(['red', 'black', 'yellow'])
    for i in range(1, 6):
        plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))
    plt.legend(loc='best')
    plt.show()
    

    enter image description here

    If you'd like to explicitly specify the colors that will be used, just pass it to the color kwarg (html colors names are accepted, as are rgb tuples and hex strings):

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.linspace(0, 1, 10)
    for i, color in enumerate(['red', 'black', 'blue', 'brown', 'green'], start=1):
        plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))
    plt.legend(loc='best')
    plt.show()
    

    enter image description here

    Finally, if you'd like to automatically select a specified number of colors from an existing colormap:

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.linspace(0, 1, 10)
    number = 5
    cmap = plt.get_cmap('gnuplot')
    colors = [cmap(i) for i in np.linspace(0, 1, number)]
    
    for i, color in enumerate(colors, start=1):
        plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))
    plt.legend(loc='best')
    plt.show()
    

    enter image description here

    How do you automatically set the focus to a textbox when a web page loads?

    IMHO, the 'cleanest' way to select the First, visible, enabled text field on the page, is to use jQuery and do something like this:

    $(document).ready(function() {
      $('input:text[value=""]:visible:enabled:first').focus();
    });
    

    Hope that helps...

    Thanks...

    SQL Server: Invalid Column Name

    This error may ALSO occur in encapsulated SQL statements e.g.

    DECLARE @tableName nvarchar(20) SET @tableName = 'GROC'

    DECLARE @updtStmt nvarchar(4000)

    SET @updtStmt = 'Update tbProductMaster_' +@tableName +' SET department_str = ' + @tableName exec sp_executesql @updtStmt

    Only to discover that there are missing quotations to encapsulate the parameter "@tableName" further like the following:

    SET @updtStmt = 'Update tbProductMaster_' +@tableName +' SET department_str = ''' + @tableName + ''' '

    Thanks

    String "true" and "false" to boolean

    Perhaps str.to_s.downcase == 'true' for completeness. Then nothing can crash even if str is nil or 0.

    ASP.NET MVC Razor render without encoding

    You can also use the WriteLiteral method

    Why doesn't calling a Python string method do anything unless you assign its output?

    All string functions as lower, upper, strip are returning a string without modifying the original. If you try to modify a string, as you might think well it is an iterable, it will fail.

    x = 'hello'
    x[0] = 'i' #'str' object does not support item assignment
    

    There is a good reading about the importance of strings being immutable: Why are Python strings immutable? Best practices for using them

    How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

    it's well documented here:

    https://cwiki.apache.org/confluence/display/TOMCAT/Connectors#Connectors-Q6

    How do I bind to a specific ip address? - "Each Connector element allows an address property. See the HTTP Connector docs or the AJP Connector docs". And HTTP Connectors docs:

    http://tomcat.apache.org/tomcat-7.0-doc/config/http.html

    Standard Implementation -> address

    "For servers with more than one IP address, this attribute specifies which address will be used for listening on the specified port. By default, this port will be used on all IP addresses associated with the server."

    Swift extract regex matches

    The fastest way to return all matches and capture groups in Swift 5

    extension String {
        func match(_ regex: String) -> [[String]] {
            let nsString = self as NSString
            return (try? NSRegularExpression(pattern: regex, options: []))?.matches(in: self, options: [], range: NSMakeRange(0, count)).map { match in
                (0..<match.numberOfRanges).map { match.range(at: $0).location == NSNotFound ? "" : nsString.substring(with: match.range(at: $0)) }
            } ?? []
        }
    }
    

    Returns a 2-dimentional array of strings:

    "prefix12suffix fix1su".match("fix([0-9]+)su")
    

    returns...

    [["fix12su", "12"], ["fix1su", "1"]]
    
    // First element of sub-array is the match
    // All subsequent elements are the capture groups
    

    WebView and Cookies on Android

    From the Android documentation:

    The CookieSyncManager is used to synchronize the browser cookie store between RAM and permanent storage. To get the best performance, browser cookies are saved in RAM. A separate thread saves the cookies between, driven by a timer.

    To use the CookieSyncManager, the host application has to call the following when the application starts:

    CookieSyncManager.createInstance(context)
    

    To set up for sync, the host application has to call

    CookieSyncManager.getInstance().startSync()
    

    in Activity.onResume(), and call

     CookieSyncManager.getInstance().stopSync()
    

    in Activity.onPause().

    To get instant sync instead of waiting for the timer to trigger, the host can call

    CookieSyncManager.getInstance().sync()
    

    The sync interval is 5 minutes, so you will want to force syncs manually anyway, for instance in onPageFinished(WebView, String). Note that even sync() happens asynchronously, so don't do it just as your activity is shutting down.

    Finally something like this should work:

    // use cookies to remember a logged in status   
    CookieSyncManager.createInstance(this);
    CookieSyncManager.getInstance().startSync();
    WebView webview = new WebView(this);
    webview.getSettings().setJavaScriptEnabled(true);
    setContentView(webview);      
    webview.loadUrl([MY URL]);
    

    How to add 10 days to current time in Rails

    Try this on Rails

    Time.new + 10.days 
    

    Try this on Ruby

    require 'date'
    DateTime.now.next_day(10).to_time
    

    Generating HTML email body in C#

    As an alternative to MailDefinition, have a look at RazorEngine https://github.com/Antaris/RazorEngine.

    This looks like a better solution.

    Attributted to...

    how to send email wth email template c#

    E.g

    using RazorEngine;
    using RazorEngine.Templating;
    using System;
    
    namespace RazorEngineTest
    {
        class Program
        {
            static void Main(string[] args)
            {
        string template =
        @"<h1>Heading Here</h1>
    Dear @Model.UserName,
    <br />
    <p>First part of the email body goes here</p>";
    
        const string templateKey = "tpl";
    
        // Better to compile once
        Engine.Razor.AddTemplate(templateKey, template);
        Engine.Razor.Compile(templateKey);
    
        // Run is quicker than compile and run
        string output = Engine.Razor.Run(
            templateKey, 
            model: new
            {
                UserName = "Fred"
            });
    
        Console.WriteLine(output);
            }
        }
    }
    

    Which outputs...

    <h1>Heading Here</h1>
    Dear Fred,
    <br />
    <p>First part of the email body goes here</p>
    

    Heading Here

    Dear Fred,

    First part of the email body goes here

    How to access static resources when mapping a global front controller servlet on /*

    'Static' files in App Engine aren't directly accessible by your app. You either need to upload them twice, or serve the static files yourself, rather than using a static handler.

    Insert json file into mongodb

    It happened to me couple of weeks back. The version of mongoimport was too old. Once i Updated to latest version it ran successfully and imported all documents.

    Reference: http://docs.mongodb.org/master/tutorial/install-mongodb-on-ubuntu/?_ga=1.11365492.1588529687.1434379875

    What is the difference between "px", "dip", "dp" and "sp"?

    1) dp: (density independent pixels)

    The number of pixels represented in one unit of dp will increase as the screen resolution increases (when you have more dots/pixels per inch). Conversely on devices with lower resolution, the number of pixels represented in on unit of dp will decrease. Since this is a relative unit, it needs to have a baseline to be compared with. This baseline is a 160 dpi screen. This is the equation: px = dp * (dpi / 160).


    2) sp: (scale independent pixels)

    This unit scales according to the screen dpi (similar to dp) as well as the user’s font size preference.


    3) px: (pixels)

    Actual pixels or dots on the screen.


    For more details you can visit

    Android Developer Guide > Dimension
    Android Developer Guide > Screens

    How to create a hidden <img> in JavaScript?

    Try setting the style to display=none:

    <img src="a.gif" style="display:none">
    

    Writing unit tests in Python: How do I start?

    If you're brand new to using unittests, the simplest approach to learn is often the best. On that basis along I recommend using py.test rather than the default unittest module.

    Consider these two examples, which do the same thing:

    Example 1 (unittest):

    import unittest
    
    class LearningCase(unittest.TestCase):
        def test_starting_out(self):
            self.assertEqual(1, 1)
    
    def main():
        unittest.main()
    
    if __name__ == "__main__":
        main()
    

    Example 2 (pytest):

    def test_starting_out():
        assert 1 == 1
    

    Assuming that both files are named test_unittesting.py, how do we run the tests?

    Example 1 (unittest):

    cd /path/to/dir/
    python test_unittesting.py
    

    Example 2 (pytest):

    cd /path/to/dir/
    py.test
    

    How to remove new line characters from a string?

    You can use Trim if you want to remove from start and end.

    string stringWithoutNewLine = "\n\nHello\n\n".Trim();
    

    Is key-value pair available in Typescript?

    Another simple way is to use a tuple:

    // Declare a tuple type
    let x: [string, number];
    // Initialize it
    x = ["hello", 10];
    // Access elements
    console.log("First: " + x["0"] + " Second: " + x["1"]);
    

    Output:

    First: hello Second: 10

    git: How to ignore all present untracked files?

    If you want to permanently ignore these files, a simple way to add them to .gitignore is:

    1. Change to the root of the git tree.
    2. git ls-files --others --exclude-standard >> .gitignore

    This will enumerate all files inside untracked directories, which may or may not be what you want.

    How to create a custom attribute in C#

    You start by writing a class that derives from Attribute:

    public class MyCustomAttribute: Attribute
    {
        public string SomeProperty { get; set; }
    }
    

    Then you could decorate anything (class, method, property, ...) with this attribute:

    [MyCustomAttribute(SomeProperty = "foo bar")]
    public class Foo
    {
    
    }
    

    and finally you would use reflection to fetch it:

    var customAttributes = (MyCustomAttribute[])typeof(Foo).GetCustomAttributes(typeof(MyCustomAttribute), true);
    if (customAttributes.Length > 0)
    {
        var myAttribute = customAttributes[0];
        string value = myAttribute.SomeProperty;
        // TODO: Do something with the value
    }
    

    You could limit the target types to which this custom attribute could be applied using the AttributeUsage attribute:

    /// <summary>
    /// This attribute can only be applied to classes
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public class MyCustomAttribute : Attribute
    

    Important things to know about attributes:

    • Attributes are metadata.
    • They are baked into the assembly at compile-time which has very serious implications of how you could set their properties. Only constant (known at compile time) values are accepted
    • The only way to make any sense and usage of custom attributes is to use Reflection. So if you don't use reflection at runtime to fetch them and decorate something with a custom attribute don't expect much to happen.
    • The time of creation of the attributes is non-deterministic. They are instantiated by the CLR and you have absolutely no control over it.

    How can I find WPF controls by name or type?

    exciton80... I was having a problem with your code not recursing through usercontrols. It was hitting the Grid root and throwing an error. I believe this fixes it for me:

    public static object[] FindControls(this FrameworkElement f, Type childType, int maxDepth)
    {
        return RecursiveFindControls(f, childType, 1, maxDepth);
    }
    
    private static object[] RecursiveFindControls(object o, Type childType, int depth, int maxDepth = 0)
    {
        List<object> list = new List<object>();
        var attrs = o.GetType().GetCustomAttributes(typeof(ContentPropertyAttribute), true);
        if (attrs != null && attrs.Length > 0)
        {
            string childrenProperty = (attrs[0] as ContentPropertyAttribute).Name;
            if (String.Equals(childrenProperty, "Content") || String.Equals(childrenProperty, "Children"))
            {
                var collection = o.GetType().GetProperty(childrenProperty).GetValue(o, null);
                if (collection is System.Windows.Controls.UIElementCollection) // snelson 6/6/11
                {
                    foreach (var c in (IEnumerable)collection)
                    {
                        if (c.GetType().FullName == childType.FullName)
                            list.Add(c);
                        if (maxDepth == 0 || depth < maxDepth)
                            list.AddRange(RecursiveFindControls(
                                c, childType, depth + 1, maxDepth));
                    }
                }
                else if (collection != null && collection.GetType().BaseType.Name == "Panel") // snelson 6/6/11; added because was skipping control (e.g., System.Windows.Controls.Grid)
                {
                    if (maxDepth == 0 || depth < maxDepth)
                        list.AddRange(RecursiveFindControls(
                            collection, childType, depth + 1, maxDepth));
                }
            }
        }
        return list.ToArray();
    }
    

    SQL ORDER BY multiple columns

    Yes, the sorting is different.

    Items in the ORDER BY list are applied in order.
    Later items only order peers left from the preceding step.

    Why don't you just try?

    foreach with index

    I just figured out interesting solution:

    public class DepthAware<T> : IEnumerable<T>
    {
        private readonly IEnumerable<T> source;
    
        public DepthAware(IEnumerable<T> source)
        {
            this.source = source;
            this.Depth = 0;
        }
    
        public int Depth { get; private set; }
    
        private IEnumerable<T> GetItems()
        {
            foreach (var item in source)
            {
                yield return item;
                ++this.Depth;
            }
        }
    
        public IEnumerator<T> GetEnumerator()
        {
            return GetItems().GetEnumerator();
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
    
    // Generic type leverage and extension invoking
    public static class DepthAware
    {
        public static DepthAware<T> AsDepthAware<T>(this IEnumerable<T> source)
        {
            return new DepthAware<T>(source);
        }
    
        public static DepthAware<T> New<T>(IEnumerable<T> source)
        {
            return new DepthAware<T>(source);
        }
    }
    

    Usage:

    var chars = new[] {'a', 'b', 'c', 'd', 'e', 'f', 'g'}.AsDepthAware();
    
    foreach (var item in chars)
    {
        Console.WriteLine("Char: {0}, depth: {1}", item, chars.Depth);
    }
    

    Windows command to convert Unix line endings?

    Late to the party, but there is still no correct answer using a FOR /F loop.
    (But you don't need a FOR loop at all, the solution from @TampaHaze works too and is much simpler)

    The answer from @IR relevant has some drawbacks.
    It drops the exclamation marks and can also drop carets.

    @echo off
    (
        setlocal Disabledelayedexpansion
        for /f "tokens=* delims=" %%L in ('findstr /n "^" "%~1"') do (
            set "line=%%L"
            setlocal enabledelayedexpansion
            set "line=!line:*:=!"
            (echo(!line!)
            endlocal
        )
    ) > file.dos
    

    The trick is to use findstr /n to prefix each line with <line number>:, this avoids skipping of empty lines or lines beginning with ;.
    To remove the <number>: the FOR "tokens=1,* delims=:" option can't be used, because this would remove all leading colons in a line, too.

    Therefore the line number is removed by set "line=!line:*:=!", this requires EnableDelayedExpansion.
    But with EnableDelayedExpansion the line set "line=%%L" would drop all exclamation marks and also carets (only when exclams are in the line).

    That's why I disable the delayed expansion before and only enable it for the two lines, where it is required.

    The (echo(!line!) looks strange, but has the advantage, that echo( can display any content in !line! and the outer parenthesis avoids accidentials whitespaces at the line end.

    Regular Expression to find a string included between two characters while EXCLUDING the delimiters

    If you are using JavaScript, the solution provided by cletus, (?<=\[)(.*?)(?=\]) won't work because JavaScript doesn't support the lookbehind operator.

    Edit: actually, now (ES2018) it's possible to use the lookbehind operator. Just add / to define the regex string, like this:

    var regex = /(?<=\[)(.*?)(?=\])/;
    

    Old answer:

    Solution:

    var regex = /\[(.*?)\]/;
    var strToMatch = "This is a test string [more or less]";
    var matched = regex.exec(strToMatch);
    

    It will return:

    ["[more or less]", "more or less"]
    

    So, what you need is the second value. Use:

    var matched = regex.exec(strToMatch)[1];
    

    To return:

    "more or less"
    

    Proper way to restrict text input values (e.g. only numbers)

    I use this one:

    
    import { Directive, ElementRef, HostListener, Input, Output, EventEmitter } from '@angular/core';
    
    @Directive({
        selector: '[ngModel][onlyNumber]',
        host: {
            "(input)": 'onInputChange($event)'
        }
    })
    export class OnlyNumberDirective {
    
        @Input() onlyNumber: boolean;
        @Output() ngModelChange: EventEmitter<any> = new EventEmitter()
    
        constructor(public el: ElementRef) {
        }
    
        public onInputChange($event){
            if ($event.target.value == '-') {
                return;
            }
    
            if ($event.target.value && $event.target.value.endsWith('.')) {
                return;
            }
    
            $event.target.value = this.parseNumber($event.target.value);
            $event.target.dispatchEvent(new Event('input'));
        }
    
        @HostListener('blur', ['$event'])
        public onBlur(event: Event) {
            if (!this.onlyNumber) {
                return;
            }
    
            this.el.nativeElement.value = this.parseNumber(this.el.nativeElement.value);
            this.el.nativeElement.dispatchEvent(new Event('input'));
        }
    
        private parseNumber(input: any): any {
            let trimmed = input.replace(/[^0-9\.-]+/g, '');
            let parsedNumber = parseFloat(trimmed);
    
            return !isNaN(parsedNumber) ? parsedNumber : '';
        }
    
    }
    

    and usage is following

    <input onlyNumbers="true" ... />
    

    Combine :after with :hover

    Just append :after to your #alertlist li:hover selector the same way you do with your #alertlist li.selected selector:

    #alertlist li.selected:after, #alertlist li:hover:after
    {
        position:absolute;
        top: 0;
        right:-10px;
        bottom:0;
    
        border-top: 10px solid transparent;
        border-bottom: 10px solid transparent;
        border-left: 10px solid #303030;
        content: "";
    }
    

    Can I write into the console in a unit test? If yes, why doesn't the console window open?

    IMHO, output messages are relevant only for failed test cases in most cases. I made up the below format, and you can make your own too. This is displayed in the Visual Studio Test Explorer Window itself.

    How can we throw this message in the Visual Studio Test Explorer Window?

    Sample code like this should work:

    if(test_condition_fails)
        Assert.Fail(@"Test Type: Positive/Negative.
                    Mock Properties: someclass.propertyOne: True
                    someclass.propertyTwo: True
                    Test Properties: someclass.testPropertyOne: True
                    someclass.testPropertyOne: False
                    Reason for Failure: The Mail was not sent on Success Task completion.");
    

    You can have a separate class dedicated to this for you.

    Multidimensional arrays in Swift

    For future readers, here is an elegant solution(5x5):

    var matrix = [[Int]](repeating: [Int](repeating: 0, count: 5), count: 5)

    and a dynamic approach:

    var matrix = [[Int]]() // creates an empty matrix
    var row = [Int]() // fill this row
    matrix.append(row) // add this row
    

    Long Press in JavaScript?

    You can use taphold event of jQuery mobile API.

    jQuery("a").on("taphold", function( event ) { ... } )
    

    Preview an image before it is uploaded

    Example with multiple images using JavaScript (jQuery) and HTML5

    JavaScript (jQuery)

    function readURL(input) {
         for(var i =0; i< input.files.length; i++){
             if (input.files[i]) {
                var reader = new FileReader();
    
                reader.onload = function (e) {
                   var img = $('<img id="dynamic">');
                   img.attr('src', e.target.result);
                   img.appendTo('#form1');  
                }
                reader.readAsDataURL(input.files[i]);
               }
            }
        }
    
        $("#imgUpload").change(function(){
            readURL(this);
        });
    }
    

    Markup (HTML)

    <form id="form1" runat="server">
        <input type="file" id="imgUpload" multiple/>
    </form>
    

    SSH SCP Local file to Remote in Terminal Mac Os X

    Watch that your file name doesn't have : in them either. I found that I had to mv blah-07-08-17-02:69.txt no_colons.txt and then scp no-colons.txt server: then don't forget to mv back on the server. Just in case this was an issue.

    Return Boolean Value on SQL Select Statement

    DECLARE @isAvailable      BIT = 0;
    
    IF EXISTS(SELECT 1  FROM [User] WHERE (UserID = 20070022))
    BEGIN
     SET @isAvailable = 1
    END
    

    initially isAvailable boolean value is set to 0

    Fragment onResume() & onPause() is not called on backstack

    getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {
                List<Fragment> fragments = getFragmentManager().getFragments();
                if (fragments.size() > 0 && fragments.get(fragments.size() - 1) instanceof YoureFragment){
                    //todo if fragment visible
                } else {
                    //todo if fragment invisible
                }
    
            }
        });
    

    but be careful if more than one fragment visible

    Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

    Remove the FormsModule from Declaration:[] and Add the FormsModule in imports:[]

    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        FormsModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    
    

    How to find the size of a table in SQL?

    SQL Server provides a built-in stored procedure that you can run to easily show the size of a table, including the size of the indexes… which might surprise you.

    Syntax:

     sp_spaceused 'Tablename'
    

    see in :

    http://www.howtogeek.com/howto/database/determine-size-of-a-table-in-sql-server/

    New lines (\r\n) are not working in email body

    Using <BR> is not allways enough. MS Outlook 2007 will ignore this if you dont tell outlook that it is a selfclosing html tag by using

     <BR />
    

    Link to download apache http server for 64bit windows.

    Check out the link given it has Apache HTTP Server 2.4.2 x86 and x64 Windows Installers http://www.anindya.com/apache-http-server-2-4-2-x86-and-x64-windows-installers/

    Change Screen Orientation programmatically using a Button

    Yes, you can set the screen orientation programatically anytime you want using:

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    

    for landscape and portrait mode respectively. The setRequestedOrientation() method is available for the Activity class, so it can be used inside your Activity.

    And this is how you can get the current screen orientation and set it adequatly depending on its current state:

    Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
    final int orientation = display.getOrientation(); 
     // OR: orientation = getRequestedOrientation(); // inside an Activity
    
    // set the screen orientation on button click
    Button btn = (Button) findViewById(R.id.yourbutton);
    btn.setOnClickListener(new View.OnClickListener() {
              public void onClick(View v) {
    
                  switch(orientation) {
                       case Configuration.ORIENTATION_PORTRAIT:
                           setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                           break;
                       case Configuration.ORIENTATION_LANDSCAPE:
                           setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                           break;                   
                   }
              }
       });
    

    Taken from here: http://techblogon.com/android-screen-orientation-change-rotation-example/

    EDIT

    Also, you can get the screen orientation using the Configuration:

    Activity.getResources().getConfiguration().orientation
    

    Limit number of characters allowed in form input text field

    According to w3c, the default value for the MAXLENGTH attribute is an unlimited number. So if you don't specify the max a user could cut and paste the bible a couple of times and stick it in your form.

    Even if you do specify the MAXLENGTH to a reasonable number make sure you double check the length of the submitted data on the server before processing (using something like php or asp) as it's quite easy to get around the basic MAXLENGTH restriction anyway

    Is there a function to round a float in C or do I need to write my own?

    you can use #define round(a) (int) (a+0.5) as macro so whenever you write round(1.6) it returns 2 and whenever you write round(1.3) it return 1.

    dplyr mutate with conditional values

    Try this:

    myfile %>% mutate(V5 = (V1 == 1 & V2 != 4) + 2 * (V2 == 4 & V3 != 1))
    

    giving:

      V1 V2 V3 V4 V5
    1  1  2  3  5  1
    2  2  4  4  1  2
    3  1  4  1  1  0
    4  4  5  1  3  0
    5  5  5  5  4  0
    

    or this:

    myfile %>% mutate(V5 = ifelse(V1 == 1 & V2 != 4, 1, ifelse(V2 == 4 & V3 != 1, 2, 0)))
    

    giving:

      V1 V2 V3 V4 V5
    1  1  2  3  5  1
    2  2  4  4  1  2
    3  1  4  1  1  0
    4  4  5  1  3  0
    5  5  5  5  4  0
    

    Note

    Suggest you get a better name for your data frame. myfile makes it seem as if it holds a file name.

    Above used this input:

    myfile <- 
    structure(list(V1 = c(1L, 2L, 1L, 4L, 5L), V2 = c(2L, 4L, 4L, 
    5L, 5L), V3 = c(3L, 4L, 1L, 1L, 5L), V4 = c(5L, 1L, 1L, 3L, 4L
    )), .Names = c("V1", "V2", "V3", "V4"), class = "data.frame", row.names = c("1", 
    "2", "3", "4", "5"))
    

    Update 1 Since originally posted dplyr has changed %.% to %>% so have modified answer accordingly.

    Update 2 dplyr now has case_when which provides another solution:

    myfile %>% 
           mutate(V5 = case_when(V1 == 1 & V2 != 4 ~ 1, 
                                 V2 == 4 & V3 != 1 ~ 2,
                                 TRUE ~ 0))
    

    Set Page Title using PHP

    Move the data retrieval at the top of the script, and after that use:

    <title>Ultan.me - <?php echo htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); ?></title>
    

    Using Mockito to mock classes with generic parameters

    You could always create an intermediate class/interface that would satisfy the generic type that you are wanting to specify. For example, if Foo was an interface, you could create the following interface in your test class.

    private interface FooBar extends Foo<Bar>
    {
    }
    

    In situations where Foo is a non-final class, you could just extend the class with the following code and do the same thing:

    public class FooBar extends Foo<Bar>
    {
    }
    

    Then you could consume either of the above examples with the following code:

    Foo<Bar> mockFoo = mock(FooBar.class);
    when(mockFoo.getValue()).thenReturn(new Bar());
    

    Remove header and footer from window.print()

    This will be the simplest solution. I tried most of the solutions in the internet but only this helped me.

    @print{
        @page :footer {color: #fff }
        @page :header {color: #fff}
    }
    

    Get a specific bit from byte

    another way of doing it :)

    return ((b >> bitNumber) & 1) != 0;
    

    Where is the correct location to put Log4j.properties in an Eclipse project?

    Add the log4j.properties file to the runtime class path of the project. Some people add this to the root of the source tree (so that it gets copied to the root of the compiled classes).

    Edit: If your project is a maven project, you can put the log4j.properties in the src/main/resources folder (and the src/test/resources for your unit tests).

    If you have multiple environments (for example development and production), want different logging for each environment, and want to deploy the same jar (or war, or ear) file to each environment (as in one build for all environments) then store the log4j.properties file outside of the jar file and put it in the class path for each environment (configurable by environment). Historically, I would include some known directory in each environment in the classpath and deploy environment specific stuff there. For example, ~tomcat_user/localclasspath where ~tomcat_user is the home directory of the user that will be running the tomcat instance to which my war file will be deployed.

    Get string character by index - Java

    CharAt function not working

    Edittext.setText(YourString.toCharArray(),0,1);

    This code working fine

    Computing cross-correlation function?

    I just finished writing my own optimised implementation of normalized cross-correlation for N-dimensional arrays. You can get it from here.

    It will calculate cross-correlation either directly, using scipy.ndimage.correlate, or in the frequency domain, using scipy.fftpack.fftn/ifftn depending on whichever will be quickest.

    There has been an error processing your request, Error log record number

    Go to magento/var/report and open the file with the Error log record number name i.e 673618173351 in your case. In that file you can find the complete description of the error.

    For log files like system.log and exception.log, go to magento/var/log/.

    Sleep function in C++

    Use std::this_thread::sleep_for:

    #include <chrono>
    #include <thread>
    
    std::chrono::milliseconds timespan(111605); // or whatever
    
    std::this_thread::sleep_for(timespan);
    

    There is also the complementary std::this_thread::sleep_until.


    Prior to C++11, C++ had no thread concept and no sleep capability, so your solution was necessarily platform dependent. Here's a snippet that defines a sleep function for Windows or Unix:

    #ifdef _WIN32
        #include <windows.h>
    
        void sleep(unsigned milliseconds)
        {
            Sleep(milliseconds);
        }
    #else
        #include <unistd.h>
        
        void sleep(unsigned milliseconds)
        {
            usleep(milliseconds * 1000); // takes microseconds
        }
    #endif
    

    But a much simpler pre-C++11 method is to use boost::this_thread::sleep.

    Macro to Auto Fill Down to last adjacent cell

    Untested....but should work.

    Dim lastrow as long
    
    lastrow = range("D65000").end(xlup).Row
    
    ActiveCell.FormulaR1C1 = _
            "=IF(MONTH(RC[-1])>3,"" ""&YEAR(RC[-1])&""-""&RIGHT(YEAR(RC[-1])+1,2),"" ""&YEAR(RC[-1])-1&""-""&RIGHT(YEAR(RC[-1]),2))"
        Selection.AutoFill Destination:=Range("E2:E" & lastrow)
        'Selection.AutoFill Destination:=Range("E2:E"& lastrow)
        Range("E2:E1344").Select
    

    Only exception being are you sure your Autofill code is perfect...

    How can I catch a ctrl-c event?

    signal isn't the most reliable way as it differs in implementations. I would recommend using sigaction. Tom's code would now look like this :

    #include <signal.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <unistd.h>
    
    void my_handler(int s){
               printf("Caught signal %d\n",s);
               exit(1); 
    
    }
    
    int main(int argc,char** argv)
    {
    
       struct sigaction sigIntHandler;
    
       sigIntHandler.sa_handler = my_handler;
       sigemptyset(&sigIntHandler.sa_mask);
       sigIntHandler.sa_flags = 0;
    
       sigaction(SIGINT, &sigIntHandler, NULL);
    
       pause();
    
       return 0;    
    }
    

    How to automate drag & drop functionality using Selenium WebDriver Java

    For xpath you can use the above commands like this :

    WebElement element = driver.findElement(By.xpath("enter xpath of source element here")); 
    WebElement target = driver.findElement(By.xpath("enter xpath of target here"));
    (new Actions(driver)).dragAndDrop(element, target).perform();
    

    Submit button not working in Bootstrap form

    The .btn classes are designed for , or elements (though some browsers may apply a slightly different rendering).

    If you’re using .btn classes on elements that are used to trigger functionality ex. collapsing content, these links should be given a role="button" to adequately communicate their meaning to assistive technologies such as screen readers. I hope this help.

    Close Form Button Event

    Try this:

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        // You may decide to prompt to user else just kill.
        Process.GetCurrentProcess().Goose();
    } 
    

    Difference between FetchType LAZY and EAGER in Java Persistence API?

    I want to add this note to what said above.

    Suppose you are using Spring Rest with this simple architect:

    Controller <-> Service <-> Repository

    And you want to return some data to the front-end, if you are using FetchType.LAZY, you will get an exception after you return data to the controller method since the session is closed in the Service so the JSON Mapper Object can't get the data.

    There is three common options to solve this problem, depends on the design, performance and the developer:

    1. The easiest one is to use FetchType.EAGER, So that the session will still alive at the controller method, but this method will impact the performance.
    2. Anti-patterns solutions, to make the session live until the execution ends, it is make a huge performance issue in the system.
    3. The best practice is to use FetchType.LAZY with mapper like MapStruct to transfer data from Entity to another data object DTO and then send it back to the controller, so there is no exception if the session closed.

    Draw horizontal rule in React Native

    This is in React Native (JSX) code, updated to today:

    <View style = {styles.viewStyleForLine}></View>
    
    const styles = StyleSheet.create({
    viewStyleForLine: {
        borderBottomColor: "black", 
        borderBottomWidth: StyleSheet.hairlineWidth, 
        alignSelf:'stretch',
        width: "100%"
      }
    })
    

    you can use either alignSelf:'stretch' or width: "100%" both should work... and,

    borderBottomWidth: StyleSheet.hairlineWidth
    

    here StyleSheet.hairlineWidth is the thinnest, then,

    borderBottomWidth: 1,
    

    and so on to increase thickness of the line.

    Is there a cross-browser onload event when clicking the back button?

    Some modern browsers (Firefox, Safari, and Opera, but not Chrome) support the special "back/forward" cache (I'll call it bfcache, which is a term invented by Mozilla), involved when the user navigates Back. Unlike the regular (HTTP) cache, it captures the complete state of the page (including the state of JS, DOM). This allows it to re-load the page quicker and exactly as the user left it.

    The load event is not supposed to fire when the page is loaded from this bfcache. For example, if you created your UI in the "load" handler, and the "load" event was fired once on the initial load, and the second time when the page was re-loaded from the bfcache, the page would end up with duplicate UI elements.

    This is also why adding the "unload" handler stops the page from being stored in the bfcache (thus making it slower to navigate back to) -- the unload handler could perform clean-up tasks, which could leave the page in unworkable state.

    For pages that need to know when they're being navigated away/back to, Firefox 1.5+ and the version of Safari with the fix for bug 28758 support special events called "pageshow" and "pagehide".

    References:

    Put spacing between divs in a horizontal row?

    Another idea: Compensate for your margin on the opposite side of the div.

    For the side with the spacing you are looking to achieve as an example: 10px, and for the opposing side, compensate with a -10px. It works for me. This likely won't work in all scenarios, but depending on your layout and spacing of other elements, it might work great.

    Get the filePath from Filename using Java

    Look at the methods in the java.io.File class:

    File file = new File("yourfileName");
    String path = file.getAbsolutePath();
    

    How to update each dependency in package.json to the latest version?

    The above commands are unsafe because you might break your module when switching versions. Instead I recommend the following

    • Set actual current node modules version into package.json using npm shrinkwrap command.
    • Update each dependency to the latest version IF IT DOES NOT BREAK YOUR TESTS using https://github.com/bahmutov/next-update command line tool
    npm install -g next-update
    // from your package
    next-update
    

    Set Locale programmatically

     /**
     * Requests the system to update the list of system locales.
     * Note that the system looks halted for a while during the Locale migration,
     * so the caller need to take care of it.
     */
    public static void updateLocales(LocaleList locales) {
        try {
            final IActivityManager am = ActivityManager.getService();
            final Configuration config = am.getConfiguration();
    
            config.setLocales(locales);
            config.userSetLocale = true;
    
            am.updatePersistentConfiguration(config);
        } catch (RemoteException e) {
            // Intentionally left blank
        }
    }
    

    jQuery javascript regex Replace <br> with \n

    True jQuery way if you want to change directly the DOM without messing with inner HTML:

    $('#text').find('br').prepend(document.createTextNode('\n')).remove();

    Prepend inserts inside the element, before() is the method we need here:

    $('#text').find('br').before(document.createTextNode('\n')).remove();
    

    Code will find any <br> elements, insert raw text with new line character and then remove the <br> elements.

    This should be faster if you work with long texts since there are no string operations here.

    To display the new lines:

    $('#text').css('white-space', 'pre-line');
    

    Inserting values to SQLite table in Android

    Since you are new to Android development you may not know about Content Providers, which are database abstractions. They may not be the right thing for your project, but you should check them out: http://developer.android.com/guide/topics/providers/content-providers.html

    How do I access (read, write) Google Sheets spreadsheets with Python?

    Take a look at gspread port for api v4 - pygsheets. It should be very easy to use rather than the google client.

    Sample example

    import pygsheets
    
    gc = pygsheets.authorize()
    
    # Open spreadsheet and then workseet
    sh = gc.open('my new ssheet')
    wks = sh.sheet1
    
    # Update a cell with value (just to let him know values is updated ;) )
    wks.update_cell('A1', "Hey yank this numpy array")
    
    # update the sheet with array
    wks.update_cells('A2', my_nparray.to_list())
    
    # share the sheet with your friend
    sh.share("[email protected]")
    

    See the docs here.

    Author here.

    Mysql: Setup the format of DATETIME to 'DD-MM-YYYY HH:MM:SS' when creating a table

    "MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format." This is from mysql site. You can store only this type, but you can use one of the many time format functions to change it, when you need to display it.

    Mysql Time and Date functions

    For example, one of those functions is the DATE_FORMAT, which can be used like so:

    SELECT DATE_FORMAT(column_name, '%m/%d/%Y %H:%i') FROM tablename
    

    ASP.net using a form to insert data into an sql server table

    Simple, make a simple asp page with the designer (just for the beginning) Lets say the body is something like this:

    <body>
        <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            <br />
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        </div>
        <p>
            <asp:Button ID="Button1" runat="server" Text="Button" />
        </p>
        </form>
    </body>
    

    Great, now every asp object IS an object. So you can access it in the asp's CS code. The asp's CS code is triggered by events (mostly). The class will probably inherit from System.Web.UI.Page

    If you go to the cs file of the asp page, you'll see a protected void Page_Load(object sender, EventArgs e) ... That's the load event, you can use that to populate data into your objects when the page loads.

    Now, go to the button in your designer (Button1) and look at its properties, you can design it, or add events from there. Just change to the events view, and create a method for the event.

    The button is a web control Button Add a Click event to the button call it Button1Click:

    void Button1Click(Object sender,EventArgs e) { }
    

    Now when you click the button, this method will be called. Because ASP is object oriented, you can think of the page as the actual class, and the objects will hold the actual current data.

    So if for example you want to access the text in TextBox1 you just need to call that object in the C# code:

    String firstBox = TextBox1.Text;
    

    In the same way you can populate the objects when event occur.

    Now that you have the data the user posted in the textboxes , you can use regular C# SQL connections to add the data to your database.

    When should an Excel VBA variable be killed or set to Nothing?

    I have at least one situation where the data is not automatically cleaned up, which would eventually lead to "Out of Memory" errors. In a UserForm I had:

    Public mainPicture As StdPicture
    ...
    mainPicture = LoadPicture(PAGE_FILE)
    

    When UserForm was destroyed (after Unload Me) the memory allocated for the data loaded in the mainPicture was not being de-allocated. I had to add an explicit

    mainPicture = Nothing
    

    in the terminate event.

    PostgreSQL psql terminal command

    These are not command line args. Run psql. Manage to log into database (so pass the hostname, port, user and database if needed). And then write it in the psql program.

    Example (below are two commands, write the first one, press enter, wait for psql to login, write the second):

    psql -h host -p 5900 -U username database
    \pset format aligned
    

    Substitute a comma with a line break in a cell

    Windows (unlike some other OS's, like Linux), uses CR+LF for line breaks:

    • CR = 13 = 0x0D = ^M = \r = carriage return

    • LF = 10 = 0x0A = ^J = \n = new line

    The characters need to be in that order, if you want the line breaks to be consistently visible when copied to other Windows programs. So the Excel function would be:

    =SUBSTITUTE(A1,",",CHAR(13) & CHAR(10))

    Jquery get input array field

    You can give your input textboxes class names, like so:

    <input type="text" value="2" name="pages_title[1]" class="pages_title">
    <input type="text" value="1" name="pages_title[2]" class="pages_title">
    

    and iterate like so:

    $('input.pages_title').each(function() {
        alert($(this).val()); 
    });
    

    Clicking the back button twice to exit an activity

    You may use a snackbar instead of a toast, so you can rely on their visibility to decide whether to close the app or not. Take this example:

    Snackbar mSnackbar;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        final LinearLayout layout = findViewById(R.id.layout_main);
        mSnackbar = Snackbar.make(layout, R.string.press_back_again, Snackbar.LENGTH_SHORT);
    }
    
    @Override
    public void onBackPressed() {
        if (mSnackbar.isShown()) {
            super.onBackPressed();
        } else {
            mSnackbar.show();
        }
    }
    

    How do I add items to an array in jQuery?

    Since $.getJSON is async, I think your console.log(list.length); code is firing before your array has been populated. To correct this put your console.log statement inside your callback:

    var list = new Array();
    $.getJSON("json.js", function(data) {
        $.each(data, function(i, item) {
            console.log(item.text);
            list.push(item.text);
        });
        console.log(list.length);
    });
    

    Why would an Enum implement an Interface?

    I used an inner enum in an interface describing a strategy to keep instance control (each strategy is a Singleton) from there.

    public interface VectorizeStrategy {
    
        /**
         * Keep instance control from here.
         * 
         * Concrete classes constructors should be package private.
         */
        enum ConcreteStrategy implements VectorizeStrategy {
            DEFAULT (new VectorizeImpl());
    
            private final VectorizeStrategy INSTANCE;
    
            ConcreteStrategy(VectorizeStrategy concreteStrategy) {
                INSTANCE = concreteStrategy;
            }
    
            @Override
            public VectorImageGridIntersections processImage(MarvinImage img) {
                return INSTANCE.processImage(img);
            }
        }
    
        /**
         * Should perform edge Detection in order to have lines, that can be vectorized.
         * 
         * @param img An Image suitable for edge detection.
         * 
         * @return the VectorImageGridIntersections representing img's vectors 
         * intersections with the grids.
         */
        VectorImageGridIntersections processImage(MarvinImage img);
    }
    

    The fact that the enum implements the strategy is convenient to allow the enum class to act as proxy for its enclosed Instance. which also implements the interface.

    it's a sort of strategyEnumProxy :P the clent code looks like this:

    VectorizeStrategy.ConcreteStrategy.DEFAULT.processImage(img);
    

    If it didn't implement the interface it'd had been:

    VectorizeStrategy.ConcreteStrategy.DEFAULT.getInstance().processImage(img);
    

    HTML text input field with currency symbol

    _x000D_
    _x000D_
    .currencyinput {_x000D_
        border: 1px inset #ccc;_x000D_
        padding-bottom: 1px;//FOR IE & Chrome_x000D_
    }_x000D_
    .currencyinput input {_x000D_
        border: 0;_x000D_
    }
    _x000D_
    <span class="currencyinput">$<input type="text" name="currency"></span>
    _x000D_
    _x000D_
    _x000D_

    Updating a java map entry

    Use

    table.put(key, val);
    

    to add a new key/value pair or overwrite an existing key's value.

    From the Javadocs:

    V put(K key, V value): Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)

    Combining multiple condition in single case statement in Sql Server

    You can put the condition after the WHEN clause, like so:

    SELECT
      CASE
        WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.ELIGIBILITY is null THEN 'Favor'
        WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.EL = 'No' THEN 'Error'
        WHEN PAT_ENTRY.EL = 'Yes' and ISNULL(DS.DES, 'OFF') = 'OFF' THEN 'Active'
        WHEN DS.DES = 'N' THEN 'Early Term'
        WHEN DS.DES = 'Y' THEN 'Complete'
      END
    FROM
      ....
    

    Of course, the argument could be made that complex rules like this belong in your business logic layer, not in a stored procedure in the database...

    Get current URL with jQuery?

    For the host name only, use:

    window.location.hostname
    

    Vue.js toggle class on click

    I've got a solution that allows you to check for different values of a prop and thus different <th> elements will become active/inactive. Using vue 2 syntax.

    <th 
    class="initial " 
    @click.stop.prevent="myFilter('M')"
    :class="[(activeDay == 'M' ? 'active' : '')]">
    <span class="wkday">M</span>
    </th>
    ...
    <th 
    class="initial " 
    @click.stop.prevent="myFilter('T')"
    :class="[(activeDay == 'T' ? 'active' : '')]">
    <span class="wkday">T</span>
    </th>
    
    
    
    new Vue({
      el: '#my-container',
    
      data: {
          activeDay: 'M'
      },
    
      methods: {
        myFilter: function(day){
            this.activeDay = day;
          // some code to filter users
        }
      }
    })
    

    How to validate date with format "mm/dd/yyyy" in JavaScript?

    I think Niklas has the right answer to your problem. Besides that, I think the following date validation function is a little bit easier to read:

    // Validates that the input string is a valid date formatted as "mm/dd/yyyy"
    function isValidDate(dateString)
    {
        // First check for the pattern
        if(!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString))
            return false;
    
        // Parse the date parts to integers
        var parts = dateString.split("/");
        var day = parseInt(parts[1], 10);
        var month = parseInt(parts[0], 10);
        var year = parseInt(parts[2], 10);
    
        // Check the ranges of month and year
        if(year < 1000 || year > 3000 || month == 0 || month > 12)
            return false;
    
        var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
    
        // Adjust for leap years
        if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
            monthLength[1] = 29;
    
        // Check the range of the day
        return day > 0 && day <= monthLength[month - 1];
    };
    

    add string to String array

    Since Java arrays hold a fixed number of values, you need to create a new array with a length of 5 in this case. A better solution would be to use an ArrayList and simply add strings to the array.

    Example:

    ArrayList<String> scripts = new ArrayList<String>();
    scripts.add("test3");
    scripts.add("test4");
    scripts.add("test5");
    
    // Then later you can add more Strings to the ArrayList
    scripts.add("test1");
    scripts.add("test2");
    

    Wait until page is loaded with Selenium WebDriver for Python

    You can do that very simple by this function:

    def page_is_loading(driver):
        while True:
            x = driver.execute_script("return document.readyState")
            if x == "complete":
                return True
            else:
                yield False
    

    and when you want do something after page loading complete,you can use:

    Driver = webdriver.Firefox(options=Options, executable_path='geckodriver.exe')
    Driver.get("https://www.google.com/")
    
    while not page_is_loading(Driver):
        continue
    
    Driver.execute_script("alert('page is loaded')")
    

    How to convert a string of numbers to an array of numbers?

    You can use JSON.parse, adding brakets to format Array

    _x000D_
    _x000D_
    const a = "1,2,3,4";
    const myArray = JSON.parse(`[${a}]`)
    console.log(myArray)
    console.info('pos 2 = ',  myArray[2])
    _x000D_
    _x000D_
    _x000D_

    Is it possible to use vh minus pixels in a CSS calc()?

    It does work indeed. Issue was with my less compiler. It was compiled in to:

    .container {
      min-height: calc(-51vh);
    }
    

    Fixed with the following code in less file:

    .container {
      min-height: calc(~"100vh - 150px");
    }
    

    Thanks to this link: Less Aggressive Compilation with CSS3 calc

    Removing an item from a select box

    I just want to suggest another way to add an option. Instead of setting the value and text as a string one can also do:

    var option = $('<option/>')
                      .val('option5')
                      .text('option5');
    
    $('#selectBox').append(option);
    

    This is a less error-prone solution when adding options' values and texts dynamically.

    How do I check if an element is hidden in jQuery?

    Instead of writing an event for every single element, do this:

    $('div').each(function(){
      if($(this).css('display') === 'none'){
        $(this).css({'display':'block'});
      }
    });
    

    Also you can use it on the inputs:

    $('input').each(function(){
      if($(this).attr('type') === 'hidden'){
        $(this).attr('type', 'text');
      }
    });
    

    Error in if/while (condition) {: missing Value where TRUE/FALSE needed

    this works with "NA" not for NA

    comments = c("no","yes","NA")
      for (l in 1:length(comments)) {
        #if (!is.na(comments[l])) print(comments[l])
        if (comments[l] != "NA") print(comments[l])
      }
    

    git diff between cloned and original remote repository

    1) Add any remote repositories you want to compare:

    git remote add foobar git://github.com/user/foobar.git
    

    2) Update your local copy of a remote:

    git fetch foobar
    

    Fetch won't change your working copy.

    3) Compare any branch from your local repository to any remote you've added:

    git diff master foobar/master
    

    ERROR 2006 (HY000): MySQL server has gone away

    Just in case, to check variables you can use

    $> mysqladmin variables -u user -p 
    

    This will display the current variables, in this case max_allowed_packet, and as someone said in another answer you can set it temporarily with

    mysql> SET GLOBAL max_allowed_packet=1072731894
    

    In my case the cnf file was not taken into account and I don't know why, so the SET GLOBAL code really helped.

    What's the function like sum() but for multiplication? product()?

    Numeric.product 
    

    ( or

    reduce(lambda x,y:x*y,[3,4,5])
    

    )

    Is it possible to install iOS 6 SDK on Xcode 5?

    I downloaded XCode 4 and took iOS 6.1 SDK from it to the XCode 5 as described in other answers. Then I also installed iOS 6.1 Simulator (it was available in preferences). I also switched Base SDK to iOS 6.1 in project settings.

    After all these manipulations the project with 6.1 base sdk runs in comp ability mode in iOS 7 Simulator.

    What do Clustered and Non clustered index actually mean?

    Clustered Index: Primary Key constraint creates clustered Index automatically if no clustered Index already exists on the table. Actual data of clustered index can be stored at leaf level of Index.

    Non Clustered Index: Actual data of non clustered index is not directly found at leaf node, instead it has to take an additional step to find because it has only values of row locators pointing towards actual data. Non clustered Index can't be sorted as clustered index. There can be multiple non clustered indexes per table, actually it depends on the sql server version we are using. Basically Sql server 2005 allows 249 Non Clustered Indexes and for above versions like 2008, 2016 it allows 999 Non Clustered Indexes per table.

    PowerShell: Run command from script's directory

    I made a one-liner out of @JohnL's solution:

    $MyInvocation.MyCommand.Path | Split-Path | Push-Location
    

    Powershell: count members of a AD group

    Try:

    $group = Get-ADGroup -Identity your-group-name -Properties *
    
    $group.members | count
    

    This worked for me for a group with over 17000 members.

    Cannot change column used in a foreign key constraint

    The type and definition of foreign key field and reference must be equal. This means your foreign key disallows changing the type of your field.

    One solution would be this:

    LOCK TABLES 
        favorite_food WRITE,
        person WRITE;
    
    ALTER TABLE favorite_food
        DROP FOREIGN KEY fk_fav_food_person_id,
        MODIFY person_id SMALLINT UNSIGNED;
    

    Now you can change you person_id

    ALTER TABLE person MODIFY person_id SMALLINT UNSIGNED AUTO_INCREMENT;
    

    recreate foreign key

    ALTER TABLE favorite_food
        ADD CONSTRAINT fk_fav_food_person_id FOREIGN KEY (person_id)
              REFERENCES person (person_id);
    
    UNLOCK TABLES;
    

    EDIT: Added locks above, thanks to comments

    You have to disallow writing to the database while you do this, otherwise you risk data integrity problems.

    I've added a write lock above

    All writing queries in any other session than your own ( INSERT, UPDATE, DELETE ) will wait till timeout or UNLOCK TABLES; is executed

    http://dev.mysql.com/doc/refman/5.5/en/lock-tables.html

    EDIT 2: OP asked for a more detailed explanation of the line "The type and definition of foreign key field and reference must be equal. This means your foreign key disallows changing the type of your field."

    From MySQL 5.5 Reference Manual: FOREIGN KEY Constraints

    Corresponding columns in the foreign key and the referenced key must have similar internal data types inside InnoDB so that they can be compared without a type conversion. The size and sign of integer types must be the same. The length of string types need not be the same. For nonbinary (character) string columns, the character set and collation must be the same.

    With android studio no jvm found, JAVA_HOME has been set

    Here is the tutorial :- http://javatechig.com/android/installing-android-studio and http://codearetoy.wordpress.com/2010/12/23/jdk-not-found-on-installing-android-sdk/

    Adding a system variable JDK_HOME with value c:\Program Files\Java\jdk1.7.0_21\ worked for me. The latest Java release can be downloaded here. Additionally, make sure the variable JAVA_HOME is also set with the above location.

    Please note that the above location is my java location. Please post your location in the path

    Only allow Numbers in input Tag without Javascript

    Try this with the + after [0-9]:

    input type="text" pattern="[0-9]+" title="number only"
    

    git stash changes apply to new branch?

    Since you've already stashed your changes, all you need is this one-liner:

    • git stash branch <branchname> [<stash>]

    From the docs (https://www.kernel.org/pub/software/scm/git/docs/git-stash.html):

    Creates and checks out a new branch named <branchname> starting from the commit at which the <stash> was originally created, applies the changes recorded in <stash> to the new working tree and index. If that succeeds, and <stash> is a reference of the form stash@{<revision>}, it then drops the <stash>. When no <stash> is given, applies the latest one.

    This is useful if the branch on which you ran git stash save has changed enough that git stash apply fails due to conflicts. Since the stash is applied on top of the commit that was HEAD at the time git stash was run, it restores the originally stashed state with no conflicts.

    Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

    contentType option to false is used for multipart/form-data forms that pass files.

    When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.


    To try and fix your issue:

    Use jQuery's .serialize() method which creates a text string in standard URL-encoded notation.

    You need to pass un-encoded data when using contentType: false.

    Try using new FormData instead of .serialize():

      var formData = new FormData($(this)[0]);
    

    See for yourself the difference of how your formData is passed to your php page by using console.log().

      var formData = new FormData($(this)[0]);
      console.log(formData);
    
      var formDataSerialized = $(this).serialize();
      console.log(formDataSerialized);
    

    Failed to load resource: the server responded with a status of 404 (Not Found) error in server

    By default, IUSR account is used for anonymous user.

    All you need to do is:

    IIS -> Authentication --> Set Anonymous Authentication to Application Pool Identity.

    Problem solved :)

    Change Row background color based on cell value DataTable

    Since datatables v1.10.18, you should specify the column key instead of index, it should be like this:

    rowCallback: function(row, data, index){
                if(data["column_key"] == "ValueHere"){
                    $('td', row).css('background-color', 'blue');
                }
            }
    

    Replace a string in a file with nodejs

    I ran into issues when replacing a small placeholder with a large string of code.

    I was doing:

    var replaced = original.replace('PLACEHOLDER', largeStringVar);
    

    I figured out the problem was JavaScript's special replacement patterns, described here. Since the code I was using as the replacing string had some $ in it, it was messing up the output.

    My solution was to use the function replacement option, which DOES NOT do any special replacement:

    var replaced = original.replace('PLACEHOLDER', function() {
        return largeStringVar;
    });
    

    Removing a non empty directory programmatically in C or C++

    How to delete a non empty folder using unlinkat() in c?

    Here is my work on it:

        /*
         * Program to erase the files/subfolders in a directory given as an input
         */
    
        #include <stdio.h>
        #include <stdlib.h>
        #include <string.h>
        #include <dirent.h>
        #include <unistd.h>
        #include <sys/types.h>
        #include <sys/stat.h>
        #include <fcntl.h>
        void remove_dir_content(const char *path)
        {
            struct dirent *de;
            char fname[300];
            DIR *dr = opendir(path);
            if(dr == NULL)
            {
                printf("No file or directory found\n");
                return;
            }
            while((de = readdir(dr)) != NULL)
            {
                int ret = -1;
                struct stat statbuf;
                sprintf(fname,"%s/%s",path,de->d_name);
                if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
                            continue;
                if(!stat(fname, &statbuf))
                {
                    if(S_ISDIR(statbuf.st_mode))
                    {
                        printf("Is dir: %s\n",fname);
                        printf("Err: %d\n",ret = unlinkat(dirfd(dr),fname,AT_REMOVEDIR));
                        if(ret != 0)
                        {
                            remove_dir_content(fname);
                            printf("Err: %d\n",ret = unlinkat(dirfd(dr),fname,AT_REMOVEDIR));
                        }
                    }
                    else
                    {
                        printf("Is file: %s\n",fname);
                        printf("Err: %d\n",unlink(fname));
                    }
                }
            }
            closedir(dr);
        }
        void main()
        {
            char str[10],str1[20] = "../",fname[300]; // Use str,str1 as your directory path where it's files & subfolders will be deleted.
            printf("Enter the dirctory name: ");
            scanf("%s",str);
            strcat(str1,str);
            printf("str1: %s\n",str1);
            remove_dir_content(str1); //str1 indicates the directory path
        }