SyntaxFix.com - Programming Questions & Answers Hub For Beginners


Some Of The Best Answers From Latest Asked Questions

Create a symbolic link of directory in Ubuntu

This is the behavior of ln if the second arg is a directory. It places a link to the first arg inside it. If you want /etc/nginx to be the symlink, you should remove that directory first and run that same command.

multiple axis in matplotlib with different scales

Bootstrapping something fast to chart multiple y-axes sharing an x-axis using @joe-kington's answer: enter image description here

# d = Pandas Dataframe, 
# ys = [ [cols in the same y], [cols in the same y], [cols in the same y], .. ] 
def chart(d,ys):

    from itertools import cycle
    fig, ax = plt.subplots()

    axes = [ax]
    for y in ys[1:]:
        # Twin the x-axis twice to make independent y-axes.
        axes.append(ax.twinx())

    extra_ys =  len(axes[2:])

    # Make some space on the right side for the extra y-axes.
    if extra_ys>0:
        temp = 0.85
        if extra_ys<=2:
            temp = 0.75
        elif extra_ys<=4:
            temp = 0.6
        if extra_ys>5:
            print 'you are being ridiculous'
        fig.subplots_adjust(right=temp)
        right_additive = (0.98-temp)/float(extra_ys)
    # Move the last y-axis spine over to the right by x% of the width of the axes
    i = 1.
    for ax in axes[2:]:
        ax.spines['right'].set_position(('axes', 1.+right_additive*i))
        ax.set_frame_on(True)
        ax.patch.set_visible(False)
        ax.yaxis.set_major_formatter(matplotlib.ticker.OldScalarFormatter())
        i +=1.
    # To make the border of the right-most axis visible, we need to turn the frame
    # on. This hides the other plots, however, so we need to turn its fill off.

    cols = []
    lines = []
    line_styles = cycle(['-','-','-', '--', '-.', ':', '.', ',', 'o', 'v', '^', '<', '>',
               '1', '2', '3', '4', 's', 'p', '*', 'h', 'H', '+', 'x', 'D', 'd', '|', '_'])
    colors = cycle(matplotlib.rcParams['axes.color_cycle'])
    for ax,y in zip(axes,ys):
        ls=line_styles.next()
        if len(y)==1:
            col = y[0]
            cols.append(col)
            color = colors.next()
            lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
            ax.set_ylabel(col,color=color)
            #ax.tick_params(axis='y', colors=color)
            ax.spines['right'].set_color(color)
        else:
            for col in y:
                color = colors.next()
                lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
                cols.append(col)
            ax.set_ylabel(', '.join(y))
            #ax.tick_params(axis='y')
    axes[0].set_xlabel(d.index.name)
    lns = lines[0]
    for l in lines[1:]:
        lns +=l
    labs = [l.get_label() for l in lns]
    axes[0].legend(lns, labs, loc=0)

    plt.show()

CSS Outside Border

Put your div inside another div, apply the border to the outer div with n amount of padding/margin where n is the space you want between them.

Cast Double to Integer in Java

Like this:

Double foo = 123.456;
Integer bar = foo.intValue();

text-align: right; not working for <label>

You can make a text align to the right inside of any element, including labels.

Html:

<label>Text</label>

Css:

label {display:block; width:x; height:y; text-align:right;}

This way, you give a width and height to your label and make any text inside of it align to the right.

Pure CSS multi-level drop-down menu

I needed a multilevel dropdown menu in css. I couldn't find an error-free menu that I searched. Then I created a menu instance using the Css hover transition effect.I hope it will be useful for users.

enter image description here Css codes:

#AnaMenu {
width: 920px;            /* Menu width */
height: 30px;           /* Menu height */
position: relative;
background: #0080ff;
margin:0 0 0 -30px;
padding: 10px 0 0 15px;
border: 0;              
}
#nav { display:block;background:transparent;
margin:0;padding: 0;border: 0 }
#nav ul { float: none; display:block;
height:35px; 
margin:16px 0 0 0;border:0;
padding: 15px 0 3px 0; 
overflow: visible;
 }
#nav ul li{border:0;}
#nav li a, #nav li a:link, #nav li a:visited {height:23px;
-webkit-transition: background-color 1s ease-out;
-moz-transition: background-color 1s ease-out;
-o-transition: background-color 1s ease-out;
transition: background-color 1s ease-out;
color: #fff;                               /* Change colour of link */
display: block;border:0;border-right:1px solid #efefef;text-decoration:none;
margin: 0;letter-spacing:0.6px;
padding: 2px 10px 2px 10px;             
}
#nav li a:hover, #nav li a:active {
color: #fff;  
margin: 0;background:#6ab5ff;border:0;
padding: 2px 10px 2px 10px;      
}
#nav li li a, #nav li li a:link, #nav li li a:visited {
background: #fafafa;      
width: 200px;
color: #05429b;           /* Link text color */
float: none;
margin: 0;border-bottom:1px solid #9be6e9;
padding: 8px 15px;        
}
#nav li li a:hover, #nav li li a:active {
background: #2793ff;        /* Mouse hover color */
color: #fff;               
padding: 8px 15px;border:0 ;text-decoration:none}
#nav li {float: none; display: inline-block;margin: 0; padding: 0; border: 0 }
#nav li ul { z-index: 9999; position: absolute; left: -999em; height: auto; width: 200px; margin: 0; padding: 0;background:transparent}
#nav li ul a { width: 170px;border:0;text-decoration:none;font-size:14px } 
#nav li ul ul { margin: -40px 0 0 230px }
#nav li:hover ul ul, #nav li:hover ul ul ul, #nav li.sfhover ul ul, #nav li.sfhover ul ul ul {left: -999em; } 
#nav li:hover ul, #nav li li:hover ul, #nav li li li:hover ul, #nav li.sfhover ul, #nav li li.sfhover ul, #nav li li li.sfhover ul { left: auto; } 
#nav li:hover, #nav li.sfhover {position: static;}

Multilevel dropdown menu can be used in Blogger blogs. Details at : Css multilevel dropdown menu

MySQL SELECT LIKE or REGEXP to match multiple words in one record

Assuming that your search is stylus photo 2100. Try the following example is using RLIKE.

SELECT * FROM `buckets` WHERE `bucketname` RLIKE REPLACE('stylus photo 2100', ' ', '+.*');

EDIT

Another way is to use FULLTEXT index on bucketname and MATCH ... AGAINST syntax in your SELECT statement. So to re-write the above example...

SELECT * FROM `buckets` WHERE MATCH(`bucketname`) AGAINST (REPLACE('stylus photo 2100', ' ', ','));

How can I add comments in MySQL?

From here you can use

#  For single line comments
-- Also for single line, must be followed by space/control character
/*
    C-style multiline comment
*/

jQuery ajax request with json response, how to?

Firstly, it will help if you set the headers of your PHP to serve JSON:

header('Content-type: application/json');

Secondly, it will help to adjust your ajax call:

$.ajax({
    url: "main.php",
    type: "POST",
    dataType: "json",
    data: {"action": "loadall", "id": id},
    success: function(data){
        console.log(data);
    },
    error: function(error){
         console.log("Error:");
         console.log(error);
    }
});

If successful, the response you receieve should be picked up as true JSON and an object should be logged to console.

NOTE: If you want to pick up pure html, you might want to consider using another method to JSON, but I personally recommend using JSON and rendering it into html using templates (such as Handlebars js).

Aren't Python strings immutable? Then why does a + " " + b work?

Adding a bit more to above-mentioned answers.

id of a variable changes upon reassignment.

>>> a = 'initial_string'
>>> id(a)
139982120425648
>>> a = 'new_string'
>>> id(a)
139982120425776

Which means that we have mutated the variable a to point to a new string. Now there exist two string(str) objects:

'initial_string' with id = 139982120425648

and

'new_string' with id = 139982120425776

Consider the below code:

>>> b = 'intitial_string'
>>> id(b)
139982120425648

Now, b points to the 'initial_string' and has the same id as a had before reassignment.

Thus, the 'intial_string' has not been mutated.

Adding an onclicklistener to listview (android)

The prestListView.getItemAtPosition(position); returns the UI widget: Text, Icon, ...

Try this instead:

Object o = prestationAdapterEco.getItemAtPosition(position);

or

Object o = arg0.getItemAtPosition(position);

Get the object from the adapter. Not from the list-view.

2. Object o is a prestationEco object. Not a String.

Bloomberg Open API

Since the data is not free, you can use this Bloomberg API Emulator (disclaimer: it's my project) to learn how to send requests and make subscriptions. This emulator looks and acts just like the real Bloomberg API, although it doesn't return real data. In my time developing applications that use the Bloomberg API, I rarely care about the actual data that I'm handling; I care about how to retrieve data.

If you want to learn how to use the Bloomberg API give it a try. If you want to test out your code without an account, use this. A Bloomberg account costs about $2,000 a month, so you can save a lot with this project.

The emulator now supports Java and C++ in addition to C#.

C#, C++, and Java:

  • Intraday Tick Requests
  • Intraday Bar Requests
  • Reference Data Requests
  • Historical Data Requests
  • Market Data Subscriptions

Edit: Updated Project link, moved to github

Uninstalling Android ADT

The only way to remove the ADT plugin from Eclipse is to go to Help > About Eclipse/About ADT > Installation Details.

Select a plug-in you want to uninstall, then click Uninstall... button at the bottom.

enter image description here

If you cannot remove ADT from this location, then your best option is probably to start fresh with a clean Eclipse install.

Get CPU Usage from Windows Command Prompt

typeperf "\processor(_total)\% processor time"

does work on Win7, you just need to extract the percent value yourself from the last quoted string.

How to retrieve available RAM from Windows command line?

Just in case you need this functionality in a Java program, you might want to look at the sigar API: http://www.hyperic.com/products/sigar

Actually, this is no answer to the question, I know, but a hint so you don't have to reinvent the wheel.

How to use andWhere and orWhere in Doctrine?

Why not just

$q->where("a = 1");
$q->andWhere("b = 1 OR b = 2");
$q->andWhere("c = 1 OR d = 2");

EDIT: You can also use the Expr class (Doctrine2).

How to check if a std::thread is still running?

This simple mechanism you can use for detecting finishing of a thread without blocking in join method.

std::thread thread([&thread]() {
    sleep(3);
    thread.detach();
});

while(thread.joinable())
    sleep(1);

change html input type by JS?

This is not supported by some browsers (IE if I recall), but it works in the rest:

document.getElementById("password-field").attributes["type"] = "password";

or

document.getElementById("password-field").attributes["type"] = "text";

Installation error: INSTALL_FAILED_OLDER_SDK

Fix for new Android 6.0 Marshmallow Fixed my issue when I updated to API 23 (Android 6.0 Marshmallow) by updating the build tools version to 23.0.0 as follows:

android {
    buildToolsVersion '23.0.0'
...

And went to File > Project Structure , chose Properties tab then updated the Compile Sdk version to "API 23: Android 5.X (MNC)" and the Build tools version to "23.0.0"

How to capture a JFrame's close button click event?

This may work:

jdialog.addWindowListener(new WindowAdapter() {
    public void windowClosed(WindowEvent e) {
        System.out.println("jdialog window closed event received");
    }

    public void windowClosing(WindowEvent e) {
        System.out.println("jdialog window closing event received");
    }
});

Source: https://alvinalexander.com/java/jdialog-close-closing-event

START_STICKY and START_NOT_STICKY

Both codes are only relevant when the phone runs out of memory and kills the service before it finishes executing. START_STICKY tells the OS to recreate the service after it has enough memory and call onStartCommand() again with a null intent. START_NOT_STICKY tells the OS to not bother recreating the service again. There is also a third code START_REDELIVER_INTENT that tells the OS to recreate the service and redeliver the same intent to onStartCommand().

This article by Dianne Hackborn explained the background of this a lot better than the official documentation.

Source: http://android-developers.blogspot.com.au/2010/02/service-api-changes-starting-with.html

The key part here is a new result code returned by the function, telling the system what it should do with the service if its process is killed while it is running:

START_STICKY is basically the same as the previous behavior, where the service is left "started" and will later be restarted by the system. The only difference from previous versions of the platform is that it if it gets restarted because its process is killed, onStartCommand() will be called on the next instance of the service with a null Intent instead of not being called at all. Services that use this mode should always check for this case and deal with it appropriately.

START_NOT_STICKY says that, after returning from onStartCreated(), if the process is killed with no remaining start commands to deliver, then the service will be stopped instead of restarted. This makes a lot more sense for services that are intended to only run while executing commands sent to them. For example, a service may be started every 15 minutes from an alarm to poll some network state. If it gets killed while doing that work, it would be best to just let it be stopped and get started the next time the alarm fires.

START_REDELIVER_INTENT is like START_NOT_STICKY, except if the service's process is killed before it calls stopSelf() for a given intent, that intent will be re-delivered to it until it completes (unless after some number of more tries it still can't complete, at which point the system gives up). This is useful for services that are receiving commands of work to do, and want to make sure they do eventually complete the work for each command sent.

switch case statement error: case expressions must be constant expression

In a regular Android project, constants in the resource R class are declared like this:

public static final int main=0x7f030004;

However, as of ADT 14, in a library project, they will be declared like this:

public static int main=0x7f030004;

In other words, the constants are not final in a library project. Therefore your code would no longer compile.

The solution for this is simple: Convert the switch statement into an if-else statement.

public void onClick(View src)
{
    int id = src.getId();
    if (id == R.id.playbtn){
        checkwificonnection();
    } else if (id == R.id.stopbtn){
        Log.d(TAG, "onClick: stopping srvice");
        Playbutton.setImageResource(R.drawable.playbtn1);
        Playbutton.setVisibility(0); //visible
        Stopbutton.setVisibility(4); //invisible
        stopService(new Intent(RakistaRadio.this,myservice.class));
        clearstatusbar();
        timer.cancel();
        Title.setText(" ");
        Artist.setText(" ");
    } else if (id == R.id.btnmenu){
        openOptionsMenu();
    }
}

http://tools.android.com/tips/non-constant-fields

You can quickly convert a switch statement to an if-else statement using the following:

In Eclipse
Move your cursor to the switch keyword and press Ctrl + 1 then select

Convert 'switch' to 'if-else'.

In Android Studio
Move your cursor to the switch keyword and press Alt + Enter then select

Replace 'switch' with 'if'.

Check if a folder exist in a directory and create them using C#

This should help:

using System.IO;
...

string path = @"C:\MP_Upload";
if(!Directory.Exists(path))
{
    Directory.CreateDirectory(path);
}

Broadcast Receiver within a Service

as your service is already setup, simply add a broadcast receiver in your service:

private final BroadcastReceiver receiver = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
        //action for sms received
      }
      else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
           //action for phone state changed
      }     
   }
};

in your service's onCreate do this:

IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction("your_action_strings"); //further more
filter.addAction("your_action_strings"); //further more

registerReceiver(receiver, filter);

and in your service's onDestroy:

unregisterReceiver(receiver);

and you are good to go to receive broadcast for what ever filters you mention in onCreate. Make sure to add any permission if required. for e.g.

<uses-permission android:name="android.permission.RECEIVE_SMS" />

how to show confirmation alert with three buttons 'Yes' 'No' and 'Cancel' as it shows in MS Word

This cannot be done with the native javascript dialog box, but a lot of javascript libraries include more flexible dialogs. You can use something like jQuery UI's dialog box for this.

See also these very similar questions:

Here's an example, as demonstrated in this jsFiddle:

<html><head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
    <link rel="stylesheet" type="text/css" href="/css/normalize.css">
    <link rel="stylesheet" type="text/css" href="/css/result-light.css">
    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/base/jquery-ui.css">
</head>
<body>
    <a class="checked" href="http://www.google.com">Click here</a>
    <script type="text/javascript">

        $(function() {
            $('.checked').click(function(e) {
                e.preventDefault();
                var dialog = $('<p>Are you sure?</p>').dialog({
                    buttons: {
                        "Yes": function() {alert('you chose yes');},
                        "No":  function() {alert('you chose no');},
                        "Cancel":  function() {
                            alert('you chose cancel');
                            dialog.dialog('close');
                        }
                    }
                });
            });
        });

    </script>
</body><html>

Copying files using rsync from remote server to local machine

I think it is better to copy files from your local computer, because if files number or file size is very big, copying process could be interrupted if your current ssh session would be lost (broken pipe or whatever).

If you have configured ssh key to connect to your remote server, you could use the following command:

rsync -avP -e "ssh -i /home/local_user/ssh/key_to_access_remote_server.pem" remote_user@remote_host.ip:/home/remote_user/file.gz /home/local_user/Downloads/

Where v option is --verbose, a option is --archive - archive mode, P option same as --partial - keep partially transferred files, e option is --rsh=COMMAND - specifying the remote shell to use.

rsync man page

What is the http-header "X-XSS-Protection"?

This header is getting somehow deprecated. You can read more about it here - X-XSS-Protection

  • Chrome has removed their XSS Auditor
  • Firefox has not, and will not implement X-XSS-Protection
  • Edge has retired their XSS filter

This means that if you do not need to support legacy browsers, it is recommended that you use Content-Security-Policy without allowing unsafe-inline scripts instead.

How to check if a double is null?

How are you getting the value of "results"? Are you getting it via ResultSet.getDouble()? In that case, you can check ResultSet.wasNull().

Can you have a <span> within a <span>?

HTML4 specification states that:

Inline elements may contain only data and other inline elements

Span is an inline element, therefore having span inside span is valid. There's a related question: Can <span> tags have any type of tags inside them? which makes it completely clear.

HTML5 specification (including the most current draft of HTML 5.3 dated November 16, 2017) changes terminology, but it's still perfectly valid to place span inside another span.

How to initialize a list with constructor?

Are you looking for this?

ContactNumbers = new List<ContactNumber>(){ new ContactNumber("555-5555"),
                                            new ContactNumber("555-1234"),
                                            new ContactNumber("555-5678") };

T-SQL: Export to new Excel file

This is by far the best post for exporting to excel from SQL:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926

To quote from user madhivanan,

Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel

Create an Excel file named testing having the headers same as that of table columns and use these queries

1 Export data to existing EXCEL file from SQL Server table

insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;', 
    'SELECT * FROM [SheetName$]') select * from SQLServerTable

2 Export data from Excel to new SQL Server table

select * 
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [Sheet1$]')

3 Export data from Excel to existing SQL Server table (edited)

Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [SheetName$]')

4 If you dont want to create an EXCEL file in advance and want to export data to it, use

EXEC sp_makewebtask 
    @outputfile = 'd:\testing.xls', 
    @query = 'Select * from Database_name..SQLServerTable', 
    @colheaders =1, 
    @FixedFont=0,@lastupdated=0,@resultstitle='Testing details'

(Now you can find the file with data in tabular format)

5 To export data to new EXCEL file with heading(column names), create the following procedure

create procedure proc_generate_excel_with_columns
(
    @db_name    varchar(100),
    @table_name varchar(100),   
    @file_name  varchar(100)
)
as

--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select 
    @columns=coalesce(@columns+',','')+column_name+' as '+column_name 
from 
    information_schema.columns
where 
    table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')

--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'

--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)

--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)

--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)

--Delete dummy file 
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)

After creating the procedure, execute it by supplying database name, table name and file path:

EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'

Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.

Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.

To update single cells

A member also there Peter Larson posts the following: I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?

This is the principle of how you do manage that

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99

You can also add formulas to Excel using this:

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'

Exporting with column names using T-SQL

Member Mladen Prajdic also has a blog entry on how to do this here

References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server). For error referencing I used this

Errors that may occur

If you get the following error:

OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries

Then run this:

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO

The OutputPath property is not set for this project

The error shown in visual studio for the project (Let's say A) does not have issues. When I looked at the output window for the build line by line for each project, I saw that it was complaining about another project (B) that had been referred as assembly in project A. Project B added into the solution. But it had not been referred in the project A as project reference instead as assembly reference from different location. That location contains the assembly which compiled for Platform AnyCpu. Then I removed the assembly reference from the project A and added project B as a reference. It started compiling. Not sure though how this fix worked.

How to compare pointers?

The == operator on pointers will compare their numeric address and hence determine if they point to the same object.

Check If only numeric values were entered in input. (jQuery)

There is a built-in function in jQuery to check this (isNumeric), so try the following:

var phone = $("input#phone").val();
    if (phone !== "" && !$.isNumeric(phone)) {
  //Check if phone is numeric
  $("label#phone_error").show(); //Show error
  $("input#phone").focus(); //Focus on field
  return false;
}

Bash array with spaces in elements

Not exactly an answer to the quoting/escaping problem of the original question but probably something that would actually have been more useful for the op:

unset FILES
for f in 2011-*.jpg; do FILES+=("$f"); done
echo "${FILES[@]}"

Where of course the expression would have to be adopted to the specific requirement (e.g. *.jpg for all or 2001-09-11*.jpg for only the pictures of a certain day).

What is &amp used for

if you're doing a string of characters. make:

let linkGoogle = 'https://www.google.com/maps/dir/?api=1'; 
let origin = '&origin=' + locations[0][1] + ',' + locations[0][2];


aNav.href = linkGoogle + origin;

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

My case on Ubuntu 14.04.2 LTS was similar to others with my.cnf, but for me the cause was a ~/.my.cnf that was leftover from a previous installation. After deleting that file and purging/re-installing mysql-server, it worked fine.

Convert a number into a Roman Numeral in javaScript

I know this is a dated question but I have the shortest solution of the ones listed here and thought I would share since I think its easier to understand.

This version does not require any hard coded logic for edge cases such as 4(IV),9(IX),40(XL),900(CM), etc. as the others do. This also means it can handle larger numbers greater than the maximum roman scale could (3999). For example if "T" became a new symbol you could add it to the beginning of the romanLookup object and it would keep the same algorithmic affect; or course assuming the "no more than 3 of the same symbol in a row" rule applies.

I have tested this against a data set from 1-3999 and it works flawlessly.

function convertToRoman(num) {
  //create key:value pairs
  var romanLookup = {M:1000, D:500, C:100, L:50, X:10, V:5, I:1};
  var roman = [];
  var romanKeys = Object.keys(romanLookup);
  var curValue;
  var index;
  var count = 1;

  for(var numeral in romanLookup){
    curValue = romanLookup[numeral];
    index = romanKeys.indexOf(numeral);

    while(num >= curValue){

      if(count < 4){
        //push up to 3 of the same numeral
        roman.push(numeral);
      } else {
        //else we had to push four, so we need to convert the numerals 
        //to the next highest denomination "coloring-up in poker speak"

        //Note: We need to check previous index because it might be part of the current number.
        //Example:(9) would attempt (VIIII) so we would need to remove the V as well as the I's
        //otherwise removing just the last three III would be incorrect, because the swap 
        //would give us (VIX) instead of the correct answer (IX)
        if(roman.indexOf(romanKeys[index - 1]) > -1){
          //remove the previous numeral we worked with 
          //and everything after it since we will replace them
          roman.splice(roman.indexOf(romanKeys[index - 1]));
          //push the current numeral and the one that appeared two iterations ago; 
          //think (IX) where we skip (V)
          roman.push(romanKeys[index], romanKeys[index - 2]);
        } else {
          //else Example:(4) would attemt (IIII) so remove three I's and replace with a V 
          //to get the correct answer of (IV)

          //remove the last 3 numerals which are all the same
          roman.splice(-3);
          //push the current numeral and the one that appeared right before it; think (IV)
          roman.push(romanKeys[index], romanKeys[index - 1]);
        }
      }
      //reduce our number by the value we already converted to a numeral
      num -= curValue;
      count++;
    }
    count = 1;
  }
  return roman.join("");
}

convertToRoman(36);

Custom domain for GitHub project pages

As of Aug 29, 2013, Github's documentation claim that:

Warning: Project pages subpaths like http://username.github.io/projectname will not be redirected to a project's custom domain.

How to debug apk signed for release?

I know this is old question, but future references. In Android Studio with Gradle:

buildTypes {
    release {
        debuggable true
        runProguard true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
}

The line debuggable true was the trick for me.

Update:

Since gradle 1.0 it's minifyEnabled instead of runProguard. Look at here

Using jQuery to programmatically click an <a> link

Add onclick="window.location = this.href" to your <a> element. After this modification it could be .click()ed with expected behaviour. To do so with every link on your page, you can add this:

<script type="text/javascript">
    $(function () {
        $("a").attr("onclick", "window.location = this.href");
    });
</script>

Is Django for the frontend or backend?

Neither.

Django is a framework, not a language. Python is the language in which Django is written.

Django is a collection of Python libs allowing you to quickly and efficiently create a quality Web application, and is suitable for both frontend and backend.

However, Django is pretty famous for its "Django admin", an auto generated backend that allows you to manage your website in a blink for a lot of simple use cases without having to code much.

More precisely, for the front end, Django helps you with data selection, formatting, and display. It features URL management, a templating language, authentication mechanisms, cache hooks, and various navigation tools such as paginators.

For the backend, Django comes with an ORM that lets you manipulate your data source with ease, forms (an HTML independent implementation) to process user input and validate data and signals, and an implementation of the observer pattern. Plus a tons of use-case specific nifty little tools.

For the rest of the backend work Django doesn't help with, you just use regular Python. Business logic is a pretty broad term.

You probably want to know as well that Django comes with the concept of apps, a self contained pluggable Django library that solves a problem. The Django community is huge, and so there are numerous apps that do specific business logic that vanilla Django doesn't.

REST - HTTP Post Multipart with JSON

If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes. You set request header Content-Type: multipart/form-data; boundary=HereGoes. Then this should be a valid request body:

--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json

{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<...JPEG content in base64...>
--HereGoes--

Node.js - Find home directory in platform agnostic way

Well, it would be more accurate to rely on the feature and not a variable value. Especially as there are 2 possible variables for Windows.

function getUserHome() {
  return process.env.HOME || process.env.USERPROFILE;
}

EDIT: as mentioned in a more recent answer, https://stackoverflow.com/a/32556337/103396 is the right way to go (require('os').homedir()).

Update multiple columns in SQL

The "tiresome way" is standard SQL and how mainstream RDBMS do it.

With a 100+ columns, you mostly likely have a design problem... also, there are mitigating methods in client tools (eg generation UPDATE statements) or by using ORMs

Visual Studio popup: "the operation could not be completed"

Worked for me after I closed Visual Studio (2015 Community Edition), opened it and opened project again.Had Happened to me because I was using this project as a dependency in another project and it was opened in another instance but the changes were not imitated.

How do I detect the Python version at runtime?

Try this code, this should work:

import platform
print(platform.python_version())

Access key value from Web.config in Razor View-MVC3 ASP.NET

@System.Configuration.ConfigurationManager.AppSettings["myKey"]

How to autoplay HTML5 mp4 video on Android?

don't use "mute" alone, use [muted]="true" for example following code:

<video id="videoPlayer" [muted]="true" autoplay playsinline loop style="width:100%; height: 100%;">
<source type="video/mp4" src="assets/Video/Home.mp4">
<source type="video/webm" src="assets/Video/Home.webm">
</video>

I test in more Android and ios

How to input automatically when running a shell over SSH?

ssh-key with passphrase, with keychain

keychain is a small utility which manages ssh-agent on your behalf and allows the ssh-agent to remain running when the login session ends. On subsequent logins, keychain will connect to the existing ssh-agent instance. In practice, this means that the passphrase must be be entered only during the first login after a reboot. On subsequent logins, the unencrypted key from the existing ssh-agent instance is used. This can also be useful for allowing passwordless RSA/DSA authentication in cron jobs without passwordless ssh-keys.

To enable keychain, install it and add something like the following to ~/.bash_profile:

eval keychain --agents ssh --eval id_rsa From a security point of view, ssh-ident and keychain are worse than ssh-agent instances limited to the lifetime of a particular session, but they offer a high level of convenience. To improve the security of keychain, some people add the --clear option to their ~/.bash_profile keychain invocation. By doing this passphrases must be re-entered on login as above, but cron jobs will still have access to the unencrypted keys after the user logs out. The keychain wiki page has more information and examples.

Got this info from;

https://unix.stackexchange.com/questions/90853/how-can-i-run-ssh-add-automatically-without-password-prompt

Hope this helps

I have personally been able to automatically enter my passphrase upon terminal launch by doing this: (you can, of course, modify the script and fit it to your needs)

  1. edit the bashrc file to add this script;

    Check if the SSH agent is awake

    if [ -z "$SSH_AUTH_SOCK" ] ; then exec ssh-agent bash -c "ssh-add ; $0" echo "The SSH agent was awakened" exit fi

    Above line will start the expect script upon terminal launch.

    ./ssh.exp

here's the content of this expect script

#!/usr/bin/expect

set timeout 20

set passphrase "test"

spawn "./keyadding.sh"

expect "Enter passphrase for /the/path/of/yourkey_id_rsa:"

send "$passphrase\r";

interact

Here's the content of my keyadding.sh script (you must put both scripts in your home folder, usually /home/user)

#!/bin/bash

ssh-add /the/path/of/yourkey_id_rsa

exit 0

I would HIGHLY suggest encrypting the password on the .exp script as well as renaming this .exp file to something like term_boot.exp or whatever else for security purposes. Don't forget to create the files directly from the terminal using nano or vim (ex: nano ~/.bashrc | nano term_boot.exp) and also a chmod +x script.sh to make it executable. A chmod +r term_boot.exp would be also useful but you'll have to add sudo before ./ssh.exp in your bashrc file. So you'll have to enter your sudo password each time you launch your terminal. For me, it's more convenient than the passphrase cause I remember my admin (sudo) password by the hearth.

Also, here's another way to do it I think; https://www.cyberciti.biz/faq/noninteractive-shell-script-ssh-password-provider/

Will certainly change my method for this one when I'll have the time.

How to insert a data table into SQL Server database table?

I am giving a very simple code, which i used in my solution (I have the same problem statement as yours)

    SqlConnection con = connection string ;
//new SqlConnection("Data Source=.;uid=sa;pwd=sa123;database=Example1");
con.Open();
string sql = "Create Table abcd (";
foreach (DataColumn column in dt.Columns)
{
    sql += "[" + column.ColumnName + "] " + "nvarchar(50)" + ",";
}
sql = sql.TrimEnd(new char[] { ',' }) + ")";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.ExecuteNonQuery();
using (var adapter = new SqlDataAdapter("SELECT * FROM abcd", con)) 
using(var builder = new SqlCommandBuilder(adapter))
{
adapter.InsertCommand = builder.GetInsertCommand();
adapter.Update(dt);
// adapter.Update(ds.Tables[0]); (Incase u have a data-set)
}
con.Close();

I have given a predefined table-name as "abcd" (you must take care that a table by this name doesn't exist in your database). Please vote my answer if it works for you!!!! :)

YouTube Video Embedded via iframe Ignoring z-index?

The answers abow didnt really work for me, i had a click event on the wrapper and ie 7,8,9,10 ignored the z-index, so my fix was giving the wrapper a background-color and it all of a sudden worked. Al though it was suppose to be transparent, so i defined the wrapper with the background-color white, and then opacity 0.01, and now it works. I also have the functions above, so it could be a combination.

I dont know why it works, im just happy it does.

POST an array from an HTML form without javascript

You can also post multiple inputs with the same name and have them save into an array by adding empty square brackets to the input name like this:

<input type="text" name="comment[]" value="comment1"/>
<input type="text" name="comment[]" value="comment2"/>
<input type="text" name="comment[]" value="comment3"/>
<input type="text" name="comment[]" value="comment4"/>

If you use php:

print_r($_POST['comment']) 

you will get this:

Array ( [0] => 'comment1' [1] => 'comment2' [2] => 'comment3' [3] => 'comment4' )

Where to find the complete definition of off_t type?

If you are having trouble tracing the definitions, you can use the preprocessed output of the compiler which will tell you all you need to know. E.g.

$ cat test.c
#include <stdio.h>
$ cc -E test.c | grep off_t
typedef long int __off_t;
typedef __off64_t __loff_t;
  __off_t __pos;
  __off_t _old_offset;
typedef __off_t off_t;
extern int fseeko (FILE *__stream, __off_t __off, int __whence);
extern __off_t ftello (FILE *__stream) ;

If you look at the complete output you can even see the exact header file location and line number where it was defined:

# 132 "/usr/include/bits/types.h" 2 3 4


typedef unsigned long int __dev_t;
typedef unsigned int __uid_t;
typedef unsigned int __gid_t;
typedef unsigned long int __ino_t;
typedef unsigned long int __ino64_t;
typedef unsigned int __mode_t;
typedef unsigned long int __nlink_t;
typedef long int __off_t;
typedef long int __off64_t;

...

# 91 "/usr/include/stdio.h" 3 4
typedef __off_t off_t;

How can I check if a string contains ANY letters from the alphabet?

Regex should be a fast approach:

re.search('[a-zA-Z]', the_string)

configure Git to accept a particular self-signed server certificate for a particular https remote

On windows in a corporate environment where certificates are distributed from a single source, I found this answer solved the issue: https://stackoverflow.com/a/48212753/761755

How to enable ASP classic in IIS7.5

I found some detailed instructions here: http://digitallibraryworld.com/?p=6

The key piece of advice seems to be, don't use the 64-bit ASP.DLL (found in system32) if you've configured the app pool to run 32-bit applications (instead, use the 32-bit ASP.DLL).

Add a script map using the following setting:

Request Path: *.asp
Executable: C:\Windows\system32\inetsrv\asp.dll
Name: whatever you want. I named my Classic ASP

The executable above is 64 BIT ASP handler for your asp script. If you want your ASP script to be handled in 32 bit environment, you need to use executable from this location: C:\Windows\SysWOW64\inetsrv\asp.dll.

Of course, if you don't need to load any 32-bit libraries (or data providers, etc.), just make your life easier by running the 64-bit ASP.DLL!

Contain an image within a div?

#container img{
 height:100%;
 width:100%;   
}

Insert auto increment primary key to existing table

For those like myself getting a Multiple primary key defined error try:

ALTER TABLE `myTable` ADD COLUMN `id` INT AUTO_INCREMENT UNIQUE FIRST NOT NULL;

On MySQL v5.5.31 this set the id column as the primary key for me and populated each row with an incrementing value.

How do I free memory in C?

You have to free() the allocated memory in exact reverse order of how it was allocated using malloc().

Note that You should free the memory only after you are done with your usage of the allocated pointers.

memory allocation for 1D arrays:

    buffer = malloc(num_items*sizeof(double));

memory deallocation for 1D arrays:

    free(buffer);

memory allocation for 2D arrays:

    double **cross_norm=(double**)malloc(150 * sizeof(double *));
    for(i=0; i<150;i++)
    {
        cross_norm[i]=(double*)malloc(num_items*sizeof(double));
    }

memory deallocation for 2D arrays:

    for(i=0; i<150;i++)
    {
        free(cross_norm[i]);
    }

    free(cross_norm);

What is the difference between `git merge` and `git merge --no-ff`?

Other answers indicate perfectly well that --no-ff results in a merge commit. This retains historical information about the feature branch which is useful since feature branches are regularly cleaned up and deleted.

This answer may provide context for when to use or not to use --no-ff.

Merging from feature into the main branch: use --no-ff

Worked example:

$ git checkout -b NewFeature
[work...work...work]
$ git commit -am  "New feature complete!"
$ git checkout main
$ git merge --no-ff NewFeature
$ git push origin main
$ git branch -d NewFeature

Merging changes from main into feature branch: leave off --no-ff

Worked example:

$ git checkout -b NewFeature
[work...work...work]
[New changes made for HotFix in the main branch! Lets get them...]
$ git commit -am  "New feature in progress"
$ git pull origin main
[shortcut for "git fetch origin main", "git merge origin main"]

Import text file as single character string

Too bad that Sharon's solution cannot be used anymore. I've added Josh O'Brien's solution with asieira's modification to my .Rprofile file:

read.text = function(pathname)
{
    return (paste(readLines(pathname), collapse="\n"))
}

and use it like this: txt = read.text('path/to/my/file.txt'). I couldn't replicate bumpkin's (28 oct. 14) finding, and writeLines(txt) showed the contents of file.txt. Also, after write(txt, '/tmp/out') the command diff /tmp/out path/to/my/file.txt reported no differences.

Best way to "negate" an instanceof

No, there is no better way; yours is canonical.

How to align two elements on the same line without changing HTML

_x000D_
_x000D_
div {
  display: flex;
  justify-content: space-between;
}
_x000D_
<div>
  <p>Item one</p>
  <a>Item two</a>
</div>
_x000D_
_x000D_
_x000D_

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

When you want to create an external_table, all field's name must be written in UPPERCASE.

Done.

If a folder does not exist, create it

You can use a try/catch clause and check to see if it exist:

  try
  {
    if (!Directory.Exists(path))
    {
       // Try to create the directory.
       DirectoryInfo di = Directory.CreateDirectory(path);
    }
  }
  catch (IOException ioex)
  {
     Console.WriteLine(ioex.Message);
  }

How can I write maven build to add resources to classpath?

A cleaner alternative of putting your config file into a subfolder of src/main/resources would be to enhance your classpath locations. This is extremely easy to do with Maven.

For instance, place your property file in a new folder src/main/config, and add the following to your pom:

 <build>
    <resources>
        <resource>
            <directory>src/main/config</directory>
        </resource>
    </resources>
 </build>

From now, every files files under src/main/config is considered as part of your classpath (note that you can exclude some of them from the final jar if needed: just add in the build section:

    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>my-config.properties</exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>

so that my-config.properties can be found in your classpath when you run your app from your IDE, but will remain external from your jar in your final distribution).

How to determine whether code is running in DEBUG / RELEASE build?

In xcode 7, there is a field under Apple LLVM 7.0 - preprocessing, which called "Preprocessors Macros Not Used In Precompiled..." I put DEBUG in front of Debug and it works for me by using below code:

#ifdef DEBUG
    NSString* const kURL = @"http://debug.com";
#else
    NSString* const kURL = @"http://release.com";
#endif

How to check if dropdown is disabled?

I was searching for something like this, because I've got to check which of all my selects are disabled.

So I use this:

let select= $("select");

for (let i = 0; i < select.length; i++) {
    const element = select[i];
    if(element.disabled == true ){
        console.log(element)
    }
}

What is the difference between Document style and RPC style communication?

Can some body explain me the differences between a Document style and RPC style webservices?

There are two communication style models that are used to translate a WSDL binding to a SOAP message body. They are: Document & RPC

The advantage of using a Document style model is that you can structure the SOAP body any way you want it as long as the content of the SOAP message body is any arbitrary XML instance. The Document style is also referred to as Message-Oriented style.

However, with an RPC style model, the structure of the SOAP request body must contain both the operation name and the set of method parameters. The RPC style model assumes a specific structure to the XML instance contained in the message body.

Furthermore, there are two encoding use models that are used to translate a WSDL binding to a SOAP message. They are: literal, and encoded

When using a literal use model, the body contents should conform to a user-defined XML-schema(XSD) structure. The advantage is two-fold. For one, you can validate the message body with the user-defined XML-schema, moreover, you can also transform the message using a transformation language like XSLT.

With a (SOAP) encoded use model, the message has to use XSD datatypes, but the structure of the message need not conform to any user-defined XML schema. This makes it difficult to validate the message body or use XSLT based transformations on the message body.

The combination of the different style and use models give us four different ways to translate a WSDL binding to a SOAP message.

Document/literal
Document/encoded
RPC/literal
RPC/encoded

I would recommend that you read this article entitled Which style of WSDL should I use? by Russell Butek which has a nice discussion of the different style and use models to translate a WSDL binding to a SOAP message, and their relative strengths and weaknesses.

Once the artifacts are received, in both styles of communication, I invoke the method on the port. Now, this does not differ in RPC style and Document style. So what is the difference and where is that difference visible?

The place where you can find the difference is the "RESPONSE"!

RPC Style:

package com.sample;

import java.util.ArrayList;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

@WebService
@SOAPBinding(style=Style.RPC)
public interface StockPrice { 

    public String getStockPrice(String stockName); 

    public ArrayList getStockPriceList(ArrayList stockNameList); 
}

The SOAP message for second operation will have empty output and will look like:

RPC Style Response:

<ns2:getStockPriceListResponse 
       xmlns:ns2="http://sample.com/">
    <return/>
</ns2:getStockPriceListResponse>
</S:Body>
</S:Envelope>

Document Style:

package com.sample;

import java.util.ArrayList;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

@WebService
@SOAPBinding(style=Style.DOCUMENT)
public interface StockPrice {

    public String getStockPrice(String stockName);

    public ArrayList getStockPriceList(ArrayList stockNameList);
}

If we run the client for the above SEI, the output is:

123 [123, 456]

This output shows that ArrayList elements are getting exchanged between the web service and client. This change has been done only by the changing the style attribute of SOAPBinding annotation. The SOAP message for the second method with richer data type is shown below for reference:

Document Style Response:

<ns2:getStockPriceListResponse 
       xmlns:ns2="http://sample.com/">
<return xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xsi:type="xs:string">123</return>
<return xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xsi:type="xs:string">456</return>
</ns2:getStockPriceListResponse>
</S:Body>
</S:Envelope>

Conclusion

  • As you would have noticed in the two SOAP response messages that it is possible to validate the SOAP response message in case of DOCUMENT style but not in RPC style web services.
  • The basic disadvantage of using RPC style is that it doesn’t support richer data types and that of using Document style is that it brings some complexity in the form of XSD for defining the richer data types.
  • The choice of using one out of these depends upon the operation/method requirements and the expected clients.

Similarly, in what way SOAP over HTTP differ from XML over HTTP? After all SOAP is also XML document with SOAP namespace. So what is the difference here?

Why do we need a standard like SOAP? By exchanging XML documents over HTTP, two programs can exchange rich, structured information without the introduction of an additional standard such as SOAP to explicitly describe a message envelope format and a way to encode structured content.

SOAP provides a standard so that developers do not have to invent a custom XML message format for every service they want to make available. Given the signature of the service method to be invoked, the SOAP specification prescribes an unambiguous XML message format. Any developer familiar with the SOAP specification, working in any programming language, can formulate a correct SOAP XML request for a particular service and understand the response from the service by obtaining the following service details.

  • Service name
  • Method names implemented by the service
  • Method signature of each method
  • Address of the service implementation (expressed as a URI)

Using SOAP streamlines the process for exposing an existing software component as a Web service since the method signature of the service identifies the XML document structure used for both the request and the response.

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.

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

Built-in support since Handlebars 1.0rc1

Support for this functionality has been added to Handlebars.js, so there is no more need for external helpers.

How to use it

For arrays:

{{#each myArray}}
    Index: {{@index}} Value = {{this}}
{{/each}}

For objects:

{{#each myObject}}
    Key: {{@key}} Value = {{this}}
{{/each}}

Note that only properties passing the hasOwnProperty test will be enumerated.

how to bold words within a paragraph in HTML/CSS?

<p><b> BOLD TEXT </b> not in bold </p>;

Include the text you want to be in bold between <b>...</b>

Getting attributes of a class

If you want to "get" an attribute, there is a very simple answer, which should be obvious: getattr

class MyClass(object):
a = '12'
b = '34'
def myfunc(self):
    return self.a

>>> getattr(MyClass, 'a')
'12'

>>> getattr(MyClass, 'myfunc')
<function MyClass.myfunc at 0x10de45378>

It works dandy both in Python 2.7 and Python 3.x.

If you want a list of these items, you will still need to use inspect.

Opening database file from within SQLite command-line shell

create different db files using
      >sqlite3 test1.db
sqlite> create table test1 (name text);
sqlite> insert into test1 values('sourav');
sqlite>.exit
      >sqlite3 test2.db
sqlite> create table test2 (eid integer);
sqlite> insert into test2 values (6);
sqlite>.exit
      >sqlite
SQLite version 3.8.5 2014-06-04 14:06:34
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .open test1.db
sqlite> select * from test1;
sourav
sqlite> .open test2.db
sqlite> select * from test1;
Error: no such table: test1
sqlite> select * from test2;
6
sqlite> .exit
      >

Thank YOU.

What does API level mean?

This actually sums it up pretty nicely.

API Levels generally mean that as a programmer, you can communicate with the devices' built in functions and functionality. As the API level increases, functionality adds up (although some of it can get deprecated).

Choosing an API level for an application development should take at least two thing into account:

  1. Current distribution - How many devices can actually support my application, if it was developed for API level 9, it cannot run on API level 8 and below, then "only" around 60% of devices can run it (true to the date this post was made).
  2. Choosing a lower API level may support more devices but gain less functionality for your app. you may also work harder to achieve features you could've easily gained if you chose higher API level.

Android API levels can be divided to five main groups (not scientific, but what the heck):

  1. Android 1.5 - 2.3 (Cupcake to Gingerbread) - (API levels 3-10) - Android made specifically for smartphones.
  2. Android 3.0 - 3.2 (Honeycomb) (API levels 11-13) - Android made for tablets.
  3. Android 4.0 - 4.4 (KitKat) - (API levels 14-19) - A big merge with tons of additional functionality, totally revamped Android version, for both phone and tablets.
  4. Android 5.0 - 5.1 (Lollipop) - (API levels 21-22) - Material Design introduced.
  5. Android 6.0 - 6.… (Marshmallow) - (API levels 23-…) - Runtime Permissions,Apache HTTP Client Removed

Difference between .on('click') vs .click()

No, there isn't.
The point of on() is its other overloads, and the ability to handle events that don't have shortcut methods.

Call An Asynchronous Javascript Function Synchronously

Async functions, a feature in ES2017, make async code look sync by using promises (a particular form of async code) and the await keyword. Also notice in the code examples below the keyword async in front of the function keyword that signifies an async/await function. The await keyword won't work without being in a function pre-fixed with the async keyword. Since currently there is no exception to this that means no top level awaits will work (top level awaits meaning an await outside of any function). Though there is a proposal for top-level await.

ES2017 was ratified (i.e. finalized) as the standard for JavaScript on June 27th, 2017. Async await may already work in your browser, but if not you can still use the functionality using a javascript transpiler like babel or traceur. Chrome 55 has full support of async functions. So if you have a newer browser you may be able to try out the code below.

See kangax's es2017 compatibility table for browser compatibility.

Here's an example async await function called doAsync which takes three one second pauses and prints the time difference after each pause from the start time:

_x000D_
_x000D_
function timeoutPromise (time) {_x000D_
  return new Promise(function (resolve) {_x000D_
    setTimeout(function () {_x000D_
      resolve(Date.now());_x000D_
    }, time)_x000D_
  })_x000D_
}_x000D_
_x000D_
function doSomethingAsync () {_x000D_
  return timeoutPromise(1000);_x000D_
}_x000D_
_x000D_
async function doAsync () {_x000D_
  var start = Date.now(), time;_x000D_
  console.log(0);_x000D_
  time = await doSomethingAsync();_x000D_
  console.log(time - start);_x000D_
  time = await doSomethingAsync();_x000D_
  console.log(time - start);_x000D_
  time = await doSomethingAsync();_x000D_
  console.log(time - start);_x000D_
}_x000D_
_x000D_
doAsync();
_x000D_
_x000D_
_x000D_

When the await keyword is placed before a promise value (in this case the promise value is the value returned by the function doSomethingAsync) the await keyword will pause execution of the function call, but it won't pause any other functions and it will continue executing other code until the promise resolves. After the promise resolves it will unwrap the value of the promise and you can think of the await and promise expression as now being replaced by that unwrapped value.

So, since await just pauses waits for then unwraps a value before executing the rest of the line you can use it in for loops and inside function calls like in the below example which collects time differences awaited in an array and prints out the array.

_x000D_
_x000D_
function timeoutPromise (time) {_x000D_
  return new Promise(function (resolve) {_x000D_
    setTimeout(function () {_x000D_
      resolve(Date.now());_x000D_
    }, time)_x000D_
  })_x000D_
}_x000D_
_x000D_
function doSomethingAsync () {_x000D_
  return timeoutPromise(1000);_x000D_
}_x000D_
_x000D_
// this calls each promise returning function one after the other_x000D_
async function doAsync () {_x000D_
  var response = [];_x000D_
  var start = Date.now();_x000D_
  // each index is a promise returning function_x000D_
  var promiseFuncs= [doSomethingAsync, doSomethingAsync, doSomethingAsync];_x000D_
  for(var i = 0; i < promiseFuncs.length; ++i) {_x000D_
    var promiseFunc = promiseFuncs[i];_x000D_
    response.push(await promiseFunc() - start);_x000D_
    console.log(response);_x000D_
  }_x000D_
  // do something with response which is an array of values that were from resolved promises._x000D_
  return response_x000D_
}_x000D_
_x000D_
doAsync().then(function (response) {_x000D_
  console.log(response)_x000D_
})
_x000D_
_x000D_
_x000D_

The async function itself returns a promise so you can use that as a promise with chaining like I do above or within another async await function.

The function above would wait for each response before sending another request if you would like to send the requests concurrently you can use Promise.all.

_x000D_
_x000D_
// no change_x000D_
function timeoutPromise (time) {_x000D_
  return new Promise(function (resolve) {_x000D_
    setTimeout(function () {_x000D_
      resolve(Date.now());_x000D_
    }, time)_x000D_
  })_x000D_
}_x000D_
_x000D_
// no change_x000D_
function doSomethingAsync () {_x000D_
  return timeoutPromise(1000);_x000D_
}_x000D_
_x000D_
// this function calls the async promise returning functions all at around the same time_x000D_
async function doAsync () {_x000D_
  var start = Date.now();_x000D_
  // we are now using promise all to await all promises to settle_x000D_
  var responses = await Promise.all([doSomethingAsync(), doSomethingAsync(), doSomethingAsync()]);_x000D_
  return responses.map(x=>x-start);_x000D_
}_x000D_
_x000D_
// no change_x000D_
doAsync().then(function (response) {_x000D_
  console.log(response)_x000D_
})
_x000D_
_x000D_
_x000D_

If the promise possibly rejects you can wrap it in a try catch or skip the try catch and let the error propagate to the async/await functions catch call. You should be careful not to leave promise errors unhandled especially in Node.js. Below are some examples that show off how errors work.

_x000D_
_x000D_
function timeoutReject (time) {_x000D_
  return new Promise(function (resolve, reject) {_x000D_
    setTimeout(function () {_x000D_
      reject(new Error("OOPS well you got an error at TIMESTAMP: " + Date.now()));_x000D_
    }, time)_x000D_
  })_x000D_
}_x000D_
_x000D_
function doErrorAsync () {_x000D_
  return timeoutReject(1000);_x000D_
}_x000D_
_x000D_
var log = (...args)=>console.log(...args);_x000D_
var logErr = (...args)=>console.error(...args);_x000D_
_x000D_
async function unpropogatedError () {_x000D_
  // promise is not awaited or returned so it does not propogate the error_x000D_
  doErrorAsync();_x000D_
  return "finished unpropogatedError successfully";_x000D_
}_x000D_
_x000D_
unpropogatedError().then(log).catch(logErr)_x000D_
_x000D_
async function handledError () {_x000D_
  var start = Date.now();_x000D_
  try {_x000D_
    console.log((await doErrorAsync()) - start);_x000D_
    console.log("past error");_x000D_
  } catch (e) {_x000D_
    console.log("in catch we handled the error");_x000D_
  }_x000D_
  _x000D_
  return "finished handledError successfully";_x000D_
}_x000D_
_x000D_
handledError().then(log).catch(logErr)_x000D_
_x000D_
// example of how error propogates to chained catch method_x000D_
async function propogatedError () {_x000D_
  var start = Date.now();_x000D_
  var time = await doErrorAsync() - start;_x000D_
  console.log(time - start);_x000D_
  return "finished propogatedError successfully";_x000D_
}_x000D_
_x000D_
// this is what prints propogatedError's error._x000D_
propogatedError().then(log).catch(logErr)
_x000D_
_x000D_
_x000D_

If you go here you can see the finished proposals for upcoming ECMAScript versions.

An alternative to this that can be used with just ES2015 (ES6) is to use a special function which wraps a generator function. Generator functions have a yield keyword which may be used to replicate the await keyword with a surrounding function. The yield keyword and generator function are a lot more general purpose and can do many more things then just what the async await function does. If you want a generator function wrapper that can be used to replicate async await I would check out co.js. By the way co's function much like async await functions return a promise. Honestly though at this point browser compatibility is about the same for both generator functions and async functions so if you just want the async await functionality you should use Async functions without co.js.

Browser support is actually pretty good now for Async functions (as of 2017) in all major current browsers (Chrome, Safari, and Edge) except IE.

Javascript: The prettiest way to compare one value against multiple values

Why not using indexOf from array like bellow?

if ([foo, bar].indexOf(foobar) !== -1) {
    // do something
}

Just plain Javascript, no frameworks or libraries but it will not work on IE < 9.

Facebook share link without JavaScript

You could use

<a href="https://www.facebook.com/sharer/sharer.php?u=#url" target="_blank">Share</a>

Currently there is no sharing option without passing current url as a parameter. You can use an indirect way to achieve this.

  1. Create a server side page for example: "/sharer.aspx"
  2. Link this page whenever you want the share functionality.
  3. In the "sharer.aspx" get the refering url, and redirect user to "https://www.facebook.com/sharer/sharer.php?u={referer}"

Example ASP .Net code:

public partial class Sharer : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var referer = Request.UrlReferrer.ToString();

        if(string.IsNullOrEmpty(referer))
        {
            // some error logic
            return;
        }

        Response.Clear();
        Response.Redirect("https://www.facebook.com/sharer/sharer.php?u=" + HttpUtility.UrlEncode(referer));
        Response.End();
    }
}

How to present a simple alert message in java?

If you don't like "verbosity" you can always wrap your code in a short method:

private void msgbox(String s){
   JOptionPane.showMessageDialog(null, s);
}

and the usage:

msgbox("don't touch that!");

"Unable to locate tools.jar" when running ant

The order of items in the PATH matters. If there are multiple entries for various java installations, the first one in your PATH will be used.

I have had similar issues after installing a product, like Oracle, that puts it's JRE at the beginning of the PATH.

Ensure that the JDK you want to be loaded is the first entry in your PATH (or at least that it appears before C:\Program Files\Java\jre6\bin appears).

C++ class forward declaration

class tile_tree_apple should be defined in a separate .h file.

tta.h:
#include "tile.h"

class tile_tree_apple : public tile
{
      public:
          tile onDestroy() {return *new tile_grass;};
          tile tick() {if (rand()%20==0) return *new tile_tree;};
          void onCreate() {health=rand()%5+4; type=TILET_TREE_APPLE;}; 
          tile onUse() {return *new tile_tree;};       
};

file tt.h
#include "tile.h"

class tile_tree : public tile
{
      public:
          tile onDestroy() {return *new tile_grass;};
          tile tick() {if (rand()%20==0) return *new tile_tree_apple;};
          void onCreate() {health=rand()%5+4; type=TILET_TREE;};        
};

another thing: returning a tile and not a tile reference is not a good idea, unless a tile is a primitive or very "small" type.

Test if a string contains a word in PHP?

_x000D_
_x000D_
use _x000D_
_x000D_
if(stripos($str,'job')){_x000D_
   // do your work_x000D_
}
_x000D_
_x000D_
_x000D_

Excluding Maven dependencies

You can utilize the dependency management mechanism.

If you create entries in the <dependencyManagement> section of your pom for spring-security-web and spring-web with the desired 3.1.0 version set the managed version of the artifact will override those specified in the transitive dependency tree.

I'm not sure if that really saves you any code, but it is a cleaner solution IMO.

Linux/Unix command to determine if process is running?

Putting the various suggestions together, the cleanest version I was able to come up with (without unreliable grep which triggers parts of words) is:

kill -0 $(pidof mysql) 2> /dev/null || echo "Mysql ain't runnin' message/actions"

kill -0 doesn't kill the process but checks if it exists and then returns true, if you don't have pidof on your system, store the pid when you launch the process:

$ mysql &
$ echo $! > pid_stored

then in the script:

kill -0 $(cat pid_stored) 2> /dev/null || echo "Mysql ain't runnin' message/actions"

UIView Hide/Show with animation

To fade out:

Objective-C

[UIView animateWithDuration:0.3 animations:^{
    button.alpha = 0;
} completion: ^(BOOL finished) {//creates a variable (BOOL) called "finished" that is set to *YES* when animation IS completed.
    button.hidden = finished;//if animation is finished ("finished" == *YES*), then hidden = "finished" ... (aka hidden = *YES*)
}];

Swift 2

UIView.animateWithDuration(0.3, animations: {
    button.alpha = 0
}) { (finished) in
    button.hidden = finished
}

Swift 3, 4, 5

UIView.animate(withDuration: 0.3, animations: {
    button.alpha = 0
}) { (finished) in
    button.isHidden = finished
}

To fade in:

Objective-C

button.alpha = 0;
button.hidden = NO;
[UIView animateWithDuration:0.3 animations:^{
    button.alpha = 1;
}];

Swift 2

button.alpha = 0
button.hidden = false
UIView.animateWithDuration(0.3) {
    button.alpha = 1
}

Swift 3, 4, 5

button.alpha = 0
button.isHidden = false
UIView.animate(withDuration: 0.3) {
    button.alpha = 1
}

Is it possible to indent JavaScript code in Notepad++?

JSTool is the best for stability.

Steps:

  1. Select menu Plugins>Plugin Manager>Show Plugin Manager
  2. Check to JSTool checkbox > Install > Restart Notepad++
  3. Open js file > Plugins > JSTool > JSFormat
    screenshot

Reference:

batch to copy files with xcopy

After testing most of the switches this worked for me:

xcopy C:\folder1 C:\folder2\folder1 /t /e /i /y

This will copy the folder folder1 into the folder folder2. So the directory tree would look like:

C:
   Folder1
   Folder2
      Folder1

LINQ Using Max() to select a single row

More one example:

Follow:

 qryAux = (from q in qryAux where
            q.OrdSeq == (from pp in Sessao.Query<NameTable>() where pp.FieldPk
            == q.FieldPk select pp.OrdSeq).Max() select q);

Equals:

 select t.*   from nametable t  where t.OrdSeq =
        (select max(t2.OrdSeq) from nametable t2 where t2.FieldPk= t.FieldPk)

Spacing between elements

If you want vertical spacing between elements, use a margin.

Don't add extra elements if you don't need to.

jQuery - Appending a div to body, the body is the object?

Using jQuery appendTo try this:

var holdyDiv = $('<div></div>').attr('id', 'holdy');
holdyDiv.appendTo('body');

JSON for List of int

Assuming your ints are 0, 375, 668,5 and 6:

{
    "Id": "610",
    "Name": "15",
    "Description": "1.99",
    "ItemModList": [
                       0,
                       375,
                       668,
                       5,
                       6
                   ]
}

I suggest that you change "Id": "610" to "Id": 610 since it is a integer/long and not a string. You can read more about the JSON format and examples here http://json.org/

diff current working copy of a file with another branch's committed copy

You're trying to compare your working tree with a particular branch name, so you want this:

git diff master -- foo

Which is from this form of git-diff (see the git-diff manpage)

   git diff [--options] <commit> [--] [<path>...]
       This form is to view the changes you have in your working tree
       relative to the named <commit>. You can use HEAD to compare it with
       the latest commit, or a branch name to compare with the tip of a
       different branch.

FYI, there is also a --cached (aka --staged) option for viewing the diff of what you've staged, rather than everything in your working tree:

   git diff [--options] --cached [<commit>] [--] [<path>...]
       This form is to view the changes you staged for the next commit
       relative to the named <commit>.
       ...
       --staged is a synonym of --cached.

Extract text from a string

Using -replace

 $string = '% O0033(SUB RAD MSD 50R III) G91G1X-6.4Z-2.F500 G3I6.4Z-8.G3I6.4 G3R3.2X6.4F500 G91G0Z5. G91G1X-10.4 G3I10.4 G3R5.2X10.4 G90G0Z2. M99 %'
 $program = $string -replace '^%\sO\d{4}\((.+?)\).+$','$1'
 $program

SUB RAD MSD 50R III

T-SQL: How to Select Values in Value List that are NOT IN the Table?

When you do not want to have the emails in the list that are in the database you'll can do the following:

select    u.name
        , u.EMAIL
        , a.emailadres
        , case when a.emailadres is null then 'Not exists'
               else 'Exists'
          end as 'Existence'
from      users u
          left join (          select 'email1' as emailadres
                     union all select 'email2'
                     union all select 'email3') a
            on  a.emailadres = u.EMAIL)

this way you'll get a result like

name | email  | emailadres | existence
-----|--------|------------|----------
NULL | NULL   | [email protected]    | Not exists
Jan  | [email protected] | [email protected]     | Exists

Using the IN or EXISTS operators are more heavy then the left join in this case.

Good luck :)

Jackson: how to prevent field serialization

You can mark it as @JsonIgnore.

With 1.9, you can add @JsonIgnore for getter, @JsonProperty for setter, to make it deserialize but not serialize.

How to convert Calendar to java.sql.Date in Java?

Here is a simple way to convert Calendar values into Date instances.

Calendar C = new GregorianCalendar(1993,9,21);

Date DD = C.getTime();

System.out.println(DD);

mysql SELECT IF statement with OR

IF(compliment IN('set','Y',1), 'Y', 'N') AS customer_compliment

Will do the job as Buttle Butkus suggested.

How to move the layout up when the soft keyboard is shown android

This works like a charm for me

getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);