Programs & Examples On #Presentation layer

How to check if cursor exists (open status)

I rarely employ cursors, but I just discovered one other item that can bite you here, the scope of the cursor name.

If the database CURSOR_DEFAULT is global, you will get the "cursor already exists" error if you declare a cursor in a stored procedure with a particular name (eg "cur"), and while that cursor is open you call another stored procedure which declares and opens a cursor with the same name (eg "cur"). The error will occur in the nested stored procedure when it attempts to open "cur".

Run this bit of sql to see your CURSOR_DEFAULT:

select is_local_cursor_default from sys.databases where name = '[your database name]'

If this value is "0" then how you name your nested cursor matters!

How to add a fragment to a programmatically generated layout?

Below is a working code to add a fragment e.g 3 times to a vertical LinearLayout (xNumberLinear). You can change number 3 with any other number or take a number from a spinner!

for (int i = 0; i < 3; i++) {
            LinearLayout linearDummy = new LinearLayout(getActivity());
            linearDummy.setOrientation(LinearLayout.VERTICAL);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {

                Toast.makeText(getActivity(), "This function works on newer versions of android", Toast.LENGTH_LONG).show();

            } else {
                linearDummy.setId(View.generateViewId());
            }
            fragmentManager.beginTransaction().add(linearDummy.getId(), new SomeFragment(),"someTag1").commit();

            xNumberLinear.addView(linearDummy);
        }

Converting from hex to string

If you need the result as byte array, you should pass it directly without changing it to a string, then change it back to bytes. In your example the (f.e.: 0x31 = 1) is the ASCII codes. In that case to convert a string (of hex values) to ASCII values use: Encoding.ASCII.GetString(byte[])

        byte[] data = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30 };
        string ascii=Encoding.ASCII.GetString(data);
        Console.WriteLine(ascii);

The console will display: 1234567890

Android Studio Checkout Github Error "CreateProcess=2" (Windows)

Steps:

1) Download git for windows https://git-scm.com/downloads

2) Install downloaded git with default setup

3) From Android Studio close if any project is open then Click on Configure -> Settings -> Version Control -> Git

4) Change Path to Git executable : git.exe to C:\Program Files\Git\cmd\git.exe

5) Apply and Ok

6) Try to clone from Check out project from Version Control

7) Done

enter image description here

ClassCastException, casting Integer to Double

We can cast an int to a double but we can't do the same with the wrapper classes Integer and Double:

 int     a = 1;
 Integer b = 1;   // inboxing, requires Java 1.5+

 double  c = (double) a;   // OK
 Double  d = (Double) b;   // No way.

This shows the compile time error that corresponds to your runtime exception.

How can I test a change made to Jenkinsfile locally?

Jenkins has a 'Replay' feature, which enables you to quickly replay a job without updating sources:

Replay feature

Direct download from Google Drive using Google Drive API

I know this is an old question but I could not find a solution to this problem after some research, so I am sharing what worked for me.

I have written this C# code for one of my projects. It can bypass the scan virus warning programmatically. The code can probably be converted to Java.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Text;

public class FileDownloader : IDisposable
{
    private const string GOOGLE_DRIVE_DOMAIN = "drive.google.com";
    private const string GOOGLE_DRIVE_DOMAIN2 = "https://drive.google.com";

    // In the worst case, it is necessary to send 3 download requests to the Drive address
    //   1. an NID cookie is returned instead of a download_warning cookie
    //   2. download_warning cookie returned
    //   3. the actual file is downloaded
    private const int GOOGLE_DRIVE_MAX_DOWNLOAD_ATTEMPT = 3;

    public delegate void DownloadProgressChangedEventHandler( object sender, DownloadProgress progress );

    // Custom download progress reporting (needed for Google Drive)
    public class DownloadProgress
    {
        public long BytesReceived, TotalBytesToReceive;
        public object UserState;

        public int ProgressPercentage
        {
            get
            {
                if( TotalBytesToReceive > 0L )
                    return (int) ( ( (double) BytesReceived / TotalBytesToReceive ) * 100 );

                return 0;
            }
        }
    }

    // Web client that preserves cookies (needed for Google Drive)
    private class CookieAwareWebClient : WebClient
    {
        private class CookieContainer
        {
            private readonly Dictionary<string, string> cookies = new Dictionary<string, string>();

            public string this[Uri address]
            {
                get
                {
                    string cookie;
                    if( cookies.TryGetValue( address.Host, out cookie ) )
                        return cookie;

                    return null;
                }
                set
                {
                    cookies[address.Host] = value;
                }
            }
        }

        private readonly CookieContainer cookies = new CookieContainer();
        public DownloadProgress ContentRangeTarget;

        protected override WebRequest GetWebRequest( Uri address )
        {
            WebRequest request = base.GetWebRequest( address );
            if( request is HttpWebRequest )
            {
                string cookie = cookies[address];
                if( cookie != null )
                    ( (HttpWebRequest) request ).Headers.Set( "cookie", cookie );

                if( ContentRangeTarget != null )
                    ( (HttpWebRequest) request ).AddRange( 0 );
            }

            return request;
        }

        protected override WebResponse GetWebResponse( WebRequest request, IAsyncResult result )
        {
            return ProcessResponse( base.GetWebResponse( request, result ) );
        }

        protected override WebResponse GetWebResponse( WebRequest request )
        {
            return ProcessResponse( base.GetWebResponse( request ) );
        }

        private WebResponse ProcessResponse( WebResponse response )
        {
            string[] cookies = response.Headers.GetValues( "Set-Cookie" );
            if( cookies != null && cookies.Length > 0 )
            {
                int length = 0;
                for( int i = 0; i < cookies.Length; i++ )
                    length += cookies[i].Length;

                StringBuilder cookie = new StringBuilder( length );
                for( int i = 0; i < cookies.Length; i++ )
                    cookie.Append( cookies[i] );

                this.cookies[response.ResponseUri] = cookie.ToString();
            }

            if( ContentRangeTarget != null )
            {
                string[] rangeLengthHeader = response.Headers.GetValues( "Content-Range" );
                if( rangeLengthHeader != null && rangeLengthHeader.Length > 0 )
                {
                    int splitIndex = rangeLengthHeader[0].LastIndexOf( '/' );
                    if( splitIndex >= 0 && splitIndex < rangeLengthHeader[0].Length - 1 )
                    {
                        long length;
                        if( long.TryParse( rangeLengthHeader[0].Substring( splitIndex + 1 ), out length ) )
                            ContentRangeTarget.TotalBytesToReceive = length;
                    }
                }
            }

            return response;
        }
    }

    private readonly CookieAwareWebClient webClient;
    private readonly DownloadProgress downloadProgress;

    private Uri downloadAddress;
    private string downloadPath;

    private bool asyncDownload;
    private object userToken;

    private bool downloadingDriveFile;
    private int driveDownloadAttempt;

    public event DownloadProgressChangedEventHandler DownloadProgressChanged;
    public event AsyncCompletedEventHandler DownloadFileCompleted;

    public FileDownloader()
    {
        webClient = new CookieAwareWebClient();
        webClient.DownloadProgressChanged += DownloadProgressChangedCallback;
        webClient.DownloadFileCompleted += DownloadFileCompletedCallback;

        downloadProgress = new DownloadProgress();
    }

    public void DownloadFile( string address, string fileName )
    {
        DownloadFile( address, fileName, false, null );
    }

    public void DownloadFileAsync( string address, string fileName, object userToken = null )
    {
        DownloadFile( address, fileName, true, userToken );
    }

    private void DownloadFile( string address, string fileName, bool asyncDownload, object userToken )
    {
        downloadingDriveFile = address.StartsWith( GOOGLE_DRIVE_DOMAIN ) || address.StartsWith( GOOGLE_DRIVE_DOMAIN2 );
        if( downloadingDriveFile )
        {
            address = GetGoogleDriveDownloadAddress( address );
            driveDownloadAttempt = 1;

            webClient.ContentRangeTarget = downloadProgress;
        }
        else
            webClient.ContentRangeTarget = null;

        downloadAddress = new Uri( address );
        downloadPath = fileName;

        downloadProgress.TotalBytesToReceive = -1L;
        downloadProgress.UserState = userToken;

        this.asyncDownload = asyncDownload;
        this.userToken = userToken;

        DownloadFileInternal();
    }

    private void DownloadFileInternal()
    {
        if( !asyncDownload )
        {
            webClient.DownloadFile( downloadAddress, downloadPath );

            // This callback isn't triggered for synchronous downloads, manually trigger it
            DownloadFileCompletedCallback( webClient, new AsyncCompletedEventArgs( null, false, null ) );
        }
        else if( userToken == null )
            webClient.DownloadFileAsync( downloadAddress, downloadPath );
        else
            webClient.DownloadFileAsync( downloadAddress, downloadPath, userToken );
    }

    private void DownloadProgressChangedCallback( object sender, DownloadProgressChangedEventArgs e )
    {
        if( DownloadProgressChanged != null )
        {
            downloadProgress.BytesReceived = e.BytesReceived;
            if( e.TotalBytesToReceive > 0L )
                downloadProgress.TotalBytesToReceive = e.TotalBytesToReceive;

            DownloadProgressChanged( this, downloadProgress );
        }
    }

    private void DownloadFileCompletedCallback( object sender, AsyncCompletedEventArgs e )
    {
        if( !downloadingDriveFile )
        {
            if( DownloadFileCompleted != null )
                DownloadFileCompleted( this, e );
        }
        else
        {
            if( driveDownloadAttempt < GOOGLE_DRIVE_MAX_DOWNLOAD_ATTEMPT && !ProcessDriveDownload() )
            {
                // Try downloading the Drive file again
                driveDownloadAttempt++;
                DownloadFileInternal();
            }
            else if( DownloadFileCompleted != null )
                DownloadFileCompleted( this, e );
        }
    }

    // Downloading large files from Google Drive prompts a warning screen and requires manual confirmation
    // Consider that case and try to confirm the download automatically if warning prompt occurs
    // Returns true, if no more download requests are necessary
    private bool ProcessDriveDownload()
    {
        FileInfo downloadedFile = new FileInfo( downloadPath );
        if( downloadedFile == null )
            return true;

        // Confirmation page is around 50KB, shouldn't be larger than 60KB
        if( downloadedFile.Length > 60000L )
            return true;

        // Downloaded file might be the confirmation page, check it
        string content;
        using( var reader = downloadedFile.OpenText() )
        {
            // Confirmation page starts with <!DOCTYPE html>, which can be preceeded by a newline
            char[] header = new char[20];
            int readCount = reader.ReadBlock( header, 0, 20 );
            if( readCount < 20 || !( new string( header ).Contains( "<!DOCTYPE html>" ) ) )
                return true;

            content = reader.ReadToEnd();
        }

        int linkIndex = content.LastIndexOf( "href=\"/uc?" );
        if( linkIndex < 0 )
            return true;

        linkIndex += 6;
        int linkEnd = content.IndexOf( '"', linkIndex );
        if( linkEnd < 0 )
            return true;

        downloadAddress = new Uri( "https://drive.google.com" + content.Substring( linkIndex, linkEnd - linkIndex ).Replace( "&amp;", "&" ) );
        return false;
    }

    // Handles the following formats (links can be preceeded by https://):
    // - drive.google.com/open?id=FILEID
    // - drive.google.com/file/d/FILEID/view?usp=sharing
    // - drive.google.com/uc?id=FILEID&export=download
    private string GetGoogleDriveDownloadAddress( string address )
    {
        int index = address.IndexOf( "id=" );
        int closingIndex;
        if( index > 0 )
        {
            index += 3;
            closingIndex = address.IndexOf( '&', index );
            if( closingIndex < 0 )
                closingIndex = address.Length;
        }
        else
        {
            index = address.IndexOf( "file/d/" );
            if( index < 0 ) // address is not in any of the supported forms
                return string.Empty;

            index += 7;

            closingIndex = address.IndexOf( '/', index );
            if( closingIndex < 0 )
            {
                closingIndex = address.IndexOf( '?', index );
                if( closingIndex < 0 )
                    closingIndex = address.Length;
            }
        }

        return string.Concat( "https://drive.google.com/uc?id=", address.Substring( index, closingIndex - index ), "&export=download" );
    }

    public void Dispose()
    {
        webClient.Dispose();
    }
}

And here's how you can use it:

// NOTE: FileDownloader is IDisposable!
FileDownloader fileDownloader = new FileDownloader();

// This callback is triggered for DownloadFileAsync only
fileDownloader.DownloadProgressChanged += ( sender, e ) => Console.WriteLine( "Progress changed " + e.BytesReceived + " " + e.TotalBytesToReceive );
// This callback is triggered for both DownloadFile and DownloadFileAsync
fileDownloader.DownloadFileCompleted += ( sender, e ) => Console.WriteLine( "Download completed" );

fileDownloader.DownloadFileAsync( "https://INSERT_DOWNLOAD_LINK_HERE", @"C:\downloadedFile.txt" );

How do you store Java objects in HttpSession?

Here you can do it by using HttpRequest or HttpSession. And think your problem is within the JSP.

If you are going to use the inside servlet do following,

Object obj = new Object();
session.setAttribute("object", obj);

or

HttpSession session = request.getSession();
Object obj = new Object();
session.setAttribute("object", obj);

and after setting your attribute by using request or session, use following to access it in the JSP,

<%= request.getAttribute("object")%>

or

<%= session.getAttribute("object")%>

So seems your problem is in the JSP.

If you want use scriptlets it should be as follows,

<%
Object obj = request.getSession().getAttribute("object");
out.print(obj);
%>

Or can use expressions as follows,

<%= session.getAttribute("object")%>

or can use EL as follows, ${object} or ${sessionScope.object}

How to use Apple's new .p8 certificate for APNs in firebase console

I was able to do this by selecting "All" located under the "Keys" header from the left column

enter image description here

Then I clicked the plus button in the top right corner to add a new key

enter image description here

Enter a name for your key and check "APNs"

enter image description here

Then scroll down and select Continue. You will then be brought to a screen presenting you with the option to download your .p8 now or later. In my case, I was presented with a warning that it could only be downloaded once so keep the file safe.

batch to copy files with xcopy

Based on xcopy help, I tried and found that following works perfectly for me (tried on Win 7)

xcopy C:\folder1 C:\folder2\folder1 /E /C /I /Q /G /H /R /K /Y /Z /J

OnClick Send To Ajax

<textarea name='Status'> </textarea>
<input type='button' value='Status Update'>

You have few problems with your code like using . for concatenation

Try this -

$(function () {
    $('input').on('click', function () {
        var Status = $(this).val();
        $.ajax({
            url: 'Ajax/StatusUpdate.php',
            data: {
                text: $("textarea[name=Status]").val(),
                Status: Status
            },
            dataType : 'json'
        });
    });
});

How to print a percentage value in python?

format supports a percentage floating point precision type:

>>> print "{0:.0%}".format(1./3)
33%

If you don't want integer division, you can import Python3's division from __future__:

>>> from __future__ import division
>>> 1 / 3
0.3333333333333333

# The above 33% example would could now be written without the explicit
# float conversion:
>>> print "{0:.0f}%".format(1/3 * 100)
33%

# Or even shorter using the format mini language:
>>> print "{:.0%}".format(1/3)
33%

How to abort an interactive rebase if --abort doesn't work?

Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.

git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67

Then, abort the rebase again.

center aligning a fixed position div

It is quite easy using width: 70%; left:15%;

Sets the element width to 70% of the window and leaves 15% on both sides

Easiest way to compare arrays in C#

Use Enumerable.SequenceEqual in LINQ.

int[] arr1 = new int[] { 1,2,3};
int[] arr2 = new int[] { 3,2,1 };

Console.WriteLine(arr1.SequenceEqual(arr2)); // false
Console.WriteLine(arr1.Reverse().SequenceEqual(arr2)); // true

Why Visual Studio 2015 can't run exe file (ucrtbased.dll)?

I am not sure it will help but you can try this.This worked for me

Start -> Visual Studio Installer -> Repair

after this enable the Microsoft Symbols Server under

TOOLS->Options->Debugging->Symbols

This will automatically set all the issues.

You can refer this link as well

https://social.msdn.microsoft.com/Forums/vstudio/en-US/6aa917e5-a51c-4399-9712-4b9c5d65fabf/ucrtbasedpdb-not-loaded-using-visual-studio?forum=visualstudiogeneral

UIWebView open links in Safari

In Swift you can use the following code:

extension YourViewController: UIWebViewDelegate {
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
        if let url = request.url, navigationType == UIWebView.NavigationType.linkClicked {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
            return false
        }
        return true
    }

}

Make sure you check for the URL value and the navigationType.

SQL Query to add a new column after an existing column in SQL Server 2005

If you want to alter order for columns in Sql server, There is no direct way to do this in SQL Server currently.

Have a look at http://blog.sqlauthority.com/2008/04/08/sql-server-change-order-of-column-in-database-tables/

You can change order while edit design for table.

Convert time fields to strings in Excel

copy the column paste it into notepad copy it again paste special as Text

How to use responsive background image in css3 in bootstrap

Try this:

body {
  background-image:url(img/background.jpg);
  background-repeat: no-repeat;
  min-height: 679px;
  background-size: cover;
}

How to break line in JavaScript?

Here you are ;-)

<script type="text/javascript">
    alert("Hello there.\nI am on a second line ;-)")
</script>

'ls' is not recognized as an internal or external command, operable program or batch file

I'm fairly certain that the ls command is for Linux, not Windows (I'm assuming you're using Windows as you referred to cmd, which is the command line for the Windows OS).

You should use dir instead, which is the Windows equivalent of ls.

Edit (since this post seems to be getting so many views :) ):

You can't use ls on cmd as it's not shipped with Windows, but you can use it on other terminal programs (such as GitBash). Note, ls might work on some FTP servers if the servers are linux based and the FTP is being used from cmd.

dir on Windows is similar to ls. To find out the various options available, just do dir/?.

If you really want to use ls, you could install 3rd party tools to allow you to run unix commands on Windows. Such a program is Microsoft Windows Subsystem for Linux (link to docs).

JAX-WS - Adding SOAP Headers

Data can be transferred in SOAP header (JaxWS) by using @WebParam(header = true):

@WebMethod(operationName = "SendRequest", action = "http://abcd.ru/")
@Oneway
public void sendRequest(
    @WebParam(name = "Message", targetNamespace = "http://abcd.ru/", partName = "Message")
    Data message,
    @WebParam(name = "ServiceHeader", targetNamespace = "http://abcd.ru/", header = true, partName = "ServiceHeader")
    Header serviceHeader);

If you want to generate a client with SOAP Headers, you need to use -XadditionalHeaders:

wsimport -keep -Xnocompile -XadditionalHeaders -Xdebug http://12.34.56.78:8080/TestHeaders/somewsdl?wsdl -d /home/evgeny/DEVELOPMENT/JAVA/gen

If don't need @Oneway web service, you can use Holder:

@WebMethod(operationName = "SendRequest", action = "http://abcd.ru/")
public void sendRequest(
    @WebParam(name = "Message", targetNamespace = "http://abcd.ru/", partName = "Message")
    Data message,
    @WebParam(name = "ServiceHeader", targetNamespace = "http://abcd.ru/", header = true, partName = "ServiceHeader")
    Holder<Header> serviceHeader);

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

For me the problem was very strange.
I have a testng.xml file at the root of my Eclipse project. When I changed the file through Eclipse, it wasn't changing the testng.xml file in my directory.

Turns out it made a copy of the folder into the eclipse workspace..

Hope this helps someone out

Can you force Vue.js to reload/re-render?

<router-view :key="$route.params.slug" />

just use key with your any params its auto reload children..

How do I perform the SQL Join equivalent in MongoDB?

We can merge two collection by using mongoDB sub query. Here is example, Commentss--

`db.commentss.insert([
  { uid:12345, pid:444, comment:"blah" },
  { uid:12345, pid:888, comment:"asdf" },
  { uid:99999, pid:444, comment:"qwer" }])`

Userss--

db.userss.insert([
  { uid:12345, name:"john" },
  { uid:99999, name:"mia"  }])

MongoDB sub query for JOIN--

`db.commentss.find().forEach(
    function (newComments) {
        newComments.userss = db.userss.find( { "uid": newComments.uid } ).toArray();
        db.newCommentUsers.insert(newComments);
    }
);`

Get result from newly generated Collection--

db.newCommentUsers.find().pretty()

Result--

`{
    "_id" : ObjectId("5511236e29709afa03f226ef"),
    "uid" : 12345,
    "pid" : 444,
    "comment" : "blah",
    "userss" : [
        {
            "_id" : ObjectId("5511238129709afa03f226f2"),
            "uid" : 12345,
            "name" : "john"
        }
    ]
}
{
    "_id" : ObjectId("5511236e29709afa03f226f0"),
    "uid" : 12345,
    "pid" : 888,
    "comment" : "asdf",
    "userss" : [
        {
            "_id" : ObjectId("5511238129709afa03f226f2"),
            "uid" : 12345,
            "name" : "john"
        }
    ]
}
{
    "_id" : ObjectId("5511236e29709afa03f226f1"),
    "uid" : 99999,
    "pid" : 444,
    "comment" : "qwer",
    "userss" : [
        {
            "_id" : ObjectId("5511238129709afa03f226f3"),
            "uid" : 99999,
            "name" : "mia"
        }
    ]
}`

Hope so this will help.

How does Python's super() work with multiple inheritance?

I would like to add to what @Visionscaper says at the top:

Third --> First --> object --> Second --> object

In this case the interpreter doesnt filter out the object class because its duplicated, rather its because Second appears in a head position and doesnt appear in the tail position in a hierarchy subset. While object only appears in tail positions and is not considered a strong position in C3 algorithm to determine priority.

The linearisation(mro) of a class C, L(C), is the

  • the Class C
  • plus the merge of
    • linearisation of its parents P1, P2, .. = L(P1, P2, ...) and
    • the list of its parents P1, P2, ..

Linearised Merge is done by selecting the common classes that appears as the head of lists and not the tail since order matters(will become clear below)

The linearisation of Third can be computed as follows:

    L(O)  := [O]  // the linearization(mro) of O(object), because O has no parents

    L(First)  :=  [First] + merge(L(O), [O])
               =  [First] + merge([O], [O])
               =  [First, O]

    // Similarly, 
    L(Second)  := [Second, O]

    L(Third)   := [Third] + merge(L(First), L(Second), [First, Second])
                = [Third] + merge([First, O], [Second, O], [First, Second])
// class First is a good candidate for the first merge step, because it only appears as the head of the first and last lists
// class O is not a good candidate for the next merge step, because it also appears in the tails of list 1 and 2, 
                = [Third, First] + merge([O], [Second, O], [Second])
// class Second is a good candidate for the second merge step, because it appears as the head of the list 2 and 3
                = [Third, First, Second] + merge([O], [O])            
                = [Third, First, Second, O]

Thus for a super() implementation in the following code:

class First(object):
  def __init__(self):
    super(First, self).__init__()
    print "first"

class Second(object):
  def __init__(self):
    super(Second, self).__init__()
    print "second"

class Third(First, Second):
  def __init__(self):
    super(Third, self).__init__()
    print "that's it"

it becomes obvious how this method will be resolved

Third.__init__() ---> First.__init__() ---> Second.__init__() ---> 
Object.__init__() ---> returns ---> Second.__init__() -
prints "second" - returns ---> First.__init__() -
prints "first" - returns ---> Third.__init__() - prints "that's it"

Combining multiple condition in single case statement in Sql Server

select ROUND(CASE 

WHEN  CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then  CONVERT( float, REPLACE( isnull( value3,''),',',''))

WHEN  CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))!='' then  CONVERT( float, REPLACE( isnull( value3,''),',',''))

WHEN  CONVERT( float, REPLACE( isnull( value1,''),',',''))!='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then  CONVERT( float, REPLACE( isnull( value3,''),',',''))

else CONVERT( float, REPLACE(isnull( value1,''),',','')) end,0)  from Tablename where    ID="123" 

Sending "User-agent" using Requests library in Python

It's more convenient to use a session, this way you don't have to remember to set headers each time:

session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})

session.get('https://httpbin.org/headers')

By default, session also manages cookies for you. In case you want to disable that, see this question.

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

Had this issue after a reinstall today. Make sure the Application Experience service is started and not set to disabled. If its set to manual, I believe VS will start it.

Python if not == vs if !=

@jonrsharpe has an excellent explanation of what's going on. I thought I'd just show the difference in time when running each of the 3 options 10,000,000 times (enough for a slight difference to show).

Code used:

def a(x):
    if x != 'val':
        pass


def b(x):
    if not x == 'val':
        pass


def c(x):
    if x == 'val':
        pass
    else:
        pass


x = 1
for i in range(10000000):
    a(x)
    b(x)
    c(x)

And the cProfile profiler results:

enter image description here

So we can see that there is a very minute difference of ~0.7% between if not x == 'val': and if x != 'val':. Of these, if x != 'val': is the fastest.

However, most surprisingly, we can see that

if x == 'val':
        pass
    else:

is in fact the fastest, and beats if x != 'val': by ~0.3%. This isn't very readable, but I guess if you wanted a negligible performance improvement, one could go down this route.

How to use php serialize() and unserialize()

When you want to make your php value storable, you have to turn it to be a string value, that is what serialize() does. And unserialize() does the reverse thing.

Get JSONArray without array name?

Here is a solution under 19API lvl:

  • First of all. Make a Gson obj. --> Gson gson = new Gson();

  • Second step is get your jsonObj as String with StringRequest(instead of JsonObjectRequest)

  • The last step to get JsonArray...

YoursObjArray[] yoursObjArray = gson.fromJson(response, YoursObjArray[].class);

Set Label Text with JQuery

The checkbox is in a td, so need to get the parent first:

$("input:checkbox").on("change", function() {
    $(this).parent().next().find("label").text("TESTTTT");
});

Alternatively, find a label which has a for with the same id (perhaps more performant than reverse traversal) :

$("input:checkbox").on("change", function() {
    $("label[for='" + $(this).attr('id') + "']").text("TESTTTT");
});

Or, to be more succinct just this.id:

$("input:checkbox").on("change", function() {
    $("label[for='" + this.id + "']").text("TESTTTT");
});

Creating a segue programmatically

Guess this is answered and accepted, but I just would like to add a few more details to it.

What I did to solve a problem where I would present a login-view as first screen and then wanted to segue to the application if login were correct. I created the segue from the login-view controller to the root view controller and gave it an identifier like "myidentifier".

Then after checking all login code if the login were correct I'd call

[self performSegueWithIdentifier: @"myidentifier" sender: self];

My biggest misunderstanding were that I tried to put the segue on a button and kind of interrupt the segue once it were found.

Checking for multiple conditions using "when" on single task in ansible

Also you can use default() filter. Or just a shortcut d()

- name: Generating a new SSH key for the current user it's not exists already
  local_action:
    module: user
    name: "{{ login_user.stdout }}"
    generate_ssh_key: yes 
    ssh_key_bits: 2048
  when: 
    - sshkey_result.rc == 1
    - github_username | d('none') | lower == 'none'

How to make an array of arrays in Java

While there are two excellent answers telling you how to do it, I feel that another answer is missing: In most cases you shouldn't do it at all.

Arrays are cumbersome, in most cases you are better off using the Collection API.

With Collections, you can add and remove elements and there are specialized Collections for different functionality (index-based lookup, sorting, uniqueness, FIFO-access, concurrency etc.).

While it's of course good and important to know about Arrays and their usage, in most cases using Collections makes APIs a lot more manageable (which is why new libraries like Google Guava hardly use Arrays at all).

So, for your scenario, I'd prefer a List of Lists, and I'd create it using Guava:

List<List<String>> listOfLists = Lists.newArrayList();
listOfLists.add(Lists.newArrayList("abc","def","ghi"));
listOfLists.add(Lists.newArrayList("jkl","mno","pqr"));

Deserialize JSON string to c# object

This may be useful:

var serializer = new JavaScriptSerializer();
dynamic jsonObject = serializer.Deserialize<dynamic>(json);

Where "json" is the string that contains the JSON values. Then to retrieve the values from the jsonObject you may use

myProperty = Convert.MyPropertyType(jsonObject["myProperty"]);

Changing MyPropertyType to the proper type (ToInt32, ToString, ToBoolean, etc).

How to delete zero components in a vector in Matlab?

You could use sparse(a), which would return

(1,2) 1

(1,4) 3

This allows you to keep the information about where your non-zero entries used to be.

PHP Fatal error: Using $this when not in object context

Fast method : (new foobar())->foobarfunc();

You need to load your class replace :

foobar::foobarfunc();

by :

(new foobar())->foobarfunc();

or :

$Foobar = new foobar();
$Foobar->foobarfunc();

Or make static function to use foobar::.

class foobar {
    //...

    static function foobarfunc() {
        return $this->foo();
    }
}

How can I compile LaTeX in UTF8?

I use LEd Editor with special "Filter" feature. It replaces \"{o} with รถ and vice versa in its own editor, while maintaining original \"{o} in tex files. This makes text easily readable when viewed in LEd Editor and there is no need for special packages. It works with bibliography files too.

How do I use popover from Twitter Bootstrap to display an image?

This is what I used.

$('#foo').popover({
    placement : 'bottom',
    title : 'Title',
    content : '<div id="popOverBox"><img src="http://i.telegraph.co.uk/multimedia/archive/01515/alGore_1515233c.jpg" /></div>'
});

and for the HTML

<b id="foo" rel="popover">text goes here</b>

What is the fastest way to transpose a matrix in C++?

Consider each row as a column, and each column as a row .. use j,i instead of i,j

demo: http://ideone.com/lvsxKZ

#include <iostream> 
using namespace std;

int main ()
{
    char A [3][3] =
    {
        { 'a', 'b', 'c' },
        { 'd', 'e', 'f' },
        { 'g', 'h', 'i' }
    };

    cout << "A = " << endl << endl;

    // print matrix A
    for (int i=0; i<3; i++)
    {
        for (int j=0; j<3; j++) cout << A[i][j];
        cout << endl;
    }

    cout << endl << "A transpose = " << endl << endl;

    // print A transpose
    for (int i=0; i<3; i++)
    {
        for (int j=0; j<3; j++) cout << A[j][i];
        cout << endl;
    }

    return 0;
}

How can I solve a connection pool problem between ASP.NET and SQL Server?

We encounter this problem from time to time on our web site as well. The culprit in our case, is our stats/indexes getting out of date. This causes a previously fast running query to (eventually) become slow and time out.

Try updating statistics and/or rebuilding the indexes on the tables affected by the query and see if that helps.

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

LINQ extension methods - Any() vs. Where() vs. Exists()

Any - boolean function that returns true when any of object in list satisfies condition set in function parameters. For example:

List<string> strings = LoadList();
boolean hasNonEmptyObject = strings.Any(s=>string.IsNullOrEmpty(s));

Where - function that returns list with all objects in list that satisfy condition set in function parameters. For example:

IEnumerable<string> nonEmptyStrings = strings.Where(s=> !string.IsNullOrEmpty(s));

Exists - basically the same as any but it's not generic - it's defined in List class, while Any is defined on IEnumerable interface.

Iterating over a numpy array

I think you're looking for the ndenumerate.

>>> a =numpy.array([[1,2],[3,4],[5,6]])
>>> for (x,y), value in numpy.ndenumerate(a):
...  print x,y
... 
0 0
0 1
1 0
1 1
2 0
2 1

Regarding the performance. It is a bit slower than a list comprehension.

X = np.zeros((100, 100, 100))

%timeit list([((i,j,k), X[i,j,k]) for i in range(X.shape[0]) for j in range(X.shape[1]) for k in range(X.shape[2])])
1 loop, best of 3: 376 ms per loop

%timeit list(np.ndenumerate(X))
1 loop, best of 3: 570 ms per loop

If you are worried about the performance you could optimise a bit further by looking at the implementation of ndenumerate, which does 2 things, converting to an array and looping. If you know you have an array, you can call the .coords attribute of the flat iterator.

a = X.flat
%timeit list([(a.coords, x) for x in a.flat])
1 loop, best of 3: 305 ms per loop

gcc error: wrong ELF class: ELFCLASS64

It looks like the object file was compiled on a 64-bit toolchain, and you're using a 32-bit toolchain. Have you tried recompiling the object file in 32-bit mode?

Android how to use Environment.getExternalStorageDirectory()

Have in mind though, that getExternalStorageDirectory() is not going to work properly on some phones e.g. my Motorola razr maxx, as it has 2 cards /mnt/sdcard and /mnt/sdcard-ext - for internal and external SD cards respectfully. You will be getting the /mnt/sdcard only reply every time. Google must provide a way to deal with such a situation. As it renders many SD card aware apps (i.e card backup) failing miserably on these phones.

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

Put this in C2 and copy down

=IF(ISNA(VLOOKUP(A2,$B$2:$B$65535,1,FALSE)),"not in B","")

Then if the value in A isn't in B the cell in column C will say "not in B".

Delimiter must not be alphanumeric or backslash and preg_match

You can also use T-Regx library which has automatic delimiters for you:

$matches = pattern("My name is '(.*)' and im fine")->match($string1)->all();

                 // ? No delimiters needed 

Reactjs - setting inline styles correctly

Correct and more clear way is :

<div style={{"font-size" : "10px", "height" : "100px", "width" : "100%"}}> My inline Style </div>

It is made more simple by following approach :

// JS
const styleObject = {
      "font-size" : "10px",
      "height" : "100px",
      "width" : "100%"
}

// HTML    
<div style={styleObject}> My inline Style </div>

Inline style attribute expects object. Hence its written in {}, and it becomes double {{}} as one is for default react standards.

How to use Python requests to fake a browser visit a.k.a and generate User Agent?

I had a similar issue but I was unable to use the UserAgent class inside the fake_useragent module. I was running the code inside a docker container

import requests
import ujson
import random

response = requests.get('https://fake-useragent.herokuapp.com/browsers/0.1.11')
agents_dictionary = ujson.loads(response.text)
random_browser_number = str(random.randint(0, len(agents_dictionary['randomize'])))
random_browser = agents_dictionary['randomize'][random_browser_number]
user_agents_list = agents_dictionary['browsers'][random_browser]
user_agent = user_agents_list[random.randint(0, len(user_agents_list)-1)]

I targeted the endpoint used in the module. This solution still gave me a random user agent however there is the possibility that the data structure at the endpoint could change.

Display SQL query results in php

You need to do a while loop to get the result from the SQL query, like this:

require_once('db.php');  
$sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )    
FROM modul1open) ORDER BY idM1O LIMIT 1";

$result = mysql_query($sql);

while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

    // If you want to display all results from the query at once:
    print_r($row);

    // If you want to display the results one by one
    echo $row['column1'];
    echo $row['column2']; // etc..

}

Also I would strongly recommend not using mysql_* since it's deprecated. Instead use the mysqli or PDO extension. You can read more about that here.

How can I import data into mysql database via mysql workbench?

  1. Open Connetion
  2. Select "Administration" tab
  3. Click on Data import

Upload sql file

enter image description here

Make sure to select your database in this award winning GUI:

enter image description here

How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

JavaScript variable number of arguments to function

It is preferable to use rest parameter syntax as Ramast pointed out.

function (a, b, ...args) {}

I just want to add some nice property of the ...args argument

  1. It is an array, and not an object like arguments. This allows you to apply functions like map or sort directly.
  2. It does not include all parameters but only the one passed from it on. E.g. function (a, b, ...args) in this case args contains argument 3 to arguments.length

How to get all count of mongoose model?

The code below works. Note the use of countDocuments.

 var mongoose = require('mongoose');
 var db = mongoose.connect('mongodb://localhost/myApp');
 var userSchema = new mongoose.Schema({name:String,password:String});
 var userModel =db.model('userlists',userSchema);
 var anand = new userModel({ name: 'anand', password: 'abcd'});
 anand.save(function (err, docs) {
   if (err) {
       console.log('Error');
   } else {
       userModel.countDocuments({name: 'anand'}, function(err, c) {
           console.log('Count is ' + c);
      });
   }
 }); 

JSP tricks to make templating easier?

I made quite easy, Django style JSP Template inheritance tag library. https://github.com/kwon37xi/jsp-template-inheritance

I think it make easy to manage layouts without learning curve.

example code :

base.jsp : layout

<%@page contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="http://kwonnam.pe.kr/jsp/template-inheritance" prefix="layout"%>
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>JSP Template Inheritance</title>
    </head>

<h1>Head</h1>
<div>
    <layout:block name="header">
        header
    </layout:block>
</div>

<h1>Contents</h1>
<div>
    <p>
    <layout:block name="contents">
        <h2>Contents will be placed under this h2</h2>
    </layout:block>
    </p>
</div>

<div class="footer">
    <hr />
    <a href="https://github.com/kwon37xi/jsp-template-inheritance">jsp template inheritance example</a>
</div>
</html>

view.jsp : contents

<%@page contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="http://kwonnam.pe.kr/jsp/template-inheritance" prefix="layout"%>
<layout:extends name="base.jsp">
    <layout:put name="header" type="REPLACE">
        <h2>This is an example about layout management with JSP Template Inheritance</h2>
    </layout:put>
    <layout:put name="contents">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin porta,
        augue ut ornare sagittis, diam libero facilisis augue, quis accumsan enim velit a mauris.
    </layout:put>
</layout:extends>

Propagate all arguments in a bash shell script

If you include $@ in a quoted string with other characters the behavior is very odd when there are multiple arguments, only the first argument is included inside the quotes.

Example:

#!/bin/bash
set -x
bash -c "true foo $@"

Yields:

$ bash test.sh bar baz
+ bash -c 'true foo bar' baz

But assigning to a different variable first:

#!/bin/bash
set -x
args="$@"
bash -c "true foo $args"

Yields:

$ bash test.sh bar baz
+ args='bar baz'
+ bash -c 'true foo bar baz'

In Unix, how do you remove everything in the current directory and below it?

Will delete all files/directories below the current one.

find -mindepth 1 -delete

If you want to do the same with another directory whose name you have, you can just name that

find <name-of-directory> -mindepth 1 -delete

If you want to remove not only the sub-directories and files of it, but also the directory itself, omit -mindepth 1. Do it without the -delete to get a list of the things that will be removed.

Xcode process launch failed: Security

Alternatively if one does not see "Untrust App Developer" dialog:

Go to your iPhone > Settings > General > Profile > "[email protected]" > Trust

jQuery: how to find first visible input/select/textarea excluding buttons?

This is an improvement over @Mottie's answer because as of jQuery 1.5.2 :text selects input elements that have no specified type attribute (in which case type="text" is implied):

$('form').find(':text,textarea,select').filter(':visible:first')

Is there any simple way to convert .xls file to .csv file? (Excel)

Here's a C# method to do this. Remember to add your own error handling - this mostly assumes that things work for the sake of brevity. It's 4.0+ framework only, but that's mostly because of the optional worksheetNumber parameter. You can overload the method if you need to support earlier versions.

static void ConvertExcelToCsv(string excelFilePath, string csvOutputFile, int worksheetNumber = 1) {
   if (!File.Exists(excelFilePath)) throw new FileNotFoundException(excelFilePath);
   if (File.Exists(csvOutputFile)) throw new ArgumentException("File exists: " + csvOutputFile);

   // connection string
   var cnnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;IMEX=1;HDR=NO\"", excelFilePath);
   var cnn = new OleDbConnection(cnnStr);

   // get schema, then data
   var dt = new DataTable();
   try {
      cnn.Open();
      var schemaTable = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
      if (schemaTable.Rows.Count < worksheetNumber) throw new ArgumentException("The worksheet number provided cannot be found in the spreadsheet");
      string worksheet = schemaTable.Rows[worksheetNumber - 1]["table_name"].ToString().Replace("'", "");
      string sql = String.Format("select * from [{0}]", worksheet);
      var da = new OleDbDataAdapter(sql, cnn);
      da.Fill(dt);
   }
   catch (Exception e) {
      // ???
      throw e;
   }
   finally {
      // free resources
      cnn.Close();
   }

   // write out CSV data
   using (var wtr = new StreamWriter(csvOutputFile)) {
      foreach (DataRow row in dt.Rows) {
         bool firstLine = true;
         foreach (DataColumn col in dt.Columns) {
            if (!firstLine) { wtr.Write(","); } else { firstLine = false; }
            var data = row[col.ColumnName].ToString().Replace("\"", "\"\"");
            wtr.Write(String.Format("\"{0}\"", data));
         }
         wtr.WriteLine();
      }
   }
}

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

How to print from Flask @app.route to python console

I think the core issue with Flask is that stdout gets buffered. I was able to print with print('Hi', flush=True). You can also disable buffering by setting the PYTHONUNBUFFERED environment variable (to any non-empty string).

Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

You need to stop all tracks (from webcam, microphone):

localStream.getTracks().forEach(track => track.stop());

What is difference between functional and imperative programming languages?

I know this question is older and others already explained it well, I would like to give an example problem which explains the same in simple terms.

Problem: Writing the 1's table.

Solution: -

By Imperative style: =>

    1*1=1
    1*2=2
    1*3=3
    .
    .
    .
    1*n=n 

By Functional style: =>

    1
    2
    3
    .
    .
    .
    n

Explanation in Imperative style we write the instructions more explicitly and which can be called as in more simplified manner.

Where as in Functional style, things which are self-explanatory will be ignored.

Timestamp conversion in Oracle for YYYY-MM-DD HH:MM:SS format

INSERT INTO AM_PROGRAM_TUNING_EVENT_TMP1 
VALUES(TO_DATE('2012-03-28 11:10:00','yyyy/mm/dd hh24:mi:ss'));

http://www.sqlfiddle.com/#!4/22115/1

Filename timestamp in Windows CMD batch script getting truncated

for /f "tokens=2-8 delims=.:/ " %%a in ("%date% %time: =0%") do set DateNtime=%%c-%%a-%%b_%%d-%%e-%%f.%%g
echo %DateNtime%

Or, from the command line:

for /f "tokens=2-8 delims=.:/ " %a in ("%date% %time: =0%") do echo %c-%a-%b_%d-%e-%f.%g 

EDIT: As per bryce's non-standard time/date specs. (03-Sep-12 9:06:21.54)

@echo off
setlocal enabledelayedexpansion
for /f "tokens=1-7 delims=.:/- " %%a in ("%date% %time%") do (
  if "%%b"=="Jan" set MM=01
  if "%%b"=="Feb" set MM=02
  if "%%b"=="Mar" set MM=03
  if "%%b"=="Apr" set MM=04
  if "%%b"=="May" set MM=05
  if "%%b"=="Jun" set MM=06
  if "%%b"=="Jul" set MM=07
  if "%%b"=="Aug" set MM=08
  if "%%b"=="Sep" set MM=09
  if "%%b"=="Oct" set MM=10
  if "%%b"=="Nov" set MM=11
  if "%%b"=="Dec" set MM=12
  set HH=0%%d
  set HH=!HH:~-2!
  echo 20%%c-!MM!-%%a_!HH!-%%e-%%f.%%g
)
endlocal

Show current assembly instruction in GDB

You can switch to assembly layout in GDB:

(gdb) layout asm

See here for more information. The current assembly instruction will be shown in assembler window.

   +---------------------------------------------------------------------------+
   ยฆ0x7ffff740d756 <__libc_start_main+214>  mov    0x39670b(%rip),%rax        #ยฆ
   ยฆ0x7ffff740d75d <__libc_start_main+221>  mov    0x8(%rsp),%rsi              ยฆ
   ยฆ0x7ffff740d762 <__libc_start_main+226>  mov    0x14(%rsp),%edi             ยฆ
   ยฆ0x7ffff740d766 <__libc_start_main+230>  mov    (%rax),%rdx                 ยฆ
   ยฆ0x7ffff740d769 <__libc_start_main+233>  callq  *0x18(%rsp)                 ยฆ
  >ยฆ0x7ffff740d76d <__libc_start_main+237>  mov    %eax,%edi                   ยฆ
   ยฆ0x7ffff740d76f <__libc_start_main+239>  callq  0x7ffff7427970 <exit>       ยฆ
   ยฆ0x7ffff740d774 <__libc_start_main+244>  xor    %edx,%edx                   ยฆ
   ยฆ0x7ffff740d776 <__libc_start_main+246>  jmpq   0x7ffff740d6b9 <__libc_startยฆ
   ยฆ0x7ffff740d77b <__libc_start_main+251>  mov    0x39ca2e(%rip),%rax        #ยฆ
   ยฆ0x7ffff740d782 <__libc_start_main+258>  ror    $0x11,%rax                  ยฆ
   ยฆ0x7ffff740d786 <__libc_start_main+262>  xor    %fs:0x30,%rax               ยฆ
   ยฆ0x7ffff740d78f <__libc_start_main+271>  callq  *%rax                       ยฆ
   +---------------------------------------------------------------------------+
multi-thre process 3718 In: __libc_start_main     Line: ??   PC: 0x7ffff740d76d
#3  0x00007ffff7466eb5 in _IO_do_write () from /lib/x86_64-linux-gnu/libc.so.6
#4  0x00007ffff74671ff in _IO_file_overflow ()
   from /lib/x86_64-linux-gnu/libc.so.6
#5  0x0000000000408756 in ?? ()
#6  0x0000000000403980 in ?? ()
#7  0x00007ffff740d76d in __libc_start_main ()
   from /lib/x86_64-linux-gnu/libc.so.6
(gdb)

Two dimensional array list

If your platform matrix supports Java 7 then you can use like below

List<List<String>> myList = new ArrayList<>();

Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style

If you are using vscode I would recommend you to click the option at the bottom-right of the window and set it to LF from CRLF..this fixed my errors

Invert match with regexp

Based on Daniel's answer, I think I've got something that works:

^(.(?!test))*$

The key is that you need to make the negative assertion on every character in the string

Make a phone call programmatically

The Java RoboVM equivalent:

public void dial(String number)
{
  NSURL url = new NSURL("tel://" + number);
  UIApplication.getSharedApplication().openURL(url);
}

how to write javascript code inside php

At the time the script is executed, the button does not exist because the DOM is not fully loaded. The easiest solution would be to put the script block after the form.

Another solution would be to capture the window.onload event or use the jQuery library (overkill if you only have this one JavaScript).

Select records from NOW() -1 Day

You're almost there: it's NOW() - INTERVAL 1 DAY

Stored procedure or function expects parameter which is not supplied

I came across this issue yesterday, but none of the solutions here worked exactly, however they did point me in the right direction.

Our application is a workflow tool written in C# and, overly simplified, has several stored procedures on the database, as well as a table of metadata about each parameter used by each stored procedure (name, order, data type, size, etc), allowing us to create as many new stored procedures as we need without having to change the C#.

Analysis of the problem showed that our code was setting all the correct parameters on the SqlCommand object, however once it was executed, it threw the same error as the OP got.

Further analysis revealed that some parameters had a value of null. I therefore must draw the conclusion that SqlCommand objects ignore any SqlParameter object in their .Parameters collection with a value of null.

There are two solutions to this problem that I found.

  1. In our stored procedures, give a default value to each parameter, so from @Parameter int to @Parameter int = NULL (or some other default value as required).

  2. In our code that generates the individual SqlParameter objects, assigning DBNull.Value instead of null where the intended value is a SQL NULL does the trick.

The original coder has moved on and the code was originally written with Solution 1 in mind, and having weighed up the benefits of both, I think I'll stick with Solution 1. It's much easier to specify a default value for a specific stored procedure when writing it, rather than it always being NULL as defined in the code.

Hope that helps someone.

How to sort a HashSet?

Elements in HashSet can't be sorted. Whenever you put elements into HashSet, it can mess up the ordering of the whole set. It is deliberately designed like that for performance. When you don't care about the order, HashSet will be the most efficient set for fast insertion and search.

TreeSet will sort all the elements automatically every time you insert an element.

Perhaps, what you are trying to do is to sort just once. In that case, TreeSet is not the best option because it needs to determine the placing of newly added elements all the time.

The most efficient solution is to use ArrayList. Create a new list and add all the elements then sort it once. If you want to retain only unique elements (remove all duplicates like set does, then put the list into a LinkedHashSet, it will retain the order you have already sorted)

List<Integer> list = new ArrayList<>();
list.add(6);
list.add(4);
list.add(4);
list.add(5);
Collections.sort(list);
Set<Integer> unique = new LinkedHashSet<>(list); // 4 5 6
// The above line is not copying the objects! It only copies references.

Now, you've gotten a sorted set if you want it in a list form then convert it into list.

Android MediaPlayer Stop and Play

You should use only one mediaplayer object

    public class PlayaudioActivity extends Activity {

        private MediaPlayer mp;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            Button b = (Button) findViewById(R.id.button1);
            Button b2 = (Button) findViewById(R.id.button2);
            final TextView t = (TextView) findViewById(R.id.textView1);

            b.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    stopPlaying();
                    mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
                    mp.start();
                }

            });

            b2.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    stopPlaying();
                    mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);
                    mp.start();
                }
            });
        }

        private void stopPlaying() {
            if (mp != null) {
                mp.stop();
                mp.release();
                mp = null;
           }
        }
    }

finding and replacing elements in a list

If you have several values to replace, you can also use a dictionary:

a = [1, 2, 3, 4, 1, 5, 3, 2, 6, 1, 1]
dic = {1:10, 2:20, 3:'foo'}

print([dic.get(n, n) for n in a])

> [10, 20, 'foo', 4, 10, 5, 'foo', 20, 6, 10, 10]

How to output to the console in C++/Windows

If you're using Visual Studio, it should work just fine!

Here's a code example:

#include <iostream>

using namespace std;

int main (int) {
    cout << "This will print to the console!" << endl;
}

Make sure you chose a Win32 console application when creating a new project. Still you can redirect the output of your project to a file by using the console switch (>>). This will actually redirect the console pipe away from the stdout to your file. (for example, myprog.exe >> myfile.txt).

I wish I'm not mistaken!

PHP absolute path to root

use dirname(__FILE__) in a global configuration file.

Linq Syntax - Selecting multiple columns

You can use anonymous types for example:

  var empData = from res in _db.EMPLOYEEs
                where res.EMAIL == givenInfo || res.USER_NAME == givenInfo
                select new { res.EMAIL, res.USER_NAME };

Angular: Cannot find a differ supporting object '[object Object]'

Explanation: You can *ngFor on the arrays. You have your users declared as the array. But, the response from the Get returns you an object. You cannot ngFor on the object. You should have an array for that. You can explicitly cast the object to array and that will solve the issue. data to [data]

Solution

getusers() {
    this.http.get(`https://api.github.com/
search/users?q=${this.input1.value}`)
        .map(response => response.json())
        .subscribe(
        data => this.users = [data], //Cast your object to array. that will do it.
        error => console.log(error)
        )

Python timedelta in years

Even though this thread is already dead, might i suggest a working solution for this very same problem i was facing. Here it is (date is a string in the format dd-mm-yyyy):

def validatedate(date):
    parts = date.strip().split('-')

    if len(parts) == 3 and False not in [x.isdigit() for x in parts]: 
        birth = datetime.date(int(parts[2]), int(parts[1]), int(parts[0]))
        today = datetime.date.today()

        b = (birth.year * 10000) + (birth.month * 100) + (birth.day)
        t = (today.year * 10000) + (today.month * 100) + (today.day)

        if (t - 18 * 10000) >= b:
            return True

    return False

Adding a column to a data.frame

If I understand the question correctly, you want to detect when the h_no doesn't increase and then increment the class. (I'm going to walk through how I solved this problem, there is a self-contained function at the end.)

Working

We only care about the h_no column for the moment, so we can extract that from the data frame:

> h_no <- data$h_no

We want to detect when h_no doesn't go up, which we can do by working out when the difference between successive elements is either negative or zero. R provides the diff function which gives us the vector of differences:

> d.h_no <- diff(h_no)
> d.h_no
 [1]  1  1  1 -3  1  1  1  1  1  1 -6  1  1  1

Once we have that, it is a simple matter to find the ones that are non-positive:

> nonpos <- d.h_no <= 0
> nonpos
 [1] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE
[13] FALSE FALSE

In R, TRUE and FALSE are basically the same as 1 and 0, so if we get the cumulative sum of nonpos, it will increase by 1 in (almost) the appropriate spots. The cumsum function (which is basically the opposite of diff) can do this.

> cumsum(nonpos)
 [1] 0 0 0 1 1 1 1 1 1 1 2 2 2 2

But, there are two problems: the numbers are one too small; and, we are missing the first element (there should be four in the first class).

The first problem is simply solved: 1+cumsum(nonpos). And the second just requires adding a 1 to the front of the vector, since the first element is always in class 1:

 > classes <- c(1, 1 + cumsum(nonpos))
 > classes
  [1] 1 1 1 1 2 2 2 2 2 2 2 3 3 3 3

Now, we can attach it back onto our data frame with cbind (by using the class= syntax, we can give the column the class heading):

 > data_w_classes <- cbind(data, class=classes)

And data_w_classes now contains the result.

Final result

We can compress the lines together and wrap it all up into a function to make it easier to use:

classify <- function(data) {
   cbind(data, class=c(1, 1 + cumsum(diff(data$h_no) <= 0)))
}

Or, since it makes sense for the class to be a factor:

classify <- function(data) {
   cbind(data, class=factor(c(1, 1 + cumsum(diff(data$h_no) <= 0))))
}

You use either function like:

> classified <- classify(data) # doesn't overwrite data
> data <- classify(data) # data now has the "class" column

(This method of solving this problem is good because it avoids explicit iteration, which is generally recommend for R, and avoids generating lots of intermediate vectors and list etc. And also it's kinda neat how it can be written on one line :) )

How to trigger a phone call when clicking a link in a web page on mobile phone

Most modern devices support the tel: scheme. So use <a href="tel:555-555-5555">555-555-5555</a> and you should be good to go.

If you want to use it for an image, the <a> tag can handle the <img/> placed in it just like other normal situations with : <a href="tel:555-555-5555"><img src="path/to/phone/icon.jpg" /></a>

Can I do a max(count(*)) in SQL?

Just order by count(*) desc and you'll get the highest (if you combine it with limit 1)

How to disable registration new users in Laravel

If you're using Laravel 5.2 and you installed the auth related functionality with php artisan make:auth then your app/Http/routes.php file will include all auth-related routes by simply calling Route::auth().

The auth() method can be found in vendor/laravel/framework/src/Illuminate/Routing/Router.php. So if you want to do as some people suggest here and disable registration by removing unwanted routes (probably a good idea) then you have to copy the routes you still want from the auth() method and put them in app/Http/routes.php (replacing the call to Route::auth()). So for instance:

<?php
// This is app/Http/routes.php

// Authentication Routes...
Route::get('login', 'Auth\AuthController@showLoginForm');
Route::post('login', 'Auth\AuthController@login');
Route::get('logout', 'Auth\AuthController@logout');

// Registration Routes... removed!

// Password Reset Routes...
Route::get('password/reset/{token?}', 'Auth\PasswordController@showResetForm');
Route::post('password/email', 'Auth\PasswordController@sendResetLinkEmail');
Route::post('password/reset', 'Auth\PasswordController@reset');

If you're using lower version than 5.2 then it's probably different, I remember things changed quite a bit since 5.0, at some point artisan make:auth was even removed IIRC.

Use of alloc init instead of new

One Short Answere is:

  1. Both are same. But
  2. 'new' only works with the basic 'init' initializer, and will not work with other initializers (eg initWithString:).

Remove part of a string

You can use a built-in for this, strsplit:

> s = "TGAS_1121"
> s1 = unlist(strsplit(s, split='_', fixed=TRUE))[2]
> s1    
 [1] "1121"

strsplit returns both pieces of the string parsed on the split parameter as a list. That's probably not what you want, so wrap the call in unlist, then index that array so that only the second of the two elements in the vector are returned.

Finally, the fixed parameter should be set to TRUE to indicate that the split parameter is not a regular expression, but a literal matching character.

Nested select statement in SQL Server

You need to alias the subquery.

SELECT name FROM (SELECT name FROM agentinformation) a  

or to be more explicit

SELECT a.name FROM (SELECT name FROM agentinformation) a  

EF 5 Enable-Migrations : No context type was found in the assembly

I have been getting this same problem. I have even tried above enable migrations even though I have already done. But it keeps giving same error. Then I had to use the force switch to get overcome this problem. I am sure this will help in someone else's case as well as its a possible work around.

After enabling migration with force, you should update your database (Make sure default project is set correctly). Otherwise you will get another problem like explicit migrations are pending.

Then just execute your add-migrations or any other commands, it should work.

Enable-Migrations -ProjectName <PROJECT_NAME> -ContextTypeName <FULL_CONTEXT_NAMESPACE.YOUR_CONTEXT_NAME> -force

Install specific version using laravel installer

Using composer you can specify the version you want easily by running

composer create-project laravel/laravel="5.1.*" myProject

Using the 5.1.* will ensure that you get all the latest patches in the 5.1 branch.

Scraping data from website using vba

There are several ways of doing this. This is an answer that I write hoping that all the basics of Internet Explorer automation will be found when browsing for the keywords "scraping data from website", but remember that nothing's worth as your own research (if you don't want to stick to pre-written codes that you're not able to customize).

Please note that this is one way, that I don't prefer in terms of performance (since it depends on the browser speed) but that is good to understand the rationale behind Internet automation.

1) If I need to browse the web, I need a browser! So I create an Internet Explorer browser:

Dim appIE As Object
Set appIE = CreateObject("internetexplorer.application")

2) I ask the browser to browse the target webpage. Through the use of the property ".Visible", I decide if I want to see the browser doing its job or not. When building the code is nice to have Visible = True, but when the code is working for scraping data is nice not to see it everytime so Visible = False.

With appIE
    .Navigate "http://uk.investing.com/rates-bonds/financial-futures"
    .Visible = True
End With

3) The webpage will need some time to load. So, I will wait meanwhile it's busy...

Do While appIE.Busy
    DoEvents
Loop

4) Well, now the page is loaded. Let's say that I want to scrape the change of the US30Y T-Bond: What I will do is just clicking F12 on Internet Explorer to see the webpage's code, and hence using the pointer (in red circle) I will click on the element that I want to scrape to see how can I reach my purpose.

enter image description here

5) What I should do is straight-forward. First of all, I will get by the ID property the tr element which is containing the value:

Set allRowOfData = appIE.document.getElementById("pair_8907")

Here I will get a collection of td elements (specifically, tr is a row of data, and the td are its cells. We are looking for the 8th, so I will write:

Dim myValue As String: myValue = allRowOfData.Cells(7).innerHTML

Why did I write 7 instead of 8? Because the collections of cells starts from 0, so the index of the 8th element is 7 (8-1). Shortly analysing this line of code:

  • .Cells() makes me access the td elements;
  • innerHTML is the property of the cell containing the value we look for.

Once we have our value, which is now stored into the myValue variable, we can just close the IE browser and releasing the memory by setting it to Nothing:

appIE.Quit
Set appIE = Nothing

Well, now you have your value and you can do whatever you want with it: put it into a cell (Range("A1").Value = myValue), or into a label of a form (Me.label1.Text = myValue).

I'd just like to point you out that this is not how StackOverflow works: here you post questions about specific coding problems, but you should make your own search first. The reason why I'm answering a question which is not showing too much research effort is just that I see it asked several times and, back to the time when I learned how to do this, I remember that I would have liked having some better support to get started with. So I hope that this answer, which is just a "study input" and not at all the best/most complete solution, can be a support for next user having your same problem. Because I have learned how to program thanks to this community, and I like to think that you and other beginners might use my input to discover the beautiful world of programming.

Enjoy your practice ;)

Change image source in code behind - Wpf

You are all wrong! Why? Because all you need is this code to work:

(image View) / C# Img is : your Image box

Keep this as is, without change ("ms-appx:///) this is code not your app name Images is your folder in your project you can change it. dog.png is your file in your folder, as well as i do my folder 'Images' and file 'dog.png' So the uri is :"ms-appx:///Images/dog.png" and my code :


private void Button_Click(object sender, RoutedEventArgs e)
    {
         img.Source = new BitmapImage(new Uri("ms-appx:///Images/dog.png"));
    }

What does the "yield" keyword do?

All of the answers here are great; but only one of them (the most voted one) relates to how your code works. Others are relating to generators in general, and how they work.

So I won't repeat what generators are or what yields do; I think these are covered by great existing answers. However, after spending few hours trying to understand a similar code to yours, I'll break it down how it works.

Your code traverse a binary tree structure. Let's take this tree for example:

    5
   / \
  3   6
 / \   \
1   4   8

And another simpler implementation of a binary-search tree traversal:

class Node(object):
..
def __iter__(self):
    if self.has_left_child():
        for child in self.left:
            yield child

    yield self.val

    if self.has_right_child():
        for child in self.right:
            yield child

The execution code is on the Tree object, which implements __iter__ as this:

def __iter__(self):

    class EmptyIter():
        def next(self):
            raise StopIteration

    if self.root:
        return self.root.__iter__()
    return EmptyIter()

The while candidates statement can be replaced with for element in tree; Python translate this to

it = iter(TreeObj)  # returns iter(self.root) which calls self.root.__iter__()
for element in it: 
    .. process element .. 

Because Node.__iter__ function is a generator, the code inside it is executed per iteration. So the execution would look like this:

  1. root element is first; check if it has left childs and for iterate them (let's call it it1 because its the first iterator object)
  2. it has a child so the for is executed. The for child in self.left creates a new iterator from self.left, which is a Node object itself (it2)
  3. Same logic as 2, and a new iterator is created (it3)
  4. Now we reached the left end of the tree. it3 has no left childs so it continues and yield self.value
  5. On the next call to next(it3) it raises StopIteration and exists since it has no right childs (it reaches to the end of the function without yield anything)
  6. it1 and it2 are still active - they are not exhausted and calling next(it2) would yield values, not raise StopIteration
  7. Now we are back to it2 context, and call next(it2) which continues where it stopped: right after the yield child statement. Since it has no more left childs it continues and yields it's self.val.

The catch here is that every iteration creates sub-iterators to traverse the tree, and holds the state of the current iterator. Once it reaches the end it traverse back the stack, and values are returned in the correct order (smallest yields value first).

Your code example did something similar in a different technique: it populated a one-element list for every child, then on the next iteration it pops it and run the function code on the current object (hence the self).

I hope this contributed a little to this legendary topic. I spent several good hours drawing this process to understand it.

How can I count the numbers of rows that a MySQL query returned?

Getting total rows in a query result...

You could just iterate the result and count them. You don't say what language or client library you are using, but the API does provide a mysql_num_rows function which can tell you the number of rows in a result.

This is exposed in PHP, for example, as the mysqli_num_rows function. As you've edited the question to mention you're using PHP, here's a simple example using mysqli functions:

$link = mysqli_connect("localhost", "user", "password", "database");

$result = mysqli_query($link, "SELECT * FROM table1");
$num_rows = mysqli_num_rows($result);

echo "$num_rows Rows\n";

Getting a count of rows matching some criteria...

Just use COUNT(*) - see Counting Rows in the MySQL manual. For example:

SELECT COUNT(*) FROM foo WHERE bar= 'value';

Get total rows when LIMIT is used...

If you'd used a LIMIT clause but want to know how many rows you'd get without it, use SQL_CALC_FOUND_ROWS in your query, followed by SELECT FOUND_ROWS();

SELECT SQL_CALC_FOUND_ROWS * FROM foo
   WHERE bar="value" 
   LIMIT 10;

SELECT FOUND_ROWS();

For very large tables, this isn't going to be particularly efficient, and you're better off running a simpler query to obtain a count and caching it before running your queries to get pages of data.

MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

You can delete all the documents from a collection in MongoDB, you can use the following:

db.users.remove({})

Alternatively, you could use the following method as well:

db.users.deleteMany({})

Follow the following MongoDB documentation, for further details.

To remove all documents from a collection, pass an empty filter document {} to either the db.collection.deleteMany() or the db.collection.remove() method.

App installation failed due to application-identifier entitlement

I tried a few thing myself like updating/making new provisioning profiles, fixing entitlements in Apple Member Center and in project but in my case, I simply had to delete the application and re-run it.

o_O


This application's application-identifier entitlement does not match that of the installed application.

NOTE: it says "...does not match the installed application"

I guess it happened for me because we added a new app extension and there must have been some target related migration issues? Not sure but anyways

Java to Jackson JSON serialization: Money fields

I'm one of the maintainers of jackson-datatype-money, so take this answer with a grain of salt since I'm certainly biased. The module should cover your needs and it's pretty light-weight (no additional runtime dependencies). In addition it's mentioned in the Jackson docs, Spring docs and there were even some discussions already about how to integrate it into the official ecosystem of Jackson.

ggplot2: sorting a plot

You need to make the x-factor into an ordered factor with the ordering you want, e.g

x <- data.frame("variable"=letters[1:5], "value"=rnorm(5)) ## example data
x <- x[with(x,order(-value)), ] ## Sorting
x$variable <- ordered(x$variable, levels=levels(x$variable)[unclass(x$variable)])

ggplot(x, aes(x=variable,y=value)) + geom_bar() +
   scale_y_continuous("",formatter="percent") + coord_flip()

I don't know any better way to do the ordering operation. What I have there will only work if there are no duplicate levels for x$variable.

SSRS Field Expression to change the background color of the Cell

=IIF(Fields!Column.Value = "Approved", "Green", "No Color")

Git mergetool generates unwanted .orig files

You have to be a little careful with using kdiff3 as while git mergetool can be configured to save a .orig file during merging, the default behaviour for kdiff3 is to also save a .orig backup file independently of git mergetool.

You have to make sure that mergetool backup is off:

git config --global mergetool.keepBackup false

and also that kdiff3's settings are set to not create a backup:

Configure/Options => Directory Merge => Backup Files (*.orig)

Apache won't follow symlinks (403 Forbidden)

The 403 error may also be caused by an encrypted file system, e.g. a symlink to an encrypted home folder.

If your symlink points into the encrypted folder, the apache user (e.g. www-data) cannot access the contents, even if apache and file/folder permissions are set correctly. Access of the www-data user can be tested with such a call:

sudo -u www-data ls -l /var/www/html/<your symlink>/

There are workarounds/solutions to this, e.g. adding the www-data user to your private group (exposes the encrypted data to the web user) or by setting up an unencrypted rsynced folder (probably rather secure). I for myself will probably go for an rsync solution during development.

https://askubuntu.com/questions/633625/public-folder-in-an-encrypted-home-directory

A convenient tool for my purposes is lsyncd. This allows me to work directly in my encrypted home folder and being able to see changes almost instantly in the apache web page. The synchronization is triggered by changes in the file system, calling an rsync. As I'm only working on rather small web pages and scripts, the syncing is very fast. I decided to use a short delay of 1 second before the rsync is started, even though it is possible to set a delay of 0 seconds.

Installing lsyncd (in Ubuntu):

sudo apt-get install lsyncd

Starting the background service:

lsyncd -delay 1 -rsync /home/<me>/<work folder>/ /var/www/html/<web folder>/

C++ Remove new line from multiline string

All these answers seem a bit heavy to me.

If you just flat out remove the '\n' and move everything else back a spot, you are liable to have some characters slammed together in a weird-looking way. So why not just do the simple (and most efficient) thing: Replace all '\n's with spaces?

for (int i = 0; i < str.length();i++) {
   if (str[i] == '\n') {
      str[i] = ' ';
   }
}

There may be ways to improve the speed of this at the edges, but it will be way quicker than moving whole chunks of the string around in memory.

setTimeout in for-loop does not print consecutive values

You have to arrange for a distinct copy of "i" to be present for each of the timeout functions.

function doSetTimeout(i) {
  setTimeout(function() { alert(i); }, 100);
}

for (var i = 1; i <= 2; ++i)
  doSetTimeout(i);

If you don't do something like this (and there are other variations on this same idea), then each of the timer handler functions will share the same variable "i". When the loop is finished, what's the value of "i"? It's 3! By using an intermediating function, a copy of the value of the variable is made. Since the timeout handler is created in the context of that copy, it has its own private "i" to use.

edit — there have been a couple of comments over time in which some confusion was evident over the fact that setting up a few timeouts causes the handlers to all fire at the same time. It's important to understand that the process of setting up the timer — the calls to setTimeout() — take almost no time at all. That is, telling the system, "Please call this function after 1000 milliseconds" will return almost immediately, as the process of installing the timeout request in the timer queue is very fast.

Thus, if a succession of timeout requests is made, as is the case in the code in the OP and in my answer, and the time delay value is the same for each one, then once that amount of time has elapsed all the timer handlers will be called one after another in rapid succession.

If what you need is for the handlers to be called at intervals, you can either use setInterval(), which is called exactly like setTimeout() but which will fire more than once after repeated delays of the requested amount, or instead you can establish the timeouts and multiply the time value by your iteration counter. That is, to modify my example code:

function doScaledTimeout(i) {
  setTimeout(function() {
    alert(i);
  }, i * 5000);
}

(With a 100 millisecond timeout, the effect won't be very obvious, so I bumped the number up to 5000.) The value of i is multiplied by the base delay value, so calling that 5 times in a loop will result in delays of 5 seconds, 10 seconds, 15 seconds, 20 seconds, and 25 seconds.

Update

Here in 2018, there is a simpler alternative. With the new ability to declare variables in scopes more narrow than functions, the original code would work if so modified:

for (let i = 1; i <= 2; i++) {
    setTimeout(function() { alert(i) }, 100);
}

The let declaration, unlike var, will itself cause there to be a distinct i for each iteration of the loop.

Extract the last substring from a cell

Try this:

Right(RC[-1],Len(RC[-1])-InStrRev(RC[-1]," "))

How can I run Android emulator for Intel x86 Atom without hardware acceleration on Windows 8 for API 21 and 19?

In current AVD manager you can't. You just have the opportunity to use ARM images which will not need hardware virtualization.

To run ARM images:

  1. Open AVD manager.
  2. Create a new 'Virtual Device' OR right click an existing image and select 'Duplicate'
  3. Choose arm* instead of x86/x64.
  4. Continue with the wizard.
  5. Run!

Although this is the available solution but still a slow one !!

C++ error: "Array must be initialized with a brace enclosed initializer"

You can't initialize arrays like this:

int cipher[Array_size][Array_size]=0;

The syntax for 2D arrays is:

int cipher[Array_size][Array_size]={{0}};

Note the curly braces on the right hand side of the initialization statement.

for 1D arrays:

int tomultiply[Array_size]={0};

Using two values for one switch case statement

You can use:

case text1: case text4: 
     do stuff;
     break;

Should C# or C++ be chosen for learning Games Programming (consoles)?

To tell the truth...you have to make the decision as to which is the better language. I know what I can do with C#. I know what can be done in C++. C# isn't made to do what C++ was made to do...write code at the most basic level and still be somewhat meaningful when read by human eyes.

We are developing a game engine with C#, DirectX...is it a challenge? hell yeah...but it's something we chose to do. We are looking at some performance levels that are very close to what C++ can give. So, I see no problems with this effort.

To cross-platform development, if it weren't for .Net, we might not have the Mono platform. The Mono platform has broadened our platform base.

Here is some support to my arguments...

Trying to get Laravel 5 email to work

  1. You go to the Mailgun
  2. Click Authorized Recipients
  3. Add the email address you wish send mail to.
  4. Verify the message sent to the mail.
  5. Bravo!...You're good to go.

How do I execute a MS SQL Server stored procedure in java/jsp, returning table data?

FWIW, sp_test will not be returning anything but an integer (all SQL Server stored procs just return an integer) and no result sets on the wire (since no SELECT statements). To get the output of the PRINT statements, you normally use the InfoMessage event on the connection (not the command) in ADO.NET.

Add two numbers and display result in textbox with Javascript

When you assign your variables "first_number" and "second_number", you need to change "document.getElementsById" to the singular "document.getElementById".

Difference between margin and padding?

Basically, the difference between padding and margin come in terms of the background. Padding will decide the space between content, while margin decide the outside edge of elements!

get basic SQL Server table structure information

For total columns information use below syntax : Use "DBName" go Exec SP_Columns "TableName"

For total table information use below syntax : Use "DBName" go Exec SP_help "Table Name"

How to make a checkbox checked with jQuery?

$('#checkbox').prop('checked', true);

When you want it unchecked:

$('#checkbox').prop('checked', false);

Java. Implicit super constructor Employee() is undefined. Must explicitly invoke another constructor

Any constructor for any class as you know creates an object. So, the constructor should contain proper initialization code for its class. But if you have some class which extends another one (lets call it "parent") then constructor for the class cannot contain all the code needed for the initialization by definition (for example, you cannot define private fields of the parent). That's why constructor of the class has to call constructor of its parent. If you do not call it explicitly then the default parent constructor is called (which is without any parameter).

So, in your case, you can either implement default constructor in parent or directly call any constructor in the class.

Char array to hex string C++

The simplest:

int main()
{
    const char* str = "hello";
    for (const char* p = str; *p; ++p)
    {
        printf("%02x", *p);
    }
    printf("\n");
    return 0;
}

List directory tree structure in python?

You can execute 'tree' command of Linux shell.

Installation:

   ~$sudo apt install tree

Using in python

    >>> import os
    >>> os.system('tree <desired path>')

Example:

    >>> os.system('tree ~/Desktop/myproject')

This gives you a cleaner structure and is visually more comprehensive and easy to type.

Java read file and store text in an array

I use this method:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class TEST {
    static Scanner scn;

public static void main(String[] args) {
    String text = "";

    try{
        scn = new Scanner(new File("test.txt"));
    }catch(FileNotFoundException ex){System.out.println(ex.getMessage());}
    while(scn.hasNext()){
        text += scn.next();
        }
        String[] arry = text.split(",");

    //if need converting to float do this:
    Float[] arrdy = new Float[arry.length];
    for(int i = 0; i < arry.length; i++){
            arrdy[i] = Float.parseFloat(arry[i]);
        }
    System.out.println(Arrays.toString(arrdy));
            }
}

Create local maven repository

Set up a simple repository using a web server with its default configuration. The key is the directory structure. The documentation does not mention it explicitly, but it is the same structure as a local repository.

To set up an internal repository just requires that you have a place to put it, and then start copying required artifacts there using the same layout as in a remote repository such as repo.maven.apache.org. Source

Add a file to your repository like this:

mvn install:install-file \
  -Dfile=YOUR_JAR.jar -DgroupId=YOUR_GROUP_ID 
  -DartifactId=YOUR_ARTIFACT_ID -Dversion=YOUR_VERSION \
  -Dpackaging=jar \
  -DlocalRepositoryPath=/var/www/html/mavenRepository

If your domain is example.com and the root directory of the web server is located at /var/www/html/, then maven can find "YOUR_JAR.jar" if configured with <url>http://example.com/mavenRepository</url>.

Passing data to a bootstrap modal

You can try simpleBootstrapDialog. Here you can pass title, message, callback options for cancel and submit etc...

To use this plugin include simpleBootstrapDialog.js file like below

<script type="text/javascript" src="/simpleDialog.js"></script>

Basic Usage

<script type="text/javascript>
$.simpleDialog();
</script>

Custom Title and description

$.simpleDialog({
  title:"Alert Dialog",
  message:"Alert Message"
});

With Callback

<script type="text/javascript>
$.simpleDialog({
    onSuccess:function(){
        alert("You confirmed");
    },
    onCancel:function(){
        alert("You cancelled");
    }
});
</script>

Does Visual Studio Code have box select/multi-line edit?

For multiple select in Visual Studio Code, hold down the Alt key and starting clicking wherever you want to edit.

Visual Studio Code supports multiple line edit.

wget/curl large file from google drive

Use youtube-dl!

youtube-dl https://drive.google.com/open?id=ABCDEFG1234567890

You can also pass --get-url to get a direct download URL.

Getting the text from a drop-down box

document.getElementById('newSkill').options[document.getElementById('newSkill').selectedIndex].value 

Should work

Adding three months to a date in PHP

You need to convert the date into a readable value. You may use strftime() or date().

Try this:

$effectiveDate = strtotime("+3 months", strtotime($effectiveDate));
$effectiveDate = strftime ( '%Y-%m-%d' , $effectiveDate );
echo $effectiveDate;

This should work. I like using strftime better as it can be used for localization you might want to try it.

How to change the blue highlight color of a UITableViewCell?

Zonble has already provided an excellent answer. I thought it may be useful to include a short code snippet for adding a UIView to the tableview cell that will present as the selected background view.

cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];

    UIView *selectionColor = [[UIView alloc] init];
    selectionColor.backgroundColor = [UIColor colorWithRed:(245/255.0) green:(245/255.0) blue:(245/255.0) alpha:1];
    cell.selectedBackgroundView = selectionColor;
  • cell is my UITableViewCell
  • I created a UIView and set its background color using RGB colours (light gray)
  • I then set the cell selectedBackgroundView to be the UIView that I created with my chosen background colour

This worked well for me. Thanks for the tip Zonble.

MySQL Join Where Not Exists

I'd probably use a LEFT JOIN, which will return rows even if there's no match, and then you can select only the rows with no match by checking for NULLs.

So, something like:

SELECT V.*
FROM voter V LEFT JOIN elimination E ON V.id = E.voter_id
WHERE E.voter_id IS NULL

Whether that's more or less efficient than using a subquery depends on optimization, indexes, whether its possible to have more than one elimination per voter, etc.

How to remove specific substrings from a set of strings in Python?

>>> x = 'Pear.good'
>>> y = x.replace('.good','')
>>> y
'Pear'
>>> x
'Pear.good'

.replace doesn't change the string, it returns a copy of the string with the replacement. You can't change the string directly because strings are immutable.

You need to take the return values from x.replace and put them in a new set.

How to set bot's status

Use this:

client.user.setActivity("with depression", {
  type: "STREAMING",
  url: "https://www.twitch.tv/monstercat"
});

In Javascript, how to conditionally add a member to an object?

Using lodash library, you can use _.omitBy

var a = _.omitBy({
    b: conditionB ? 4 : undefined,
    c: conditionC ? 5 : undefined,
}, _.IsUndefined)

This results handy when you have requests that are optional

var a = _.omitBy({
    b: req.body.optionalA,  //if undefined, will be removed
    c: req.body.optionalB,
}, _.IsUndefined)

Eloquent ->first() if ->exists()

Try it this way in a simple manner it will work

$userset = User::where('name',$data['name'])->first();
if(!$userset) echo "no user found";

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

Check which version of Entity Framework reference you have in your References and make sure that it matches with your configSections node in Web.config file. In my case it was pointing to version 5.0.0.0 in my configSections and my reference was 6.0.0.0. I just changed it and it worked...

<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>

Is the NOLOCK (Sql Server hint) bad practice?

With NOLOCK hint, the transaction isolation level for the SELECT statement is READ UNCOMMITTED. This means that the query may see dirty and inconsistent data.

This is not a good idea to apply as a rule. Even if this dirty read behavior is OK for your mission critical web based application, a NOLOCK scan can cause 601 error which will terminate the query due to data movement as a result of lack of locking protection.

I suggest reading When Snapshot Isolation Helps and When It Hurts - the MSDN recommends using READ COMMITTED SNAPSHOT rather than SNAPSHOT under most circumstances.

Regex to split a CSV

The correct regular expression to match a single quoted value with escaped [doubled] single quotes in it is:

'([^n']|(''))+'

How to create a batch file to run cmd as administrator

(This is based on @DarkXphenomenon's answer, which unfortunately had some problems.)

You need to enclose your code within this wrapper:

if _%1_==_payload_  goto :payload

:getadmin
    echo %~nx0: elevating self
    set vbs=%temp%\getadmin.vbs
    echo Set UAC = CreateObject^("Shell.Application"^)                >> "%vbs%"
    echo UAC.ShellExecute "%~s0", "payload %~sdp0 %*", "", "runas", 1 >> "%vbs%"
    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
goto :eof

:payload
    echo %~nx0: running payload with parameters:
    echo %*
    echo ---------------------------------------------------
    cd /d %2
    shift
    shift
    rem put your code here
    rem e.g.: perl myscript.pl %1 %2 %3 %4 %5 %6 %7 %8 %9
goto :eof

This makes batch file run itself as elevated user. It adds two parameters to the privileged code:

  • word payload, to indicate this is payload call, i.e. already elevated. Otherwise it would just open new processes over and over.

  • directory path where the main script was called. Due to the fact that Windows always starts elevated cmd.exe in "%windir%\system32", there's no easy way of knowing what the original path was (and retaining ability to copy your script around without touching code)

Note: Unfortunately, for some reason shift does not work for %*, so if you need to pass actual arguments on, you will have to resort to the ugly notation I used in the example (%1 %2 %3 %4 %5 %6 %7 %8 %9), which also brings in the limit of maximum of 9 arguments

How to give a Linux user sudo access?

You need run visudo and in the editor that it opens write:

igor    ALL=(ALL) ALL

That line grants all permissions to user igor.

If you want permit to run only some commands, you need to list them in the line:

igor    ALL=(ALL) /bin/kill, /bin/ps

Angular 2 Routing run in new tab

This seems a little confused.

Opening your application in another window or tab will require your entire application to be re-bootstrapped, and then for your router to... pick up that url, convert it into a route, and load the appropriate component.

This is exactly what will happen if you just use a link instead. In fact, that's all that's happening.

The point of the router is to swap components in and out of your router-outlet, which is something that's been bootstrapped and exists within the confines of your running application and isn't shared across multiple windows.

Return value of x = os.system(..)

os.system('command') returns a 16 bit number, which first 8 bits from left(lsb) talks about signal used by os to close the command, Next 8 bits talks about return code of command.

Refer my answer for more detail in What is the return value of os.system() in Python?

Algorithm to detect overlapping periods

Check this simple method (It is recommended to put This method in your dateUtility

public static bool isOverlapDates(DateTime dtStartA, DateTime dtEndA, DateTime dtStartB, DateTime dtEndB)
        {
            return dtStartA < dtEndB && dtStartB < dtEndA;
        }

Display QImage with QtGui

As far as I know, QPixmap is used for displaying images and QImage for reading them. There are QPixmap::convertFromImage() and QPixmap::fromImage() functions to convert from QImage.

jQuery ajax success error

Try to set response dataType property directly:

dataType: 'text'

and put

die(''); 

in the end of your php file. You've got error callback cause jquery cannot parse your response. In anyway, you may use a "complete:" callback, just to make sure your request has been processed.

"Auth Failed" error with EGit and GitHub

On Windows, setting GIT_SSH to openssh that comes with msys git didn't work (Eclipse hung during commit). Setting it to TortoisePlink solved the problem (I guess original plink would work as well). The added bonus is now Eclipse uses keys stored in pageant.

jQuery Validation plugin: validate check box

You can validate group checkbox and radio button without extra js code, see below example.

Your JS should be look like:

$("#formid").validate();

You can play with HTML tag and attributes: eg. group checkbox [minlength=2 and maxlength=4]

<fieldset class="col-md-12">
  <legend>Days</legend>
  <div class="form-row">
    <div class="col-12 col-md-12 form-group">
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="1" required="required" data-msg-required="This value is required." minlength="2" maxlength="4" data-msg-maxlength="Max should be 4">Monday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="2">Tuesday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="3">Wednesday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="4">Thursday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="5">Friday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="6">Saturday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="7">Sunday
        </label>
        <label for="daysgroup[]" class="error">Your error message will be display here.</label>
    </div>
  </div>
</fieldset>

You can see here first or any one input should have required, minlength="2" and maxlength="4" attributes. minlength/maxlength as per your requirement.

eg. group radio button:

<fieldset class="col-md-12">
  <legend>Gender</legend>
  <div class="form-row">
    <div class="col-12 col-md-12 form-group">
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="m" required="required" data-msg-required="This value is required.">man
        </label>
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="w">woman
        </label>
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="o">other
        </label>
        <label for="gendergroup[]" class="error">Your error message will be display here.</label>
    </div>
  </div>
</fieldset>

You can check working example here.

  • jQuery v3.3.x
  • jQuery Validation Plugin - v1.17.0

How do I specify different layouts for portrait and landscape orientations?

You just have to put it under separate folders with different names depending on orientation and resolution, the device will automatically select the right one for its screen settings

More info here:

http://developer.android.com/guide/practices/screens_support.html

under "Resource directory qualifiers for screen size and density"

How to change font-color for disabled input?

You can use readonly instead. Following would do the trick for you.

<input type="text" class="details-dialog" style="background-color: #bbbbbb" readonly>

But you need to note the following. Depends on your business requirement, you can use it.

A readonly element is just not editable, but gets sent when the according form submits. A disabled element isn't editable and isn't sent on submit.

Finding all possible permutations of a given string in python

This is a recursive solution with n! which accepts duplicate elements in the string

import math

def getFactors(root,num):
    sol = []
    # return condition
    if len(num) == 1:
            return [root+num]
    # looping in next iteration
    for i in range(len(num)):  
        # Creating a substring with all remaining char but the taken in this iteration
        if i > 0:
            rem = num[:i]+num[i+1:]
        else:
            rem = num[i+1:]
        # Concatenating existing solutions with the solution of this iteration
        sol = sol + getFactors(root + num[i], rem)
    return sol

I validated the solution taking into account two elements, the number of combinations is n! and the result can not contain duplicates. So:

inpt = "1234"
results = getFactors("",inpt)

if len(results) == math.factorial(len(inpt)) | len(results) != len(set(results)):
    print("Wrong approach")
else:
    print("Correct Approach")

get the value of input type file , and alert if empty

There should be

$('.send_upload')

but not $('.upload')

JavaScriptSerializer.Deserialize - how to change field names

I have used the using Newtonsoft.Json as below. Create an object:

 public class WorklistSortColumn
  {
    [JsonProperty(PropertyName = "field")]
    public string Field { get; set; }

    [JsonProperty(PropertyName = "dir")]
    public string Direction { get; set; }

    [JsonIgnore]
    public string SortOrder { get; set; }
  }

Now Call the below method to serialize to Json object as shown below.

string sortColumn = JsonConvert.SerializeObject(worklistSortColumn);

How to specify maven's distributionManagement organisation wide?

The best solution for this is to create a simple parent pom file project (with packaging 'pom') generically for all projects from your organization.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>your.company</groupId>
    <artifactId>company-parent</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <distributionManagement>
        <repository>
            <id>nexus-site</id>
            <url>http://central_nexus/server</url>
        </repository>
    </distributionManagement>

</project>

This can be built, released, and deployed to your local nexus so everyone has access to its artifact.

Now for all projects which you wish to use it, simply include this section:

<parent>
  <groupId>your.company</groupId>
  <artifactId>company-parent</artifactId>
  <version>1.0.0</version>
</parent>

This solution will allow you to easily add other common things to all your company's projects. For instance if you wanted to standardize your JUnit usage to a specific version, this would be the perfect place for that.

If you have projects that use multi-module structures that have their own parent, Maven also supports chaining inheritance so it is perfectly acceptable to make your project's parent pom file refer to your company's parent pom and have the project's child modules not even aware of your company's parent.

I see from your example project structure that you are attempting to put your parent project at the same level as your aggregator pom. If your project needs its own parent, the best approach I have found is to include the parent at the same level as the rest of the modules and have your aggregator pom.xml file at the root of where all your modules' directories exist.

- pom.xml (aggregator)
    - project-parent
    - project-module1
    - project-module2

What you do with this structure is include your parent module in the aggregator and build everything with a mvn install from the root directory.

We use this exact solution at my organization and it has stood the test of time and worked quite well for us.

Can Selenium WebDriver open browser windows silently in the background?

This is a simple Node.js solution that works in the new version 4.x (maybe also 3.x) of Selenium.

Chrome

const { Builder } = require('selenium-webdriver')
const chrome = require('selenium-webdriver/chrome');

let driver = await new Builder().forBrowser('chrome').setChromeOptions(new chrome.Options().headless()).build()

await driver.get('https://example.com')

Firefox

const { Builder } = require('selenium-webdriver')
const firefox = require('selenium-webdriver/firefox');

let driver = await new Builder().forBrowser('firefox').setFirefoxOptions(new firefox.Options().headless()).build()

await driver.get('https://example.com')

The whole thing just runs in the background. It is exactly what we want.

CSS - how to make image container width fixed and height auto stretched

What you're looking for is min-height and max-height.

img {
    max-width: 100%;
    height: auto;
}

.item {
    width: 120px;
    min-height: 120px;
    max-height: auto;
    float: left;
    margin: 3px;
    padding: 3px;
}

Getting the location from an IP address

I like the free GeoLite City from Maxmind which works for most applications and from which you can upgrade to a paying version if it's not precise enough. There is a PHP API included, as well as for other languages. And if you are running Lighttpd as a webserver, you can even use a module to get the information in the SERVER variable for every visitor if that's what you need.

I should add there is also a free Geolite Country (which would be faster if you don't need to pinpoint the city the IP is from) and Geolite ASN (if you want to know who owns the IP) and that finally all these are downloadable on your own server, are updated every month and are pretty quick to lookup with the provided APIs as they state "thousands of lookups per second".

sub and gsub function?

That won't work if the string contains more than one match... try this:

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo "  $0) }'

or better (if the echo isn't a placeholder for something else):

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'

In your case you want to make a copy of the value before changing it:

echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'

How do you append to an already existing string?

In classic sh, you have to do something like:

s=test1
s="${s}test2"

(there are lots of variations on that theme, like s="$s""test2")

In bash, you can use +=:

s=test1
s+=test2

Regex remove all special characters except numbers?

to remove symbol use tag [ ]

step:1

[]

step 2:place what symbol u want to remove eg:@ like [@]

[@]

step 3:

var name = name.replace(/[@]/g, "");

thats it

_x000D_
_x000D_
var name="ggggggg@fffff"
var result = name.replace(/[@]/g, "");
console .log(result)
_x000D_
_x000D_
_x000D_

Extra Tips

To remove space (give one space into square bracket like []=>[ ])

[@ ]

It Remove Everything (using except)

[^place u dont want to remove]

eg:i remove everyting except alphabet (small and caps)

[^a-zA-Z ]

_x000D_
_x000D_
var name="ggggg33333@#$%^&**I(((**gg@fffff"
var result = name.replace(/[^a-zA-Z]/g, "");
console .log(result)
_x000D_
_x000D_
_x000D_

The view 'Index' or its master was not found.

Global.asax file contain the URL Route. Default URL route like this.

"{controller}/{action}/{id}"

So,Try this.

1. Right click your controller method as below.

Example: let say we call Index() method.Right click on it. enter image description here

2. Click Add View.. and give appropriate name.In this example name should be Index.

enter image description here

Then it will add correct View by creating with relevant folder structure.

Moment.js - two dates difference in number of days

Here's how you can get the comprehensive full fledge difference of two dates.

 function diffYMDHMS(date1, date2) {

    let years = date1.diff(date2, 'year');
    date2.add(years, 'years');

    let months = date1.diff(date2, 'months');
    date2.add(months, 'months');

    let days = date1.diff(date2, 'days');
    date2.add(days, 'days');

    let hours = date1.diff(date2, 'hours');
    date2.add(hours, 'hours');

    let minutes = date1.diff(date2, 'minutes');
    date2.add(minutes, 'minutes');

    let seconds = date1.diff(date2, 'seconds');

    console.log(years + ' years ' + months + ' months ' + days + ' days ' + hours + ' 
    hours ' + minutes + ' minutes ' + seconds + ' seconds'); 

    return { years, months, days, hours, minutes, seconds};
}

How to format a Java string with leading zero?

Using Guava's Strings utility class:

Strings.padStart("Apple", 8, '0');

How to open child forms positioned within MDI parent in VB.NET?

You will want to set the MdiParent property of your new form to the name of the MDI parent form, as follows:

dim form as new yourform
form.show()
form.MdiParent = nameParent

In Typescript, How to check if a string is Numeric

Whether a string can be parsed as a number is a runtime concern. Typescript does not support this use case as it is focused on compile time (not runtime) safety.

Sending a file over TCP sockets in Python

The problem is extra 13 byte which server.py receives at the start. To resolve that write "l = c.recv(1024)" twice before the while loop as below.

print "Receiving..."
l = c.recv(1024) #this receives 13 bytes which is corrupting the data
l = c.recv(1024) # Now actual data starts receiving
while (l):

This resolves the issue, tried with different format and sizes of files. If anyone knows what this starting 13 bytes refers to, please reply.

Extracting Ajax return data in jQuery

You can use json like the following example.

PHP code:

echo json_encode($array);

$array is array data, and the jQuery code is:

$.get("period/education/ajaxschoollist.php?schoolid="+schoolid, function(responseTxt, statusTxt, xhr){
    var a = JSON.parse(responseTxt);
    $("#hideschoolid").val(a.schoolid);
    $("#section_id").val(a.section_id);
    $("#schoolname").val(a.schoolname);
    $("#country_id").val(a.country_id);
    $("#state_id").val(a.state_id);
}

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop?

Visual Studio for Windows Apps is meant to be used to build Windows Store Apps using HTML & Javascript or WinRT and XAML. These can also run on the Windows tablet that run Windows RT.

Visual Studio for Windows Desktop is meant to build applications using Windows Forms or Windows Presentation Foundation, these can run on Windows 8.1 on a normal desktop or on a tablet device like the Surface Pro in desktop mode (like a classic windows application).

How to get a div to resize its height to fit container?

You probably are going to want to use the following declaration:

height: 100%;

This will set the div's height to 100% of its containers height, which will make it fill the parent div.

How to check object is nil or not in swift?

Swift 4.2

func isValid(_ object:AnyObject!) -> Bool
{
    if let _:AnyObject = object
    {
        return true
    }

    return false
}

Usage

if isValid(selectedPost)
{
    savePost()
}

Simplest JQuery validation rules example

The examples contained in this blog post do the trick.

Create component to specific module with Angular-CLI

  1. First, you generate a module by executing.
ng g m modules/media

this will generate a module called media inside modules folder.

  1. Second, you generate a component added to this module
ng g c modules/media/picPick --module=modules/media/media.module.ts

the first part of the command ng g c modules/media/picPick will generate a component folder called picPick inside modules/media folder witch contain our new media module.

the second part will make our new picPick component declared in media module by importing it in the module file and appending it to declarations array of this module.

working tree

enter image description here

CSS I want a div to be on top of everything

You need to add position:relative; to the menu. Z-index only works when you have a non static positioning scheme.

Constants in Objective-C

// Prefs.h
extern NSString * const RAHUL;

// Prefs.m
NSString * const RAHUL = @"rahul";

Meaning of = delete after function declaration

  1. = 0 means that a function is pure virtual and you cannot instantiate an object from this class. You need to derive from it and implement this method
  2. = delete means that the compiler will not generate those constructors for you. AFAIK this is only allowed on copy constructor and assignment operator. But I am not too good at the upcoming standard.

How do I set default values for functions parameters in Matlab?

This is more or less lifted from the Matlab manual; I've only got passing experience...

function my_output = wave ( a, b, n, k, T, f, flag, varargin )
  optargin = numel(varargin);
  fTrue = inline('0');
  if optargin > 0
    fTrue = varargin{1};
  end
  % code ...
end

Disable color change of anchor tag when visited

Either delete the selector or set it to the same color as your text appears normally.

grant remote access of MySQL database from any IP address

Just create the user to some database like

GRANT ALL PRIVILEGES ON <database_name>.* TO '<username>'@'%' IDENTIFIED BY '<password>'

Then go to

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf and change the line bind-address = 127.0.0.1 to bind-address = 0.0.0.0

After that you may connect to that database from any IP.

How can I specify a [DllImport] path at runtime?

If all fails, simply put the DLL in the windows\system32 folder . The compiler will find it. Specify the DLL to load from with: DllImport("user32.dll"..., set EntryPoint = "my_unmanaged_function" to import your desired unmanaged function to your C# app:

 using System;
using System.Runtime.InteropServices;

class Example
{
   // Use DllImport to import the Win32 MessageBox function.

   [DllImport ("user32.dll", CharSet = CharSet.Auto)]
   public static extern int MessageBox 
      (IntPtr hWnd, String text, String caption, uint type);

   static void Main()
   {
      // Call the MessageBox function using platform invoke.
      MessageBox (new IntPtr(0), "Hello, World!", "Hello Dialog", 0);    
   }
}

Source and even more DllImport examples : http://msdn.microsoft.com/en-us/library/aa288468(v=vs.71).aspx

java.time.format.DateTimeParseException: Text could not be parsed at index 21

The following worked for me

import java.time.*;
import java.time.format.*;

public class Times {

  public static void main(String[] args) {
    final String dateTime = "2012-02-22T02:06:58.147Z";
    DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
    final ZonedDateTime parsed = ZonedDateTime.parse(dateTime, formatter.withZone(ZoneId.of("UTC")));
    System.out.println(parsed.toLocalDateTime());
  }
}

and gave me output as

2012-02-22T02:06:58.147

Multiple queries executed in java in single statement

Hint: If you have more than one connection property then separate them with:

&amp;

To give you somthing like:

url="jdbc:mysql://localhost/glyndwr?autoReconnect=true&amp;allowMultiQueries=true"

I hope this helps some one.

Regards,

Glyn

Why when I transfer a file through SFTP, it takes longer than FTP?

Several factors affect speed of SFTP transfer:

  1. Encryption. Though symmetric encryption is fast, it's not that fast to be unnoticed. If you comparing speeds on fast network (100mbit or larger), encryption becomes a break for your process.
  2. Hash calculation and checking.
  3. Buffer copying. SFTP running on top of SSH causes each data block to be copied at least 6 times (3 times on each side) more comparing to plain FTP where data in best cases can be passed to network interface without being copied at all. And block copy takes a bit of time as well.

Solving SharePoint Server 2010 - 503. The service is unavailable, After installation

Can You Please try this : Check the web site properties in IIS. Under home directory tab, check the application pool value Verify that all SharePoint services are started. If the application is not started do the following: I think this error might occur because of changing the service account password. You may need to change the new password to application pool
1)Click the stopped application pool 2)click advanced settings 3)Identity ->click the user to retype the user 4) Application Pool Identity dialog 5)click set -> manually type the user name and password. Then restart the server.

Delete newline in Vim

It probably depends on your settings, but I usually do this with A<delete>

Where A is append at the end of the line. It probably requires nocompatible mode :)

What is the difference between __init__ and __call__?

You can also use __call__ method in favor of implementing decorators.

This example taken from Python 3 Patterns, Recipes and Idioms

class decorator_without_arguments(object):
    def __init__(self, f):
        """
        If there are no decorator arguments, the function
        to be decorated is passed to the constructor.
        """
        print("Inside __init__()")
        self.f = f

    def __call__(self, *args):
        """
        The __call__ method is not called until the
        decorated function is called.
        """
        print("Inside __call__()")
        self.f(*args)
        print("After self.f( * args)")


@decorator_without_arguments
def sayHello(a1, a2, a3, a4):
    print('sayHello arguments:', a1, a2, a3, a4)


print("After decoration")
print("Preparing to call sayHello()")
sayHello("say", "hello", "argument", "list")
print("After first sayHello() call")
sayHello("a", "different", "set of", "arguments")
print("After second sayHello() call")

Output:

enter image description here

Execute cmd command from VBScript

Set oShell = WScript.CreateObject("WSCript.shell")
oShell.run "cmd cd /d C:dir_test\file_test & sanity_check_env.bat arg1"

Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error

I use Windows Server 2012 for hosting for a long time and it just stop working after a more than years without any problem. My solution was to add public IP address of the server to list of relays and enabled Windows Integrated Authentication.

I just made two changes and I don't which help.

Go to IIS 6 Manager

Go to IIS 6 Manager

Select properties of SMTP server

Select properties of SMTP server

On tab Access, select Relays

On tab Access, select Relays

Add your public IP address

Add your public IP address

Close the dialog and on the same tab click to Authentication button.

Add Integrated Windows Authentication

Add Integrated Windows Authentication

Maybe some step is not needed, but it works.

Import regular CSS file in SCSS file?

This was implemented and merged starting from version 3.2 (pull #754 merged on 2 Jan 2015 for libsass, issues originaly were defined here: sass#193 #556, libsass#318).

To cut the long story short, the syntax in next:

  1. to import (include) the raw CSS-file

    the syntax is without .css extension at the end (results in actual read of partial s[ac]ss|css and include of it inline to SCSS/SASS):

    @import "path/to/file";

  2. to import the CSS-file in a traditional way

    syntax goes in traditional way, with .css extension at the end (results to @import url("path/to/file.css"); in your compiled CSS):

    @import "path/to/file.css";

And it is damn good: this syntax is elegant and laconic, plus backward compatible! It works excellently with libsass and node-sass.

__

To avoid further speculations in comments, writing this explicitly: Ruby based Sass still has this feature unimplemented after 7 years of discussions. By the time of writing this answer, it's promised that in 4.0 there will be a simple way to accomplish this, probably with the help of @use. It seems there will be an implementation very soon, the new "planned" "Proposal Accepted" tag was assigned for the issue #556 and the new @use feature.

answer might be updated, as soon as something changes.

Error: getaddrinfo ENOTFOUND in nodejs for get call

for me it was because in /etc/hosts file the hostname is not added

How to change Vagrant 'default' machine name?

This is the way I've assigned names to individual VMs. Change YOURNAMEHERE to your desired name.

Contents of Vagrantfile:

Vagrant.configure("2") do |config|

  # Every Vagrant virtual environment requires a box to build off of.
  config.vm.box = "precise32"

  # The url from where the 'config.vm.box' box will be fetched if it
  # doesn't already exist on the user's system.
  config.vm.box_url = "http://files.vagrantup.com/precise32.box"

  config.vm.define :YOURNAMEHERE do |t|
  end

end

Terminal output:

$ vagrant status
Current machine states:

YOURNAMEHERE             not created (virtualbox)

How do I get the full url of the page I am on in C#

For ASP.NET Core you'll need to spell it out:

@($"{Context.Request.Scheme}://{Context.Request.Host}{Context.Request.Path}{Context.Request.QueryString}")

Or you can add a using statement to your view:

@using Microsoft.AspNetCore.Http.Extensions

then

@Context.Request.GetDisplayUrl()

The _ViewImports.cshtml might be a better place for that @using

How do I store and retrieve a blob from sqlite?

This worked fine for me (C#):

byte[] iconBytes = null;
using (var dbConnection = new SQLiteConnection(DataSource))
{
    dbConnection.Open();
    using (var transaction = dbConnection.BeginTransaction())
    {
        using (var command = new SQLiteCommand(dbConnection))
        {
            command.CommandText = "SELECT icon FROM my_table";

            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    if (reader["icon"] != null && !Convert.IsDBNull(reader["icon"]))
                    {
                        iconBytes = (byte[]) reader["icon"];
                    }
                }
            }
        }
        transaction.Commit();
    }
}

No need for chunking. Just cast to a byte array.

Quickly create large file on a Windows system

The simplest way I've found is this free utility: http://www.mynikko.com/dummy/

Creates dummy files of arbitrary size that are either filled with spaces or are filled with non-compressible content (your choice). Here's a screenshot:

enter image description here

What to do with commit made in a detached head

Create a branch where you are, then switch to master and merge it:

git branch my-temporary-work
git checkout master
git merge my-temporary-work

How to find specified name and its value in JSON-string from Java?

Gson allows for one of the simplest possible solutions. Compared to similar APIs like Jackson or svenson, Gson by default doesn't even need the unused JSON elements to have bindings available in the Java structure. Specific to the question asked, here's a working solution.

import com.google.gson.Gson;

public class Foo
{
  static String jsonInput = 
    "{" + 
      "\"name\":\"John\"," + 
      "\"age\":\"20\"," + 
      "\"address\":\"some address\"," + 
      "\"someobject\":" +
      "{" + 
        "\"field\":\"value\"" + 
      "}" + 
    "}";

  String age;

  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    Foo thing = gson.fromJson(jsonInput, Foo.class);
    if (thing.age != null)
    {
      System.out.println("age is " + thing.age);
    }
    else
    {
      System.out.println("age element not present or value is null");
    }
  }
}

Initialize a byte array to a certain value, other than the default null?

You can use a collection initializer:

UserCode = new byte[]{0x20,0x20,0x20,0x20,0x20,0x20};

This will work better than Repeat if the values are not identical.