Programs & Examples On #Alter column

How to alter a column's data type in a PostgreSQL table?

Cool @derek-kromm, Your answer is accepted and correct, But I am wondering if we need to alter more than the column. Here is how we can do.

ALTER TABLE tbl_name 
ALTER COLUMN col_name TYPE varchar (11), 
ALTER COLUMN col_name2 TYPE varchar (11),
ALTER COLUMN col_name3 TYPE varchar (11);

Documentation

Cheers!! Read Simple Write Simple

Altering a column: null to not null

Let's take an example:

TABLE NAME=EMPLOYEE

And I want to change the column EMPLOYEE_NAME to NOT NULL. This query can be used for the task:

ALTER TABLE EMPLOYEE MODIFY EMPLOYEE.EMPLOYEE_NAME datatype NOT NULL;

Alter column, add default constraint

You're specifying the table name twice. The ALTER TABLE part names the table. Try: Alter table TableName alter column [Date] default getutcdate()

ALTER TABLE on dependent column

If your constraint is on a user type, then don't forget to see if there is a Default Constraint, usually something like DF__TableName__ColumnName__6BAEFA67, if so then you will need to drop the Default Constraint, like this:

ALTER TABLE TableName DROP CONSTRAINT [DF__TableName__ColumnName__6BAEFA67]

For more info see the comments by the brilliant Aaron Bertrand on this answer.

How to ALTER multiple columns at once in SQL Server

This is not possible. You will need to do this one by one. You could:

  1. Create a Temporary Table with your modified columns in
  2. Copy the data across
  3. Drop your original table (Double check before!)
  4. Rename your Temporary Table to your original name

Change a Nullable column to NOT NULL with Default Value

I think you will need to do this as three separate statements. I've been looking around and everything i've seen seems to suggest you can do it if you are adding a column, but not if you are altering one.

ALTER TABLE dbo.MyTable
ADD CONSTRAINT my_Con DEFAULT GETDATE() for created

UPDATE MyTable SET Created = GetDate() where Created IS NULL

ALTER TABLE dbo.MyTable 
ALTER COLUMN Created DATETIME NOT NULL 

When increasing the size of VARCHAR column on a large table could there be any problems?

Another reason why you should avoid converting the column to varchar(max) is because you cannot create an index on a varchar(max) column.

How do I install Composer on a shared hosting?

This tutorial worked for me, resolving my issues with /usr/local/bin permission issues and php-cli (which composer requires, and may aliased differently on shared hosting).

First run these commands to download and install composer:

cd ~
mkdir bin
mkdir bin/composer
curl -sS https://getcomposer.org/installer | php
mv composer.phar bin/composer

Determine the location of your php-cli (needed later on):

which php-cli

(If the above fails, use which php)

It should return the path, such as /usr/bin/php-cli, /usr/php/54/usr/bin/php-cli, etc.

edit ~/.bashrc and make sure this line is at the top, adding it if it is not:

[ -z "$PS1" ] && return

and then add this alias to the bottom (using the php-cli path that you determined earlier):

alias composer="/usr/bin/php-cli ~/bin/composer/composer.phar"

Finish with these commands:

source ~/.bashrc
composer --version

Trigger function when date is selected with jQuery UI datepicker

Use the following code:

$(document).ready(function() {
    $('.date-pick').datepicker( {
     onSelect: function(date) {
        alert(date)
     },
    selectWeek: true,
    inline: true,
    startDate: '01/01/2000',
    firstDay: 1,
  });
});

You can adjust the parameters yourself :-)

Programmatically get own phone number in iOS

As you probably all ready know if you use the following line of code, your app will be rejected by Apple

NSString *num = [[NSUserDefaults standardUserDefaults] stringForKey:@"SBFormattedPhoneNumber"];

here is a reference

http://ayeapi.blogspot.com/2009/12/sbformatphonenumber-is-lie.html

you can use the following information instead

NSString *phoneName = [[UIDevice currentDevice] name];

NSString *phoneUniqueIdentifier = [[UIDevice currentDevice] uniqueIdentifier];

and so on

@property(nonatomic,readonly,retain) NSString    *name;              // e.g. "My iPhone"
@property(nonatomic,readonly,retain) NSString    *model;             // e.g. @"iPhone", @"iPod Touch"
@property(nonatomic,readonly,retain) NSString    *localizedModel;    // localized version of model
@property(nonatomic,readonly,retain) NSString    *systemName;        // e.g. @"iPhone OS"
@property(nonatomic,readonly,retain) NSString    *systemVersion;     // e.g. @"2.0"
@property(nonatomic,readonly) UIDeviceOrientation orientation;       // return current device orientation
@property(nonatomic,readonly,retain) NSString    *uniqueIdentifier;  // a string unique to each device based on various hardware info.

Hope this helps!

Write to Windows Application Event Log

This is the logger class that I use. The private Log() method has EventLog.WriteEntry() in it, which is how you actually write to the event log. I'm including all of this code here because it's handy. In addition to logging, this class will also make sure the message isn't too long to write to the event log (it will truncate the message). If the message was too long, you'd get an exception. The caller can also specify the source. If the caller doesn't, this class will get the source. Hope it helps.

By the way, you can get an ObjectDumper from the web. I didn't want to post all that here. I got mine from here: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Samples\1033\CSharpSamples.zip\LinqSamples\ObjectDumper

using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Xanico.Core.Utilities;

namespace Xanico.Core
{
    /// <summary>
    /// Logging operations
    /// </summary>
    public static class Logger
    {
        // Note: The actual limit is higher than this, but different Microsoft operating systems actually have
        //       different limits. So just use 30,000 to be safe.
        private const int MaxEventLogEntryLength = 30000;

        /// <summary>
        /// Gets or sets the source/caller. When logging, this logger class will attempt to get the
        /// name of the executing/entry assembly and use that as the source when writing to a log.
        /// In some cases, this class can't get the name of the executing assembly. This only seems
        /// to happen though when the caller is in a separate domain created by its caller. So,
        /// unless you're in that situation, there is no reason to set this. However, if there is
        /// any reason that the source isn't being correctly logged, just set it here when your
        /// process starts.
        /// </summary>
        public static string Source { get; set; }

        /// <summary>
        /// Logs the message, but only if debug logging is true.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="debugLoggingEnabled">if set to <c>true</c> [debug logging enabled].</param>
        /// <param name="source">The name of the app/process calling the logging method. If not provided,
        /// an attempt will be made to get the name of the calling process.</param>
        public static void LogDebug(string message, bool debugLoggingEnabled, string source = "")
        {
            if (debugLoggingEnabled == false) { return; }

            Log(message, EventLogEntryType.Information, source);
        }

        /// <summary>
        /// Logs the information.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="source">The name of the app/process calling the logging method. If not provided,
        /// an attempt will be made to get the name of the calling process.</param>
        public static void LogInformation(string message, string source = "")
        {
            Log(message, EventLogEntryType.Information, source);
        }

        /// <summary>
        /// Logs the warning.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="source">The name of the app/process calling the logging method. If not provided,
        /// an attempt will be made to get the name of the calling process.</param>
        public static void LogWarning(string message, string source = "")
        {
            Log(message, EventLogEntryType.Warning, source);
        }

        /// <summary>
        /// Logs the exception.
        /// </summary>
        /// <param name="ex">The ex.</param>
        /// <param name="source">The name of the app/process calling the logging method. If not provided,
        /// an attempt will be made to get the name of the calling process.</param>
        public static void LogException(Exception ex, string source = "")
        {
            if (ex == null) { throw new ArgumentNullException("ex"); }

            if (Environment.UserInteractive)
            {
                Console.WriteLine(ex.ToString());
            }

            Log(ex.ToString(), EventLogEntryType.Error, source);
        }

        /// <summary>
        /// Recursively gets the properties and values of an object and dumps that to the log.
        /// </summary>
        /// <param name="theObject">The object to log</param>
        [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Xanico.Core.Logger.Log(System.String,System.Diagnostics.EventLogEntryType,System.String)")]
        [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object")]
        public static void LogObjectDump(object theObject, string objectName, string source = "")
        {
            const int objectDepth = 5;
            string objectDump = ObjectDumper.GetObjectDump(theObject, objectDepth);

            string prefix = string.Format(CultureInfo.CurrentCulture,
                                          "{0} object dump:{1}",
                                          objectName,
                                          Environment.NewLine);

            Log(prefix + objectDump, EventLogEntryType.Warning, source);
        }

        private static void Log(string message, EventLogEntryType entryType, string source)
        {
            // Note: I got an error that the security log was inaccessible. To get around it, I ran the app as administrator
            //       just once, then I could run it from within VS.

            if (string.IsNullOrWhiteSpace(source))
            {
                source = GetSource();
            }

            string possiblyTruncatedMessage = EnsureLogMessageLimit(message);
            EventLog.WriteEntry(source, possiblyTruncatedMessage, entryType);

            // If we're running a console app, also write the message to the console window.
            if (Environment.UserInteractive)
            {
                Console.WriteLine(message);
            }
        }

        private static string GetSource()
        {
            // If the caller has explicitly set a source value, just use it.
            if (!string.IsNullOrWhiteSpace(Source)) { return Source; }

            try
            {
                var assembly = Assembly.GetEntryAssembly();

                // GetEntryAssembly() can return null when called in the context of a unit test project.
                // That can also happen when called from an app hosted in IIS, or even a windows service.

                if (assembly == null)
                {
                    assembly = Assembly.GetExecutingAssembly();
                }


                if (assembly == null)
                {
                    // From http://stackoverflow.com/a/14165787/279516:
                    assembly = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly;
                }

                if (assembly == null) { return "Unknown"; }

                return assembly.GetName().Name;
            }
            catch
            {
                return "Unknown";
            }
        }

        // Ensures that the log message entry text length does not exceed the event log viewer maximum length of 32766 characters.
        private static string EnsureLogMessageLimit(string logMessage)
        {
            if (logMessage.Length > MaxEventLogEntryLength)
            {
                string truncateWarningText = string.Format(CultureInfo.CurrentCulture, "... | Log Message Truncated [ Limit: {0} ]", MaxEventLogEntryLength);

                // Set the message to the max minus enough room to add the truncate warning.
                logMessage = logMessage.Substring(0, MaxEventLogEntryLength - truncateWarningText.Length);

                logMessage = string.Format(CultureInfo.CurrentCulture, "{0}{1}", logMessage, truncateWarningText);
            }

            return logMessage;
        }
    }
}

How to Use Order By for Multiple Columns in Laravel 4?

Use order by like this:

return User::orderBy('name', 'DESC')
    ->orderBy('surname', 'DESC')
    ->orderBy('email', 'DESC')
    ...
    ->get();

JavaScript load a page on button click

The answers here work to open the page in the same browser window/tab.

However, I wanted the page to open in a new window/tab when they click a button. (tab/window decision depends on the user's browser setting)

So here is how it worked to open the page in new tab/window:

<button type="button" onclick="window.open('http://www.example.com/', '_blank');">View Example Page</button>

It doesn't have to be a button, you can use anywhere. Notice the _blank that is used to open in new tab/window.

Calculating powers of integers

When it's power of 2. Take in mind, that you can use simple and fast shift expression 1 << exponent

example:

22 = 1 << 2 = (int) Math.pow(2, 2)
210 = 1 << 10 = (int) Math.pow(2, 10)

For larger exponents (over 31) use long instead

232 = 1L << 32 = (long) Math.pow(2, 32)

btw. in Kotlin you have shl instead of << so

(java) 1L << 32 = 1L shl 32 (kotlin)

Hidden Columns in jqGrid

It is a bit old, this post. But this is my code to show/hide the columns. I use the built in function to display the columns and just mark them.

Function that displays columns shown/hidden columns. The #jqGrid is the name of my grid, and the columnChooser is the jqGrid column chooser.

  function showHideColumns() {
        $('#jqGrid').jqGrid('columnChooser', {
            width: 250,
            dialog_opts: {
                modal: true,
                minWidth: 250,
                height: 300,
                show: 'blind',
                hide: 'explode',
                dividerLocation: 0.5
            } });

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.


If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.


It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

Nesting optgroups in a dropdownlist/select

I know this was quite a while ago, however I have a little extra to add:

This is not possible in HTML5 or any previous specs, nor is it proposed in HTML5.1 yet. I have made a request to the public-html-comments mailing list, but we'll see if anything comes of it.

Regardless, whilst this is not possible using <select> yet, you can achieve a similar effect with the following HTML, plus some CSS for prettiness:

_x000D_
_x000D_
<ul>_x000D_
  <li>_x000D_
 <input type="radio" name="location" value="0" id="loc_0" />_x000D_
 <label for="loc_0">United States</label>_x000D_
 <ul>_x000D_
   <li>_x000D_
  Northeast_x000D_
        <ul>_x000D_
       <li>_x000D_
   <input type="radio" name="location" value="1" id="loc_1" />_x000D_
   <label for="loc_1">New Hampshire</label>_x000D_
    </li>_x000D_
          <li>_x000D_
   <input type="radio" name="location" value="2" id="loc_2" />_x000D_
   <label for="loc_2">Vermont</label>_x000D_
    </li>_x000D_
          <li>_x000D_
    <input type="radio" name="location" value="3" id="loc_3" />_x000D_
    <label for="loc_3">Maine</label>_x000D_
    </li>_x000D_
   </ul>_x000D_
    </li>_x000D_
       <li>_x000D_
     Southeast_x000D_
           <ul>_x000D_
    <li>_x000D_
    <input type="radio" name="location" value="4" id="loc_4" />_x000D_
    <label for="loc_4">Georgia</label>_x000D_
    </li>_x000D_
             <li>_x000D_
    <input type="radio" name="location" value="5" id="loc_5" />_x000D_
    <label for="loc_5">Alabama</label>_x000D_
    </li>_x000D_
     </ul>_x000D_
  </li>_x000D_
   </ul>_x000D_
    </li>_x000D_
    <li>_x000D_
    <input type="radio" name="location" value="6" id="loc_6" />_x000D_
    <label for="loc_6">Canada</label>_x000D_
       <ul>_x000D_
    <li>_x000D_
    <input type="radio" name="location" value="7" id="loc_7" />_x000D_
    <label for="loc_7">Ontario</label>_x000D_
    </li>_x000D_
          <li>_x000D_
     <input type="radio" name="location" value="8" id="loc_8" />_x000D_
        <label for="loc_8">Quebec</label>_x000D_
    </li>_x000D_
          <li>_x000D_
      <input type="radio" name="location" value="9" id="loc_9" />_x000D_
      <label for="loc_9">Manitoba</label>_x000D_
    </li>_x000D_
  </ul>_x000D_
  </li>_x000D_
  </ul>
_x000D_
_x000D_
_x000D_

As an extra added benefit, this also means you can allow selection of the <optgroups> themselves. This might be useful if you had, for example, nested categories where the categories go into heavy detail and you want to allow users to select higher up in the hierarchy.

This will all work without JavaScript, however you might wish to add some to hide the radio buttons and then change the background color of the selected item or something.

Bear in mind, this is far from a perfect solution, but if you absolutely need a nested select with reasonable cross-browser compatibility, this is probably as close as you're going to get.

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)?

http://www.eclipse.org/cdt/ ^Give that a try

I have not used the CDT for eclipse but I do use Eclipse Java for Ubuntu 12.04 and it works wonders.

How do I remove all non alphanumeric characters from a string except dash?

If you are working in JS, here is a very terse version

myString = myString.replace(/[^A-Za-z0-9 -]/g, "");

require is not defined? Node.js

Node.JS is a server-side technology, not a browser technology. Thus, Node-specific calls, like require(), do not work in the browser.

See browserify or webpack if you wish to serve browser-specific modules from Node.

How does one generate a random number in Apple's Swift language?

Swift 4.2+

Swift 4.2 shipped with Xcode 10 introduces new easy-to-use random functions for many data types. You can call the random() method on numeric types.

let randomInt = Int.random(in: 0..<6)
let randomDouble = Double.random(in: 2.71828...3.14159)
let randomBool = Bool.random()

What is ":-!!" in C code?

This is, in effect, a way to check whether the expression e can be evaluated to be 0, and if not, to fail the build.

The macro is somewhat misnamed; it should be something more like BUILD_BUG_OR_ZERO, rather than ...ON_ZERO. (There have been occasional discussions about whether this is a confusing name.)

You should read the expression like this:

sizeof(struct { int: -!!(e); }))
  1. (e): Compute expression e.

  2. !!(e): Logically negate twice: 0 if e == 0; otherwise 1.

  3. -!!(e): Numerically negate the expression from step 2: 0 if it was 0; otherwise -1.

  4. struct{int: -!!(0);} --> struct{int: 0;}: If it was zero, then we declare a struct with an anonymous integer bitfield that has width zero. Everything is fine and we proceed as normal.

  5. struct{int: -!!(1);} --> struct{int: -1;}: On the other hand, if it isn't zero, then it will be some negative number. Declaring any bitfield with negative width is a compilation error.

So we'll either wind up with a bitfield that has width 0 in a struct, which is fine, or a bitfield with negative width, which is a compilation error. Then we take sizeof that field, so we get a size_t with the appropriate width (which will be zero in the case where e is zero).


Some people have asked: Why not just use an assert?

keithmo's answer here has a good response:

These macros implement a compile-time test, while assert() is a run-time test.

Exactly right. You don't want to detect problems in your kernel at runtime that could have been caught earlier! It's a critical piece of the operating system. To whatever extent problems can be detected at compile time, so much the better.

Getting "Cannot call a class as a function" in my React Project

Actually all the problem redux connect. solutions:

Correct:

export default connect(mapStateToProps, mapDispatchToProps)(PageName)

Wrong & Bug:

export default connect(PageName)(mapStateToProps, mapDispatchToProps)

String parsing in Java with delimiter tab "\t" using split

Well nobody answered - which is in part the fault of the question : the input string contains eleven fields (this much can be inferred) but how many tabs ? Most possibly exactly 10. Then the answer is

String s = "\t2\t\t4\t5\t6\t\t8\t\t10\t";
String[] fields = s.split("\t", -1);  // in your case s.split("\t", 11) might also do
for (int i = 0; i < fields.length; ++i) {
    if ("".equals(fields[i])) fields[i] = null;
}
System.out.println(Arrays.asList(fields));
// [null, 2, null, 4, 5, 6, null, 8, null, 10, null]
// with s.split("\t") : [null, 2, null, 4, 5, 6, null, 8, null, 10]

If the fields happen to contain tabs this won't work as expected, of course.
The -1 means : apply the pattern as many times as needed - so trailing fields (the 11th) will be preserved (as empty strings ("") if absent, which need to be turned to null explicitly).

If on the other hand there are no tabs for the missing fields - so "5\t6" is a valid input string containing the fields 5,6 only - there is no way to get the fields[] via split.

Getting the document object of an iframe

For even more robustness:

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

and

...
var el = document.getElementById('targetFrame');

var frame_win = getIframeWindow(el);

if (frame_win) {
  frame_win.targetFunction();
  ...
}
...

How can I execute a python script from an html button?

This would require knowledge of a backend website language.

Fortunately, Python's Flask Library is a suitable backend language for the project at hand.

Check out this answer from another thread.

Should Jquery code go in header or footer?

Only load jQuery itself in the head, via CDN of course.

Why? In some scenarios you might include a partial template (e.g. ajax login form snippet) with embedded jQuery dependent code; if jQuery is loaded at page bottom, you get a "$ is not defined" error, nice.

There are ways to workaround this of course (such as not embedding any JS and appending to a load-at-bottom js bundle), but why lose the freedom of lazily loaded js, of being able to place jQuery dependent code anywhere you please? Javascript engine doesn't care where the code lives in the DOM so long as dependencies (like jQuery being loaded) are satisfied.

For your common/shared js files, yes, place them before </body>, but for the exceptions, where it really just makes sense application maintenance-wise to stick a jQuery dependent snippet or file reference right there at that point in the html, do so.

There is no performance hit loading jquery in the head; what browser on the planet does not already have jQuery CDN file in cache?

Much ado about nothing, stick jQuery in the head and let your js freedom reign.

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

jQuery - Detecting if a file has been selected in the file input

You should be able to attach an event handler to the onchange event of the input and have that call a function to set the text in your span.

<script type="text/javascript">
  $(function() {
     $("input:file").change(function (){
       var fileName = $(this).val();
       $(".filename").html(fileName);
     });
  });
</script>

You may want to add IDs to your input and span so you can select based on those to be specific to the elements you are concerned with and not other file inputs or spans in the DOM.

How to use icons and symbols from "Font Awesome" on Native Android Application

As all answers are great but I didn't want to use a library and each solution with just one line java code made my Activities and Fragments very messy. So I over wrote the TextView class as follows:

public class FontAwesomeTextView extends TextView {
private static final String TAG = "TextViewFontAwesome";
public FontAwesomeTextView(Context context) {
    super(context);
    init();
}

public FontAwesomeTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public FontAwesomeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public FontAwesomeTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    init();
}

private void setCustomFont(Context ctx, AttributeSet attrs) {
    TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus);
    String customFont = a.getString(R.styleable.TextViewPlus_customFont);
    setCustomFont(ctx, customFont);
    a.recycle();
}

private void init() {
    if (!isInEditMode()) {
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fontawesome-webfont.ttf");
        setTypeface(tf);
    }
}

public boolean setCustomFont(Context ctx, String asset) {
    Typeface typeface = null;
    try {
        typeface = Typeface.createFromAsset(ctx.getAssets(), asset);
    } catch (Exception e) {
        Log.e(TAG, "Unable to load typeface: "+e.getMessage());
        return false;
    }

    setTypeface(typeface);
    return true;
}
}

what you should do is copy the font ttf file into assets folder .And use this cheat sheet for finding each icons string.

hope this helps.

Difference between File.separator and slash in paths

Late to the party. I'm on Windows 10 with JDK 1.8 and Eclipse MARS 1.
I find that

getClass().getClassLoader().getResourceAsStream("path/to/resource");

works and

getClass().getClassLoader().getResourceAsStream("path"+File.separator+"to"+File.separator+"resource");

does not work and

getClass().getClassLoader().getResourceAsStream("path\to\resource");

does not work. The last two are equivalent. So... I have good reason to NOT use File.separator.

How to convert a char array to a string?

The string class has a constructor that takes a NULL-terminated C-string:

char arr[ ] = "This is a test";

string str(arr);


//  You can also assign directly to a string.
str = "This is another string";

// or
str = arr;

Binding a list in @RequestParam

Or you could just do it that way:

public String controllerMethod(@RequestParam(value="myParam[]") String[] myParams){
    ....
}

That works for example for forms like this:

<input type="checkbox" name="myParam[]" value="myVal1" />
<input type="checkbox" name="myParam[]" value="myVal2" />

This is the simplest solution :)

java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused

If you are using localhost in your url and testing your application in emulator , simply you can replace system's ip address for localhost in the URL.or you can use 10.0.2.2 instead of localhost.

http://localhost/webservice.php to http://10.218.28.19/webservice.php

Where 10.218.28.19 -> System's IP Address.

or

http://localhost/webservice.php to http://10.0.2.2/webservice.php

How do I "shake" an Android device within the Android emulator to bring up the dev menu to debug my React Native app

It might be not direct solution, but I've created a lib that allows you to use 3 fingers touch instead of shake to open dev menu, when in development mode

https://github.com/pie6k/react-native-dev-menu-on-touch

You only have to wrap your app inside:

import DevMenuOnTouch from 'react-native-dev-menu-on-touch'; // or: import { DevMenuOnTouch } from 'react-native-dev-menu-on-touch'

class YourRootApp extends Component {
  render() {
    return (
      <DevMenuOnTouch>
        <YourApp />
      </DevMenuOnTouch>
    );
  }
}

It's really useful when you have to debug on real device and you have co-workers sitting next to you.

Send JSON data from Javascript to PHP?

PHP has a built in function called json_decode(). Just pass the JSON string into this function and it will convert it to the PHP equivalent string, array or object.

In order to pass it as a string from Javascript, you can convert it to JSON using

JSON.stringify(object);

or a library such as Prototype

From an array of objects, extract value of a property as array

In ES6, you can do:

const objArray = [{foo: 1, bar: 2}, {foo: 3, bar: 4}, {foo: 5, bar: 6}]
objArray.map(({ foo }) => foo)

How to preview git-pull without doing fetch?

What about cloning the repo elsewhere, and doing git log on both the real checkout and the fresh clone to see if you got the same thing.

Passing data to a bootstrap modal

Here's how I implemented it working from @mg1075's code. I wanted a bit more generic code so as not to have to assign classes to the modal trigger links/buttons:

Tested in Twitter Bootstrap 3.0.3.

HTML

<a href="#" data-target="#my_modal" data-toggle="modal" data-id="my_id_value">Open Modal</a>

JAVASCRIPT

$(document).ready(function() {

  $('a[data-toggle=modal], button[data-toggle=modal]').click(function () {

    var data_id = '';

    if (typeof $(this).data('id') !== 'undefined') {

      data_id = $(this).data('id');
    }

    $('#my_element_id').val(data_id);
  })
});

What's the best mock framework for Java?

Yes, Mockito is a great framework. I use it together with hamcrest and Google guice to setup my tests.

Calling a stored procedure in Oracle with IN and OUT parameters

Go to Menu Tool -> SQL Output, Run the PL/SQL statement, the output will show on SQL Output panel.

Add custom headers to WebView resource requests - android

You should be able to control all your headers by skipping loadUrl and writing your own loadPage using Java's HttpURLConnection. Then use the webview's loadData to display the response.

There is no access to the headers which Google provides. They are in a JNI call, deep in the WebView source.

How to get the body's content of an iframe in Javascript?

Using JQuery, try this:

$("#id_description_iframe").contents().find("body").html()

Select first occurring element after another element

Just hit on this when trying to solve this type of thing my self.

I did a selector that deals with the element after being something other than a p.

.here .is.the #selector h4 + * {...}

Hope this helps anyone who finds it :)

jQuery - Add ID instead of Class

Keep in mind this overwrites any ID that the element already has:

 $(".element").attr("id","SomeID");

The reason why addClass exists is because an element can have multiple classes, so you wouldn't want to necessarily overwrite the classes already set. But with most attributes, there is only one value allowed at any given time.

How do I rename a MySQL schema?

If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE

Edit: On the model overview it's under Physical Schemata

Screenshot:

enter image description here

JS jQuery - check if value is in array

Alternate solution of the values check

//Duplicate Title Entry 
    $.each(ar , function (i, val) {
        if ( jQuery("input:first").val()== val) alert('VALUE FOUND'+Valuecheck);
  });

C error: undefined reference to function, but it IS defined

Add the "extern" keyword to the function definitions in point.h

Best way to initialize (empty) array in PHP

In PHP an array is an array; there is no primitive vs. object consideration, so there is no comparable optimization to be had.

Google Maps shows "For development purposes only"

For me, Error has been fixed when activated Billing in google console. (I got 1-year developer trial)

How to hide a div with jQuery?

$("#myDiv").hide();

will set the css display to none. if you need to set visibility to hidden as well, could do this via

$("#myDiv").css("visibility", "hidden");

or combine both in a chain

$("#myDiv").hide().css("visibility", "hidden");

or write everything with one css() function

$("#myDiv").css({
  display: "none",
  visibility: "hidden"
});

Why do we use Base64?

Why/ How do we use Base64 encoding?

Base64 is one of the binary-to-text encoding scheme having 75% efficiency. It is used so that typical binary data (such as images) may be safely sent over legacy "not 8-bit clean" channels. In earlier email networks (till early 1990s), most email messages were plain text in the 7-bit US-ASCII character set. So many early comm protocol standards were designed to work over "7-bit" comm links "not 8-bit clean". Scheme efficiency is the ratio between number of bits in the input and the number of bits in the encoded output. Hexadecimal (Base16) is also one of the binary-to-text encoding scheme with 50% efficiency.

Base64 Encoding Steps (Simplified):

  1. Binary data is arranged in continuous chunks of 24 bits (3 bytes) each.
  2. Each 24 bits chunk is grouped in to four parts of 6 bit each.
  3. Each 6 bit group is converted into their corresponding Base64 character values, i.e. Base64 encoding converts three octets into four encoded characters. The ratio of output bytes to input bytes is 4:3 (33% overhead).
  4. Interestingly, the same characters will be encoded differently depending on their position within the three-octet group which is encoded to produce the four characters.
  5. The receiver will have to reverse this process to recover the original message.

How to conditionally take action if FINDSTR fails to find a string

In DOS/Windows Batch most commands return an exitCode, called "errorlevel", that is a value that customarily is equal to zero if the command ends correctly, or a number greater than zero if ends because an error, with greater numbers for greater errors (hence the name).

There are a couple methods to check that value, but the original one is:

IF ERRORLEVEL value command

Previous IF test if the errorlevel returned by the previous command was GREATER THAN OR EQUAL the given value and, if this is true, execute the command. For example:

verify bad-param
if errorlevel 1 echo Errorlevel is greater than or equal 1
echo The value of errorlevel is: %ERRORLEVEL%

Findstr command return 0 if the string was found and 1 if not:

CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat
IF ERRORLEVEL 1 XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y

Previous code will copy the file if the string was NOT found in the file.

CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat
IF NOT ERRORLEVEL 1 XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y

Previous code copy the file if the string was found. Try this:

findstr "string" file
if errorlevel 1 (
    echo String NOT found...
) else (
    echo String found
)

What is the difference between method overloading and overriding?

Method overloading deals with the notion of having two or more methods in the same class with the same name but different arguments.

void foo(int a)
void foo(int a, float b)

Method overriding means having two methods with the same arguments, but different implementations. One of them would exist in the parent class, while another will be in the derived, or child class. The @Override annotation, while not required, can be helpful to enforce proper overriding of a method at compile time.

class Parent {
    void foo(double d) {
        // do something
    }
}

class Child extends Parent {

    @Override
    void foo(double d){
        // this method is overridden.  
    }
}

How to access parent scope from within a custom directive *with own scope* in AngularJS?

Here's a trick I used once: create a "dummy" directive to hold the parent scope and place it somewhere outside the desired directive. Something like:

module.directive('myDirectiveContainer', function () {
    return {
        controller: function ($scope) {
            this.scope = $scope;
        }
    };
});

module.directive('myDirective', function () {
    return {
        require: '^myDirectiveContainer',
        link: function (scope, element, attrs, containerController) {
            // use containerController.scope here...
        }
    };
});

and then

<div my-directive-container="">
    <div my-directive="">
    </div>
</div>

Maybe not the most graceful solution, but it got the job done.

What is the official name for a credit card's 3 digit code?

From Wikipedia,

The Card Security Code is located on the back of MasterCard, Visa and Discover credit or debit cards and is typically a separate group of 3 digits to the right of the signature strip. On American Express cards, the Card Security Code is a printed (NOT embossed) group of four digits on the front towards the right.

The Card Security Code (CSC), sometimes called Card Verification Value (CVV or CV2), Card Verification Value Code (CVVC), Card Verification Code (CVC), Verification Code (V-Code or V Code), or Card Code Verification (CCV)[1] is a security feature for credit or debit card transactions, giving increased protection against credit card fraud.

There are actually several types of security codes:

* The first code, called CVC1 or CVV1, is encoded on the magnetic stripe of the card and used for transactions in person.
* The second code, and the most cited, is CVV2 or CVC2. This CSC (also known as a CCID or Credit Card ID) is often asked for by merchants for them to secure "card not present" transactions occurring over the Internet, by mail, fax or over the phone. In many countries in Western Europe, due to increased attempts at card fraud, it is now mandatory to provide this code when the cardholder is not present in person.
* Contactless Card and Chip cards may supply their own codes generated electronically, such as iCVV or Dynamic CVV.

The CVC should not be confused with the standard card account number appearing in embossed or printed digits. (The standard card number undergoes a separate validation algorithm called the Luhn algorithm which serves to determine whether a given card's number is appropriate.)

The CVC should not be confused with PIN codes such as MasterCard SecureCode or Visa Verified by Visa. These codes are not printed or embedded in the card but are entered at the time of transaction using a keypad.

What is Android's file system?

It depends on what filesystem, for example /system and /data are yaffs2 while /sdcard is vfat. This is the output of mount:

rootfs / rootfs ro 0 0
tmpfs /dev tmpfs rw,mode=755 0 0
devpts /dev/pts devpts rw,mode=600 0 0
proc /proc proc rw 0 0
sysfs /sys sysfs rw 0 0
tmpfs /sqlite_stmt_journals tmpfs rw,size=4096k 0 0
none /dev/cpuctl cgroup rw,cpu 0 0
/dev/block/mtdblock0 /system yaffs2 ro 0 0
/dev/block/mtdblock1 /data yaffs2 rw,nosuid,nodev 0 0
/dev/block/mtdblock2 /cache yaffs2 rw,nosuid,nodev 0 0
/dev/block//vold/179:0 /sdcard vfat rw,dirsync,nosuid,nodev,noexec,uid=1000,gid=1015,fmask=0702,dmask=0702,allow_utime=0020,codepage=cp437,iocharset=iso8859-1,shortname=mixed,utf8,errors=remount-ro 0 0

and with respect to other filesystems supported, this is the list

nodev   sysfs
nodev   rootfs
nodev   bdev
nodev   proc
nodev   cgroup
nodev   binfmt_misc
nodev   sockfs
nodev   pipefs
nodev   anon_inodefs
nodev   tmpfs
nodev   inotifyfs
nodev   devpts
nodev   ramfs
         vfat
         msdos
nodev   nfsd
nodev   smbfs
         yaffs
         yaffs2
nodev   rpc_pipefs

Html.Raw() in ASP.NET MVC Razor view

The accepted answer is correct, but I prefer:

@{int count = 0;} 
@foreach (var item in Model.Resources) 
{ 
    @Html.Raw(count <= 3 ? "<div class=\"resource-row\">" : "")  
    // some code 
    @Html.Raw(count <= 3 ? "</div>" : "")  
    @(count++)
} 

I hope this inspires someone, even though I'm late to the party.

VB.NET Empty String Array

Dim array As String() = Array.Empty(Of String)

Redirecting to a certain route based on condition

Here is maybe a more elegant and flexible solution with 'resolve' configuration property and 'promises' enabling eventual data loading on routing and routing rules depending on data.

You specify a function in 'resolve' in routing config and in the function load and check data, do all redirects. If you need to load data, you return a promise, if you need to do redirect - reject promise before that. All details can be found on $routerProvider and $q documentation pages.

'use strict';

var app = angular.module('app', [])
    .config(['$routeProvider', function($routeProvider) {
        $routeProvider
            .when('/', {
                templateUrl: "login.html",
                controller: LoginController
            })
            .when('/private', {
                templateUrl: "private.html",
                controller: PrivateController,
                resolve: {
                    factory: checkRouting
                }
            })
            .when('/private/anotherpage', {
                templateUrl:"another-private.html",
                controller: AnotherPriveController,
                resolve: {
                    factory: checkRouting
                }
            })
            .otherwise({ redirectTo: '/' });
    }]);

var checkRouting= function ($q, $rootScope, $location) {
    if ($rootScope.userProfile) {
        return true;
    } else {
        var deferred = $q.defer();
        $http.post("/loadUserProfile", { userToken: "blah" })
            .success(function (response) {
                $rootScope.userProfile = response.userProfile;
                deferred.resolve(true);
            })
            .error(function () {
                deferred.reject();
                $location.path("/");
             });
        return deferred.promise;
    }
};

For russian-speaking folks there is a post on habr "??????? ????????? ???????? ? AngularJS."

How to get row data by clicking a button in a row in an ASP.NET gridview

You can also use button click event like this:

<asp:TemplateField>
    <ItemTemplate>
        <asp:Button ID="Button1" runat="server" Text="Button" 
                    OnClick="MyButtonClick" />
    </ItemTemplate>
</asp:TemplateField>
protected void MyButtonClick(object sender, System.EventArgs e)
{
    //Get the button that raised the event
    Button btn = (Button)sender;

    //Get the row that contains this button
    GridViewRow gvr = (GridViewRow)btn.NamingContainer;
} 

OR

You can do like this to get data:

 void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
 {

    // If multiple ButtonField column fields are used, use the
    // CommandName property to determine which button was clicked.
    if(e.CommandName=="Select")
    {
      // Convert the row index stored in the CommandArgument
      // property to an Integer.
      int index = Convert.ToInt32(e.CommandArgument);    

      // Get the last name of the selected author from the appropriate
      // cell in the GridView control.
      GridViewRow selectedRow = CustomersGridView.Rows[index];
    }
}

and Button in gridview should have command like this and handle rowcommand event:

<asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSqlDataSource" 
        autogeneratecolumns="false"
        onrowcommand="CustomersGridView_RowCommand"
        runat="server">

        <columns>
          <asp:buttonfield buttontype="Button" 
            commandname="Select"
            headertext="Select Customer" 
            text="Select"/>
        </columns>
  </asp:gridview>

Check full example on MSDN

Failure [INSTALL_FAILED_ALREADY_EXISTS] when I tried to update my application

You are getting that error because an application with a package name same as your application already exists. If you are sure that you have not installed the same application before, change the package name and try.

Else wise, here is what you can do:

  1. Uninstall the application from the device: Go to Settings -> Manage Applications and choose Uninstall OR
  2. Uninstall the app using adb command line interface: type adb uninstall After you are done with this step, try installing the application again.

Console.WriteLine does not show up in Output window

Try to uncheck the CheckBox “Use Managed Compatibility Mode” in

Tools => Options => Debugging => General

It worked for me.

How to Scroll Down - JQuery

$('.btnMedio').click(function(event) {
    // Preventing default action of the event
    event.preventDefault();
    // Getting the height of the document
    var n = $(document).height();
    $('html, body').animate({ scrollTop: n }, 50);
//                                       |    |
//                                       |    --- duration (milliseconds) 
//                                       ---- distance from the top
});

FIFO class in Java

Try ArrayDeque or LinkedList, which both implement the Queue interface.

http://docs.oracle.com/javase/6/docs/api/java/util/ArrayDeque.html

Override intranet compatibility mode IE8

Try putting the following in the header:

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

Courtesy Paul Irish's HTML5 Boilerplate (but it works in XHTML Transitional, too).

^[A-Za-Z ][A-Za-z0-9 ]* regular expression?

First must be Alphabet and then dot not allowed in target string. below is code.

        string input = "A_aaA";

        // B
        // The regular expression we use to match
        Regex r1 = new Regex("^[A-Za-z][^.]*$"); //[\t\0x0020] tab and spaces.

        // C
        // Match the input and write results
        Match match = r1.Match(input);
        if (match.Success)
        {
            Console.WriteLine("Valid: {0}", match.Value);

        }
        else
        {
            Console.WriteLine("Not Match");
        }


        Console.ReadLine();

What is a LAMP stack?

That simply means using Linux, Apache, MySQL and PHP as your operating system, web server, database, and programming language, respectively.

How to test my servlet using JUnit

You can do this using Mockito to have the mock return the correct params, verify they were indeed called (optionally specify number of times), write the 'result' and verify it's correct.

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.io.*;
import javax.servlet.http.*;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

public class TestMyServlet extends Mockito{

    @Test
    public void testServlet() throws Exception {
        HttpServletRequest request = mock(HttpServletRequest.class);       
        HttpServletResponse response = mock(HttpServletResponse.class);    

        when(request.getParameter("username")).thenReturn("me");
        when(request.getParameter("password")).thenReturn("secret");

        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);
        when(response.getWriter()).thenReturn(writer);

        new MyServlet().doPost(request, response);

        verify(request, atLeast(1)).getParameter("username"); // only if you want to verify username was called...
        writer.flush(); // it may not have been flushed yet...
        assertTrue(stringWriter.toString().contains("My expected string"));
    }
}

Best way to define error codes/strings in Java?

There are many ways to solve this. My preferred approach is to have interfaces:

public interface ICode {
     /*your preferred code type here, can be int or string or whatever*/ id();
}

public interface IMessage {
    ICode code();
}

Now you can define any number of enums which provide messages:

public enum DatabaseMessage implements IMessage {
     CONNECTION_FAILURE(DatabaseCode.CONNECTION_FAILURE, ...);
}

Now you have several options to turn those into Strings. You can compile the strings into your code (using annotations or enum constructor parameters) or you can read them from a config/property file or from a database table or a mixture. The latter is my preferred approach because you will always need some messages that you can turn into text very early (ie. while you connect to the database or read the config).

I'm using unit tests and reflection frameworks to find all types that implement my interfaces to make sure each code is used somewhere and that the config files contain all expected messages, etc.

Using frameworks that can parse Java like https://github.com/javaparser/javaparser or the one from Eclipse, you can even check where the enums are used and find unused ones.

Using client certificate in Curl command

This is how I did it:

curl -v \
  --key ./admin-key.pem \
  --cert ./admin.pem \
  https://xxxx/api/v1/

Running an outside program (executable) in Python?

That's the correct usage, but perhaps the spaces in the path name are messing things up for some reason.

You may want to run the program under cmd.exe as well so you can see any output from flow.exe that might be indicating an error.

How to read data of an Excel file using C#?

public void excelRead(string sheetName)
        {
            Excel.Application appExl = new Excel.Application();
            Excel.Workbook workbook = null;
            try
            {
                string methodName = "";


                Excel.Worksheet NwSheet;
                Excel.Range ShtRange;

                //Opening Excel file(myData.xlsx)
                appExl = new Excel.Application();


                workbook = appExl.Workbooks.Open(sheetName, Missing.Value, ReadOnly: false);
                NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);
                ShtRange = NwSheet.UsedRange; //gives the used cells in sheet


                int rCnt1 = 0;
                int cCnt1 = 0;

                for (rCnt1 = 1; rCnt1 <= ShtRange.Rows.Count; rCnt1++)
                {
                    for (cCnt1 = 1; cCnt1 <= ShtRange.Columns.Count; cCnt1++)
                    {
                        if (Convert.ToString(NwSheet.Cells[rCnt1, cCnt1].Value2) == "Y")
                        {

                            methodName = NwSheet.Cells[rCnt1, cCnt1 - 2].Value2;
                            Type metdType = this.GetType();
                            MethodInfo mthInfo = metdType.GetMethod(methodName);

                            if (Convert.ToString(NwSheet.Cells[rCnt1, cCnt1 - 2].Value2) == "fn_AddNum" || Convert.ToString(NwSheet.Cells[rCnt1, cCnt1 - 2].Value2) == "fn_SubNum")
                            {
                                StaticVariable.intParam1 = Convert.ToInt32(NwSheet.Cells[rCnt1, cCnt1 + 3].Value2);
                                StaticVariable.intParam2 = Convert.ToInt32(NwSheet.Cells[rCnt1, cCnt1 + 4].Value2);
                                object[] mParam1 = new object[] { StaticVariable.intParam1, StaticVariable.intParam2 };
                                object result = mthInfo.Invoke(this, mParam1);
                                StaticVariable.intOutParam1 = Convert.ToInt32(result);
                                NwSheet.Cells[rCnt1, cCnt1 + 5].Value2 = Convert.ToString(StaticVariable.intOutParam1) != "" ? Convert.ToString(StaticVariable.intOutParam1) : String.Empty;
                            }

                            else
                            {
                                object[] mParam = new object[] { };
                                mthInfo.Invoke(this, mParam);

                                NwSheet.Cells[rCnt1, cCnt1 + 5].Value2 = StaticVariable.outParam1 != "" ? StaticVariable.outParam1 : String.Empty;
                                NwSheet.Cells[rCnt1, cCnt1 + 6].Value2 = StaticVariable.outParam2 != "" ? StaticVariable.outParam2 : String.Empty;
                            }
                            NwSheet.Cells[rCnt1, cCnt1 + 1].Value2 = StaticVariable.resultOut;
                            NwSheet.Cells[rCnt1, cCnt1 + 2].Value2 = StaticVariable.resultDescription;
                        }

                        else if (Convert.ToString(NwSheet.Cells[rCnt1, cCnt1].Value2) == "N")
                        {
                            MessageBox.Show("Result is No");
                        }
                        else if (Convert.ToString(NwSheet.Cells[rCnt1, cCnt1].Value2) == "EOF")
                        {
                            MessageBox.Show("End of File");
                        }

                    }
                }

                workbook.Save();
                workbook.Close(true, Missing.Value, Missing.Value);
                appExl.Quit();
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ShtRange);
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(NwSheet);
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workbook);
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(appExl);
            }
            catch (Exception)
            {
                workbook.Close(true, Missing.Value, Missing.Value);
            }
            finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                System.Runtime.InteropServices.Marshal.CleanupUnusedObjectsInCurrentContext();
            }
        }

//code for reading excel data in datatable
public void testExcel(string sheetName)
        {
            try
            {
                MessageBox.Show(sheetName);

                foreach(Process p in Process.GetProcessesByName("EXCEL"))
                {
                    p.Kill();
                }
                //string fileName = "E:\\inputSheet";
                Excel.Application oXL;
                Workbook oWB;
                Worksheet oSheet;
                Range oRng;


                //  creat a Application object
                oXL = new Excel.Application();




                //   get   WorkBook  object
                oWB = oXL.Workbooks.Open(sheetName);


                //   get   WorkSheet object
                oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.Sheets[1];
                System.Data.DataTable dt = new System.Data.DataTable();
                //DataSet ds = new DataSet();
                //ds.Tables.Add(dt);
                DataRow dr;


                StringBuilder sb = new StringBuilder();
                int jValue = oSheet.UsedRange.Cells.Columns.Count;
                int iValue = oSheet.UsedRange.Cells.Rows.Count;


                //  get data columns
                for (int j = 1; j <= jValue; j++)
                {
                    oRng = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1, j];
                    string strValue = oRng.Text.ToString();
                    dt.Columns.Add(strValue, System.Type.GetType("System.String"));
                }


                //string colString = sb.ToString().Trim();
                //string[] colArray = colString.Split(':');


                //  get data in cell
                for (int i = 2; i <= iValue; i++)
                {
                    dr = dt.NewRow();
                    for (int j = 1; j <= jValue; j++)
                    {
                        oRng = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[i, j];
                        string strValue = oRng.Text.ToString();
                        dr[j - 1] = strValue;


                    }
                    dt.Rows.Add(dr);
                }
                if(StaticVariable.dtExcel != null)
                {
                    StaticVariable.dtExcel.Clear();
                    StaticVariable.dtExcel = dt.Copy();
                }
                else
                StaticVariable.dtExcel = dt.Copy();

                oWB.Close(true, Missing.Value, Missing.Value);
                oXL.Quit();
                MessageBox.Show(sheetName);

            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {

            }
        }

//code for class initialize
 public static void startTesting(TestContext context)
        {

            Playback.Initialize();
            ReadExcel myClassObj = new ReadExcel();
            string sheetName="";
            StreamReader sr = new StreamReader(@"E:\SaveSheetName.txt");
            sheetName = sr.ReadLine();
            sr.Close();
            myClassObj.excelRead(sheetName);
            myClassObj.testExcel(sheetName);
        }

//code for test initalize
public  void runValidatonTest()
        {

            DataTable dtFinal = StaticVariable.dtExcel.Copy();
            for (int i = 0; i < dtFinal.Rows.Count; i++)
            {
                if (TestContext.TestName == dtFinal.Rows[i][2].ToString() && dtFinal.Rows[i][3].ToString() == "Y" && dtFinal.Rows[i][4].ToString() == "TRUE")
                {
                    MessageBox.Show(TestContext.TestName);
                    MessageBox.Show(dtFinal.Rows[i][2].ToString());
                    StaticVariable.runValidateResult = "true";
                    break;
                }
            }
            //StaticVariable.dtExcel = dtFinal.Copy();
        }

What is the correct way to create a single-instance WPF application?

Well, I have a disposable Class for this that works easily for most use cases:

Use it like this:

static void Main()
{
    using (SingleInstanceMutex sim = new SingleInstanceMutex())
    {
        if (sim.IsOtherInstanceRunning)
        {
            Application.Exit();
        }

        // Initialize program here.
    }
}

Here it is:

/// <summary>
/// Represents a <see cref="SingleInstanceMutex"/> class.
/// </summary>
public partial class SingleInstanceMutex : IDisposable
{
    #region Fields

    /// <summary>
    /// Indicator whether another instance of this application is running or not.
    /// </summary>
    private bool isNoOtherInstanceRunning;

    /// <summary>
    /// The <see cref="Mutex"/> used to ask for other instances of this application.
    /// </summary>
    private Mutex singleInstanceMutex = null;

    /// <summary>
    /// An indicator whether this object is beeing actively disposed or not.
    /// </summary>
    private bool disposed;

    #endregion

    #region Constructor

    /// <summary>
    /// Initializes a new instance of the <see cref="SingleInstanceMutex"/> class.
    /// </summary>
    public SingleInstanceMutex()
    {
        this.singleInstanceMutex = new Mutex(true, Assembly.GetCallingAssembly().FullName, out this.isNoOtherInstanceRunning);
    }

    #endregion

    #region Properties

    /// <summary>
    /// Gets an indicator whether another instance of the application is running or not.
    /// </summary>
    public bool IsOtherInstanceRunning
    {
        get
        {
            return !this.isNoOtherInstanceRunning;
        }
    }

    #endregion

    #region Methods

    /// <summary>
    /// Closes the <see cref="SingleInstanceMutex"/>.
    /// </summary>
    public void Close()
    {
        this.ThrowIfDisposed();
        this.singleInstanceMutex.Close();
    }

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            /* Release unmanaged ressources */

            if (disposing)
            {
                /* Release managed ressources */
                this.Close();
            }

            this.disposed = true;
        }
    }

    /// <summary>
    /// Throws an exception if something is tried to be done with an already disposed object.
    /// </summary>
    /// <remarks>
    /// All public methods of the class must first call this.
    /// </remarks>
    public void ThrowIfDisposed()
    {
        if (this.disposed)
        {
            throw new ObjectDisposedException(this.GetType().Name);
        }
    }

    #endregion
}

mkdir's "-p" option

PATH: Answered long ago, however, it maybe more helpful to think of -p as "Path" (easier to remember), as in this causes mkdir to create every part of the path that isn't already there.

mkdir -p /usr/bin/comm/diff/er/fence

if /usr/bin/comm already exists, it acts like: mkdir /usr/bin/comm/diff mkdir /usr/bin/comm/diff/er mkdir /usr/bin/comm/diff/er/fence

As you can see, it saves you a bit of typing, and thinking, since you don't have to figure out what's already there and what isn't.

Error 'tunneling socket' while executing npm install

Following commands may solve your issue:

npm config set proxy false
npm cache clean

It solved my same issue.

Which is the preferred way to concatenate a string in Python?

If you are concatenating a lot of values, then neither. Appending a list is expensive. You can use StringIO for that. Especially if you are building it up over a lot of operations.

from cStringIO import StringIO
# python3:  from io import StringIO

buf = StringIO()

buf.write('foo')
buf.write('foo')
buf.write('foo')

buf.getvalue()
# 'foofoofoo'

If you already have a complete list returned to you from some other operation, then just use the ''.join(aList)

From the python FAQ: What is the most efficient way to concatenate many strings together?

str and bytes objects are immutable, therefore concatenating many strings together is inefficient as each concatenation creates a new object. In the general case, the total runtime cost is quadratic in the total string length.

To accumulate many str objects, the recommended idiom is to place them into a list and call str.join() at the end:

chunks = []
for s in my_strings:
    chunks.append(s)
result = ''.join(chunks)

(another reasonably efficient idiom is to use io.StringIO)

To accumulate many bytes objects, the recommended idiom is to extend a bytearray object using in-place concatenation (the += operator):

result = bytearray()
for b in my_bytes_objects:
    result += b

Edit: I was silly and had the results pasted backwards, making it look like appending to a list was faster than cStringIO. I have also added tests for bytearray/str concat, as well as a second round of tests using a larger list with larger strings. (python 2.7.3)

ipython test example for large lists of strings

try:
    from cStringIO import StringIO
except:
    from io import StringIO

source = ['foo']*1000

%%timeit buf = StringIO()
for i in source:
    buf.write(i)
final = buf.getvalue()
# 1000 loops, best of 3: 1.27 ms per loop

%%timeit out = []
for i in source:
    out.append(i)
final = ''.join(out)
# 1000 loops, best of 3: 9.89 ms per loop

%%timeit out = bytearray()
for i in source:
    out += i
# 10000 loops, best of 3: 98.5 µs per loop

%%timeit out = ""
for i in source:
    out += i
# 10000 loops, best of 3: 161 µs per loop

## Repeat the tests with a larger list, containing
## strings that are bigger than the small string caching 
## done by the Python
source = ['foo']*1000

# cStringIO
# 10 loops, best of 3: 19.2 ms per loop

# list append and join
# 100 loops, best of 3: 144 ms per loop

# bytearray() +=
# 100 loops, best of 3: 3.8 ms per loop

# str() +=
# 100 loops, best of 3: 5.11 ms per loop

In a Git repository, how to properly rename a directory?

Simply rename the folder. git is a "content-tracker", so the SHA1 hashes are the same and git knows, that you rename it. The only thing that changes is the tree-object.

rm <directory>
git add .
git commit

Automatically run %matplotlib inline in IPython Notebook

In (the current) IPython 3.2.0 (Python 2 or 3)

Open the configuration file within the hidden folder .ipython

~/.ipython/profile_default/ipython_kernel_config.py

add the following line

c.IPKernelApp.matplotlib = 'inline'

add it straight after

c = get_config()

Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

You cannot display a lot of websites inside an iFrame. Reason being that they send an "X-Frame-Options: SAMEORIGIN" response header. This option prevents the browser from displaying iFrames that are not hosted on the same domain as the parent page. This is a security feature to prevent click-jacking. Some details at How to show google.com in an iframe?

This could be of some help : https://www.maketecheasier.com/create-survey-form-with-google-docs/

How to implement infinity in Java?

double supports Infinity

double inf = Double.POSITIVE_INFINITY;
System.out.println(inf + 5);
System.out.println(inf - inf); // same as Double.NaN
System.out.println(inf * -1); // same as Double.NEGATIVE_INFINITY

prints

Infinity
NaN
-Infinity

note: Infinity - Infinity is Not A Number.

How to stop java process gracefully?

Shutdown hooks execute in all cases where the VM is not forcibly killed. So, if you were to issue a "standard" kill (SIGTERM from a kill command) then they will execute. Similarly, they will execute after calling System.exit(int).

However a hard kill (kill -9 or kill -SIGKILL) then they won't execute. Similarly (and obviously) they won't execute if you pull the power from the computer, drop it into a vat of boiling lava, or beat the CPU into pieces with a sledgehammer. You probably already knew that, though.

Finalizers really should run as well, but it's best not to rely on that for shutdown cleanup, but rather rely on your shutdown hooks to stop things cleanly. And, as always, be careful with deadlocks (I've seen far too many shutdown hooks hang the entire process)!

Multiple lines of text in UILabel

I found a solution.

One just has to add the following code:

// Swift
textLabel.lineBreakMode = .ByWordWrapping // or NSLineBreakMode.ByWordWrapping
textLabel.numberOfLines = 0 

// For Swift >= 3
textLabel.lineBreakMode = .byWordWrapping // notice the 'b' instead of 'B'
textLabel.numberOfLines = 0

// Objective-C
textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.numberOfLines = 0;

// C# (Xamarin.iOS)
textLabel.LineBreakMode = UILineBreakMode.WordWrap;
textLabel.Lines = 0;  

Restored old answer (for reference and devs willing to support iOS below 6.0):

textLabel.lineBreakMode = UILineBreakModeWordWrap;
textLabel.numberOfLines = 0;

On the side: both enum values yield to 0 anyway.

How can I sanitize user input with PHP?

There is the filter extension (howto-link, manual), which works pretty well with all GPC variables. It's not a magic-do-it-all thing though, you will still have to use it.

Convert pem key to ssh-rsa format

FWIW, this BASH script will take a PEM- or DER-format X.509 certificate or OpenSSL public key file (also PEM format) as the first argument and disgorge an OpenSSH RSA public key. This expands upon @mkalkov's answer above. Requirements are cat, grep, tr, dd, xxd, sed, xargs, file, uuidgen, base64, openssl (1.0+), and of course bash. All except openssl (contains base64) are pretty much guaranteed to be part of the base install on any modern Linux system, except maybe xxd (which Fedora shows in the vim-common package). If anyone wants to clean it up and make it nicer, caveat lector.

#!/bin/bash
#
# Extract a valid SSH format public key from an X509 public certificate.
#

# Variables:
pubFile=$1
fileType="no"
pkEightTypeFile="$pubFile"
tmpFile="/tmp/`uuidgen`-pkEightTypeFile.pk8"

# See if a file was passed:
[ ! -f "$pubFile" ] && echo "Error, bad or no input file $pubFile." && exit 1

# If it is a PEM format X.509 public cert, set $fileType appropriately:
pemCertType="X$(file $pubFile | grep 'PEM certificate')"
[ "$pemCertType" != "X" ] && fileType="PEM"

# If it is an OpenSSL PEM-format PKCS#8-style public key, set $fileType appropriately:
pkEightType="X$(grep -e '-BEGIN PUBLIC KEY-' $pubFile)"
[ "$pkEightType" != "X" ] && fileType="PKCS"

# If this is a file we can't recognise, try to decode a (binary) DER-format X.509 cert:
if [ "$fileType" = "no" ]; then
        openssl x509 -in $pubFile -inform DER -noout
        derResult=$(echo $?)
        [ "$derResult" = "0" ] && fileType="DER"
fi

# Exit if not detected as a file we can use:
[ "$fileType" = "no" ] && echo "Error, input file not of type X.509 public certificate or OpenSSL PKCS#8-style public key (not encrypted)." && exit 1

# Convert the X.509 public cert to an OpenSSL PEM-format PKCS#8-style public key:
if [ "$fileType" = "PEM" -o "$fileType" = "DER" ]; then
        openssl x509 -in $pubFile -inform $fileType -noout -pubkey > $tmpFile
        pkEightTypeFile="$tmpFile"
fi

# Build the string:
# Front matter:
frontString="$(echo -en 'ssh-rsa ')"

# Encoded modulus and exponent, with appropriate pointers:
encodedModulus="$(cat $pkEightTypeFile | grep -v -e "----" | tr -d '\n' | base64 -d | dd bs=1 skip=32 count=257 status=none | xxd -p -c257 | sed s/^/00000007\ 7373682d727361\ 00000003\ 010001\ 00000101\ / | xxd -p -r | base64 -w0 )"

# Add a comment string based on the filename, just to be nice:
commentString=" $(echo $pubFile | xargs basename | sed -e 's/\.crt\|\.cer\|\.pem\|\.pk8\|\.der//')"

# Give the user a string:
echo $frontString $encodedModulus $commentString

# cleanup:
rm -f $tmpFile

<strong> vs. font-weight:bold & <em> vs. font-style:italic

The problem is an issue of semantic meaning (as BoltClock mentions) and visual rendering.

Originally HTML used <b> and <i> for these purposes, entirely stylistic commands, laid down in the semantic environment of the document markup. CSS is an attempt to separate out as far as possible the stylistic elements of the medium. Thus style information such as bold and italics should go in CSS.

<strong> and <em> were introduced to fill the semantic need for text to be marked as more important or stressed. They have default stylistic interpretations akin to bold and italic, but they are not bound to that fate.

How do I assign a port mapping to an existing Docker container?

In Fujimoto Youichi's example test01 is a container, whereas test02 is an image.

Before doing docker run you can remove the original container and then assign the container the same name again:

$ docker stop container01
$ docker commit container01 image01
$ docker rm container01
$ docker run -d -P --name container01 image01

(Using -P to expose ports to random ports rather than manually assigning).

npm install Error: rollbackFailedOptional

I had the same issue. But it can run properly with switching from company's internal network to visitor network.

How do I make a checkbox required on an ASP.NET form?

C# version of andrew's answer:

<asp:CustomValidator ID="CustomValidator1" runat="server" 
        ErrorMessage="Please accept the terms..." 
        onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
    <asp:CheckBox ID="CheckBox1" runat="server" />

Code-behind:

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
    args.IsValid = CheckBox1.Checked;
}

ProcessBuilder: Forwarding stdout and stderr of started processes without blocking the main thread

It's as simple as following:

    File logFile = new File(...);
    ProcessBuilder pb = new ProcessBuilder()
        .command("somecommand", "arg1", "arg2")
    processBuilder.redirectErrorStream(true);
    processBuilder.redirectOutput(logFile);

by .redirectErrorStream(true) you tell process to merge error and output stream and then by .redirectOutput(file) you redirect merged output to a file.

Update:

I did manage to do this as follows:

public static void main(String[] args) {
    // Async part
    Runnable r = () -> {
        ProcessBuilder pb = new ProcessBuilder().command("...");
        // Merge System.err and System.out
        pb.redirectErrorStream(true);
        // Inherit System.out as redirect output stream
        pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        try {
            pb.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    };
    new Thread(r, "asyncOut").start();
    // here goes your main part
}

Now you're able to see both outputs from main and asyncOut threads in System.out

Send array with Ajax to PHP script

Data in jQuery ajax() function accepts anonymous objects as its input, see documentation. So example of what you're looking for is:

dataString = {key: 'val', key2: 'val2'};
$.ajax({
        type: "POST",
        url: "script.php",
        data: dataString, 
        cache: false,

        success: function(){
            alert("OK");
        }
    });

You may also write POST/GET query on your own, like key=val&key2=val2, but you'd have to handle escaping yourself which is impractical.

how to delete a specific row in codeigniter?

My controller

public function delete_category()   //Created a controller class //
    {      
         $this->load->model('Managecat'); //Load model Managecat here 
         $id=$this->input->get('id');     //  get the requested in a variable
         $sql_del=$this->Managecat->deleteRecord($id); //send the parameter $id in Managecat  there I have created a function name deleteRecord

         if($sql_del){

               $data['success'] = "Category Have been deleted Successfully!!";  //success message goes here 

         }

    }

My Model

public function deleteRecord($id) {

    $this->db->where('cat_id', $id);
    $del=$this->db->delete('category');   
    return $del;

}

No @XmlRootElement generated by JAXB

It's not working for us either. But we did find a widely-quoted article that adds SOME background... I'll link to it here for the sake of the next person: http://weblogs.java.net/blog/kohsuke/archive/2006/03/why_does_jaxb_p.html

How to get the jQuery $.ajax error response text?

you can try it too:

$(document).ajaxError(
    function (event, jqXHR, ajaxSettings, thrownError) {
        alert('[event:' + event + '], [jqXHR:' + jqXHR + '], [ajaxSettings:' + ajaxSettings + '], [thrownError:' + thrownError + '])');
    });

Excel VBA For Each Worksheet Loop

Try this more succinct code:

Sub LoopOverEachColumn()
    Dim WS As Worksheet
    For Each WS In ThisWorkbook.Worksheets
        ResizeColumns WS
    Next WS
End Sub

Private Sub ResizeColumns(WS As Worksheet)
    Dim StrSize As String
    Dim ColIter As Long
    StrSize = "20.14;9.71;35.86;30.57;23.57;21.43;18.43;23.86;27.43;36.71;30.29;31.14;31;41.14;33.86"
    For ColIter = 1 To 15
        WS.Columns(ColIter).ColumnWidth = Split(StrSize, ";")(ColIter - 1)
    Next ColIter
End Sub

If you want additional columns, just change 1 to 15 to 1 to X where X is the column index of the column you want, and append the column size you want to StrSize.

For example, if you want P:P to have a width of 25, just add ;25 to StrSize and change ColIter... to ColIter = 1 to 16.

Hope this helps.

Linux: command to open URL in default browser

I think using xdg-open http://example.com is probably the best choice.

In case they don't have it installed I suppose they might have just kde-open or gnome-open (both of which take a single file/url) or some other workaround such as looping over common browser executable names until you find one which can be executed(using which). If you want a full list of workarounds/fallbacks I suggest reading xdg-open(it's a shell script which calls out to kde-open/gnome-open/etc. or some other fallback).

But since xdg-open and xdg-mime(used for one of the fallbacks,) are shell scripts I'd recommend including them in your application and if calling which xdg-open fails add them to temporary PATH variable in your subprograms environment and call out to them. If xdg-open fails, I'd recommend throwing an Exception with an error message from what it output on stderr and catching the exception and printing/displaying the error message.

I would ignore the java awt Desktop solution as the bug seems to indicate they don't plan on supporting non-gnome desktops anytime soon.

Changing .gitconfig location on Windows

  1. Change to folder %PROGRAMFILES%\Git\etc
  2. Edit file profile
  3. Add to first line HOME="c:\location_were_you_want_gitconfig"
  4. Done

Note: The file permissions are usually restricted, so change them accordingly or you won't be able to save your changes.

Array of PHP Objects

Yes.

$array[] = new stdClass;
$array[] = new stdClass;

print_r($array);

Results in:

Array
(
    [0] => stdClass Object
        (
        )

    [1] => stdClass Object
        (
        )

)

else & elif statements not working in Python

Besides that your indention is wrong. The code wont work. I know you are using python 3. something. I am using python 2.7.3 the code that will actually work for what you trying accomplish is this.

number = str(23)
guess =  input('Enter a number: ')
if guess == number:
   print('Congratulations! You guessed it.')
elif guess < number:
     print('Wrong Number')
elif guess < number:
     print("Wrong Number')

The only difference I would tell python that number is a string of character for the code to work. If not is going to think is a Integer. When somebody runs the code they are inputing a string not an integer. There are many ways of changing this code but this is the easy solution I wanted to provide there is another way that I cant think of without making the 23 into a string. Or you could of "23" put quotations or you could of use int() function in the input. that would transform anything they input into and integer a number.

Better way to right align text in HTML Table

Use jquery to apply class to all tr unobtrusively.

$(”table td”).addClass(”right-align-class");

Use enhanced filters on td in case you want to select a particular td.

See jquery

How to stretch children to fill cross-axis?

  • The children of a row-flexbox container automatically fill the container's vertical space.

  • Specify flex: 1; for a child if you want it to fill the remaining horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
  flex: 1; _x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  • Specify flex: 1; for both children if you want them to fill equal amounts of the horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > div _x000D_
{_x000D_
  flex: 1; _x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

DataGridView.Clear()

Basically below code line is only useful in data binding scenarios

datagridview.DataSource = null; 

otherwise below is the used when no data binding and datagridview is populated manually

dataGridView1.Rows.Clear();
dataGridView1.Refresh();

So, check first what you are doing.

HTML input - name vs. id

The name attribute on an input is used by its parent HTML <form>s to include that element as a member of the HTTP form in a POST request or the query string in a GET request.

The id should be unique as it should be used by JavaScript to select the element in the DOM for manipulation and used in CSS selectors.

Why is conversion from string constant to 'char*' valid in C but invalid in C++

You can declare like one of the below options:

char data[] = "Testing String";

or

const char* data = "Testing String";

or

char* data = (char*) "Testing String";

What are these attributes: `aria-labelledby` and `aria-hidden`

aria-hidden="true" will hide decorative items like glyphicon icons from screen readers, which doesn't have meaningful pronunciation so as not to cause confusions. It's a nice thing do as matter of good practice.

Can I have multiple primary keys in a single table?

Some people use the term "primary key" to mean exactly an integer column that gets its values generated by some automatic mechanism. For example AUTO_INCREMENT in MySQL or IDENTITY in Microsoft SQL Server. Are you using primary key in this sense?

If so, the answer depends on the brand of database you're using. In MySQL, you can't do this, you get an error:

mysql> create table foo (
  id int primary key auto_increment, 
  id2 int auto_increment
);
ERROR 1075 (42000): Incorrect table definition; 
there can be only one auto column and it must be defined as a key

In some other brands of database, you are able to define more than one auto-generating column in a table.

No Multiline Lambda in Python: Why not?

I'm guilty of practicing this dirty hack in some of my projects which is bit simpler:

    lambda args...:( expr1, expr2, expr3, ...,
            exprN, returnExpr)[-1]

I hope you can find a way to stay pythonic but if you have to do it this less painful than using exec and manipulating globals.

Underline text in UIlabel

This is what i did. It works like butter.

1) Add CoreText.framework to your Frameworks.

2) import <CoreText/CoreText.h> in the class where you need underlined label.

3) Write the following code.

    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:@"My Messages"];
    [attString addAttribute:(NSString*)kCTUnderlineStyleAttributeName
              value:[NSNumber numberWithInt:kCTUnderlineStyleSingle]
              range:(NSRange){0,[attString length]}];
    self.myMsgLBL.attributedText = attString;
    self.myMsgLBL.textColor = [UIColor whiteColor];

IF/ELSE Stored Procedure

It isn't giving any errors? Try
SET @tmpType = 'premium'
and
SET @tmpType = 'basic'

pointer to array c++

j[0]; dereferences a pointer to int, so its type is int.

(*j)[0] has no type. *j dereferences a pointer to an int, so it returns an int, and (*j)[0] attempts to dereference an int. It's like attempting int x = 8; x[0];.

Opening Android Settings programmatically

Use this intent to open security and location screen in settings app of android device

    startActivity(new Intent(Settings.ACTION_SECURITY_SETTINGS));

How to add a form load event (currently not working)

Three ways you can do this - from the form designer, select the form, and where you normally see the list of properties, just above it there should be a little lightning symbol - this shows you all the events of the form. Find the form load event in the list, and you should be able to pick ProgramViwer_Load from the dropdown.

A second way to do it is programmatically - somewhere (constructor maybe) you'd need to add it, something like: ProgramViwer.Load += new EventHandler(ProgramViwer_Load);

A third way using the designer (probably the quickest) - when you create a new form, double click on the middle of it on it in design mode. It'll create a Form load event for you, hook it in, and take you to the event handler code. Then you can just add your two lines and you're good to go!

Angular + Material - How to refresh a data source (mat-table)

After reading Material Table not updating post data update #11638 Bug Report I found the best (read, the easiest solution) was as suggested by the final commentor 'shhdharmen' with a suggestion to use an EventEmitter.

This involves a few simple changes to the generated datasource class

ie) add a new private variable to your datasource class

import { EventEmitter } from '@angular/core';
...
private tableDataUpdated = new EventEmitter<any>();

and where I push new data to the internal array (this.data), I emit an event.

public addRow(row:myRowInterface) {
    this.data.push(row);
    this.tableDataUpdated.emit();
}

and finally, change the 'dataMutation' array in the 'connect' method - as follows

const dataMutations = [
    this.tableDataUpdated,
    this.paginator.page,
    this.sort.sortChange
];

When do items in HTML5 local storage expire?

Here highly recommended to use sessionStorage

  • it is same as localStorage but destroy when session destroyed / browser close
  • also localStorage can share between tabs while sessionStorage can use in current tab only, but value does not change on refresh page or change the page
  • sessionStorage is also useful to reduce network traffic against cookie

for set value use

sessionStorage.setItem("key","my value");

for get value use

var value = sessionStorage.getItem("key");

click here for view api

all ways for set are

  sessionStorage.key = "my val";
  sessionStorage["key"] = "my val";
  sessionStorage.setItem("key","my value");

all ways for get are

  var value = sessionStorage.key;
  var value = sessionStorage["key"];
  var value = sessionStorage.getItem("key");

How can I check out a GitHub pull request with git?

The problem with some of options above, is that if someone pushes more commits to the PR after opening the PR, they won't give you the most updated version. For me what worked best is - go to the PR, and press 'Commits', scroll to the bottom to see the most recent commit hash enter image description here and then simply use git checkout, i.e.

git checkout <commit number>

in the above example

git checkout 0ba1a50

How to maintain a Unique List in Java?

I want to clarify some things here for the original poster which others have alluded to but haven't really explicitly stated. When you say that you want a Unique List, that is the very definition of an Ordered Set. Some other key differences between the Set Interface and the List interface are that List allows you to specify the insert index. So, the question is do you really need the List Interface (i.e. for compatibility with a 3rd party library, etc.), or can you redesign your software to use the Set interface? You also have to consider what you are doing with the interface. Is it important to find elements by their index? How many elements do you expect in your set? If you are going to have many elements, is ordering important?

If you really need a List which just has a unique constraint, there is the Apache Common Utils class org.apache.commons.collections.list.SetUniqueList which will provide you with the List interface and the unique constraint. Mind you, this breaks the List interface though. You will, however, get better performance from this if you need to seek into the list by index. If you can deal with the Set interface, and you have a smaller data set, then LinkedHashSet might be a good way to go. It just depends on the design and intent of your software.

Again, there are certain advantages and disadvantages to each collection. Some fast inserts but slow reads, some have fast reads but slow inserts, etc. It makes sense to spend a fair amount of time with the collections documentation to fully learn about the finer details of each class and interface.

How do I make Visual Studio pause after executing a console application in debug mode?

I would use a "wait"-command for a specific time (milliseconds) of your own choice. The application executes until the line you want to inspect and then continues after the time expired.

Include the <time.h> header:

clock_t wait;

wait = clock();
while (clock() <= (wait + 5000)) // Wait for 5 seconds and then continue
    ;
wait = 0;

How to set viewport meta for iPhone that handles rotation properly?

just want to share, i've played around with the viewport settings for my responsive design, if i set the Max scale to 0.8, the initial scale to 1 and scalable to no then i get the smallest view in portrait mode and the iPad view for landscape :D... this is properly an ugly hack but it seems to work, i don't know why so i won't be using it, but interesting results

<meta name="viewport" content="user-scalable=no, initial-scale = 1.0,maximum-scale = 0.8,width=device-width" />

enjoy :)

Can't use WAMP , port 80 is used by IIS 7.5

Left Click on wamp go to apache> select http.config Listen [::0]:8080

How do I 'foreach' through a two-dimensional array?

Multidimensional arrays aren't enumerable. Just iterate the good old-fashioned way:

for (int i = 0; i < table.GetLength(0); i++)
{
    Console.WriteLine(table[i, 0] + " " + table[i, 1]);
}

Which port(s) does XMPP use?

According to Wikipedia:

5222 TCP     XMPP client connection (RFC 6120)        Official  
5223 TCP     XMPP client connection over SSL          Unofficial
5269 TCP     XMPP server connection (RFC 6120)        Official
5298 TCP UDP XMPP JEP-0174: Link-Local Messaging /    Official
             XEP-0174: Serverless Messaging
8010 TCP     XMPP File transfers                      Unofficial    

The port numbers are defined in RFC 6120 § 14.7.

Extract part of a regex match

Try using capturing groups:

title = re.search('<title>(.*)</title>', html, re.IGNORECASE).group(1)

Fiddler not capturing traffic from browsers

For it was betternet extension was causing issue. I think any kind of proxy extension installed on Chrome causing issue.

NameError: name 'self' is not defined

Default argument values are evaluated at function define-time, but self is an argument only available at function call time. Thus arguments in the argument list cannot refer each other.

It's a common pattern to default an argument to None and add a test for that in code:

def p(self, b=None):
    if b is None:
        b = self.a
    print b

Create Map in Java

I use such kind of a Map population thanks to Java 9. In my honest opinion, this approach provides more readability to the code.

  public static void main(String[] args) {
    Map<Integer, Point2D.Double> map = Map.of(
        1, new Point2D.Double(1, 1),
        2, new Point2D.Double(2, 2),
        3, new Point2D.Double(3, 3),
        4, new Point2D.Double(4, 4));
    map.entrySet().forEach(System.out::println);
  }

JavaScript, get date of the next day

Copy-pasted from here: Incrementing a date in JavaScript

Three options for you:

Using just JavaScript's Date object (no libraries):

var today = new Date();
var tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000));

Or if you don't mind changing the date in place (rather than creating a new date):

var dt = new Date();
dt.setTime(dt.getTime() + (24 * 60 * 60 * 1000));

Edit: See also Jigar's answer and David's comment below: var tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1);

Using MomentJS:

var today = moment();
var tomorrow = moment(today).add(1, 'days');

(Beware that add modifies the instance you call it on, rather than returning a new instance, so today.add(1, 'days') would modify today. That's why we start with a cloning op on var tomorrow = ....)

Using DateJS, but it hasn't been updated in a long time:

var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();

not None test in Python

Either of the latter two, since val could potentially be of a type that defines __eq__() to return true when passed None.

How do I determine height and scrolling position of window in jQuery?

from http://api.jquery.com/height/ (Note: The difference between the use for the window and the document object)

$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document

from http://api.jquery.com/scrollTop/

$(window).scrollTop() // return the number of pixels scrolled vertically

Connecting to remote URL which requires authentication using Java

I'd like to provide an answer for the case that you do not have control over the code that opens the connection. Like I did when using the URLClassLoader to load a jar file from a password protected server.

The Authenticator solution would work but has the drawback that it first tries to reach the server without a password and only after the server asks for a password provides one. That's an unnecessary roundtrip if you already know the server would need a password.

public class MyStreamHandlerFactory implements URLStreamHandlerFactory {

    private final ServerInfo serverInfo;

    public MyStreamHandlerFactory(ServerInfo serverInfo) {
        this.serverInfo = serverInfo;
    }

    @Override
    public URLStreamHandler createURLStreamHandler(String protocol) {
        switch (protocol) {
            case "my":
                return new MyStreamHandler(serverInfo);
            default:
                return null;
        }
    }

}

public class MyStreamHandler extends URLStreamHandler {

    private final String encodedCredentials;

    public MyStreamHandler(ServerInfo serverInfo) {
        String strCredentials = serverInfo.getUsername() + ":" + serverInfo.getPassword();
        this.encodedCredentials = Base64.getEncoder().encodeToString(strCredentials.getBytes());
    }

    @Override
    protected URLConnection openConnection(URL url) throws IOException {
        String authority = url.getAuthority();
        String protocol = "http";
        URL directUrl = new URL(protocol, url.getHost(), url.getPort(), url.getFile());

        HttpURLConnection connection = (HttpURLConnection) directUrl.openConnection();
        connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);

        return connection;
    }

}

This registers a new protocol my that is replaced by http when credentials are added. So when creating the new URLClassLoader just replace http with my and everything is fine. I know URLClassLoader provides a constructor that takes an URLStreamHandlerFactory but this factory is not used if the URL points to a jar file.

How to fix warning from date() in PHP"

You could also use this:

ini_alter('date.timezone','Asia/Calcutta');

You should call this before calling any date function. It accepts the key as the first parameter to alter PHP settings during runtime and the second parameter is the value.

I had done these things before I figured out this:

  1. Changed the PHP.timezone to "Asia/Calcutta" - but did not work
  2. Changed the lat and long parameters in the ini - did not work
  3. Used date_default_timezone_set("Asia/Calcutta"); - did not work
  4. Used ini_alter() - IT WORKED
  5. Commented date_default_timezone_set("Asia/Calcutta"); - IT WORKED
  6. Reverted the changes made to the PHP.ini - IT WORKED

For me the init_alter() method got it all working.

I am running Apache 2 (pre-installed), PHP 5.3 on OSX mountain lion

javascript get x and y coordinates on mouse click

Like this.

_x000D_
_x000D_
function printMousePos(event) {_x000D_
  document.body.textContent =_x000D_
    "clientX: " + event.clientX +_x000D_
    " - clientY: " + event.clientY;_x000D_
}_x000D_
_x000D_
document.addEventListener("click", printMousePos);
_x000D_
_x000D_
_x000D_

MouseEvent - MDN

MouseEvent.clientX Read only
The X coordinate of the mouse pointer in local (DOM content) coordinates.

MouseEvent.clientY Read only
The Y coordinate of the mouse pointer in local (DOM content) coordinates.

Python unittest passing arguments

So the doctors here that are saying "You say that hurts? Then don't do that!" are probably right. But if you really want to, here's one way of passing arguments to a unittest test:

import sys
import unittest

class MyTest(unittest.TestCase):
    USERNAME = "jemima"
    PASSWORD = "password"

    def test_logins_or_something(self):
        print('username : {}'.format(self.USERNAME))
        print('password : {}'.format(self.PASSWORD))


if __name__ == "__main__":
    if len(sys.argv) > 1:
        MyTest.USERNAME = sys.argv.pop()
        MyTest.PASSWORD = sys.argv.pop()
    unittest.main()

that will let you run with:

python mytests.py ausername apassword

You need the argv.pops so your command line params don't mess with unittest's own...

[update] The other thing you might want to look into is using environment variables:

import os
import unittest

class MyTest(unittest.TestCase):
    USERNAME = "jemima"
    PASSWORD = "password"

    def test_logins_or_something(self):
        print('username : {}'.format(self.USERNAME))
        print('password : {}'.format(self.PASSWORD))


if __name__ == "__main__":
    MyTest.USERNAME = os.environ.get('TEST_USERNAME', MyTest.USERNAME)            
    MyTest.PASSWORD = os.environ.get('TEST_PASSWORD', MyTest.PASSWORD)
    unittest.main()

That will let you run with:

TEST_USERNAME=ausername TEST_PASSWORD=apassword python mytests.py

and it has the advantage that you're not messing with unittest's own argument parsing. downside is it won't work quite like that on Windows...

SmtpException: Unable to read data from the transport connection: net_io_connectionclosed

removing

client.UseDefaultCredentials = false; 

seemed to solve it for me.

angular-cli server - how to proxy API requests to another server?

EDIT: THIS NO LONGER WORKS IN CURRENT ANGULAR-CLI

See answer from @imal hasaranga perera for up-to-date solution


The server in angular-cli comes from the ember-cli project. To configure the server, create an .ember-cli file in the project root. Add your JSON config in there:

{
   "proxy": "https://api.example.com"
}

Restart the server and it will proxy all requests there.

For example, I'm making relative requests in my code to /v1/foo/123, which is being picked up at https://api.example.com/v1/foo/123.

You can also use a flag when you start the server: ng serve --proxy https://api.example.com

Current for angular-cli version: 1.0.0-beta.0

What is the difference between WCF and WPF?

The quick answer is: Windows Presentation Foundation (WPF) is basically a way of displaying user interface. (see this)

Windows Communication Foundation (WCF) is a framework for creating service oriented applications. (see this)

As for which one you should use, it depends on your requirement. Usually an application written in WPF, ASP.NET..etc called the WCF service to do some processing at the server-side and the service returns the result to the application that called it.

When to use malloc for char pointers

As was indicated by others, you don't need to use malloc just to do:

const char *foo = "bar";

The reason for that is exactly that *foo is a pointer — when you initialize foo you're not creating a copy of the string, just a pointer to where "bar" lives in the data section of your executable. You can copy that pointer as often as you'd like, but remember, they're always pointing back to the same single instance of that string.

So when should you use malloc? Normally you use strdup() to copy a string, which handles the malloc in the background. e.g.

const char *foo = "bar";
char *bar = strdup(foo); /* now contains a new copy of "bar" */
printf("%s\n", bar);     /* prints "bar" */
free(bar);               /* frees memory created by strdup */

Now, we finally get around to a case where you may want to malloc if you're using sprintf() or, more safely snprintf() which creates / formats a new string.

char *foo = malloc(sizeof(char) * 1024);        /* buffer for 1024 chars */
snprintf(foo, 1024, "%s - %s\n", "foo", "bar"); /* puts "foo - bar\n" in foo */
printf(foo);                                    /* prints "foo - bar" */
free(foo);                                      /* frees mem from malloc */

Select statement to find duplicates on certain fields

If you're using SQL Server 2005 or later (and the tags for your question indicate SQL Server 2008), you can use ranking functions to return the duplicate records after the first one if using joins is less desirable or impractical for some reason. The following example shows this in action, where it also works with null values in the columns examined.

create table Table1 (
 Field1 int,
 Field2 int,
 Field3 int,
 Field4 int 
)

insert  Table1 
values    (1,1,1,1)
        , (1,1,1,2)
        , (1,1,1,3)
        , (2,2,2,1)
        , (3,3,3,1)
        , (3,3,3,2)
        , (null, null, 2, 1)
        , (null, null, 2, 3)

select    *
from     (select      Field1
                    , Field2
                    , Field3
                    , Field4
                    , row_number() over (partition by   Field1
                                                      , Field2
                                                      , Field3
                                         order by       Field4) as occurrence
          from      Table1) x
where     occurrence > 1

Notice after running this example that the first record out of every "group" is excluded, and that records with null values are handled properly.

If you don't have a column available to order the records within a group, you can use the partition-by columns as the order-by columns.

Razor If/Else conditional operator syntax

You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:

@(deletedView ? "Deleted" : "Created by")

Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.

SQL JOIN - WHERE clause vs. ON clause

Normally, filtering is processed in the WHERE clause once the two tables have already been joined. It’s possible, though that you might want to filter one or both of the tables before joining them. i.e, the where clause applies to the whole result set whereas the on clause only applies to the join in question.

Vertically align text within input field of fixed-height without display: table or padding?

This is how I do it.

<ul>
   <li>First group of text here.</li>
   <li><input type="" value="" /></li>
</ul>

then inside your CSS file,

ul li {
  display: block;
  float: left;
}

That should work for you.

PHP Using RegEx to get substring of a string

$string = "producturl.php?id=736375493?=tm";
$number = preg_replace("/[^0-9]/", '', $string);

The executable gets signed with invalid entitlements in Xcode

Simple clean-and-build seemed to fix it for me.

Simple Deadlock Examples

CountDownLatch countDownLatch = new CountDownLatch(1);
ExecutorService executorService = ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(() -> {
    Future<?> future = executorService.submit(() -> {
        System.out.println("generated task");
    });
    countDownLatch.countDown();
    try {
        future.get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
         e.printStackTrace();
    }
});


countDownLatch.await();
executorService.shutdown();

Input length must be multiple of 16 when decrypting with padded cipher

This is a very old question, but my answer may help someone.

  • In the encrypt method, don't forget to encode your string to Base64
  • In the decrypt method, don't forget to decode your string to Base64

Below is the working code

    import java.util.Arrays;
    import java.util.Base64;

    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;

    public class EncryptionDecryptionUtil {

    public static String encrypt(final String secret, final String data) {


        byte[] decodedKey = Base64.getDecoder().decode(secret);

        try {
            Cipher cipher = Cipher.getInstance("AES");
            // rebuild key using SecretKeySpec
            SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, originalKey);
            byte[] cipherText = cipher.doFinal(data.getBytes("UTF-8"));
            return Base64.getEncoder().encodeToString(cipherText);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Error occured while encrypting data", e);
        }

    }

    public static String decrypt(final String secret,
            final String encryptedString) {


        byte[] decodedKey = Base64.getDecoder().decode(secret);

        try {
            Cipher cipher = Cipher.getInstance("AES");
            // rebuild key using SecretKeySpec
            SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
            cipher.init(Cipher.DECRYPT_MODE, originalKey);
            byte[] cipherText = cipher.doFinal(Base64.getDecoder().decode(encryptedString));
            return new String(cipherText);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Error occured while decrypting data", e);
        }
    }


    public static void main(String[] args) {

        String data = "This is not easy as you think";
        String key = "---------------------------------";
        String encrypted = encrypt(key, data);
        System.out.println(encrypted);
        System.out.println(decrypt(key, encrypted));
      }
  }

For Generating Key you can use below class

    import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class SecretKeyGenerator {

    public static void main(String[] args) throws NoSuchAlgorithmException {

        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");

        SecureRandom secureRandom = new SecureRandom();
        int keyBitSize = 256;
        keyGenerator.init(keyBitSize, secureRandom);

        SecretKey secretKey = keyGenerator.generateKey();

 System.out.println(Base64.getEncoder().encodeToString(secretKey.getEncoded()));
    }

}

C#: Dynamic runtime cast

This should work:

public static dynamic Cast(dynamic obj, Type castTo)
{
    return Convert.ChangeType(obj, castTo);
}

Edit

I've written the following test code:

var x = "123";
var y = Cast(x, typeof(int));
var z = y + 7;
var w = Cast(z, typeof(string)); // w == "130"

It does resemble the kind of "typecasting" one finds in languages like PHP, JavaScript or Python (because it also converts the value to the desired type). I don't know if that's a good thing, but it certainly works... :-)

ASP.NET page life cycle explanation

There are 10 events in ASP.NET page life cycle, and the sequence is:

  1. Init
  2. Load view state
  3. Post back data
  4. Load
  5. Validate
  6. Events
  7. Pre-render
  8. Save view state
  9. Render
  10. Unload

Below is a pictorial view of ASP.NET Page life cycle with what kind of code is expected in that event. I suggest you read this article I wrote on the ASP.NET Page life cycle, which explains each of the 10 events in detail and when to use them.

ASP.NET life cycle

Image source: my own article at https://www.c-sharpcorner.com/uploadfile/shivprasadk/Asp-Net-application-and-page-life-cycle/ from 19 April 2010

Most efficient solution for reading CLOB to String, and String to CLOB in Java?

Ok I will suppose a general use, first you have to download apache commons, there you will find an utility class named IOUtils which has a method named copy();

Now the solution is: get the input stream of your CLOB object using getAsciiStream() and pass it to the copy() method.

InputStream in = clobObject.getAsciiStream();
StringWriter w = new StringWriter();
IOUtils.copy(in, w);
String clobAsString = w.toString();

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

You can check out this blog post. It had solved my problem.

http://dotnetguts.blogspot.com/2010/06/restore-failed-for-server-restore.html

Select @@Version
It had given me following output Microsoft SQL Server 2005 - 9.00.4053.00 (Intel X86) May 26 2009 14:24:20 Copyright (c) 1988-2005 Microsoft Corporation Express Edition on Windows NT 6.0 (Build 6002: Service Pack 2)

You will need to re-install to a new named instance to ensure that you are using the new SQL Server version.

PHP convert string to hex and hex to string

Using @bill-shirley answer with a little addition

function str_to_hex($string) {
$hexstr = unpack('H*', $string);
return array_shift($hexstr);
}
function hex_to_str($string) {
return hex2bin("$string");
}

Usage:

  $str = "Go placidly amidst the noise";
  $hexstr = str_to_hex($str);// 476f20706c616369646c7920616d6964737420746865206e6f697365
  $strstr = hex_to_str($str);// Go placidly amidst the noise

Deploying just HTML, CSS webpage to Tomcat

If you want to create a .war file you can deploy to a Tomcat instance using the Manager app, create a folder, put all your files in that folder (including an index.html file) move your terminal window into that folder, and execute the following command:

zip -r <AppName>.war *

I've tested it with Tomcat 8 on the Mac, but it should work anywhere

Upload file to SFTP using PowerShell

There isn't currently a built-in PowerShell method for doing the SFTP part. You'll have to use something like psftp.exe or a PowerShell module like Posh-SSH.

Here is an example using Posh-SSH:

# Set the credentials
$Password = ConvertTo-SecureString 'Password1' -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ('root', $Password)

# Set local file path, SFTP path, and the backup location path which I assume is an SMB path
$FilePath = "C:\FileDump\test.txt"
$SftpPath = '/Outbox'
$SmbPath = '\\filer01\Backup'

# Set the IP of the SFTP server
$SftpIp = '10.209.26.105'

# Load the Posh-SSH module
Import-Module C:\Temp\Posh-SSH

# Establish the SFTP connection
$ThisSession = New-SFTPSession -ComputerName $SftpIp -Credential $Credential

# Upload the file to the SFTP path
Set-SFTPFile -SessionId ($ThisSession).SessionId -LocalFile $FilePath -RemotePath $SftpPath

#Disconnect all SFTP Sessions
Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }

# Copy the file to the SMB location
Copy-Item -Path $FilePath -Destination $SmbPath

Some additional notes:

  • You'll have to download the Posh-SSH module which you can install to your user module directory (e.g. C:\Users\jon_dechiro\Documents\WindowsPowerShell\Modules) and just load using the name or put it anywhere and load it like I have in the code above.
  • If having the credentials in the script is not acceptable you'll have to use a credential file. If you need help with that I can update with some details or point you to some links.
  • Change the paths, IPs, etc. as needed.

That should give you a decent starting point.

Find Facebook user (url to profile page) by known email address

First I thank you. # 57ar7up and I will add the following code it helps in finding the return phone number.

function index(){
    // $keyword = "0946664869";
    $sql = "SELECT * FROM phone_find LIMIT 10";
    $result =  $this->GlobalMD->query_global($sql);
    $fb = array();
    foreach($result as $value){
        $keyword = $value['phone'];
        $fb[] = $this->facebook_search($keyword);
    }
    var_dump($fb);

}

function facebook_search($query, $type = 'all'){
    $url = 'http://www.facebook.com/search/'.$type.'/?q='.$query;
    $user_agent = $this->loaduserAgent();

    $c = curl_init();
    curl_setopt_array($c, array(
        CURLOPT_URL             => $url,
        CURLOPT_USERAGENT       => $user_agent,
        CURLOPT_RETURNTRANSFER  => TRUE,
        CURLOPT_FOLLOWLOCATION  => TRUE,
        CURLOPT_SSL_VERIFYPEER  => FALSE
    ));
    $data = curl_exec($c);
    preg_match('/\&#123;&quot;id&quot;:(?P<fbUserId>\d+)\,/', $data, $matches);
    if(isset($matches["fbUserId"]) && $matches["fbUserId"] != ""){
        $fbUserId = $matches["fbUserId"];
        $params = array($query,$fbUserId);
    }else{
        $fbUserId = "";
        $params = array($query,$fbUserId);
    }
    return $params;
}

a = open("file", "r"); a.readline() output without \n

A solution, can be:

with open("file", "r") as fd:
    lines = fd.read().splitlines()

You get the list of lines without "\r\n" or "\n".

Or, use the classic way:

with open("file", "r") as fd:
    for line in fd:
        line = line.strip()

You read the file, line by line and drop the spaces and newlines.

If you only want to drop the newlines:

with open("file", "r") as fd:
    for line in fd:
        line = line.replace("\r", "").replace("\n", "")

Et voilà.

Note: The behavior of Python 3 is a little different. To mimic this behavior, use io.open.

See the documentation of io.open.

So, you can use:

with io.open("file", "r", newline=None) as fd:
    for line in fd:
        line = line.replace("\n", "")

When the newline parameter is None: lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n'.

newline controls how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:

On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.

How to add a href link in PHP?

Just do it in HTML

<a href="https://www.google.com">Google</a>

How to test code dependent on environment variables using JUnit?

You can use Powermock for mocking the call. Like:

PowerMockito.mockStatic(System.class);
PowerMockito.when(System.getenv("MyEnvVariable")).thenReturn("DesiredValue");

You can also mock all the calls with:

PowerMockito.mockStatic(System.class);
PowerMockito.when(System.getenv(Mockito.anyString())).thenReturn(envVariable);

In Perl, how do I create a hash whose keys come from a given array?

%hash = map { $_ => 1 } @array;

It's not as short as the "@hash{@array} = ..." solutions, but those ones require the hash and array to already be defined somewhere else, whereas this one can take an anonymous array and return an anonymous hash.

What this does is take each element in the array and pair it up with a "1". When this list of (key, 1, key, 1, key 1) pairs get assigned to a hash, the odd-numbered ones become the hash's keys, and the even-numbered ones become the respective values.

Delete directory with files in it?

For windows:

system("rmdir ".escapeshellarg($path) . " /s /q");

How to insert array of data into mysql using php

First of all you should stop using mysql_*. MySQL supports multiple inserting like

INSERT INTO example
VALUES
  (100, 'Name 1', 'Value 1', 'Other 1'),
  (101, 'Name 2', 'Value 2', 'Other 2'),
  (102, 'Name 3', 'Value 3', 'Other 3'),
  (103, 'Name 4', 'Value 4', 'Other 4');

You just have to build one string in your foreach loop which looks like that

$values = "(100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1')";

and then insert it after the loop

$sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) VALUES ".$values;

Another way would be Prepared Statements, which are even more suited for your situation.

Easiest way to copy a table from one database to another?

For me I need to specific schema to "information_schema.TABLES"

for example.

SELECT concat('CREATE TABLE new_db.', TABLE_NAME, ' LIKE old_db.', TABLE_NAME, ';') FROM information_schema.TABLES  WHERE TABLE_SCHEMA = 'old_db';

Is there a Python caching library?

This project aims to provide "Caching for humans" (seems like it's fairly unknown though)

Some info from the project page:

Installation

pip install cache

Usage:

import pylibmc
from cache import Cache

backend = pylibmc.Client(["127.0.0.1"])

cache = Cache(backend)

@cache("mykey")
def some_expensive_method():
    sleep(10)
    return 42

# writes 42 to the cache
some_expensive_method()

# reads 42 from the cache
some_expensive_method()

# re-calculates and writes 42 to the cache
some_expensive_method.refresh()

# get the cached value or throw an error
# (unless default= was passed to @cache(...))
some_expensive_method.cached()

How to make script execution wait until jquery is loaded

you can use the defer attribute to load the script at the really end.

<script type='text/javascript' src='myscript.js' defer='defer'></script>

but normally loading your script in correct order should do the trick, so be sure to place jquery inclusion before your own script

If your code is in the page and not in a separate js file so you have to execute your script only after the document is ready and encapsulating your code like this should work too:

$(function(){
//here goes your code
});

Execute PHP scripts within Node.js web server

You can try to implement direct link node -> fastcgi -> php. In the previous answer, nginx serves php requests using http->fastcgi serialisation->unix socket->php and node requests as http->nginx reverse proxy->node http server.

It seems that node-fastcgi paser is useable at the moment, but only as a node fastcgi backend. You need to adopt it to use as a fastcgi client to php fastcgi server.

Removing the remembered login and password list in SQL Server Management Studio

As gluecks pointed out, no more SqlStudio.bin in Microsoft SQL Server Management Studio 18. I also found this UserSettings.xml in C:\Users\userName\AppData\Roaming\Microsoft\SQL Server Management Studio\18.0. But removing the <Element> containing the credential seems not working, it comes right back on the xml file, if I close and re-open it again.

Turns out, you need to close the SQL Server Management Studio first, then edit the UserSettings.xml file in your favorite editor, e.g. Visual Studio Code. I guess it's cached somewhere in SSMS besides this xml file?! And it's not on Control Panel\All Control Panel Items\Credential Manager\Windows Credentials.

How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

You can cast it to

(<any>$('.selector') ).function();

Ex: date picker initialize using jquery

(<any>$('.datepicker') ).datepicker();

git: diff between file in local repo and origin

For that I wrote a bash script:

#set -x 
branchname=`git branch | grep -F '*' |  awk '{print $2}'`
echo $branchname
git fetch origin ${branchname}
for file in `git status | awk '{if ($1 == "modified:") print $2;}'`
do
echo "PLEASE CHECK OUT GIT DIFF FOR "$file 
git difftool  FETCH_HEAD $file ;
done

In the above script, I fetch the remote main branch (not necessary its master branch ANY branch) to FETCH_HEAD, then make a list of my modified file only and compare modified files to git difftool.

There are many difftool supported by git, I configured Meld Diff Viewer for good GUI comparison.
From the above script, I have prior knowledge what changes done by other teams in same file, before I follow git stages untrack-->staged-->commit which help me to avoid unnecessary resolve merge conflict with remote team or make new local branch and compare and merge on the main branch.

Redirect to a page/URL after alert button is pressed

window.location = mypage.href is a direct command for the browser to dump it's contents and start loading up some more. So for better clarification, here's what's happening in your PHP script:

echo '<script type="text/javascript">'; 
echo 'alert("review your answer");'; 
echo 'window.location = "index.php";';
echo '</script>';

1) prepare to accept a modification or addition to the current Javascript cache. 2) show the alert 3) dump everything in browser memory and get ready for some more (albeit an older method of loading a new URL (AND NOTICE that there are no "\n" (new line) indicators between the lines and is therefore causing some havoc in the JS decoder.

Let me suggest that you do this another way..

echo '<script type="text/javascript">\n'; 
echo 'alert("review your answer");\n'; 
echo 'document.location.href = "index.php";\n';
echo '</script>\n';

1) prepare to accept a modification or addition to the current Javascript cache. 2) show the alert 3) dump everything in browser memory and get ready for some more (in a better fashion than before) And WOW - it all works because the JS decoder can see that each command is anow a new line.

Best of luck!

Laravel update model with unique validation rule for attribute

'email' => [
    'required',
    Rule::exists('staff')->where(function ($query) {
        $query->where('account_id', 1);
    }),
],

'email' => [
    'required',
    Rule::unique('users')->ignore($user->id)->where(function ($query) {
        $query->where('account_id', 1);
    })
],

Python extract pattern matches

You need to capture from regex. search for the pattern, if found, retrieve the string using group(index). Assuming valid checks are performed:

>>> p = re.compile("name (.*) is valid")
>>> result = p.search(s)
>>> result
<_sre.SRE_Match object at 0x10555e738>
>>> result.group(1)     # group(1) will return the 1st capture (stuff within the brackets).
                        # group(0) will returned the entire matched text.
'my_user_name'

Waiting on a list of Future

maybe this would help (nothing would replaced with raw thread, yeah!) I suggest run each Future guy with a separated thread (they goes parallel), then when ever one of the got error, it just signal the manager(Handler class).

class Handler{
//...
private Thread thisThread;
private boolean failed=false;
private Thread[] trds;
public void waitFor(){
  thisThread=Thread.currentThread();
  List<Future<Object>> futures = getFutures();
  trds=new Thread[futures.size()];
  for (int i = 0; i < trds.length; i++) {
    RunTask rt=new RunTask(futures.get(i), this);
    trds[i]=new Thread(rt);
  }
  synchronized (this) {
    for(Thread tx:trds){
      tx.start();
    }  
  }
  for(Thread tx:trds){
    try {tx.join();
    } catch (InterruptedException e) {
      System.out.println("Job failed!");break;
    }
  }if(!failed){System.out.println("Job Done");}
}

private List<Future<Object>> getFutures() {
  return null;
}

public synchronized void cancelOther(){if(failed){return;}
  failed=true;
  for(Thread tx:trds){
    tx.stop();//Deprecated but works here like a boss
  }thisThread.interrupt();
}
//...
}
class RunTask implements Runnable{
private Future f;private Handler h;
public RunTask(Future f,Handler h){this.f=f;this.h=h;}
public void run(){
try{
f.get();//beware about state of working, the stop() method throws ThreadDeath Error at any thread state (unless it blocked by some operation)
}catch(Exception e){System.out.println("Error, stopping other guys...");h.cancelOther();}
catch(Throwable t){System.out.println("Oops, some other guy has stopped working...");}
}
}

I have to say the above code would error(didn't check), but I hope I could explain the solution. please have a try.

Setting HttpContext.Current.Session in a unit test

Milox solution is better than the accepted one IMHO but I had some problems with this implementation when handling urls with querystring.

I made some changes to make it work properly with any urls and to avoid Reflection.

public static HttpContext FakeHttpContext(string url)
{
    var uri = new Uri(url);
    var httpRequest = new HttpRequest(string.Empty, uri.ToString(),
                                        uri.Query.TrimStart('?'));
    var stringWriter = new StringWriter();
    var httpResponse = new HttpResponse(stringWriter);
    var httpContext = new HttpContext(httpRequest, httpResponse);

    var sessionContainer = new HttpSessionStateContainer("id",
                                    new SessionStateItemCollection(),
                                    new HttpStaticObjectsCollection(),
                                    10, true, HttpCookieMode.AutoDetect,
                                    SessionStateMode.InProc, false);

    SessionStateUtility.AddHttpSessionStateToContext(
                                         httpContext, sessionContainer);

    return httpContext;
}

Mercurial: how to amend the last commit?

Recent versions of Mercurial include the evolve extension which provides the hg amend command. This allows amending a commit without losing the pre-amend history in your version control.

hg amend [OPTION]... [FILE]...

aliases: refresh

combine a changeset with updates and replace it with a new one

Commits a new changeset incorporating both the changes to the given files
and all the changes from the current parent changeset into the repository.

See 'hg commit' for details about committing changes.

If you don't specify -m, the parent's message will be reused.

Behind the scenes, Mercurial first commits the update as a regular child
of the current parent. Then it creates a new commit on the parent's
parents with the updated contents. Then it changes the working copy parent
to this new combined changeset. Finally, the old changeset and its update
are hidden from 'hg log' (unless you use --hidden with log).

See https://www.mercurial-scm.org/doc/evolution/user-guide.html#example-3-amend-a-changeset-with-evolve for a complete description of the evolve extension.

Update Item to Revision vs Revert to Revision

@BaltoStar update to revision syntax:

http://svnbook.red-bean.com/en/1.6/svn.ref.svn.c.update.html

svn update -r30

Where 30 is revision number. Hope this help!

How to remove unused dependencies from composer?

In fact, it is very easy.

composer update

will do all this for you, but it will also update the other packages.

To remove a package without updating the others, specifiy that package in the command, for instance:

composer update monolog/monolog

will remove the monolog/monolog package.

Nevertheless, there may remain some empty folders or files that cannot be removed automatically, and that have to be removed manually.

Redirecting new tab on button click.(Response.Redirect) in asp.net C#

I think your code should work just remove one thing from here but it'll do redirection from current page within existing window

<asp:Button ID="btn" runat="Server" Text="SUBMIT" 

 OnClick="btnNewEntry_Click"/>    



protected void btnNewEntry_Click(object sender, EventArgs e)
 {
    Response.Redirect("CMS_1.aspx");
 }

And if u wanna do the this via client side scripting Use this way

<asp:Button ID="BTN" runat="server" Text="Submit" OnClientClick="window.open('Default2.aspx')" />

According to me you should prefer the Client Side Scripting because just to open a new window server side will take a post back and that will be useless..

Detect when browser receives file download

Create an iframe when button/link is clicked and append this to body.

                  $('<iframe />')
                 .attr('src', url)
                 .attr('id','iframe_download_report')
                 .hide()
                 .appendTo('body'); 

Create an iframe with delay and delete it after download.

                            var triggerDelay =   100;
                            var cleaningDelay =  20000;
                            var that = this;
                            setTimeout(function() {
                                var frame = $('<iframe style="width:1px; height:1px;" class="multi-download-frame"></iframe>');
                                frame.attr('src', url+"?"+ "Content-Disposition: attachment ; filename="+that.model.get('fileName'));
                                $(ev.target).after(frame);
                                setTimeout(function() {
                                    frame.remove();
                                }, cleaningDelay);
                            }, triggerDelay);

Bash integer comparison

This script works!

#/bin/bash
if [[ ( "$#" < 1 ) || ( !( "$1" == 1 ) && !( "$1" == 0 ) ) ]] ; then
    echo this script requires a 1 or 0 as first parameter.
else
    echo "first parameter is $1"
    xinput set-prop 12 "Device Enabled" $0
fi

But this also works, and in addition keeps the logic of the OP, since the question is about calculations. Here it is with only arithmetic expressions:

#/bin/bash
if (( $# )) && (( $1 == 0 || $1 == 1 )); then
    echo "first parameter is $1"
    xinput set-prop 12 "Device Enabled" $0
else
    echo this script requires a 1 or 0 as first parameter.
fi

The output is the same1:

$ ./tmp.sh 
this script requires a 1 or 0 as first parameter.

$ ./tmp.sh 0
first parameter is 0

$ ./tmp.sh 1
first parameter is 1

$ ./tmp.sh 2
this script requires a 1 or 0 as first parameter.

[1] the second fails if the first argument is a string

Setting PHPMyAdmin Language

At the first site is a dropdown field to select the language of phpmyadmin.

In the config.inc.php you can set:

$cfg['Lang'] = '';

More details you can find in the documentation: http://www.phpmyadmin.net/documentation/

How to find the kafka version in linux

There are several methods to find kafka version

Method 1 simple:-

ps -ef|grep kafka

it will displays all running kafka clients in the console... Ex:- /usr/hdp/current/kafka-broker/bin/../libs/kafka-clients-0.10.0.2.5.3.0-37.jar we are using 0.10.0.2.5.3.0-37 version of kafka

Method 2:- go to

cd /usr/hdp/current/kafka-broker/libs
ll |grep kafka

Ex:- kafka_2.10-0.10.0.2.5.3.0-37.jar kafka-clients-0.10.0.2.5.3.0-37.jar

same result as method 1 we can find the version of kafka using in kafka libs.

Function pointer as parameter

You need to declare disconnectFunc as a function pointer, not a void pointer. You also need to call it as a function (with parentheses), and no "*" is needed.

get the value of DisplayName attribute

If instead

[DisplayName("Something To Name")]

you use

[Display(Name = "Something To Name")]

Just do this:

private string GetDisplayName(Class1 class1)
{
    string displayName = string.Empty;

    string propertyName = class1.Name.GetType().Name;

    CustomAttributeData displayAttribute = class1.GetType().GetProperty(propertyName).CustomAttributes.FirstOrDefault(x => x.AttributeType.Name == "DisplayAttribute");

    if (displayAttribute != null)
    {
        displayName = displayAttribute.NamedArguments.FirstOrDefault().TypedValue.Value;
    }

    return displayName;
}

Unexpected token < in first line of HTML

Well... I flipped the internet upside down three times but did not find anything that might help me because it was a Drupal project rather than other scenarios people described.

My problem was that someone in the project added a js which his address was: <script src="http://base_url/?p4sxbt"></script> and it was attached in this way:

drupal_add_js('',
    array('scope' => 'footer', 'weight' => 5)
  );

Hope this will help someone in the future.

iOS8 Beta Ad-Hoc App Download (itms-services)

If you have already installed app on your device, try to change bundle identifer on the web .plist (not app plist) with something else like "com.vistair.docunet-test2", after that refresh webpage and try to reinstall... It works for me

Reading binary file and looping over each byte

To sum up all the brilliant points of chrispy, Skurmedel, Ben Hoyt and Peter Hansen, this would be the optimal solution for processing a binary file one byte at a time:

with open("myfile", "rb") as f:
    while True:
        byte = f.read(1)
        if not byte:
            break
        do_stuff_with(ord(byte))

For python versions 2.6 and above, because:

  • python buffers internally - no need to read chunks
  • DRY principle - do not repeat the read line
  • with statement ensures a clean file close
  • 'byte' evaluates to false when there are no more bytes (not when a byte is zero)

Or use J. F. Sebastians solution for improved speed

from functools import partial

with open(filename, 'rb') as file:
    for byte in iter(partial(file.read, 1), b''):
        # Do stuff with byte

Or if you want it as a generator function like demonstrated by codeape:

def bytes_from_file(filename):
    with open(filename, "rb") as f:
        while True:
            byte = f.read(1)
            if not byte:
                break
            yield(ord(byte))

# example:
for b in bytes_from_file('filename'):
    do_stuff_with(b)

Expression must be a modifiable lvalue

Remember that a single = is always an assignment in C or C++.

Your test should be if ( match == 0 && k == M )you made a typo on the k == M test.

If you really mean k=M (i.e. a side-effecting assignment inside a test) you should for readability reasons code if (match == 0 && (k=m) != 0) but most coding rules advise not writing that.

BTW, your mistake suggests to ask for all warnings (e.g. -Wall option to g++), and to upgrade to recent compilers. The next GCC 4.8 will give you:

 % g++-trunk -Wall -c ederman.cc
 ederman.cc: In function ‘void foo()’:
 ederman.cc:9:30: error: lvalue required as left operand of assignment
          if ( match == 0 && k = M )
                               ^

and Clang 3.1 also tells you ederman.cc:9:30: error: expression is not assignable

So use recent versions of free compilers and enable all the warnings when using them.

Difference between a SOAP message and a WSDL?

In a simple terms if you have a web service of calculator. WSDL tells about the functions that you can implement or exposed to the client. For example: add, delete, subtract and so on. Where as using SOAP you actually perform actions like doDelete(), doSubtract(), doAdd(). So SOAP and WSDL are apples and oranges. We should not compare them. They both have their own different functionality.

Description Box using "onmouseover"

Although not necessarily a JavaScript solution, there is also a "title" global tag attribute that may be helpful.

<a href="https://stackoverflow.com/questions/3559467/description-box-on-mouseover" title="This is a title.">Mouseover me</a>

Mouseover me

Proper way of checking if row exists in table in PL/SQL block

If you are using an explicit cursor, It should be as follows.

DECLARE
   CURSOR get_id IS 
    SELECT id 
      FROM person 
      WHERE id = 10;

  id_value_ person.id%ROWTYPE;
BEGIN 
   OPEN get_id;
   FETCH get_id INTO id_value_;

   IF (get_id%FOUND) THEN
     DBMS_OUTPUT.PUT_LINE('Record Found.');
   ELSE
     DBMS_OUTPUT.PUT_LINE('Record Not Found.');
   END IF;
   CLOSE get_id;

EXCEPTION
  WHEN no_data_found THEN
  --do things when record doesn't exist
END;

What is the quickest way to HTTP GET in Python?

How to also send headers

Python 3:

import urllib.request
contents = urllib.request.urlopen(urllib.request.Request(
    "https://api.github.com/repos/cirosantilli/linux-kernel-module-cheat/releases/latest",
    headers={"Accept" : 'application/vnd.github.full+json"text/html'}
)).read()
print(contents)

Python 2:

import urllib2
contents = urllib2.urlopen(urllib2.Request(
    "https://api.github.com",
    headers={"Accept" : 'application/vnd.github.full+json"text/html'}
)).read()
print(contents)

AngularJS - Access to child scope

Using $emit and $broadcast, (as mentioned by walv in the comments above)

To fire an event upwards (from child to parent)

$scope.$emit('myTestEvent', 'Data to send');

To fire an event downwards (from parent to child)

$scope.$broadcast('myTestEvent', {
  someProp: 'Sending you some data'
});

and finally to listen

$scope.$on('myTestEvent', function (event, data) {
  console.log(data);
});

For more details :- https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

Enjoy :)

What's the difference between session.persist() and session.save() in Hibernate?

I have done good research on the save() vs. persist() including running it on my local machine several times. All the previous explanations are confusing and incorrect. I compare save() and persist() methods below after a thorough research.

Save()

  1. Returns generated Id after saving. Its return type is Serializable;
  2. Saves the changes to the database outside of the transaction;
  3. Assigns the generated id to the entity you are persisting;
  4. session.save() for a detached object will create a new row in the table.

Persist()

  1. Does not return generated Id after saving. Its return type is void;
  2. Does not save the changes to the database outside of the transaction;
  3. Assigns the generated Id to the entity you are persisting;
  4. session.persist() for a detached object will throw a PersistentObjectException, as it is not allowed.

All these are tried/tested on Hibernate v4.0.1.

Remove HTML tags from a String

You can simply use the Android's default HTML filter

    public String htmlToStringFilter(String textToFilter){

    return Html.fromHtml(textToFilter).toString();

    }

The above method will return the HTML filtered string for your input.

Function is not defined - uncaught referenceerror

Your issue here is that you're not understanding the scope that you're setting.

You are passing the ready function a function itself. Within this function, you're creating another function called codeAddress. This one exists within the scope that created it and not within the window object (where everything and its uncle could call it).

For example:

var myfunction = function(){
    var myVar = 12345;
};

console.log(myVar); // 'undefined' - since it is within 
                    // the scope of the function only.

Have a look here for a bit more on anonymous functions: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

Another thing is that I notice you're using jQuery on that page. This makes setting click handlers much easier and you don't need to go into the hassle of setting the 'onclick' attribute in the HTML. You also don't need to make the codeAddress method available to all:

$(function(){
    $("#imgid").click(function(){
        var address = $("#formatedAddress").value;
        geocoder.geocode( { 'address': address}, function(results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
             map.setCenter(results[0].geometry.location);
           }
        });
    });  
});

(You should remove the existing onclick and add an ID to the image element that you want to handle)

Note that I've replaced $(document).ready() with its shortcut of just $() (http://api.jquery.com/ready/). Then the click method is used to assign a click handler to the element. I've also replaced your document.getElementById with the jQuery object.

Setting CSS pseudo-class rules from JavaScript

Instead of directly setting pseudo-class rules with javascript, you can set the rules differently in different CSS files, and then use Javascript to switch one stylesheet off and to switch another on. A method is described at A List Apart (qv. for more detail).

Set up the CSS files as,

<link rel="stylesheet" href="always_on.css">
<link rel="stylesheet" title="usual" href="preferred.css"> <!-- on by default -->
<link rel="alternate stylesheet" title="strange" href="alternate.css"> <!-- off by default -->

And then switch between them using javascript:

function setActiveStyleSheet(title) {
   var i, a, main;
   for(i=0; (a = document.getElementsByTagName("link")<i>); i++) {
     if(a.getAttribute("rel").indexOf("style") != -1
        && a.getAttribute("title")) {
       a.disabled = true;
       if(a.getAttribute("title") == title) a.disabled = false;
     }
   }
}

CURL alternative in Python

import requests

url = 'https://example.tld/'
auth = ('username', 'password')

r = requests.get(url, auth=auth)
print r.content

This is the simplest I've been able to get it.

how to check and set max_allowed_packet mysql variable

goto cpanel and login as Main Admin or Super Administrator

  1. find SSH/Shell Access ( you will find under the security tab of cpanel )

  2. now give the username and password of Super Administrator as root or whatyougave

    note: do not give any username, cos, it needs permissions
    
  3. once your into console type

    type ' mysql ' and press enter now you find youself in

    mysql> /* and type here like */

    mysql> set global net_buffer_length=1000000;

    Query OK, 0 rows affected (0.00 sec)

    mysql> set global max_allowed_packet=1000000000;

    Query OK, 0 rows affected (0.00 sec)

Now upload and enjoy!!!

Run git pull over all subdirectories

The mr utility (a.k.a., myrepos) provides an outstanding solution to this very problem. Install it using your favorite package manager, or just grab the mr script directly from github and put it in $HOME/bin or somewhere else on your PATH. Then, cd to the parent plugins folder shared by these repos and create a basic .mrconfig file with contents similar to the following (adjusting the URLs as needed):

# File: .mrconfig
[cms]
checkout = git clone 'https://<username>@github.com/<username>/cms' 'cms'

[admin]
checkout = git clone 'https://<username>@github.com/<username>/admin' 'admin'

[chart]
checkout = git clone 'https://<username>@github.com/<username>/chart' 'chart'

After that, you can run mr up from the top level plugins folder to pull updates from each repository. (Note that this will also do the initial clone if the target working copy doesn't yet exist.) Other commands you can execute include mr st, mr push, mr log, mr diff, etc—run mr help to see what's possible. There's a mr run command that acts as a pass-through, allowing you to access VCS commands not directly suported by mr itself (e.g., mr run git tag STAGING_081220015). And you can even create your own custom commands that execute arbitrary bits of shell script targeting all repos!

mr is an extremely useful tool for dealing with multiple repos. Since the plugins folder is in your home directory, you might also be interested in vcsh. Together with mr, it provides a powerful mechanism for managing all of your configuration files. See this blog post by Thomas Ferris Nicolaisen for an overview.

What's the simplest way of detecting keyboard input in a script from the terminal?

Well, since the date of this question post, a Python library addressed this topic. pynput library, from Moses Palmer, is GREAT to catch keyboard and mouse events in a very simple way.

(mind the missing 'i' in pynput - I missed it too... ;-) )

Get names of all keys in the collection

As per the mongoldb documentation, a combination of distinct

Finds the distinct values for a specified field across a single collection or view and returns the results in an array.

and indexes collection operations are what would return all possible values for a given key, or index:

Returns an array that holds a list of documents that identify and describe the existing indexes on the collection

So in a given method one could do use a method like the following one, in order to query a collection for all it's registered indexes, and return, say an object with the indexes for keys (this example uses async/await for NodeJS, but obviously you could use any other asynchronous approach):

async function GetFor(collection, index) {

    let currentIndexes;
    let indexNames = [];
    let final = {};
    let vals = [];

    try {
        currentIndexes = await collection.indexes();
        await ParseIndexes();
        //Check if a specific index was queried, otherwise, iterate for all existing indexes
        if (index && typeof index === "string") return await ParseFor(index, indexNames);
        await ParseDoc(indexNames);
        await Promise.all(vals);
        return final;
    } catch (e) {
        throw e;
    }

    function ParseIndexes() {
        return new Promise(function (result) {
            let err;
            for (let ind in currentIndexes) {
                let index = currentIndexes[ind];
                if (!index) {
                    err = "No Key For Index "+index; break;
                }
                let Name = Object.keys(index.key);
                if (Name.length === 0) {
                    err = "No Name For Index"; break;
                }
                indexNames.push(Name[0]);
            }
            return result(err ? Promise.reject(err) : Promise.resolve());
        })
    }

    async function ParseFor(index, inDoc) {
        if (inDoc.indexOf(index) === -1) throw "No Such Index In Collection";
        try {
            await DistinctFor(index);
            return final;
        } catch (e) {
            throw e
        }
    }
    function ParseDoc(doc) {
        return new Promise(function (result) {
            let err;
            for (let index in doc) {
                let key = doc[index];
                if (!key) {
                    err = "No Key For Index "+index; break;
                }
                vals.push(new Promise(function (pushed) {
                    DistinctFor(key)
                        .then(pushed)
                        .catch(function (err) {
                            return pushed(Promise.resolve());
                        })
                }))
            }
            return result(err ? Promise.reject(err) : Promise.resolve());
        })
    }

    async function DistinctFor(key) {
        if (!key) throw "Key Is Undefined";
        try {
            final[key] = await collection.distinct(key);
        } catch (e) {
            final[key] = 'failed';
            throw e;
        }
    }
}

So querying a collection with the basic _id index, would return the following (test collection only has one document at the time of the test):

Mongo.MongoClient.connect(url, function (err, client) {
    assert.equal(null, err);

    let collection = client.db('my db').collection('the targeted collection');

    GetFor(collection, '_id')
        .then(function () {
            //returns
            // { _id: [ 5ae901e77e322342de1fb701 ] }
        })
        .catch(function (err) {
            //manage your error..
        })
});

Mind you, this uses methods native to the NodeJS Driver. As some other answers have suggested, there are other approaches, such as the aggregate framework. I personally find this approach more flexible, as you can easily create and fine-tune how to return the results. Obviously, this only addresses top-level attributes, not nested ones. Also, to guarantee that all documents are represented should there be secondary indexes (other than the main _id one), those indexes should be set as required.

How can I save a base64-encoded image to disk?

You can use a third-party library like base64-img or base64-to-image.

  1. base64-img
const base64Img = require('base64-img');

const data = 'data:image/png;base64,...';
const destpath = 'dir/to/save/image';
const filename = 'some-filename';

base64Img.img(data, destpath, filename, (err, filepath) => {}); // Asynchronous using

const filepath = base64Img.imgSync(data, destpath, filename); // Synchronous using
  1. base64-to-image
const base64ToImage = require('base64-to-image');

const base64Str = 'data:image/png;base64,...';
const path = 'dir/to/save/image/'; // Add trailing slash
const optionalObj = { fileName: 'some-filename', type: 'png' };

const { imageType, fileName } = base64ToImage(base64Str, path, optionalObj); // Only synchronous using

How can I find a specific file from a Linux terminal?

In general, the best way to find any file in any arbitrary location is to start a terminal window and type in the classic Unix command "find":

find / -name index.html -print

Since the file you're looking for is the root file in the root directory of your web server, it's probably easier to find your web server's document root. For example, look under:

/var/www/*

Or type:

find /var/www -name index.html -print

What is an attribute in Java?

A class contains data field descriptions (or properties, fields, data members, attributes), i.e., field types and names, that will be associated with either per-instance or per-class state variables at program run time.

Writing file to web server - ASP.NET

There are methods like WriteAllText in the File class for common operations on files.

Use the MapPath method to get the physical path for a file in your web application.

File.WriteAllText(Server.MapPath("~/data.txt"), TextBox1.Text);

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document'

You are allowed to use IDs that start with a digit in your HTML5 documents:

The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.

But querySelector method uses CSS3 selectors for querying the DOM and CSS3 doesn't support ID selectors that start with a digit:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.

Use a value like b22 for the ID attribute and your code will work.

Since you want to select an element by ID you can also use .getElementById method:

document.getElementById('22')