Programs & Examples On #Totals

Summing radio input values

Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:

<script type="text/javascript">   $(function() { //jQuery trick to say after all the HTML is parsed.     $("input[type=radio]").click(function() {       var total = 0;       $("input[type=radio]:checked").each(function() {         total += parseFloat($(this).val());       });        $("#totalSum").val(total);     });   }); </script> 

EDIT: This code works for me

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body>   <strong>Choose a base package:</strong>   <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942   <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313   <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829   <strong>Choose an add on:</strong>   <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0   <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146)   <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455)   <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764)   <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073)   <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382)   <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691)   <strong>Your total is:</strong>   <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" />   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>   <script type="text/javascript">       $("input[type=radio]").click(function() {         var total = 0;         $("input[type=radio]:checked").each(function() {           total += parseFloat($(this).val());         });          $("#totalSum").val(total);       });     </script> </body> </html> 

AttributeError: 'dict' object has no attribute 'predictors'

#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29

If "0" then leave the cell blank

You can change the number format of the column to this custom format:

0;-0;;@

which will hide all 0 values.

To do this, select the column, right-click > Format Cells > Custom.

Elasticsearch difference between MUST and SHOULD bool query

must means: The clause (query) must appear in matching documents. These clauses must match, like logical AND.

should means: At least one of these clauses must match, like logical OR.

Basically they are used like logical operators AND and OR. See this.

Now in a bool query:

must means: Clauses that must match for the document to be included.

should means: If these clauses match, they increase the _score; otherwise, they have no effect. They are simply used to refine the relevance score for each document.


Yes you can use multiple filters inside must.

android download pdf from url then open it with a pdf reader

This is the best method to download and view PDF file.You can just call it from anywhere as like

PDFTools.showPDFUrl(context, url);

here below put the code. It will works fine

public class PDFTools {
private static final String TAG = "PDFTools";
private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url=";
private static final String PDF_MIME_TYPE = "application/pdf";
private static final String HTML_MIME_TYPE = "text/html";


public static void showPDFUrl(final Context context, final String pdfUrl ) {
    if ( isPDFSupported( context ) ) {
        downloadAndOpenPDF(context, pdfUrl);
    } else {
        askToOpenPDFThroughGoogleDrive( context, pdfUrl );
    }
}


@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
    // Get filename
    //final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
    String filename = "";
    try {
        filename = new GetFileInfo().execute(pdfUrl).get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    // The place where the downloaded PDF file will be put
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
    Log.e(TAG,"File Path:"+tempFile);
    if ( tempFile.exists() ) {
        // If we have downloaded the file before, just go ahead and show it.
        openPDF( context, Uri.fromFile( tempFile ) );
        return;
    }

    // Show progress dialog while downloading
    final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ), context.getString( R.string.pdf_show_local_progress_content ), true );

    // Create the download request
    DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
    r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
    final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
    BroadcastReceiver onComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ( !progress.isShowing() ) {
                return;
            }
            context.unregisterReceiver( this );

            progress.dismiss();
            long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
            Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

            if ( c.moveToFirst() ) {
                int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                    openPDF( context, Uri.fromFile( tempFile ) );
                }
            }
            c.close();
        }
    };
    context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

    // Enqueue the request
    dm.enqueue( r );
}


public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
    new AlertDialog.Builder( context )
            .setTitle( R.string.pdf_show_online_dialog_title )
            .setMessage( R.string.pdf_show_online_dialog_question )
            .setNegativeButton( R.string.pdf_show_online_dialog_button_no, null )
            .setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    openPDFThroughGoogleDrive(context, pdfUrl);
                }
            })
            .show();
}

public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
    context.startActivity( i );
}

public static final void openPDF(Context context, Uri localUri ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType( localUri, PDF_MIME_TYPE );
    context.startActivity( i );
}

public static boolean isPDFSupported( Context context ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
    i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
    return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
}

// get File name from url
static class GetFileInfo extends AsyncTask<String, Integer, String>
{
    protected String doInBackground(String... urls)
    {
        URL url;
        String filename = null;
        try {
            url = new URL(urls[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            conn.setInstanceFollowRedirects(false);
            if(conn.getHeaderField("Content-Disposition")!=null){
                String depo = conn.getHeaderField("Content-Disposition");

                String depoSplit[] = depo.split("filename=");
                filename = depoSplit[1].replace("filename=", "").replace("\"", "").trim();
            }else{
                filename = "download.pdf";
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
        }
        return filename;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // use result as file name
    }
}

}

try it. it will works, enjoy

Pandas - Plotting a stacked Bar Chart

That should help

df.groupby(['NFF', 'ABUSE']).size().unstack().plot(kind='bar', stacked=True)

How to use multiple conditions (With AND) in IIF expressions in ssrs

You don't need an IIF() at all here. The comparisons return true or false anyway.

Also, since this row visibility is on a group row, make sure you use the same aggregate function on the fields as you use in the fields in the row. So if your group row shows sums, then you'd put this in the Hidden property.

=Sum(Fields!OpeningStock.Value) = 0 And
Sum(Fields!GrossDispatched.Value) = 0 And 
Sum(Fields!TransferOutToMW.Value) = 0 And
Sum(Fields!TransferOutToDW.Value) = 0 And
Sum(Fields!TransferOutToOW.Value) = 0 And
Sum(Fields!NetDispatched.Value) = 0 And
Sum(Fields!QtySold.Value) = 0 And
Sum(Fields!StockAdjustment.Value) = 0 And
Sum(Fields!ClosingStock.Value) = 0

But with the above version, if one record has value 1 and one has value -1 and all others are zero then sum is also zero and the row could be hidden. If that's not what you want you could write a more complex expression:

=Sum(
    IIF(
        Fields!OpeningStock.Value=0 AND
        Fields!GrossDispatched.Value=0 AND
        Fields!TransferOutToMW.Value=0 AND
        Fields!TransferOutToDW.Value=0 AND 
        Fields!TransferOutToOW.Value=0 AND
        Fields!NetDispatched.Value=0 AND
        Fields!QtySold.Value=0 AND
        Fields!StockAdjustment.Value=0 AND
        Fields!ClosingStock.Value=0,
        0,
        1
    )
) = 0

This is essentially a fancy way of counting the number of rows in which any field is not zero. If every field is zero for every row in the group then the expression returns true and the row is hidden.

TSQL PIVOT MULTIPLE COLUMNS

Since you want to pivot multiple columns of data, I would first suggest unpivoting the result, score and grade columns so you don't have multiple columns but you will have multiple rows.

Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:

select ratio, col, value
from GRAND_TOTALS
cross apply
(
  select 'result', cast(result as varchar(10)) union all
  select 'score', cast(score as varchar(10)) union all
  select 'grade', grade
) c(col, value)

See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:

select ratio = col,
  [current ratio], [gearing ratio], [performance ratio], total
from
(
  select ratio, col, value
  from GRAND_TOTALS
  cross apply
  (
    select 'result', cast(result as varchar(10)) union all
    select 'score', cast(score as varchar(10)) union all
    select 'grade', grade
  ) c(col, value)
) d
pivot
(
  max(value)
  for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;

See SQL Fiddle with Demo. This will give you the result:

|  RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO |     TOTAL |
|--------|---------------|---------------|-------------------|-----------|
|  grade |          Good |          Good |      Satisfactory |      Good |
| result |       1.29400 |       0.33840 |           0.04270 |    (null) |
|  score |      60.00000 |      70.00000 |          50.00000 | 180.00000 |

Counting words in string

String.prototype.match returns an array, we can then check the length,

I find this method to be most descriptive

var str = 'one two three four five';

str.match(/\w+/g).length;

Increasing the Command Timeout for SQL command

Setting command timeout to 2 minutes.

 scGetruntotals.CommandTimeout = 120;

but you can optimize your stored Procedures to decrease that time! like

  • removing courser or while and etc
  • using paging
  • using #tempTable and @variableTable
  • optimizing joined tables

python max function using 'key' and lambda expression

Strongly simplified version of max:

def max(items, key=lambda x: x):
    current = item[0]
    for item in items:
        if key(item) > key(current):
            current = item
    return current

Regarding lambda:

>>> ident = lambda x: x
>>> ident(3)
3
>>> ident(5)
5

>>> times_two = lambda x: 2*x
>>> times_two(2)
4

Add a summary row with totals

You could use the ROLLUP operator

SELECT  CASE 
            WHEN (GROUPING([Type]) = 1) THEN 'Total'
            ELSE [Type] END AS [TYPE]
        ,SUM([Total Sales]) as Total_Sales
From    Before
GROUP BY
        [Type] WITH ROLLUP

how to get 2 digits after decimal point in tsql?

Try cast result to numeric

CAST(sum(cast(datediff(second, IEC.CREATE_DATE, IEC.STATUS_DATE) as float) / 60)
    AS numeric(10,2)) TotalSentMinutes

Input

1
2
3

Output

1.00
2.00
3.00

JS: Uncaught TypeError: object is not a function (onclick)

Since the behavior is kind of strange, I have done some testing on the behavior, and here's my result:

TL;DR

If you are:

  • In a form, and
  • uses onclick="xxx()" on an element
  • don't add id="xxx" or name="xxx" to that element
    • (e.g. <form><button id="totalbandwidth" onclick="totalbandwidth()">BAD</button></form> )

Here's are some test and their result:

Control sample (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <button onclick="totalbandwidth()">SUCCESS</button>
</form>
_x000D_
_x000D_
_x000D_

Add id to button (failed to call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <button id="totalbandwidth" onclick="totalbandwidth()">FAILED</button>
</form>
_x000D_
_x000D_
_x000D_

Add name to button (failed to call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <button name="totalbandwidth" onclick="totalbandwidth()">FAILED</button>
</form>
_x000D_
_x000D_
_x000D_

Add value to button (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
  <input type="button" value="totalbandwidth" onclick="totalbandwidth()" />SUCCESS
</form>
_x000D_
_x000D_
_x000D_

Add id to button, but not in a form (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<button id="totalbandwidth" onclick="totalbandwidth()">SUCCESS</button>
_x000D_
_x000D_
_x000D_

Add id to another element inside the form (can successfully call function)

_x000D_
_x000D_
function totalbandwidth(){ alert("The answer is no, the span will not affect button"); }
_x000D_
<form onsubmit="return false;">
<span name="totalbandwidth" >Will this span affect button? </span>
<button onclick="totalbandwidth()">SUCCESS</button>
</form>
_x000D_
_x000D_
_x000D_

How to rollback or commit a transaction in SQL Server

The good news is a transaction in SQL Server can span multiple batches (each exec is treated as a separate batch.)

You can wrap your EXEC statements in a BEGIN TRANSACTION and COMMIT but you'll need to go a step further and rollback if any errors occur.

Ideally you'd want something like this:

BEGIN TRY
    BEGIN TRANSACTION 
        exec( @sqlHeader)
        exec(@sqlTotals)
        exec(@sqlLine)
    COMMIT
END TRY
BEGIN CATCH

    IF @@TRANCOUNT > 0
        ROLLBACK
END CATCH

The BEGIN TRANSACTION and COMMIT I believe you are already familiar with. The BEGIN TRY and BEGIN CATCH blocks are basically there to catch and handle any errors that occur. If any of your EXEC statements raise an error, the code execution will jump to the CATCH block.

Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.

MySQL - sum column value(s) based on row from the same table

I think you're making this a bit more complicated than it needs to be.

SELECT
    ProductID,
    SUM(IF(PaymentMethod = 'Cash', Amount, 0)) AS 'Cash',
    -- snip
    SUM(Amount) AS Total
FROM
    Payments
WHERE
    SaleDate = '2012-02-10'
GROUP BY
    ProductID

Most efficient method to groupby on an array of objects

Let's fully answer the original question while reusing code that was already written (i.e., Underscore). You can do much more with Underscore if you combine its >100 functions. The following solution demonstrates this.

Step 1: group the objects in the array by an arbitrary combination of properties. This uses the fact that _.groupBy accepts a function that returns the group of an object. It also uses _.chain, _.pick, _.values, _.join and _.value. Note that _.value is not strictly needed here, because chained values will automatically unwrap when used as a property name. I'm including it to safeguard against confusion in case somebody tries to write similar code in a context where automatic unwrapping does not take place.

// Given an object, return a string naming the group it belongs to.
function category(obj) {
    return _.chain(obj).pick(propertyNames).values().join(' ').value();
}

// Perform the grouping.
const intermediate = _.groupBy(arrayOfObjects, category);

Given the arrayOfObjects in the original question and setting propertyNames to ['Phase', 'Step'], intermediate will get the following value:

{
    "Phase 1 Step 1": [
        { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
        { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" }
    ],
    "Phase 1 Step 2": [
        { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
        { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" }
    ],
    "Phase 2 Step 1": [
        { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
        { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" }
    ],
    "Phase 2 Step 2": [
        { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
        { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
    ]
}

Step 2: reduce each group to a single flat object and return the results in an array. Besides the functions we have seen before, the following code uses _.pluck, _.first, _.pick, _.extend, _.reduce and _.map. _.first is guaranteed to return an object in this case, because _.groupBy does not produce empty groups. _.value is necessary in this case.

// Sum two numbers, even if they are contained in strings.
const addNumeric = (a, b) => +a + +b;

// Given a `group` of objects, return a flat object with their common
// properties and the sum of the property with name `aggregateProperty`.
function summarize(group) {
    const valuesToSum = _.pluck(group, aggregateProperty);
    return _.chain(group).first().pick(propertyNames).extend({
        [aggregateProperty]: _.reduce(valuesToSum, addNumeric)
    }).value();
}

// Get an array with all the computed aggregates.
const result = _.map(intermediate, summarize);

Given the intermediate that we obtained before and setting aggregateProperty to Value, we get the result that the asker desired:

[
    { Phase: "Phase 1", Step: "Step 1", Value: 15 },
    { Phase: "Phase 1", Step: "Step 2", Value: 35 },
    { Phase: "Phase 2", Step: "Step 1", Value: 55 },
    { Phase: "Phase 2", Step: "Step 2", Value: 75 }
]

We can put this all together in a function that takes arrayOfObjects, propertyNames and aggregateProperty as parameters. Note that arrayOfObjects can actually also be a plain object with string keys, because _.groupBy accepts either. For this reason, I have renamed arrayOfObjects to collection.

function aggregate(collection, propertyNames, aggregateProperty) {
    function category(obj) {
        return _.chain(obj).pick(propertyNames).values().join(' ');
    }
    const addNumeric = (a, b) => +a + +b;
    function summarize(group) {
        const valuesToSum = _.pluck(group, aggregateProperty);
        return _.chain(group).first().pick(propertyNames).extend({
            [aggregateProperty]: _.reduce(valuesToSum, addNumeric)
        }).value();
    }
    return _.chain(collection).groupBy(category).map(summarize).value();
}

aggregate(arrayOfObjects, ['Phase', 'Step'], 'Value') will now give us the same result again.

We can take this a step further and enable the caller to compute any statistic over the values in each group. We can do this and also enable the caller to add arbitrary properties to the summary of each group. We can do all of this while making our code shorter. We replace the aggregateProperty parameter by an iteratee parameter and pass this straight to _.reduce:

function aggregate(collection, propertyNames, iteratee) {
    function category(obj) {
        return _.chain(obj).pick(propertyNames).values().join(' ');
    }
    function summarize(group) {
        return _.chain(group).first().pick(propertyNames)
            .extend(_.reduce(group, iteratee)).value();
    }
    return _.chain(collection).groupBy(category).map(summarize).value();
}

In effect, we move some of the responsibility to the caller; she must provide an iteratee that can be passed to _.reduce, so that the call to _.reduce will produce an object with the aggregate properties she wants to add. For example, we obtain the same result as before with the following expression:

aggregate(arrayOfObjects, ['Phase', 'Step'], (memo, value) => ({
    Value: +memo.Value + +value.Value
}));

For an example of a slightly more sophisticated iteratee, suppose that we want to compute the maximum Value of each group instead of the sum, and that we want to add a Tasks property that lists all the values of Task that occur in the group. Here's one way we can do this, using the last version of aggregate above (and _.union):

aggregate(arrayOfObjects, ['Phase', 'Step'], (memo, value) => ({
    Value: Math.max(memo.Value, value.Value),
    Tasks: _.union(memo.Tasks || [memo.Task], [value.Task])
}));

We obtain the following result:

[
    { Phase: "Phase 1", Step: "Step 1", Value: 10, Tasks: [ "Task 1", "Task 2" ] },
    { Phase: "Phase 1", Step: "Step 2", Value: 20, Tasks: [ "Task 1", "Task 2" ] },
    { Phase: "Phase 2", Step: "Step 1", Value: 30, Tasks: [ "Task 1", "Task 2" ] },
    { Phase: "Phase 2", Step: "Step 2", Value: 40, Tasks: [ "Task 1", "Task 2" ] }
]

Credit to @much2learn, who also posted an answer that can handle arbitrary reducing functions. I wrote a couple more SO answers that demonstrate how one can achieve sophisticated things by combining multiple Underscore functions:

Converting string to number in javascript/jQuery

var string = 123 (is string),

parseInt(parameter is string);

var string = '123';

var int= parseInt(string );

console.log(int);  //Output will be 123.

Text-align class for inside a table

Here is a short and sweet answer with an example.

_x000D_
_x000D_
table{_x000D_
    width: 100%;_x000D_
}_x000D_
table td, table th {_x000D_
    border: 1px solid #000;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<body>_x000D_
  <table>_x000D_
    <tr>_x000D_
      <th class="text-left">Text align left.</th>_x000D_
      <th class="text-center">Text align center.</th>_x000D_
      <th class="text-right">Text align right.</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td class="text-left">Text align left.</td>_x000D_
      <td class="text-center">Text align center.</td>_x000D_
      <td class="text-right">Text align right.</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to use RANK() in SQL Server

Select T.Tamil, T.English, T.Maths, T.Total, Dense_Rank()Over(Order by T.Total Desc) as Std_Rank From (select Tamil,English,Maths,(Tamil+English+Maths) as Total From Student) as T

enter image description here

Run two async tasks in parallel and collect results in .NET 4.5

To answer this point:

I want Sleep to be an async method so it can await other methods

you can maybe rewrite the Sleep function like this:

private static async Task<int> Sleep(int ms)
{
    Console.WriteLine("Sleeping for " + ms);
    var task = Task.Run(() => Thread.Sleep(ms));
    await task;
    Console.WriteLine("Sleeping for " + ms + "END");
    return ms;
}

static void Main(string[] args)
{
    Console.WriteLine("Starting");

    var task1 = Sleep(2000);
    var task2 = Sleep(1000);

    int totalSlept = task1.Result +task2.Result;

    Console.WriteLine("Slept for " + totalSlept + " ms");
    Console.ReadKey();
}

running this code will output :

Starting
Sleeping for 2000
Sleeping for 1000
*(one second later)*
Sleeping for 1000END
*(one second later)*
Sleeping for 2000END
Slept for 3000 ms

JavaScript: function returning an object

In JavaScript, most functions are both callable and instantiable: they have both a [[Call]] and [[Construct]] internal methods.

As callable objects, you can use parentheses to call them, optionally passing some arguments. As a result of the call, the function can return a value.

var player = makeGamePlayer("John Smith", 15, 3);

The code above calls function makeGamePlayer and stores the returned value in the variable player. In this case, you may want to define the function like this:

function makeGamePlayer(name, totalScore, gamesPlayed) {
  // Define desired object
  var obj = {
    name:  name,
    totalScore: totalScore,
    gamesPlayed: gamesPlayed
  };
  // Return it
  return obj;
}

Additionally, when you call a function you are also passing an additional argument under the hood, which determines the value of this inside the function. In the case above, since makeGamePlayer is not called as a method, the this value will be the global object in sloppy mode, or undefined in strict mode.

As constructors, you can use the new operator to instantiate them. This operator uses the [[Construct]] internal method (only available in constructors), which does something like this:

  1. Creates a new object which inherits from the .prototype of the constructor
  2. Calls the constructor passing this object as the this value
  3. It returns the value returned by the constructor if it's an object, or the object created at step 1 otherwise.
var player = new GamePlayer("John Smith", 15, 3);

The code above creates an instance of GamePlayer and stores the returned value in the variable player. In this case, you may want to define the function like this:

function GamePlayer(name,totalScore,gamesPlayed) {
  // `this` is the instance which is currently being created
  this.name =  name;
  this.totalScore = totalScore;
  this.gamesPlayed = gamesPlayed;
  // No need to return, but you can use `return this;` if you want
}

By convention, constructor names begin with an uppercase letter.

The advantage of using constructors is that the instances inherit from GamePlayer.prototype. Then, you can define properties there and make them available in all instances

Reading Data From Database and storing in Array List object

try this

import java.sql.ResultSet;
import java.util.ArrayList;

import com.rcb.dbconnection.DbConnection;
import com.rcb.model.Docter;


public class DocterService {



public ArrayList<Docter> getAllDocters() {
    ArrayList<Docter> docters = new ArrayList<Docter>();

    try {
        String sql = "SELECT tbl_docters";

        ResultSet rs = db.getData(sql);
        while (rs.next()) {
            Docter docter = new Docter();

            docter.setD_id(rs.getInt("d_id"));
            docter.setD_FName(rs.getString("d_fname"));
            docter.setD_LName(rs.getString("d_lname"));

            docters.add(docter);

        }

    } catch (Exception e) {
        System.out.println("getAllDocters()");
        e.printStackTrace();
    }

    return (docters);
}

public static void main(String args[]) {
    DocterService ds = new DocterService();
    ArrayList<Docter> doctersList = ds.getAllDocters();
    String s[] = null;
    for (int i = 0; i < doctersList.size(); i++) {

        System.out.println(doctersList.get(i).getD_id());
        System.out.println(doctersList.get(i).getD_FName());
    }

  }
}

ORA-01652 Unable to extend temp segment by in tablespace

Create a new datafile by running the following command:

alter tablespace TABLE_SPACE_NAME add datafile 'D:\oracle\Oradata\TEMP04.dbf'            
   size 2000M autoextend on;

Get the difference between two dates both In Months and days in sql

Find out Year - Month- Day between two Days in Orale Sql


select 
trunc(trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD')))/12) years ,
trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD'))) 
-
(trunc(trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD')))/12))*12
months,
             round(To_date('20120101', 'YYYYMMDD')-add_months(to_date('19910228','YYYYMMDD'),
                           trunc(months_between(To_date('20120101', 'YYYYMMDD'),to_date('19910228','YYYYMMDD'))))) days
        from dual;

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

You can have a different goroutine that detects syscall.SIGINT and syscall.SIGTERM signals and relay them to a channel using signal.Notify. You can send a hook to that goroutine using a channel and save it in a function slice. When the shutdown signal is detected on the channel, you can execute those functions in the slice. This can be used to clean up the resources, wait for running goroutines to finish, persist data, or print partial run totals.

I wrote a small and simple utility to add and run hooks at shutdown. Hope it can be of help.

https://github.com/ankit-arora/go-utils/blob/master/go-shutdown-hook/shutdown-hook.go

You can do this in a 'defer' fashion.

example for shutting down a server gracefully :

srv := &http.Server{}

go_shutdown_hook.ADD(func() {
    log.Println("shutting down server")
    srv.Shutdown(nil)
    log.Println("shutting down server-done")
})

l, err := net.Listen("tcp", ":3090")

log.Println(srv.Serve(l))

go_shutdown_hook.Wait()

Partition Function COUNT() OVER possible using DISTINCT

Necromancing:

It's relativiely simple to emulate a COUNT DISTINCT over PARTITION BY with MAX via DENSE_RANK:

;WITH baseTable AS
(
    SELECT 'RM1' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM1' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR3' AS ADR
    UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
    UNION ALL SELECT 'RM3' AS RM, 'ADR2' AS ADR
)
,CTE AS
(
    SELECT RM, ADR, DENSE_RANK() OVER(PARTITION BY RM ORDER BY ADR) AS dr 
    FROM baseTable
)
SELECT
     RM
    ,ADR

    ,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY ADR) AS cnt1 
    ,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM) AS cnt2 
    -- Not supported
    --,COUNT(DISTINCT CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY CTE.ADR) AS cntDist
    ,MAX(CTE.dr) OVER (PARTITION BY CTE.RM ORDER BY CTE.RM) AS cntDistEmu 
FROM CTE

Note:
This assumes the fields in question are NON-nullable fields.
If there is one or more NULL-entries in the fields, you need to subtract 1.

Increment a value in Postgres

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill';

If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill'
  AND total = 203;

How to get file size in Java

Did a quick google. Seems that to find the file size you do this,

long size = f.length();

The differences between the three methods you posted can be found here

getFreeSpace() and getTotalSpace() are pretty self explanatory, getUsableSpace() seems to be the space that the JVM can use, which in most cases will be the same as the amount of free space.

SQL Server Group By Month

SELECT CONVERT(NVARCHAR(10), PaymentDate, 120) [Month], SUM(Amount) [TotalAmount]
FROM Payments
GROUP BY CONVERT(NVARCHAR(10), PaymentDate, 120)
ORDER BY [Month]

You could also try:

SELECT DATEPART(Year, PaymentDate) Year, DATEPART(Month, PaymentDate) Month, SUM(Amount) [TotalAmount]
FROM Payments
GROUP BY DATEPART(Year, PaymentDate), DATEPART(Month, PaymentDate)
ORDER BY Year, Month

Java, "Variable name" cannot be resolved to a variable

I've noticed bizarre behavior with Eclipse version 4.2.1 delivering me this error:

String cannot be resolved to a variable

With this Java code:

if (true)
    String my_variable = "somevalue";
    System.out.println("foobar");

You would think this code is very straight forward, the conditional is true, we set my_variable to somevalue. And it should print foobar. Right?

Wrong, you get the above mentioned compile time error. Eclipse is trying to prevent you from making a mistake by assuming that both statements are within the if statement.

If you put braces around the conditional block like this:

if (true){
    String my_variable = "somevalue"; }
    System.out.println("foobar");

Then it compiles and runs fine. Apparently poorly bracketed conditionals are fair game for generating compile time errors now.

Getting Exception(org.apache.poi.openxml4j.exception - no content type [M1.13]) when reading xlsx file using Apache POI?

Cleaned up the code (commented out the logger mostly) to make it run in my Eclipse environment.

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;

public class ReadXLSX {
private String filepath;
private XSSFWorkbook workbook;
// private static Logger logger=null;
private InputStream resourceAsStream;

public ReadXLSX(String filePath) {
    // logger=LoggerFactory.getLogger("ReadXLSX");
    this.filepath = filePath;
    resourceAsStream = ClassLoader.getSystemResourceAsStream(filepath);
}

public ReadXLSX(InputStream fileStream) {
    // logger=LoggerFactory.getLogger("ReadXLSX");
    this.resourceAsStream = fileStream;
}

private void loadFile() throws FileNotFoundException,
        NullObjectFoundException {

    if (resourceAsStream == null)
        throw new FileNotFoundException("Unable to locate give file..");
    else {
        try {
            workbook = new XSSFWorkbook(resourceAsStream);

        } catch (IOException ex) {

        }

    }
}// end loadxlsFile

public String[] getSheetsName() {
    int totalsheet = 0;
    int i = 0;
    String[] sheetName = null;

    try {
        loadFile();
        totalsheet = workbook.getNumberOfSheets();
        sheetName = new String[totalsheet];
        while (i < totalsheet) {
            sheetName[i] = workbook.getSheetName(i);
            i++;
        }

    } catch (FileNotFoundException ex) {
        // logger.error(ex);
    } catch (NullObjectFoundException ex) {
        // logger.error(ex);
    }

    return sheetName;
}

public int[] getSheetsIndex() {
    int totalsheet = 0;
    int i = 0;
    int[] sheetIndex = null;
    String[] sheetname = getSheetsName();
    try {
        loadFile();
        totalsheet = workbook.getNumberOfSheets();
        sheetIndex = new int[totalsheet];
        while (i < totalsheet) {
            sheetIndex[i] = workbook.getSheetIndex(sheetname[i]);
            i++;
        }

    } catch (FileNotFoundException ex) {
        // logger.error(ex);
    } catch (NullObjectFoundException ex) {
        // logger.error(ex);
    }

    return sheetIndex;
}

private boolean validateIndex(int index) {
    if (index < getSheetsIndex().length && index >= 0)
        return true;
    else
        return false;
}

public int getNumberOfSheet() {
    int totalsheet = 0;
    try {
        loadFile();
        totalsheet = workbook.getNumberOfSheets();

    } catch (FileNotFoundException ex) {
        // logger.error(ex.getMessage());
    } catch (NullObjectFoundException ex) {
        // logger.error(ex.getMessage());
    }

    return totalsheet;
}

public int getNumberOfColumns(int SheetIndex) {
    int NO_OF_Column = 0;
    @SuppressWarnings("unused")
    XSSFCell cell = null;
    XSSFSheet sheet = null;
    try {
        loadFile(); // load give Excel
        if (validateIndex(SheetIndex)) {
            sheet = workbook.getSheetAt(SheetIndex);
            Iterator<Row> rowIter = sheet.rowIterator();
            XSSFRow firstRow = (XSSFRow) rowIter.next();
            Iterator<Cell> cellIter = firstRow.cellIterator();
            while (cellIter.hasNext()) {
                cell = (XSSFCell) cellIter.next();
                NO_OF_Column++;
            }
        } else
            throw new InvalidSheetIndexException("Invalid sheet index.");
    } catch (Exception ex) {
        // logger.error(ex.getMessage());

    }

    return NO_OF_Column;
}

public int getNumberOfRows(int SheetIndex) {
    int NO_OF_ROW = 0;
    XSSFSheet sheet = null;

    try {
        loadFile(); // load give Excel
        if (validateIndex(SheetIndex)) {
            sheet = workbook.getSheetAt(SheetIndex);
            NO_OF_ROW = sheet.getLastRowNum();
        } else
            throw new InvalidSheetIndexException("Invalid sheet index.");
    } catch (Exception ex) {
        // logger.error(ex);
    }

    return NO_OF_ROW;
}

public String[] getSheetHeader(int SheetIndex) {
    int noOfColumns = 0;
    XSSFCell cell = null;
    int i = 0;
    String columns[] = null;
    XSSFSheet sheet = null;

    try {
        loadFile(); // load give Excel
        if (validateIndex(SheetIndex)) {
            sheet = workbook.getSheetAt(SheetIndex);
            noOfColumns = getNumberOfColumns(SheetIndex);
            columns = new String[noOfColumns];
            Iterator<Row> rowIter = sheet.rowIterator();
            XSSFRow Row = (XSSFRow) rowIter.next();
            Iterator<Cell> cellIter = Row.cellIterator();

            while (cellIter.hasNext()) {
                cell = (XSSFCell) cellIter.next();
                columns[i] = cell.getStringCellValue();
                i++;
            }
        } else
            throw new InvalidSheetIndexException("Invalid sheet index.");
    }

    catch (Exception ex) {
        // logger.error(ex);
    }

    return columns;
}// end of method

public String[][] getSheetData(int SheetIndex) {
    int noOfColumns = 0;
    XSSFRow row = null;
    XSSFCell cell = null;
    int i = 0;
    int noOfRows = 0;
    int j = 0;
    String[][] data = null;
    XSSFSheet sheet = null;

    try {
        loadFile(); // load give Excel
        if (validateIndex(SheetIndex)) {
            sheet = workbook.getSheetAt(SheetIndex);
            noOfColumns = getNumberOfColumns(SheetIndex);
            noOfRows = getNumberOfRows(SheetIndex) + 1;
            data = new String[noOfRows][noOfColumns];
            Iterator<Row> rowIter = sheet.rowIterator();
            while (rowIter.hasNext()) {
                row = (XSSFRow) rowIter.next();
                Iterator<Cell> cellIter = row.cellIterator();
                j = 0;
                while (cellIter.hasNext()) {
                    cell = (XSSFCell) cellIter.next();
                    if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                        data[i][j] = cell.getStringCellValue();
                    } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                        if (HSSFDateUtil.isCellDateFormatted(cell)) {
                            String formatCellValue = new DataFormatter()
                                    .formatCellValue(cell);
                            data[i][j] = formatCellValue;
                        } else {
                            data[i][j] = Double.toString(cell
                                    .getNumericCellValue());
                        }

                    } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
                        data[i][j] = Boolean.toString(cell
                                .getBooleanCellValue());
                    }

                    else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
                        data[i][j] = cell.getCellFormula().toString();
                    }

                    j++;
                }

                i++;
            } // outer while

        } else
            throw new InvalidSheetIndexException("Invalid sheet index.");

    } catch (Exception ex) {
        // logger.error(ex);
    }
    return data;
}

public String[][] getSheetData(int SheetIndex, int noOfRows) {
    int noOfColumns = 0;
    XSSFRow row = null;
    XSSFCell cell = null;
    int i = 0;
    int j = 0;
    String[][] data = null;
    XSSFSheet sheet = null;

    try {
        loadFile(); // load give Excel

        if (validateIndex(SheetIndex)) {
            sheet = workbook.getSheetAt(SheetIndex);
            noOfColumns = getNumberOfColumns(SheetIndex);
            data = new String[noOfRows][noOfColumns];
            Iterator<Row> rowIter = sheet.rowIterator();
            while (i < noOfRows) {

                row = (XSSFRow) rowIter.next();
                Iterator<Cell> cellIter = row.cellIterator();
                j = 0;
                while (cellIter.hasNext()) {
                    cell = (XSSFCell) cellIter.next();
                    if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                        data[i][j] = cell.getStringCellValue();
                    } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                        if (HSSFDateUtil.isCellDateFormatted(cell)) {
                            String formatCellValue = new DataFormatter()
                                    .formatCellValue(cell);
                            data[i][j] = formatCellValue;
                        } else {
                            data[i][j] = Double.toString(cell
                                    .getNumericCellValue());
                        }
                    }

                    j++;
                }

                i++;
            } // outer while
        } else
            throw new InvalidSheetIndexException("Invalid sheet index.");
    } catch (Exception ex) {
        // logger.error(ex);
    }

    return data;
}
}

Created this little testcode:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;


public class ReadXLSXTest {

/**
 * @param args
 * @throws FileNotFoundException 
 */
public static void main(String[] args) throws FileNotFoundException {
    // TODO Auto-generated method stub


    ReadXLSX test = new ReadXLSX(new FileInputStream(new File("./sample.xlsx")));

    System.out.println(test.getSheetsName());
    System.out.println(test.getNumberOfSheet());


}

}

All this ran like a charm, so my guess is you have an XLSX file that is 'corrupt' in one way or another. Try testing with other data.

Cheers, Wim

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

Printing with "\t" (tabs) does not result in aligned columns

The problem is the length of the filenames. The first filename is only 7 chars long, so the tab occurs at char 8 (doing a tab after every 4 characters). However the next filenames are 8 chars long, so the next tab won't be until char 12. And if you had filenames longer than 11 chars, you'd run into the same problem again.

How to sum columns in a dataTable?

Try this:

            DataTable dt = new DataTable();
            int sum = 0;
            foreach (DataRow dr in dt.Rows)
            {
                foreach (DataColumn dc in dt.Columns)
                {
                    sum += (int)dr[dc];
                }
            } 

Two models in one view in ASP MVC 3

Another way that is never talked about is Create a view in MSSQL with all the data you want to present. Then use LINQ to SQL or whatever to map it. In your controller return it to the view. Done.

How do I write a method to calculate total cost for all items in an array?

In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like

float total;
total += theItem.getUnits() * theItem.getPrice();

total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.

MySQL: Get column name or alias from query

Looks like MySQLdb doesn't actually provide a translation for that API call. The relevant C API call is mysql_fetch_fields, and there is no MySQLdb translation for that

Timing a command's execution in PowerShell

Here's a function I wrote which works similarly to the Unix time command:

function time {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$command,
        [switch]$quiet = $false
    )
    $start = Get-Date
    try {
        if ( -not $quiet ) {
            iex $command | Write-Host
        } else {
            iex $command > $null
        }
    } finally {
        $(Get-Date) - $start
    }
}

Source: https://gist.github.com/bender-the-greatest/741f696d965ed9728dc6287bdd336874

How can I convert a DateTime to the number of seconds since 1970?

That approach will be good if the date-time in question is in UTC, or represents local time in an area that has never observed daylight saving time. The DateTime difference routines do not take into account Daylight Saving Time, and consequently will regard midnight June 1 as being a multiple of 24 hours after midnight January 1. I'm unaware of anything in Windows that reports historical daylight-saving rules for the current locale, so I don't think there's any good way to correctly handle any time prior to the most recent daylight-saving rule change.

CSS3 gradient background set on body doesn't stretch but instead repeats?

There is a lot of partial information on this page, but not a complete one. Here is what I do:

  1. Create a gradient here: http://www.colorzilla.com/gradient-editor/
  2. Set gradient on HTML instead of BODY.
  3. Fix the background on HTML with "background-attachment: fixed;"
  4. Turn off the top and bottom margins on BODY
  5. (optional) I usually create a <DIV id='container'> that I put all of my content in

Here is an example:

html {  
  background: #a9e4f7; /* Old browsers */
  background: -moz-linear-gradient(-45deg,  #a9e4f7 0%, #0fb4e7 100%); /* FF3.6+ */
  background: -webkit-gradient(linear, left top, right bottom, color-stop(0%,#a9e4f7), color-stop(100%,#0fb4e7)); /* Chrome,Safari4+ */ 
  background: -webkit-linear-gradient(-45deg,  #a9e4f7 0%,#0fb4e7 100%); /* Chrome10+,Safari5.1+ */
  background: -o-linear-gradient(-45deg,  #a9e4f7 0%,#0fb4e7 100%); /* Opera 11.10+ */
  background: -ms-linear-gradient(-45deg,  #a9e4f7 0%,#0fb4e7 100%); /* IE10+ */
  background: linear-gradient(135deg,  #a9e4f7 0%,#0fb4e7 100%); /* W3C */ 
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#a9e4f7', endColorstr='#0fb4e7',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */

  background-attachment: fixed;
}

body {
  margin-top: 0px;
  margin-bottom: 0px;
}

/* OPTIONAL: div to store content.  Many of these attributes should be changed to suit your needs */
#container
{
  width: 800px;
  margin: auto;
  background-color: white;
  border: 1px solid gray;
  border-top: none;
  border-bottom: none;
  box-shadow: 3px 0px 20px #333;
  padding: 10px;
}

This has been tested with IE, Chrome, and Firefox on pages of various sizes and scrolling needs.

How do I put variable values into a text string in MATLAB?

As Peter and Amro illustrate, you have to convert numeric values to formatted strings first in order to display them or concatenate them with other character strings. You can do this using the functions FPRINTF, SPRINTF, NUM2STR, and INT2STR.


With respect to getting ans = 3 as an output, it is probably because you are not assigning the output from answer to a variable. If you want to get all of the output values, you will have to call answer in the following way:

[out1,out2,out3] = answer(1,2);

This will place the value d in out1, the value e in out2, and the value f in out3. When you do the following:

answer(1,2)

MATLAB will automatically assign the first output d (which has the value 3 in this case) to the default workspace variable ans.


With respect to suggesting a good resource for learning MATLAB, you shouldn't underestimate the value of the MATLAB documentation. I've learned most of what I know on my own using it. You can access it online, or within your copy of MATLAB using the functions DOC, HELP, or HELPWIN.

C# equivalent of C++ map<string,double>

Dictionary is the most common, but you can use other types of collections, e.g. System.Collections.Generic.SynchronizedKeyedCollection, System.Collections.Hashtable, or any KeyValuePair collection

SQL JOIN, GROUP BY on three tables to get totals

I know this is late, but it does answer your original question.

/*Read the comments the same way that SQL runs the query
    1) FROM 
    2) GROUP 
    3) SELECT 
    4) My final notes at the bottom 
*/
SELECT 
        list.invoiceid
    ,   cust.customernumber 
    ,   MAX(list.inv_amount) AS invoice_amount/* we select the max because it will be the same for each payment to that invoice (presumably invoice amounts do not vary based on payment) */
    ,   MAX(list.inv_amount) - SUM(list.pay_amount)  AS [amount_due]
FROM 
Customers AS cust 
    INNER JOIN 
Payments  AS pay 
    ON 
        pay.customerid = cust.customerid
INNER JOIN  (   /* generate a list of payment_ids, their amounts, and the totals of the invoices they billed to*/
    SELECT 
            inpay.paymentid AS paymentid
        ,   inv.invoiceid AS invoiceid 
        ,   inv.amount  AS inv_amount 
        ,   pay.amount AS pay_amount 
    FROM 
    InvoicePayments AS inpay
        INNER JOIN 
    Invoices AS inv 
        ON  inv.invoiceid = inpay.invoiceid 
        INNER JOIN 
    Payments AS pay 
        ON pay.paymentid = inpay.paymentid
    )  AS list
ON 
    list.paymentid = pay.paymentid
    /* so at this point my result set would look like: 
    -- All my customers (crossed by) every paymentid they are associated to (I'll call this A)
    -- Every invoice payment and its association to: its own ammount, the total invoice ammount, its own paymentid (what I call list) 
    -- Filter out all records in A that do not have a paymentid matching in (list)
     -- we filter the result because there may be payments that did not go towards invoices!
 */
GROUP BY
    /* we want a record line for each customer and invoice ( or basically each invoice but i believe this makes more sense logically */ 
        cust.customernumber 
    ,   list.invoiceid 
/*
    -- we can improve this query by only hitting the Payments table once by moving it inside of our list subquery, 
    -- but this is what made sense to me when I was planning. 
    -- Hopefully it makes it clearer how the thought process works to leave it in there
    -- as several people have already pointed out, the data structure of the DB prevents us from looking at customers with invoices that have no payments towards them.
*/

'System.OutOfMemoryException' was thrown when there is still plenty of memory free

Check that you are building a 64-bit process, and not a 32-bit one, which is the default compilation mode of Visual Studio. To do this, right click on your project, Properties -> Build -> platform target : x64. As any 32-bit process, Visual Studio applications compiled in 32-bit have a virtual memory limit of 2GB.

64-bit processes do not have this limitation, as they use 64-bit pointers, so their theoretical maximum address space (the size of their virtual memory) is 16 exabytes (2^64). In reality, Windows x64 limits the virtual memory of processes to 8TB. The solution to the memory limit problem is then to compile in 64-bit.

However, object’s size in Visual Studio is still limited to 2GB, by default. You will be able to create several arrays whose combined size will be greater than 2GB, but you cannot by default create arrays bigger than 2GB. Hopefully, if you still want to create arrays bigger than 2GB, you can do it by adding the following code to you app.config file:

<configuration>
  <runtime>
    <gcAllowVeryLargeObjects enabled="true" />
  </runtime>
</configuration>

Calculate a Running Total in SQL Server

Though best way is to get it done will be using a window function, it can also be done using a simple correlated sub-query.

Select id, someday, somevalue, (select sum(somevalue) 
                                from testtable as t2
                                where t2.id = t1.id
                                and t2.someday <= t1.someday) as runningtotal
from testtable as t1
order by id,someday;

How to get directory size in PHP

function get_dir_size($directory){
    $size = 0;
    $files = glob($directory.'/*');
    foreach($files as $path){
        is_file($path) && $size += filesize($path);
        is_dir($path)  && $size += get_dir_size($path);
    }
    return $size;
} 

How can I convert a Unix timestamp to DateTime and vice versa?

public static class UnixTime
    {
        private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);

        public static DateTime UnixTimeToDateTime(double unixTimeStamp)
        {
            return Epoch.AddSeconds(unixTimeStamp).ToUniversalTime();
        }
    }

you can call UnixTime.UnixTimeToDateTime(double datetime))

How do I monitor the computer's CPU, memory, and disk usage in Java?

The accepted answer in 2008 recommended SIGAR. However, as a comment from 2014 (@Alvaro) says:

Be careful when using Sigar, there are problems on x64 machines... Sigar 1.6.4 is crashing: EXCEPTION_ACCESS_VIOLATION and it seems the library doesn't get updated since 2010

My recommendation is to use https://github.com/oshi/oshi

Or the answer mentioned above.

wget can't download - 404 error

Wget 404 error also always happens if you want to download the pages from Wordpress-website by typing

wget -r http://somewebsite.com

If this website is built using Wordpress you'll get such an error:

ERROR 404: Not Found.

There's no way to mirror Wordpress-website because the website content is stored in the database and wget is not able to grab .php files. That's why you get Wget 404 error.

I know it's not this question's case, because Sam only wants to download a single picture, but it can be helpful for others.

assign function return value to some variable using javascript

Or just...

var response = (function() {
    var a;
    // calculate a
    return a;
})();  

In this case, the response variable receives the return value of the function. The function executes immediately.

You can use this construct if you want to populate a variable with a value that needs to be calculated. Note that all calculation happens inside the anonymous function, so you don't pollute the global namespace.

Trying to make bootstrap modal wider

You could try:

.modal.modal-wide .modal-dialog {
  width: 90%;
}

.modal-wide .modal-body {
  overflow-y: auto;
}

Just add .modal-wide to your classes

How does a hash table work?

A hash table totally works on the fact that practical computation follows random access machine model i.e. value at any address in memory can be accessed in O(1) time or constant time.

So, if I have a universe of keys (set of all possible keys that I can use in a application, e.g. roll no. for student, if it's 4 digit then this universe is a set of numbers from 1 to 9999), and a way to map them to a finite set of numbers of size I can allocate memory in my system, theoretically my hash table is ready.

Generally, in applications the size of universe of keys is very large than number of elements I want to add to the hash table(I don't wanna waste a 1 GB memory to hash ,say, 10000 or 100000 integer values because they are 32 bit long in binary reprsentaion). So, we use this hashing. It's sort of a mixing kind of "mathematical" operation, which maps my large universe to a small set of values that I can accomodate in memory. In practical cases, often space of a hash table is of the same "order"(big-O) as the (number of elements *size of each element), So, we don't waste much memory.

Now, a large set mapped to a small set, mapping must be many-to-one. So, different keys will be alloted the same space(?? not fair). There are a few ways to handle this, I just know the popular two of them:

  • Use the space that was to be allocated to the value as a reference to a linked list. This linked list will store one or more values, that come to reside in same slot in many to one mapping. The linked list also contains keys to help someone who comes searching. It's like many people in same apartment, when a delivery-man comes, he goes to the room and asks specifically for the guy.
  • Use a double hash function in an array which gives the same sequence of values every time rather than a single value. When I go to store a value, I see whether the required memory location is free or occupied. If it's free, I can store my value there, if it's occupied I take next value from the sequence and so on until I find a free location and I store my value there. When searching or retreiving the value, I go back on same path as given by the sequence and at each location ask for the vaue if it's there until I find it or search all possible locations in the array.

Introduction to Algorithms by CLRS provides a very good insight on the topic.

Difference between Width:100% and width:100vw?

You can solve this issue be adding max-width:

#element {
   width: 100vw;
   height: 100vw;
   max-width: 100%;
}

When you using CSS to make the wrapper full width using the code width: 100vw; then you will notice a horizontal scroll in the page, and that happened because the padding and margin of html and body tags added to the wrapper size, so the solution is to add max-width: 100%

Cannot set property 'innerHTML' of null

Let us first try to understand the root cause as to why it is happening in first place.

Why do I get an error or Uncaught TypeError: Cannot set property 'innerHTML' of null?

The browser always loads the entire HTML DOM from top to bottom. Any JavaScript code written inside the script tags (present in head section of your HTML file) gets executed by the browser rendering engine even before your whole DOM (various HTML element tags present within body tag) is loaded. The scripts present in head tag are trying to access an element having id hello even before it has actually been rendered in the DOM. So obviously, JavaScript failed to see the element and hence you end up seeing the null reference error.

How can you make it work as before?

You want to show the "hi" message on the page as soon as the user lands on your page for the first time. So you need to hook up your code at a point when you are completely sure of the fact that DOM is fully loaded and the hello id element is accessible/available. It is achievable in two ways:

  1. Reorder your scripts: This way your scripts get fired only after the DOM containing your hello id element is already loaded. You can achieve it by simply moving the script tag after all the DOM elements i.e. at the bottom where body tag is ending. Since rendering happens from top to bottom so your scripts get executed in the end and you face no error.

_x000D_
_x000D_
    <!DOCTYPE HTML>_x000D_
    <html>_x000D_
    <head>_x000D_
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">_x000D_
    <title>Untitled Document</title>_x000D_
    </head>_x000D_
    _x000D_
    <body>_x000D_
    <div id="hello"></div>_x000D_
    _x000D_
    <script type ="text/javascript">_x000D_
        what();_x000D_
        function what(){_x000D_
            document.getElementById('hello').innerHTML = 'hi';_x000D_
        };_x000D_
    </script>_x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

  1. Use event hooking: Browser's rendering engine provides an event based hook through window.onload event which gives you the hint that browser has finished loading the DOM. So by the time when this event gets fired, you can be rest assured that your element with hello id already loaded in the DOM and any JavaScript fired thereafter which tries to access this element will not fail. So you do something like below code snippet. Please note that in this case, your script works even though it is present at the top of your HTML document inside the head tag.

_x000D_
_x000D_
<!DOCTYPE HTML>_x000D_
        <html>_x000D_
        <head>_x000D_
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">_x000D_
        <title>Untitled Document</title>_x000D_
        <script type ="text/javascript">_x000D_
            window.onload = function() {_x000D_
            what();_x000D_
            function what(){_x000D_
                document.getElementById('hello').innerHTML = 'hi';_x000D_
            };_x000D_
        }_x000D_
        </script>_x000D_
        </head>_x000D_
        _x000D_
        <body>_x000D_
        <div id="hello"></div>_x000D_
        </body>_x000D_
        </html>
_x000D_
_x000D_
_x000D_

PostgreSQL Crosstab Query

SELECT section,
       SUM(CASE status WHEN 'Active' THEN count ELSE 0 END) AS active, --here you pivot each status value as a separate column explicitly
       SUM(CASE status WHEN 'Inactive' THEN count ELSE 0 END) AS inactive --here you pivot each status  value as a separate column explicitly

FROM t
GROUP BY section

What is the best way to merge mp3 files?

The time problem has to do with the ID3 headers of the MP3 files, which is something your method isn't taking into account as the entire file is copied.

Do you have a language of choice that you want to use or doesn't it matter? That will affect what libraries are available that support the operations you want.

org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15

This was a Tomcat bug that resurfaced again with the Java 9 bytecode. The exact versions which fix this (for both Java 8/9 bytecode) are:

  • trunk for 9.0.0.M18 onwards
  • 8.5.x for 8.5.12 onwards
  • 8.0.x for 8.0.42 onwards
  • 7.0.x for 7.0.76 onwards

On - window.location.hash - Change?

A decent implementation can be found at http://code.google.com/p/reallysimplehistory/. The only (but also) problem and bug it has is: in Internet Explorer modifying the location hash manually will reset the entire history stack (this is a browser issue and it cannot be solved).

Note, Internet Explorer 8 does have support for the "hashchange" event, and since it is becoming part of HTML5 you may expect other browsers to catch up.

Moving all files from one directory to another using Python

For example, if I wanted to move all .txt files from one location to another ( on a Windows OS for instance ) I would do it something like this:

import shutil
import os,glob

inpath = 'R:/demo/in' 
outpath = 'R:/demo/out'

os.chdir(inpath)
for file in glob.glob("*.txt"):

    shutil.move(inpath+'/'+file,outpath)

MySQL FULL JOIN?

SELECT  p.LastName, p.FirstName, o.OrderNo
FROM    persons AS p
LEFT JOIN
        orders AS o
ON      o.orderNo = p.p_id
UNION ALL
SELECT  NULL, NULL, orderNo
FROM    orders
WHERE   orderNo NOT IN
        (
        SELECT  p_id
        FROM    persons
        )

check if file exists on remote host with ssh

You're missing ;s. The general syntax if you put it all in one line would be:

if thing ; then ... ; else ... ; fi

The thing can be pretty much anything that returns an exit code. The then branch is taken if that thing returns 0, the else branch otherwise.

[ isn't syntax, it's the test program (check out ls /bin/[, it actually exists, man test for the docs – although can also have a built-in version with different/additional features.) which is used to test various common conditions on files and variables. (Note that [[ on the other hand is syntax and is handled by your shell, if it supports it).

For your case, you don't want to use test directly, you want to test something on the remote host. So try something like:

if ssh user@host test -e "$file" ; then ... ; else ... ; fi

jQuery Ajax simple call

please set dataType config property in your ajax call and give it another try!

another point is you are using ajax call setup configuration properties as string and it is wrong as reference site

$.ajax({

    url : 'http://voicebunny.comeze.com/index.php',
    type : 'GET',
    data : {
        'numberOfWords' : 10
    },
    dataType:'json',
    success : function(data) {              
        alert('Data: '+data);
    },
    error : function(request,error)
    {
        alert("Request: "+JSON.stringify(request));
    }
});

I hope be helpful!

Android: How to programmatically access the device serial number shown in the AVD manager (API Version 8)

Build.SERIAL can be empty or sometimes return a different value (proof 1, proof 2) than what you can see in your device's settings.

If you want a more complete and robust solution, I've compiled every possible solution I could found in a single gist. Here's a simplified version of it :

public static String getSerialNumber() {
    String serialNumber;

    try {
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method get = c.getMethod("get", String.class);

        serialNumber = (String) get.invoke(c, "gsm.sn1");
        if (serialNumber.equals(""))
            serialNumber = (String) get.invoke(c, "ril.serialnumber");
        if (serialNumber.equals(""))
            serialNumber = (String) get.invoke(c, "ro.serialno");
        if (serialNumber.equals(""))
            serialNumber = (String) get.invoke(c, "sys.serialnumber");
        if (serialNumber.equals(""))
            serialNumber = Build.SERIAL;

        // If none of the methods above worked
        if (serialNumber.equals(""))
            serialNumber = null;
    } catch (Exception e) {
        e.printStackTrace();
        serialNumber = null;
    }

    return serialNumber;
}

I try to update the gist regularly whenever I can test on a new device or Android version. Contributions are welcome too.

AngularJS - How can I do a redirect with a full page load?

We had the same issue, working from JS code (i.e. not from HTML anchor). This is how we solved that:

  1. If needed, virtually alter current URL through $location service. This might be useful if your destination is just a variation on the current URL, so that you can take advantage of $location helper methods. E.g. we ran $location.search(..., ...) to just change value of a querystring paramater.

  2. Build up the new destination URL, using current $location.url() if needed. In order to work, this new one had to include everything after schema, domain and port. So e.g. if you want to move to:

    http://yourdomain.com/YourAppFolder/YourAngularApp/#/YourArea/YourAction?culture=en

    then you should set URL as in:

    var destinationUrl = '/YourAppFolder/YourAngularApp/#/YourArea/YourAction?culture=en';

    (with the leading '/' as well).

  3. Assign new destination URL at low-level: $window.location.href = destinationUrl;

  4. Force reload, still at low-level: $window.location.reload();

Fragment onCreateView and onActivityCreated called twice

The two upvoted answers here show solutions for an Activity with navigation mode NAVIGATION_MODE_TABS, but I had the same issue with a NAVIGATION_MODE_LIST. It caused my Fragments to inexplicably lose their state when the screen orientation changed, which was really annoying. Thankfully, due to their helpful code I managed to figure it out.

Basically, when using a list navigation, ``onNavigationItemSelected()is automatically called when your activity is created/re-created, whether you like it or not. To prevent your Fragment'sonCreateView()from being called twice, this initial automatic call toonNavigationItemSelected()should check whether the Fragment is already in existence inside your Activity. If it is, return immediately, because there is nothing to do; if it isn't, then simply construct the Fragment and add it to the Activity like you normally would. Performing this check prevents your Fragment from needlessly being created again, which is what causesonCreateView()` to be called twice!

See my onNavigationItemSelected() implementation below.

public class MyActivity extends FragmentActivity implements ActionBar.OnNavigationListener
{
    private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";

    private boolean mIsUserInitiatedNavItemSelection;

    // ... constructor code, etc.

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);

        if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM))
        {
            getActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState)
    {
        outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar().getSelectedNavigationIndex());

        super.onSaveInstanceState(outState);
    }

    @Override
    public boolean onNavigationItemSelected(int position, long id)
    {    
        Fragment fragment;
        switch (position)
        {
            // ... choose and construct fragment here
        }

        // is this the automatic (non-user initiated) call to onNavigationItemSelected()
        // that occurs when the activity is created/re-created?
        if (!mIsUserInitiatedNavItemSelection)
        {
            // all subsequent calls to onNavigationItemSelected() won't be automatic
            mIsUserInitiatedNavItemSelection = true;

            // has the same fragment already replaced the container and assumed its id?
            Fragment existingFragment = getSupportFragmentManager().findFragmentById(R.id.container);
            if (existingFragment != null && existingFragment.getClass().equals(fragment.getClass()))
            {
                return true; //nothing to do, because the fragment is already there 
            }
        }

        getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
        return true;
    }
}

I borrowed inspiration for this solution from here.

How to read a PEM RSA private key from .NET

I've created the PemUtils library that does exactly that. The code is available on GitHub and can be installed from NuGet:

PM> Install-Package PemUtils

or if you only want a DER converter:

PM> Install-Package DerConverter

Usage for reading a RSA key from PEM data:

using (var stream = File.OpenRead(path))
using (var reader = new PemReader(stream))
{
    var rsaParameters = reader.ReadRsaKey();
    // ...
}

Hide element by class in pure Javascript

Array.filter( document.getElementsByClassName('appBanner'), function(elem){ elem.style.visibility = 'hidden'; });

Forked @http://jsfiddle.net/QVJXD/

Difference between style = "position:absolute" and style = "position:relative"

position: absolute can be placed anywhere and remain there such as 0,0.

position: relative is placed with offset from the location it is originally placed in the browser.

How to get file name when user select a file via <input type="file" />?

You can get the file name, but you cannot get the full client file-system path.

Try to access to the value attribute of your file input on the change event.

Most browsers will give you only the file name, but there are exceptions like IE8 which will give you a fake path like: "C:\fakepath\myfile.ext" and older versions (IE <= 6) which actually will give you the full client file-system path (due its lack of security).

document.getElementById('fileInput').onchange = function () {
  alert('Selected file: ' + this.value);
};

What is the difference between an interface and abstract class?

In short the differences are the following:

Syntactical Differences Between Interface and Abstract Class:

  1. Methods and members of an abstract class can have any visibility. All methods of an interface must be public. //Does not hold true from Java 9 anymore
  2. A concrete child class of an Abstract Class must define all the abstract methods. An Abstract child class can have abstract methods. An interface extending another interface need not provide default implementation for methods inherited from the parent interface.
  3. A child class can only extend a single class. An interface can extend multiple interfaces. A class can implement multiple interfaces.
  4. A child class can define abstract methods with the same or less restrictive visibility, whereas class implementing an interface must define all interface methods as public.
  5. Abstract Classes can have constructors but not interfaces.
  6. Interfaces from Java 9 have private static methods.

In Interfaces now:

public static - supported
public abstract - supported
public default - supported
private static - supported
private abstract - compile error
private default - compile error
private - supported

write a shell script to ssh to a remote machine and execute commands

Install sshpass using, apt-get install sshpass then edit the script and put your linux machines IPs, usernames and password in respective order. After that run that script. Thats it ! This script will install VLC in all systems.

#!/bin/bash
SCRIPT="cd Desktop; pwd;  echo -e 'PASSWORD' | sudo -S apt-get install vlc"
HOSTS=("192.168.1.121" "192.168.1.122" "192.168.1.123")
USERNAMES=("username1" "username2" "username3")
PASSWORDS=("password1" "password2" "password3")
for i in ${!HOSTS[*]} ; do
     echo ${HOSTS[i]}
     SCR=${SCRIPT/PASSWORD/${PASSWORDS[i]}}
     sshpass -p ${PASSWORDS[i]} ssh -l ${USERNAMES[i]} ${HOSTS[i]} "${SCR}"
done

How to know that a string starts/ends with a specific string in jQuery?

ES6 now supports the startsWith() and endsWith() method for checking beginning and ending of strings. If you want to support pre-es6 engines, you might want to consider adding one of the suggested methods to the String prototype.

if (typeof String.prototype.startsWith != 'function') {
  String.prototype.startsWith = function (str) {
    return this.match(new RegExp("^" + str));
  };
}

if (typeof String.prototype.endsWith != 'function') {
  String.prototype.endsWith = function (str) {
    return this.match(new RegExp(str + "$"));
  };
}

var str = "foobar is not barfoo";
console.log(str.startsWith("foob"); // true
console.log(str.endsWith("rfoo");   // true

Can I use a :before or :after pseudo-element on an input field?

Oddly, it works with some types of input. At least in Chrome,

<input type="checkbox" />

works fine, same as

<input type="radio" />

It's just type=text and some others that don't work.

How to declare std::unique_ptr and what is the use of it?

From cppreference, one of the std::unique_ptr constructors is

explicit unique_ptr( pointer p ) noexcept;

So to create a new std::unique_ptr is to pass a pointer to its constructor.

unique_ptr<int> uptr (new int(3));

Or it is the same as

int *int_ptr = new int(3);
std::unique_ptr<int> uptr (int_ptr);

The different is you don't have to clean up after using it. If you don't use std::unique_ptr (smart pointer), you will have to delete it like this

delete int_ptr;

when you no longer need it or it will cause a memory leak.

Why std::cout instead of simply cout?

In the C++ standard, cout is defined in the std namespace, so you need to either say std::cout or put

using namespace std;

in your code in order to get at it.

However, this was not always the case, and in the past cout was just in the global namespace (or, later on, in both global and std). I would therefore conclude that your classes used an older C++ compiler.

How to program a delay in Swift 3

Try the below code for delay

//MARK: First Way

func delayForWork() {
    delay(3.0) {
        print("delay for 3.0 second")
    }
}

delayForWork()

// MARK: Second Way

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
    // your code here delayed by 0.5 seconds
}

How to import multiple .csv files at once?

Here are some options to convert the .csv files into one data.frame using R base and some of the available packages for reading files in R.

This is slower than the options below.

# Get the files names
files = list.files(pattern="*.csv")
# First apply read.csv, then rbind
myfiles = do.call(rbind, lapply(files, function(x) read.csv(x, stringsAsFactors = FALSE)))

Edit: - A few more extra choices using data.table and readr

A fread() version, which is a function of the data.table package. This is by far the fastest option in R.

library(data.table)
DT = do.call(rbind, lapply(files, fread))
# The same using `rbindlist`
DT = rbindlist(lapply(files, fread))

Using readr, which is another package for reading csv files. It's slower than fread, faster than base R but has different functionalities.

library(readr)
library(dplyr)
tbl = lapply(files, read_csv) %>% bind_rows()

python save image from url

Python3

import urllib.request
print('Beginning file download with urllib2...')
url = 'https://akm-img-a-in.tosshub.com/sites/btmt/images/stories/modi_instagram_660_020320092717.jpg'
urllib.request.urlretrieve(url, 'modiji.jpg')

Why not use Double or Float to represent currency?

I'm troubled by some of these responses. I think doubles and floats have a place in financial calculations. Certainly, when adding and subtracting non-fractional monetary amounts there will be no loss of precision when using integer classes or BigDecimal classes. But when performing more complex operations, you often end up with results that go out several or many decimal places, no matter how you store the numbers. The issue is how you present the result.

If your result is on the borderline between being rounded up and rounded down, and that last penny really matters, you should be probably be telling the viewer that the answer is nearly in the middle - by displaying more decimal places.

The problem with doubles, and more so with floats, is when they are used to combine large numbers and small numbers. In java,

System.out.println(1000000.0f + 1.2f - 1000000.0f);

results in

1.1875

Html table tr inside td

Just add a new table in the td you want. Example: http://jsfiddle.net/AbE3Q/

_x000D_
_x000D_
<table border="1">
  <tr>
    <td>ABC</td>
    <td>ABC</td>
    <td>ABC</td>
    <td>ABC</td>
  </tr>
  <tr>
    <td>Item1</td>
    <td>Item2</td>
    <td>
      <table border="1">
        <tr>
          <td>qweqwewe</td>
          <td>qweqwewe</td>
        </tr>
        <tr>
          <td>qweqwewe</td>
          <td>qweqwewe</td>
        </tr>
        <tr>
          <td>qweqwewe</td>
          <td>qweqwewe</td>
        </tr>
      </table>
    </td>
    <td>Item3</td>
  </tr>
  <tr>
  </tr>
  <tr>
  </tr>
  <tr>
  </tr>
  <tr>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

Angular2 - Focusing a textbox on component load

This answer is inspired by post Angular 2: Focus on newly added input element

Steps to set the focus on Html element in Angular2

  1. Import ViewChildren in your Component

    import { Input, Output, AfterContentInit, ContentChild,AfterViewInit, ViewChild, ViewChildren } from 'angular2/core';
    
  2. Declare local template variable name for the html for which you want to set the focus

  3. Implement the function ngAfterViewInit() or other appropriate life cycle hooks
  4. Following is the piece of code which I used for setting the focus

    ngAfterViewInit() {vc.first.nativeElement.focus()}
    
  5. Add #input attribute to the DOM element you want to access.

_x000D_
_x000D_
///This is typescript_x000D_
import {Component, Input, Output, AfterContentInit, ContentChild,_x000D_
  AfterViewChecked, AfterViewInit, ViewChild,ViewChildren} from 'angular2/core';_x000D_
_x000D_
export class AppComponent implements AfterViewInit,AfterViewChecked { _x000D_
   @ViewChildren('input') vc;_x000D_
  _x000D_
   ngAfterViewInit() {            _x000D_
        this.vc.first.nativeElement.focus();_x000D_
    }_x000D_
  _x000D_
 }
_x000D_
<div>_x000D_
    <form role="form" class="form-horizontal ">        _x000D_
        <div [ngClass]="{showElement:IsEditMode, hidden:!IsEditMode}">_x000D_
            <div class="form-group">_x000D_
                <label class="control-label col-md-1 col-sm-1" for="name">Name</label>_x000D_
                <div class="col-md-7 col-sm-7">_x000D_
                    <input #input id="name" type="text" [(ngModel)]="person.Name" class="form-control" />_x000D_
_x000D_
                </div>_x000D_
                <div class="col-md-2 col-sm-2">_x000D_
                    <input type="button" value="Add" (click)="AddPerson()" class="btn btn-primary" />_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div [ngClass]="{showElement:!IsEditMode, hidden:IsEditMode}">_x000D_
            <div class="form-group">_x000D_
                <label class="control-label col-md-1 col-sm-1" for="name">Person</label>_x000D_
                <div class="col-md-7 col-sm-7">_x000D_
                    <select [(ngModel)]="SelectedPerson.Id"  (change)="PersonSelected($event.target.value)" class="form-control">_x000D_
                        <option *ngFor="#item of PeopleList" value="{{item.Id}}">{{item.Name}}</option>_x000D_
                    </select>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>        _x000D_
    </form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jQuery xml error ' No 'Access-Control-Allow-Origin' header is present on the requested resource.'

There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:

url:   'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',

to this line:

url: '/path/to/phpscript.php',

and then in the php script (if you have permission to use the file_get_contents() function):

<?php

header('Content-type: application/xml');
echo file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

?>

Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.

Edit: If you want to cache the result in php, here's the php file you would use:

<?php

$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
  $contents = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
  file_put_contents($cacheName, $contents);
}

$xml = simplexml_load_file($cacheName);

header('Content-type: application/xml');
echo $xml;

?>

Caching code take from here.

"Too many characters in character literal error"

You cannot treat == or || as chars, since they are not chars, but a sequence of chars.

You could make your switch...case work on strings instead.

List of foreign keys and the tables they reference in Oracle DB

If you need all the foreign keys of the user then use the following script

SELECT a.constraint_name, a.table_name, a.column_name,  c.owner, 
       c_pk.table_name r_table_name,  b.column_name r_column_name
  FROM user_cons_columns a
  JOIN user_constraints c ON a.owner = c.owner
       AND a.constraint_name = c.constraint_name
  JOIN user_constraints c_pk ON c.r_owner = c_pk.owner
       AND c.r_constraint_name = c_pk.constraint_name
  JOIN user_cons_columns b ON C_PK.owner = b.owner
       AND  C_PK.CONSTRAINT_NAME = b.constraint_name AND b.POSITION = a.POSITION     
 WHERE c.constraint_type = 'R'

based on Vincent Malgrat code

client denied by server configuration

This has happened to me several times migrating from Apache 2.2.

What I have found is that there is an Order,Deny that I missed with VIM's Search feature somehow that is the default main Vhost, line 379. Hope this helps someone. I commented out the Order Deny,Allow and Deny from All and it worked!

How to solve ADB device unauthorized in Android ADB host device?

Check and uncheck the USB Debugging option in the device. If that doesn't work unplug and plug in the USB a couple of times.

At some point, the device should show a message box to ask you to authorize the computer. Click yes and then the device will be authorized.

Visual Studio keyboard shortcut to display IntelliSense

If you want to change whether it highlights the best fitting possibility, use:

Ctrl + Alt + Space

PHP & localStorage;

localStorage is something that is kept on the client side. There is no data transmitted to the server side.

You can only get the data with JavaScript and you can send it to the server side with Ajax.

Call to undefined function mysql_query() with Login

What is your PHP version? Extension "Mysql" was deprecated in PHP 5.5.0. Use extension Mysqli (like mysqli_query).

What's the best mock framework for Java?

I used JMock early. I've tried Mockito at my last project and liked it. More concise, more cleaner. PowerMock covers all needs which are absent in Mockito, such as mocking a static code, mocking an instance creation, mocking final classes and methods. So I have all I need to perform my work.

Convert java.util.Date to java.time.LocalDate

Date input = new Date();
LocalDateTime  conv=LocalDateTime.ofInstant(input.toInstant(), ZoneId.systemDefault());
LocalDate convDate=conv.toLocalDate();

The Date instance does contain time too along with the date while LocalDate doesn't. So you can firstly convert it into LocalDateTime using its method ofInstant() then if you want it without time then convert the instance into LocalDate.

how to set default main class in java?

You can set the Main-Class attribute in the jar file's manifest to point to which file you want to run automatically.

How to install numpy on windows using pip install?

Check installation of python 2.7 than install/reinstall pip which described here than open command line and write

pip install numpy

or

pip install scipy

if already installed try this

pip install -U numpy

How do I read a date in Excel format in Python?

When converting an excel file to CSV the date/time cell looks like this:

foo, 3/16/2016 10:38, bar,

To convert the datetime text value to datetime python object do this:

from datetime import datetime

date_object = datetime.strptime('3/16/2016 10:38', '%m/%d/%Y %H:%M')    # excel format (CSV file)

print date_object will return 2005-06-01 13:33:00

Ruby value of a hash key?

I didn't understand your problem clearly but I think this is what you're looking for(Based on my understanding)

  person =   {"name"=>"BillGates", "company_name"=>"Microsoft", "position"=>"Chairman"}

  person.delete_if {|key, value| key == "name"} #doing something if the key == "something"

  Output: {"company_name"=>"Microsoft", "position"=>"Chairman"}

Convert interface{} to int

I wrote a library that can help with type convertions https://github.com/KromDaniel/jonson

js := jonson.New([]interface{}{55.6, 70.8, 10.4, 1, "48", "-90"})

js.SliceMap(func(jsn *jonson.JSON, index int) *jonson.JSON {
    jsn.MutateToInt()
    return jsn
}).SliceMap(func(jsn *jonson.JSON, index int) *jonson.JSON {
    if jsn.GetUnsafeInt() > 50{
        jsn.MutateToString()
    }
    return jsn
}) // ["55","70",10,1,48,-90]

how to resolve DTS_E_OLEDBERROR. in ssis

I had a similar issue with my OLE DB Command and I resolved it by setting the ValidateExternalMetadata property within the component to False.

Blank HTML SELECT without blank item in dropdown list

You can't. They simply do not work that way. A drop down menu must have one of its options selected at all times.

You could (although I don't recommend it) watch for a change event and then use JS to delete the first option if it is blank.

Get hours difference between two dates in Moment Js

In my case, I wanted hours and minutes:

var duration = moment.duration(end.diff(startTime));
var hours = duration.hours(); //hours instead of asHours
var minutes = duration.minutes(); //minutes instead of asMinutes

For more info refer to the official docs.

Working with $scope.$emit and $scope.$on

The Easiest way :

HTML

  <div ng-app="myApp" ng-controller="myCtrl"> 

        <button ng-click="sendData();"> Send Data </button>

    </div>

JavaScript

    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function($scope, $rootScope) {
            function sendData($scope) {
                var arrayData = ['sam','rumona','cubby'];
                $rootScope.$emit('someEvent', arrayData);
            }

        });
        app.controller('yourCtrl', function($scope, $rootScope) {
            $rootScope.$on('someEvent', function(event, data) {
                console.log(data); 
            }); 
        });
    </script>

What techniques can be used to speed up C++ compilation times?

If you have a multicore processor, both Visual Studio (2005 and later) as well as GCC support multi-processor compiles. It is something to enable if you have the hardware, for sure.

How to check a not-defined variable in JavaScript

I often use the simplest way:

var variable;
if (variable === undefined){
    console.log('Variable is undefined');
} else {
    console.log('Variable is defined');
}

EDIT:

Without initializing the variable, exception will be thrown "Uncaught ReferenceError: variable is not defined..."

How can I combine two commits into one commit?

You want to git rebase -i to perform an interactive rebase.

If you're currently on your "commit 1", and the commit you want to merge, "commit 2", is the previous commit, you can run git rebase -i HEAD~2, which will spawn an editor listing all the commits the rebase will traverse. You should see two lines starting with "pick". To proceed with squashing, change the first word of the second line from "pick" to "squash". Then save your file, and quit. Git will squash your first commit into your second last commit.

Note that this process rewrites the history of your branch. If you are pushing your code somewhere, you'll have to git push -f and anybody sharing your code will have to jump through some hoops to pull your changes.

Note that if the two commits in question aren't the last two commits on the branch, the process will be slightly different.

How to POST JSON data with Python Requests?

From requests 2.4.2 (https://pypi.python.org/pypi/requests), the "json" parameter is supported. No need to specify "Content-Type". So the shorter version:

requests.post('http://httpbin.org/post', json={'test': 'cheers'})

PowerShell array initialization

$array = 1..5 | foreach { $false }

Difference between using "chmod a+x" and "chmod 755"

Yes - different

chmod a+x will add the exec bits to the file but will not touch other bits. For example file might be still unreadable to others and group.

chmod 755 will always make the file with perms 755 no matter what initial permissions were.

This may or may not matter for your script.

Why is January month 0 in Java Calendar?

I'd say laziness. Arrays start at 0 (everyone knows that); the months of the year are an array, which leads me to believe that some engineer at Sun just didn't bother to put this one little nicety into the Java code.

Call static methods from regular ES6 class methods

I stumbled over this thread searching for answer to similar case. Basically all answers are found, but it's still hard to extract the essentials from them.

Kinds of Access

Assume a class Foo probably derived from some other class(es) with probably more classes derived from it.

Then accessing

  • from static method/getter of Foo
    • some probably overridden static method/getter:
      • this.method()
      • this.property
    • some probably overridden instance method/getter:
      • impossible by design
    • own non-overridden static method/getter:
      • Foo.method()
      • Foo.property
    • own non-overridden instance method/getter:
      • impossible by design
  • from instance method/getter of Foo
    • some probably overridden static method/getter:
      • this.constructor.method()
      • this.constructor.property
    • some probably overridden instance method/getter:
      • this.method()
      • this.property
    • own non-overridden static method/getter:
      • Foo.method()
      • Foo.property
    • own non-overridden instance method/getter:
      • not possible by intention unless using some workaround:
        • Foo.prototype.method.call( this )
        • Object.getOwnPropertyDescriptor( Foo.prototype,"property" ).get.call(this);

Keep in mind that using this isn't working this way when using arrow functions or invoking methods/getters explicitly bound to custom value.

Background

  • When in context of an instance's method or getter
    • this is referring to current instance.
    • super is basically referring to same instance, but somewhat addressing methods and getters written in context of some class current one is extending (by using the prototype of Foo's prototype).
    • definition of instance's class used on creating it is available per this.constructor.
  • When in context of a static method or getter there is no "current instance" by intention and so
    • this is available to refer to the definition of current class directly.
    • super is not referring to some instance either, but to static methods and getters written in context of some class current one is extending.

Conclusion

Try this code:

_x000D_
_x000D_
class A {_x000D_
  constructor( input ) {_x000D_
    this.loose = this.constructor.getResult( input );_x000D_
    this.tight = A.getResult( input );_x000D_
    console.log( this.scaledProperty, Object.getOwnPropertyDescriptor( A.prototype, "scaledProperty" ).get.call( this ) );_x000D_
  }_x000D_
_x000D_
  get scaledProperty() {_x000D_
    return parseInt( this.loose ) * 100;_x000D_
  }_x000D_
  _x000D_
  static getResult( input ) {_x000D_
    return input * this.scale;_x000D_
  }_x000D_
  _x000D_
  static get scale() {_x000D_
    return 2;_x000D_
  }_x000D_
}_x000D_
_x000D_
class B extends A {_x000D_
  constructor( input ) {_x000D_
    super( input );_x000D_
    this.tight = B.getResult( input ) + " (of B)";_x000D_
  }_x000D_
  _x000D_
  get scaledProperty() {_x000D_
    return parseInt( this.loose ) * 10000;_x000D_
  }_x000D_
_x000D_
  static get scale() {_x000D_
    return 4;_x000D_
  }_x000D_
}_x000D_
_x000D_
class C extends B {_x000D_
  constructor( input ) {_x000D_
    super( input );_x000D_
  }_x000D_
  _x000D_
  static get scale() {_x000D_
    return 5;_x000D_
  }_x000D_
}_x000D_
_x000D_
class D extends C {_x000D_
  constructor( input ) {_x000D_
    super( input );_x000D_
  }_x000D_
  _x000D_
  static getResult( input ) {_x000D_
    return super.getResult( input ) + " (overridden)";_x000D_
  }_x000D_
  _x000D_
  static get scale() {_x000D_
    return 10;_x000D_
  }_x000D_
}_x000D_
_x000D_
_x000D_
let instanceA = new A( 4 );_x000D_
console.log( "A.loose", instanceA.loose );_x000D_
console.log( "A.tight", instanceA.tight );_x000D_
_x000D_
let instanceB = new B( 4 );_x000D_
console.log( "B.loose", instanceB.loose );_x000D_
console.log( "B.tight", instanceB.tight );_x000D_
_x000D_
let instanceC = new C( 4 );_x000D_
console.log( "C.loose", instanceC.loose );_x000D_
console.log( "C.tight", instanceC.tight );_x000D_
_x000D_
let instanceD = new D( 4 );_x000D_
console.log( "D.loose", instanceD.loose );_x000D_
console.log( "D.tight", instanceD.tight );
_x000D_
_x000D_
_x000D_

Ignore 'Security Warning' running script from command line

For those who want to access a file from an already loaded PowerShell session, either use Unblock-File to mark the file as safe (though you already need to have set a relaxed execution policy like Unrestricted for this to work), or change the execution policy just for the current PowerShell session:

Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process

How can I tell if a VARCHAR variable contains a substring?

The standard SQL way is to use like:

where @stringVar like '%thisstring%'

That is in a query statement. You can also do this in TSQL:

if @stringVar like '%thisstring%'

Creating a border like this using :before And :after Pseudo-Elements In CSS?

#footer:after
{
   content: "";
    width: 40px;
    height: 3px;
    background-color: #529600;
    left: 0;
    position: relative;
    display: block;
    top: 10px;
}

How to extract the first two characters of a string in shell scripting?

colrm — remove columns from a file

To leave first two chars, just remove columns starting from 3

cat file | colrm 3

Typescript interface default values

Can I tell the interface to default the properties I don't supply to null? What would let me do this

No. You cannot provide default values for interfaces or type aliases as they are compile time only and default values need runtime support

Alternative

But values that are not specified default to undefined in JavaScript runtimes. So you can mark them as optional:

interface IX {
  a: string,
  b?: any,
  c?: AnotherType
}

And now when you create it you only need to provide a:

let x: IX = {
    a: 'abc'
};

You can provide the values as needed:

x.a = 'xyz'
x.b = 123
x.c = new AnotherType()

Does svn have a `revert-all` command?

There is a command

svn revert -R .

OR
you can use the --depth=infinity, which is actually same as above:

svn revert --depth=infinity 

svn revert is inherently dangerous, since its entire purpose is to throw away data—namely, your uncommitted changes. Once you've reverted, Subversion provides no way to get back those uncommitted changes

TypeError: unhashable type: 'list' when using built-in set function

Sets require their items to be hashable. Out of types predefined by Python only the immutable ones, such as strings, numbers, and tuples, are hashable. Mutable types, such as lists and dicts, are not hashable because a change of their contents would change the hash and break the lookup code.

Since you're sorting the list anyway, just place the duplicate removal after the list is already sorted. This is easy to implement, doesn't increase algorithmic complexity of the operation, and doesn't require changing sublists to tuples:

def uniq(lst):
    last = object()
    for item in lst:
        if item == last:
            continue
        yield item
        last = item

def sort_and_deduplicate(l):
    return list(uniq(sorted(l, reverse=True)))

execJs: 'Could not find a JavaScript runtime' but execjs AND therubyracer are in Gemfile

when i generate rails g controller i got the same error. After that when do the following changes on Gemfile(in rails 4) everything went smooth.The changes i made was

gem 'execjs'
gem 'therubyracer', "0.11.4"
After that i can able to run the server and able to do all basic operations on the application.

How can I simulate an anchor click via jquery?

The question title says "How can I simulate an anchor click in jQuery?". Well, you can use the "trigger" or "triggerHandler" methods, like so:

<script type="text/javascript" src="path/to/jquery.js"></script>
<script type="text/javascript" src="path/to/thickbox.js"></script>
<script type="text/javascript">
$(function() {
    $('#btn').click(function() {
        $('#thickboxId').triggerHandler('click');
    })
})
</script>
...
<input id="btn" type="button" value="Click me">
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>

Not tested, this actual script, but I've used trigger et al before, and they worked a'ight.

UPDATE
triggerHandler doesn't actually do what the OP wants. I think 1421968 provides the best answer to this question.

Upload DOC or PDF using PHP

    <?php

    //create table

    /*

    --
    -- Database: `mydb`
    --

    -- --------------------------------------------------------

    --
    -- Table structure for table `tbl_user_data`
    --

    CREATE TABLE `tbl_user_data` (
      `attachment_id` int(11) NOT NULL,
      `attachment` varchar(200) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    --
    -- Indexes for dumped tables
    --

    --
    -- Indexes for table `tbl_user_data`
    --
    ALTER TABLE `tbl_user_data`
      ADD PRIMARY KEY (`attachment_id`);

    --
    -- AUTO_INCREMENT for dumped tables
    --

    --
    -- AUTO_INCREMENT for table `tbl_user_data`
    --
    ALTER TABLE `tbl_user_data`
      MODIFY `attachment_id` int(11) NOT NULL AUTO_INCREMENT;

      */
    $servername = "localhost";
    $username = "root";
    $password = "";
    // Create connection
    $dbname = "myDB";
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    if(isset($_POST['submit'])){

      $fileName=$_FILES["resume"]["name"];
      $fileSize=$_FILES["resume"]["size"]/1024;
      $fileType=$_FILES["resume"]["type"];
      $fileTmpName=$_FILES["resume"]["tmp_name"];
      $statusMsg = '';
      $random=rand(1111,9999);
      $newFileName=$random.$fileName;

      //file upload path
      $targetDir = "resumeUpload/";
      $fileName = basename($_FILES["resume"]["name"]);
      $targetFilePath = $targetDir . $newFileName;
      $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);

      if(!empty($_FILES["resume"]["name"])) {
          //allow certain file formats
          //$allowTypes = array('jpg','png','jpeg','gif','pdf','docx','doc');
          $allowTypes = array('pdf','docx','doc');
          if(in_array($fileType, $allowTypes)){
              //upload file to server
              if(move_uploaded_file($_FILES["resume"]["tmp_name"], $targetFilePath)){
                  $statusMsg = "The file ".$fileName. " has been uploaded.";
              }else{
                  $statusMsg = "Sorry, there was an error uploading your file.";
              }
          }else{
              $statusMsg = 'Sorry, only DOC,DOCX, & PDF files are allowed to upload.';
          }
      }else{
          $statusMsg = 'Please select a file to upload.';
      }

      //display status message
      echo $statusMsg;

      $sql="INSERT INTO `tbl_user_data` (`attachment_id`, `attachment`) VALUES
      ('NULL', '$newFileName')";

      if (mysqli_query($conn, $sql)) {

       $last_id = mysqli_insert_id($conn);
         echo "upload success";
      } else {
          echo "Error: " . $sql . "<br>" . mysqli_error($conn);
      }


    }

    ?>
    <form id="frm_upload" action="" method="post" enctype="multipart/form-data">
    Upload Resume:<input type="file" name="resume" id="resume">
    <button type="submit" name="submit">Apply  Now</button> 
    </form>

     //output sample[![check here for sample output][1]][1]

Write HTML string in JSON

4 Things You Must Do When Putting HTML in JSON:

1) Escape quotation marks used around HTML attributes like so <img src=\"someimage.png\" />

2) Escape the forward slash in HTML end tags. <div>Hello World!<\/div>. This is an ancient artifact of an old HTML spec that didn't want HTML parsers to get confused when putting strings in a <SCRIPT> tag. For some reason, today’s browsers still like it.

3) This one was totally bizarre. You should include a space between the tag name and the slash on self-closing tags. I have no idea why this is, but on MOST modern browsers, if you try using javascript to append a <li> tag as a child of an unordered list that is formatted like so: <ul/>, it won't work. It gets added to the DOM after the ul tag. But, if the code looks like this: <ul /> (notice the space before the /), everything works fine. Very strange indeed.

4) Be sure to encode any quotation marks that might be included in (bad) HTML content. This is the only thing that would really break the JSON by accidentally terminating the string early. Any " characters should be encoded as &quot; if it is meant to be included as HTML content.

via

Latex Multiple Linebreaks

\\\\

This works on pdfLatex. It creates 2 new lines for you.

How to insert values in two dimensional array programmatically?

You can't "add" values to an array as the array length is immutable. You can set values at specific array positions.

If you know how to do it with one-dimensional arrays then you know how to do it with n-dimensional arrays: There are no n-dimensional arrays in Java, only arrays of arrays (of arrays...).

But you can chain the index operator for array element access.

String[][] x = new String[2][];
x[0] = new String[1];
x[1] = new String[2];

x[0][0] = "a1";
    // No x[0][1] available
x[1][0] = "b1";
x[1][1] = "b2";

Note the dimensions of the child arrays don't need to match.

Regular expression: zero or more occurrences of optional character /

/*

If your delimiters are slash-based, escape it:

\/*

* means "0 or more of the previous repeatable pattern", which can be a single character, a character class or a group.

Change link color of the current page with CSS

Best and easiest solution:

For each page you want your respective link to change color to until switched, put an internal style in EACH PAGE for the VISITED attribute and make each an individual class in order to differentiate between links so you don't apply the feature to all accidentally. We'll use white as an example:

<style type="text/css">
.link1 a:visited {color:#FFFFFF;text-decoration:none;} 
</style>

For all other attributes such as LINK, ACTIVE and HOVER, you can keep those in your style.css. You'll want to include a VISITED there as well for the color you want the link to turn back to when you click a different link.

How to handle static content in Spring MVC?

The Problem is with URLPattern

Change your URL pattern on your servlet mapping from "/" to "/*"

Array Index Out of Bounds Exception (Java)

for ( i = 0; i < total.length; i++ );
                                    ^-- remove the semi-colon here

With this semi-colon, the loop loops until i == total.length, doing nothing, and then what you thought was the body of the loop is executed.

Looping through all the properties of object php

For testing purposes I use the following:

//return assoc array when called from outside the class it will only contain public properties and values 
var_dump(get_object_vars($obj)); 

How to edit default dark theme for Visual Studio Code?

You cannot "edit" a default theme, they are "locked in"

However, you can copy it into your own custom theme, with the exact modifications you'd like.

For more info, see these articles: https://code.visualstudio.com/Docs/customization/themes https://code.visualstudio.com/docs/extensions/install-extension#_your-extensions-folder

If all you want to change is the colors for C++ code, you should look at overwriting the c++ support colorizer. For info about that, go here: https://code.visualstudio.com/docs/customization/colorizer

EDIT: The dark theme is found here: https://github.com/Microsoft/vscode/tree/80f8000c10b4234c7b027dccfd627442623902d2/extensions/theme-colorful-defaults

EDIT2: To clarify:

Jquery to open Bootstrap v3 modal of remote url

A different perspective to the same problem away from Javascript and using php:

<a data-toggle="modal" href="#myModal">LINK</a>

<div class="modal fade" tabindex="-1" aria-labelledby="gridSystemModalLabel" id="myModal" role="dialog" style="max-width: 90%;">
    <div class="modal-dialog" style="text-align: left;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Title</h4>
            </div>
            <div class="modal-body">
                <?php include( 'remotefile.php'); ?>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

and put in the remote.php file your basic html source.

Gradle, Android and the ANDROID_HOME SDK location

In my case settings.gradle was missing.

Save the file and put it at the top level folder in your project, even you can copy from another project too.

Screenshot reference:

enter image description here

Hope this would save your time.

How to convert int to Integer

As mentioned, one way is to use

new Integer(my_int_value)

But you should not call the constructor for wrapper classes directly

So, modify the code accordingly:

mBitmapCache.put(Integer.valueOf(R.drawable.bg1),object);

How can I check if a command exists in a shell script?

The question doesn't specify a shell, so for those using fish (friendly interactive shell):

if command -v foo > /dev/null
  echo exists
else
  echo does not exist
end

For basic POSIX compatibility, we use the -v flag which is an alias for --search or -s.

Difference between JOIN and INNER JOIN

INNER JOIN = JOIN

INNER JOIN is the default if you don't specify the type when you use the word JOIN.

You can also use LEFT OUTER JOIN or RIGHT OUTER JOIN, in which case the word OUTER is optional, or you can specify CROSS JOIN.

OR

For an inner join, the syntax is:

SELECT ...
FROM TableA
[INNER] JOIN TableB

(in other words, the "INNER" keyword is optional - results are the same with or without it)

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

PreparedStatement with list of parameters in a IN clause

You need jdbc4 then you can use setArray!

In my case it didn't worked, as the UUID Datatype in postgres seems to still have its weak spots, but for the usual types it works.

ps.setArray(1, connection.createArrayOf("$VALUETYPE",myValuesAsArray));

Of course replace $VALUETYPE and myValuesAsArray with the correct values.

Remark following Marks comment:

Your database and the driver needs to support this! I tried Postgres 9.4 but I think this has been introduced earlier. You need a jdbc 4 driver, otherwise setArray won't be available. I used the postgresql 9.4-1201-jdbc41 driver that ships with spring boot

How to set MouseOver event/trigger for border in XAML?

Yes, this is confusing...

According to this blog post, it looks like this is an omission from WPF.

To make it work you need to use a style:

    <Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
        <Border.Style>
            <Style>
                <Setter Property="Border.Background" Value="Blue"/>
                <Style.Triggers>
                    <Trigger Property="Border.IsMouseOver" Value="True">
                        <Setter Property="Border.Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
    </Border>

I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.

How to break out of jQuery each Loop

I use this way (for example):

$(document).on('click', '#save', function () {
    var cont = true;
    $('.field').each(function () {
        if ($(this).val() === '') {
            alert('Please fill out all fields');
            cont = false;
            return false;
        }
    });
    if (cont === false) {
        return false;
    }
    /* commands block */
});

if cont isn't false runs commands block

How to run sql script using SQL Server Management Studio?

Found this in another thread that helped me: Use xp_cmdshell and sqlcmd Is it possible to execute a text file from SQL query? - by Gulzar Nazim

EXEC xp_cmdshell  'sqlcmd -S ' + @DBServerName + ' -d  ' + @DBName + ' -i ' + @FilePathName

Class constants in python

class Animal:
    HUGE = "Huge"
    BIG = "Big"

class Horse:
    def printSize(self):
        print(Animal.HUGE)

How do I uninstall a package installed using npm link?

If you've done something like accidentally npm link generator-webapp after you've changed it, you can fix it by cloning the right generator and linking that.

git clone https://github.com/yeoman/generator-webapp.git;
# for fixing generator-webapp, replace with your required repository
cd generator-webapp;
npm link;

Converting BigDecimal to Integer

Can you guarantee that the BigDecimal will never contain a value larger than Integer.MAX_VALUE?

If yes, then here's your code calling intValue:

Integer.valueOf(bdValue.intValue())

remove legend title in ggplot

You were almost there : just add theme(legend.title=element_blank())

ggplot(df, aes(x, y, colour=g)) +
  geom_line(stat="identity") + 
  theme(legend.position="bottom") +
  theme(legend.title=element_blank())

This page on Cookbook for R gives plenty of details on how to customize legends.

Deprecation warning in Moment.js - Not in a recognized ISO format

Add the following line in your code to Suppress the warnings:

const moment = require('moment');

moment.suppressDeprecationWarnings = true;

Extract the maximum value within each group in a dataframe

df$Gene <- as.factor(df$Gene)
do.call(rbind, lapply(split(df,df$Gene), function(x) {return(x[which.max(x$Value),])}))

Just using base R

Encrypting & Decrypting a String in C#

If you are targeting ASP.NET Core that does not support RijndaelManaged yet, you can use IDataProtectionProvider.

First, configure your application to use data protection:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDataProtection();
    }
    // ...
}

Then you'll be able to inject IDataProtectionProvider instance and use it to encrypt/decrypt data:

public class MyService : IService
{
    private const string Purpose = "my protection purpose";
    private readonly IDataProtectionProvider _provider;

    public MyService(IDataProtectionProvider provider)
    {
        _provider = provider;
    }

    public string Encrypt(string plainText)
    {
        var protector = _provider.CreateProtector(Purpose);
        return protector.Protect(plainText);
    }

    public string Decrypt(string cipherText)
    {
        var protector = _provider.CreateProtector(Purpose);
        return protector.Unprotect(cipherText);
    }
}

See this article for more details.

git: can't push (unpacker error) related to permission issues

Where I work we have been using this method on all of our repositories for a few years without any problems (except when we create a new repository and forget to set it up this way):

  1. Set 'sharedRepository = true' in the config file's '[core]' section.
  2. Change the group id of the repository to a group shared by all users who are allowed to push to it:

    chgrp -R shared_group /git/our_repos
    chmod -R g+w /git/our_repos
    
  3. Set the setgid bit on all directories in the repository so that new files/directories keep the same group:

    find /git/our_repos -type d -exec chmod g+s {} +
    
  4. Add this line to the pre-receive hook in the repository to ensure new file permissions allow group read/write:

    umask 007
    

How do I force a DIV block to extend to the bottom of a page even if it has no content?

Try Ryan Fait's "Sticky Footer" solution,

http://ryanfait.com/sticky-footer/
http://ryanfait.com/resources/footer-stick-to-bottom-of-page/

Works across IE, Firefox, Chrome, Safari and supposedly Opera too, but haven't tested that. It's a great solution. Very easy and reliable to implement.

Github permission denied: ssh add agent has no identities

first of all you need to go in your ssh directory
for this type following command in your terminal in mac or whatever you use in window

cd ~/.ssh

now it is in the ssh
here you can find all you ssh key/files related to your all projects. now, type the following command to show you if any ssh key available

ls

this will show you all available ssh, in my case there were two
now, you will need to start an agent to add a ssh in it. For this type following command

eval "$(ssh-agent -s)"

now last but not least you will add a ssh in this agent type following command

ssh-add ~/.ssh/your-ssh

replace

replace your-ssh with your ssh file name which you got a list form second step ls command

cast class into another class or convert class to another

I tried to use the Cast Extension (see https://stackoverflow.com/users/247402/stacker) in a situation where the Target Type contains a Property that is not present in the Source Type. It did not work, I'm not sure why. I refactored to the following extension that did work for my situation:

public static T Casting<T>(this Object source)
{
    Type sourceType = source.GetType();
    Type targetType = typeof(T);
    var target =  Activator.CreateInstance(targetType, false);
    var sourceMembers = sourceType.GetMembers()
        .Where(x => x.MemberType  == MemberTypes.Property)
        .ToList();
    var targetMembers = targetType.GetMembers()
        .Where(x => x.MemberType == MemberTypes.Property)
        .ToList();
    var members = targetMembers
        .Where(x => sourceMembers
            .Select(y => y.Name)
                .Contains(x.Name));
    PropertyInfo propertyInfo;
    object value;
    foreach (var memberInfo in members)
    {
        propertyInfo = typeof(T).GetProperty(memberInfo.Name);
        value = source.GetType().GetProperty(memberInfo.Name).GetValue(source, null);
        propertyInfo.SetValue(target, value, null);
    }
    return (T)target;
}

Note that I changed the name of the extension as the Name Cast conflicts with results from Linq. Hat tip https://stackoverflow.com/users/2093880/usefulbee

logout and redirecting session in php

<?php //initialize the session if (!isset($_SESSION)) {   session_start(); } 
// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
    $logoutAction .= "&". htmlentities($_SERVER['QUERY_STRING']); 
}

if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")) {
    // to fully log out a visitor we need to clear the session variables
    $_SESSION['MM_Username'] = NULL;
    $_SESSION['MM_UserGroup'] = NULL;
    $_SESSION['PrevUrl'] = NULL;
    unset($_SESSION['MM_Username']);  
    unset($_SESSION['MM_UserGroup']);
    unset($_SESSION['PrevUrl']);
    $logoutGoTo = "index.php";

    if ($logoutGoTo) {
        header("Location: $logoutGoTo");
        exit;
    }
} ?>

Jersey Exception : SEVERE: A message body reader for Java class

Q) Code was working fine in Intellj but failing in command line.

Sol) Add dependencies of jersey as a direct dependency rather than a transient one.

Reasoning: Since, it was working fine with IntelliJ, dependencies are correctly configured.

  1. Get required dependencies by one of the following:

    1. check for the IntelliJ running command. Stackoverflow-link
    2. List dependencies from maven mvn dependency:tree
  2. Now, add those problematic jersey dependencies explicitly.

Execute curl command within a Python script

You could use urllib as @roippi said:

import urllib2
data = '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}'
url = 'http://localhost:8080/firewall/rules/0000000000000001'
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
for x in f:
    print(x)
f.close()

Replace only text inside a div using jquery

Another approach is keep that element, change the text, then append that element back

const star_icon = $(li).find('.stars svg')
$(li).find('.stars').text(repo.stargazers_count).append(star_icon)

Create a new workspace in Eclipse

I use File -> Switch Workspace -> Other... and type in my new workspace name.

New workspace composite screenshot (EDIT: Added the composite screen shot.)

Once in the new workspace, File -> Import... and under General choose "Existing Projects into Workspace. Press the Next button and then Browse for the old projects you would like to import. Check "Copy projects into workspace" to make a copy.

Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304'

So in general dll has to be placed in two places:

  1. GAC ( can have 32 and 64 versions of dll's)
  2. your project bin folder

Thus, you just need add reference to log4net.dll. (In your case 32-bit with PublicKeyToken=692fbea5521e1304)

You can achive that by

How can I get the application's path in a .NET console application?

There are many ways to get executable path, which one we should use it depends on our needs here is a link which discuss different methods.

Different ways to get Application Executable Path

What is the preferred/idiomatic way to insert into a map?

Since C++17 std::map offers two new insertion methods: insert_or_assign() and try_emplace(), as also mentioned in the comment by sp2danny.

insert_or_assign()

Basically, insert_or_assign() is an "improved" version of operator[]. In contrast to operator[], insert_or_assign() doesn't require the map's value type to be default constructible. For example, the following code doesn't compile, because MyClass does not have a default constructor:

class MyClass {
public:
    MyClass(int i) : m_i(i) {};
    int m_i;
};

int main() {
    std::map<int, MyClass> myMap;

    // VS2017: "C2512: 'MyClass::MyClass' : no appropriate default constructor available"
    // Coliru: "error: no matching function for call to 'MyClass::MyClass()"
    myMap[0] = MyClass(1);

    return 0;
}

However, if you replace myMap[0] = MyClass(1); by the following line, then the code compiles and the insertion takes place as intended:

myMap.insert_or_assign(0, MyClass(1));

Moreover, similar to insert(), insert_or_assign() returns a pair<iterator, bool>. The Boolean value is true if an insertion occurred and false if an assignment was done. The iterator points to the element that was inserted or updated.

try_emplace()

Similar to the above, try_emplace() is an "improvement" of emplace(). In contrast to emplace(), try_emplace() doesn't modify its arguments if insertion fails due to a key already existing in the map. For example, the following code attempts to emplace an element with a key that is already stored in the map (see *):

int main() {
    std::map<int, std::unique_ptr<MyClass>> myMap2;
    myMap2.emplace(0, std::make_unique<MyClass>(1));

    auto pMyObj = std::make_unique<MyClass>(2);    
    auto [it, b] = myMap2.emplace(0, std::move(pMyObj));  // *

    if (!b)
        std::cout << "pMyObj was not inserted" << std::endl;

    if (pMyObj == nullptr)
        std::cout << "pMyObj was modified anyway" << std::endl;
    else
        std::cout << "pMyObj.m_i = " << pMyObj->m_i <<  std::endl;

    return 0;
}

Output (at least for VS2017 and Coliru):

pMyObj was not inserted
pMyObj was modified anyway

As you can see, pMyObj no longer points to the original object. However, if you replace auto [it, b] = myMap2.emplace(0, std::move(pMyObj)); by the the following code, then the output looks different, because pMyObj remains unchanged:

auto [it, b] = myMap2.try_emplace(0, std::move(pMyObj));

Output:

pMyObj was not inserted
pMyObj pMyObj.m_i = 2

Code on Coliru

Please note: I tried to keep my explanations as short and simple as possible to fit them into this answer. For a more precise and comprehensive description, I recommend reading this article on Fluent C++.

Stack array using pop() and push()

Here is an example of implementing stack in java (Array Based implementation):

public class MyStack extends Throwable{

/**
 * 
 */
private static final long serialVersionUID = -4433344892390700337L;

protected static int top = -1;
protected static int capacity;
protected static int size;

public int stackDatas[] = null;

public MyStack(){
    stackDatas = new int[10];
    capacity = stackDatas.length;
}

public static int size(){

    if(top < 0){
        size = top + 1;
        return size;
    }
    size = top+1;
    return size; 
}

public void push(int data){
    if(capacity == size()){
        System.out.println("no memory");
    }else{
        stackDatas[++top] = data;
    }
}

public boolean topData(){
    if(top < 0){
        return true;
    }else{
        System.out.println(stackDatas[top]);
        return false;
    }
}

public void pop(){
    if(top < 0){
        System.out.println("stack is empty");
    }else{
        int temp = stackDatas[top];
        stackDatas = ArrayUtils.remove(stackDatas, top--);
        System.out.println("poped data---> "+temp);
    }
}

public String toString(){
    String result = "[";

    if(top<0){
        return "[]";
    }else{


    for(int i = 0; i< size(); i++){
        result = result + stackDatas[i] +",";
    }
    }

    return result.substring(0, result.lastIndexOf(",")) +"]";
 }
}

calling MyStack:

    public class CallingMyStack {

public static MyStack ms;

public static void main(String[] args) {

    ms = new MyStack();
    ms.push(1);
    ms.push(2);
    ms.push(3);
    ms.push(4);
    ms.push(5);
    ms.push(6);
    ms.push(7);
    ms.push(8);
    ms.push(9);
    ms.push(10);
    System.out.println("size: "+MyStack.size());
    System.out.println("List---> "+ms);
    System.out.println("----------");
    ms.pop();
    ms.pop();
    ms.pop();
    ms.pop();
    System.out.println("List---> "+ms);
    System.out.println("size: "+MyStack.size());

 }
}

output:

size: 10
List---> [1,2,3,4,5,6,7,8,9,10]
----------
poped data---> 10
poped data---> 9
poped data---> 8
poped data---> 7
List---> [1,2,3,4,5,6]
size: 6

How do I plot in real-time in a while loop using matplotlib?

show is probably not the best choice for this. What I would do is use pyplot.draw() instead. You also might want to include a small time delay (e.g., time.sleep(0.05)) in the loop so that you can see the plots happening. If I make these changes to your example it works for me and I see each point appearing one at a time.

Get selected element's outer HTML

I have made this simple test with outerHTML being tokimon solution (without clone), and outerHTML2 being jessica solution (clone)

console.time("outerHTML");
for(i=0;i<1000;i++)
 {                 
  var html = $("<span style='padding:50px; margin:50px; display:block'><input type='text' title='test' /></span>").outerHTML();
 }                 
console.timeEnd("outerHTML");

console.time("outerHTML2");

 for(i=0;i<1000;i++)
 {                 
   var html = $("<span style='padding:50px; margin:50px; display:block'><input type='text' title='test' /></span>").outerHTML2();
  }                 
  console.timeEnd("outerHTML2");

and the result in my chromium (Version 20.0.1132.57 (0)) browser was

outerHTML: 81ms
outerHTML2: 439ms

but if we use tokimon solution without the native outerHTML function (which is now supported in probably almost every browser)

we get

outerHTML: 594ms
outerHTML2: 332ms

and there are gonna be more loops and elements in real world examples, so the perfect combination would be

$.fn.outerHTML = function() 
{
  $t = $(this);
  if( "outerHTML" in $t[0] ) return $t[0].outerHTML; 
  else return $t.clone().wrap('<p>').parent().html(); 
}

so clone method is actually faster than wrap/unwrap method
(jquery 1.7.2)

Div 100% height works on Firefox but not in IE

I think "works fine in Firefox" is in the Quirks mode rendering only. In the Standard mode rendering, that might not work fine in Firefox too.

percentage depends on "containing block", instead of viewport.

CSS Specification says

The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'.

so

#container { height: auto; }
#container #mainContentsWrapper { height: n%; }
#container #sidebarWrapper { height: n%; }

means

#container { height: auto; }
#container #mainContentsWrapper { height: auto; }
#container #sidebarWrapper { height: auto; }

To stretch to 100% height of viewport, you need to specify the height of the containing block (in this case, it's #container). Moreover, you also need to specify the height to body and html, because initial Containing Block is "UA-dependent".

All you need is...

html, body { height:100%; }
#container { height:100%; }

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.

enter image description here enter image description here

Getting Unexpected Token Export

You are using ES6 Module syntax.

This means your environment (e.g. node.js) must support ES6 Module syntax.

NodeJS uses CommonJS Module syntax (module.exports) not ES6 module syntax (export keyword).

Solution:

  • Use babel npm package to transpile your ES6 to a commonjs target

or

  • Refactor with CommonJS syntax.

Examples of CommonJS syntax are (from flaviocopes.com/commonjs/):

  • exports.uppercase = str => str.toUpperCase()
  • exports.a = 1

error 1265. Data truncated for column when trying to load data from txt file

I had this issue when trying to convert an existing varchar column to enum. For me the issue was that there were existing values for that column that were not part of the enum's list of accepted values. So if your enum will only allow values, say ('dog', 'cat') but there is a row with bird in your table, the MODIFY COLUMN will fail with this error.

How do I get the value of a textbox using jQuery?

Noticed your comment about using it for email validation and needing a plugin, the validation plugin may help you, its located at http://bassistance.de/jquery-plugins/jquery-plugin-validation/, it comes with a e-mail rule as well.

Download history stock prices automatically from yahoo finance in python

Short answer: Yes. Use Python's urllib to pull the historical data pages for the stocks you want. Go with Yahoo! Finance; Google is both less reliable, has less data coverage, and is more restrictive in how you can use it once you have it. Also, I believe Google specifically prohibits you from scraping the data in their ToS.

Longer answer: This is the script I use to pull all the historical data on a particular company. It pulls the historical data page for a particular ticker symbol, then saves it to a csv file named by that symbol. You'll have to provide your own list of ticker symbols that you want to pull.

import urllib

base_url = "http://ichart.finance.yahoo.com/table.csv?s="
def make_url(ticker_symbol):
    return base_url + ticker_symbol

output_path = "C:/path/to/output/directory"
def make_filename(ticker_symbol, directory="S&P"):
    return output_path + "/" + directory + "/" + ticker_symbol + ".csv"

def pull_historical_data(ticker_symbol, directory="S&P"):
    try:
        urllib.urlretrieve(make_url(ticker_symbol), make_filename(ticker_symbol, directory))
    except urllib.ContentTooShortError as e:
        outfile = open(make_filename(ticker_symbol, directory), "w")
        outfile.write(e.content)
        outfile.close()

Run batch file as a Windows service

As Doug Currie says use RunAsService.

From my past experience you must remember that the Service you generate will

  • have a completely different set of environment variables
  • have to be carefully inspected for rights/permissions issues
  • might cause havoc if it opens dialogs asking for any kind of input

not sure if the last one still applies ... it was one big night mare in a project I worked on some time ago.

<DIV> inside link (<a href="">) tag

This is a classic case of divitis - you don't need a div to be clickable, just give the <a> tag a class. Then edit the CSS of the class to display:block, and define a height and width like a lot of other answers have mentioned.

The <a> tag works perfectly well on its own, so you don't need an extra level of mark-up on the page.

JavaFX Application Icon

I used this in my application

Image icon = new Image(getClass().getResourceAsStream("icon.png"));
window.getIcons().add(icon);

Here window is the stage.

100% Min Height CSS layout

Here is another solution based on vh, or viewpoint height, for details visit CSS units. It is based on this solution, which uses flex instead.

_x000D_
_x000D_
* {_x000D_
    /* personal preference */_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
html {_x000D_
    /* make sure we use up the whole viewport */_x000D_
    width: 100%;_x000D_
    min-height: 100vh;_x000D_
    /* for debugging, a red background lets us see any seams */_x000D_
    background-color: red;_x000D_
}_x000D_
body {_x000D_
    /* make sure we use the full width but allow for more height */_x000D_
    width: 100%;_x000D_
    min-height: 100vh; /* this helps with the sticky footer */_x000D_
}_x000D_
main {_x000D_
    /* for debugging, a blue background lets us see the content */_x000D_
    background-color: skyblue;_x000D_
 min-height: calc(100vh - 2.5em); /* this leaves space for the sticky footer */_x000D_
}_x000D_
footer {_x000D_
    /* for debugging, a gray background lets us see the footer */_x000D_
    background-color: gray;_x000D_
 min-height:2.5em;_x000D_
}
_x000D_
<main>_x000D_
    <p>This is the content. Resize the viewport vertically to see how the footer behaves.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
</main>_x000D_
<footer>_x000D_
    <p>This is the footer. Resize the viewport horizontally to see how the height behaves when text wraps.</p>_x000D_
    <p>This is the footer.</p>_x000D_
</footer>
_x000D_
_x000D_
_x000D_

The units are vw , vh, vmax, vmin. Basically, each unit is equal to 1% of viewport size. So, as the viewport changes, the browser computes that value and adjusts accordingly.

You may find more information here:

Specifically:

1vw (viewport width) = 1% of viewport width
1vh (viewport height) = 1% of viewport height
1vmin (viewport minimum) = 1vw or 1vh, whatever is smallest
1vmax (viewport minimum) = 1vw or 1vh, whatever is largest

How to make IPython notebook matplotlib plot inline

Ctrl + Enter

%matplotlib inline

Magic Line :D

See: Plotting with Matplotlib.

What are the differences between Abstract Factory and Factory design patterns?

Let us put it clear that most of the time in production code, we use abstract factory pattern because class A is programmed with interface B. And A needs to create instances of B. So A has to have a factory object to produce instances of B. So A is not dependent on any concrete instance of B. Hope it helps.

How to retrieve the dimensions of a view?

CORRECTION: I found out that the above solution is terrible. Especially when your phone is slow. And here, I found another solution: calculate out the px value of the element, including the margins and paddings: dp to px: https://stackoverflow.com/a/6327095/1982712

or dimens.xml to px: https://stackoverflow.com/a/16276351/1982712

sp to px: https://stackoverflow.com/a/9219417/1982712 (reverse the solution)

or dimens to px: https://stackoverflow.com/a/16276351/1982712

and that's it.

What is the difference between Release and Debug modes in Visual Studio?

Debug and Release are just labels for different solution configurations. You can add others if you want. A project I once worked on had one called "Debug Internal" which was used to turn on the in-house editing features of the application. You can see this if you go to Configuration Manager... (it's on the Build menu). You can find more information on MSDN Library under Configuration Manager Dialog Box.

Each solution configuration then consists of a bunch of project configurations. Again, these are just labels, this time for a collection of settings for your project. For example, our C++ library projects have project configurations called "Debug", "Debug_Unicode", "Debug_MT", etc.

The available settings depend on what type of project you're building. For a .NET project, it's a fairly small set: #defines and a few other things. For a C++ project, you get a much bigger variety of things to tweak.

In general, though, you'll use "Debug" when you want your project to be built with the optimiser turned off, and when you want full debugging/symbol information included in your build (in the .PDB file, usually). You'll use "Release" when you want the optimiser turned on, and when you don't want full debugging information included.

bower automatically update bower.json

from bower help, save option has a capital S

-S, --save  Save installed packages into the project's bower.json dependencies

Parse date without timezone javascript

The Date object itself will contain timezone anyway, and the returned result is the effect of converting it to string in a default way. I.e. you cannot create a date object without timezone. But what you can do is mimic the behavior of Date object by creating your own one. This is, however, better to be handed over to libraries like moment.js.

Refreshing page on click of a button

<button type="button" onClick="refreshPage()">Close</button>

<script>
function refreshPage(){
    window.location.reload();
} 
</script>

or

<button type="button" onClick="window.location.reload();">Close</button>

Using a Loop to add objects to a list(python)

Auto-incrementing the index in a loop:

myArr[(len(myArr)+1)]={"key":"val"}

How to get base url with jquery or javascript?

I've run into this need on several Joomla project. The simplest way I've found to address is to add a hidden input field to my template:

<input type="hidden" id="baseurl" name="baseurl" value="<?php echo $this->baseurl; ?>" />

When I need the value in JavaScript:

var baseurl = document.getElementById('baseurl').value;

Not as fancy as using pure JavaScript but simple and gets the job done.

Is it possible to use the SELECT INTO clause with UNION [ALL]?

SELECT * INTO tmpFerdeen FROM 
(SELECT top(100)*  
FROM Customers 
UNION All 
SELECT top(100)*  
FROM CustomerEurope 
UNION All 
SELECT top(100)*  
FROM CustomerAsia 
UNION All 
SELECT top(100)*  
FROM CustomerAmericas) AS Blablabal

This "Blablabal" is necessary

What is the difference between canonical name, simple name and class name in Java Class?

It is interesting to note that getCanonicalName() and getSimpleName() can raise InternalError when the class name is malformed. This happens for some non-Java JVM languages, e.g., Scala.

Consider the following (Scala 2.11 on Java 8):

scala> case class C()
defined class C

scala> val c = C()
c: C = C()

scala> c.getClass.getSimpleName
java.lang.InternalError: Malformed class name
  at java.lang.Class.getSimpleName(Class.java:1330)
  ... 32 elided

scala> c.getClass.getCanonicalName
java.lang.InternalError: Malformed class name
  at java.lang.Class.getSimpleName(Class.java:1330)
  at java.lang.Class.getCanonicalName(Class.java:1399)
  ... 32 elided

scala> c.getClass.getName
res2: String = C

This can be a problem for mixed language environments or environments that dynamically load bytecode, e.g., app servers and other platform software.

Center text in table cell

How about simply (Please note, come up with a better name for the class name this is simply an example):

.centerText{
   text-align: center;
}


<div>
   <table style="width:100%">
   <tbody>
   <tr>
      <td class="centerText">Cell 1</td>
      <td>Cell 2</td>
    </tr>
    <tr>
      <td class="centerText">Cell 3</td>
      <td>Cell 4</td>
    </tr>
    </tbody>
    </table>
</div>

Example here

You can place the css in a separate file, which is recommended. In my example, I created a file called styles.css and placed my css rules in it. Then include it in the html document in the <head> section as follows:

<head>
    <link href="styles.css" rel="stylesheet" type="text/css">
</head>

The alternative, not creating a seperate css file, not recommended at all... Create <style> block in your <head> in the html document. Then just place your rules there.

<head>
 <style type="text/css">
   .centerText{
       text-align: center;
    }
 </style>
</head>

How to consume a webApi from asp.net Web API to store result in database?

In this tutorial is explained how to consume a web api with C#, in this example a console application is used, but you can also use another web api to consume of course.

http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

You should have a look at the HttpClient

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost/yourwebapi");

Make sure your requests ask for the response in JSON using the Accept header like this:

client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));

Now comes the part that differs from the tutorial, make sure you have the same objects as the other WEB API, if not, then you have to map the objects to your own objects. ASP.NET will convert the JSON you receive to the object you want it to be.

HttpResponseMessage response = client.GetAsync("api/yourcustomobjects").Result;
if (response.IsSuccessStatusCode)
{
    var yourcustomobjects = response.Content.ReadAsAsync<IEnumerable<YourCustomObject>>().Result;
    foreach (var x in yourcustomobjects)
    {
        //Call your store method and pass in your own object
        SaveCustomObjectToDB(x);
    }
}
else
{
    //Something has gone wrong, handle it here
}

please note that I use .Result for the case of the example. You should consider using the async await pattern here.

Unable to run Java code with Intellij IDEA

-First Move Your Code Files in side the "src" Folder

-Make sure your Main method is declared like the following

   public class Main {
         public static void main(String []args){


       }
    }

then:

  • Go to Project configurations
  • select Java application,
  • check allow parallel run
  • and select your main class

and it should work

How to copy files from host to Docker container?

My favorite method:

CONTAINERS:

CONTAINER_ID=$(docker ps | grep <string> | awk '{ print $1 }' | xargs docker inspect -f '{{.Id}}')

file.txt

mv -f file.txt /var/lib/docker/devicemapper/mnt/$CONTAINER_ID/rootfs/root/file.txt

or

mv -f file.txt /var/lib/docker/aufs/mnt/$CONTAINER_ID/rootfs/root/file.txt

Insert all values of a table into another table in SQL

I think this statement might do what you want.

INSERT INTO newTableName (SELECT column1, column2, column3 FROM oldTable);

Django {% with %} tags within {% if %} {% else %} tags?

Like this:

{% if age > 18 %}
    {% with patient as p %}
    <my html here>
    {% endwith %}
{% else %}
    {% with patient.parent as p %}
    <my html here>
    {% endwith %}
{% endif %}

If the html is too big and you don't want to repeat it, then the logic would better be placed in the view. You set this variable and pass it to the template's context:

p = (age > 18 && patient) or patient.parent

and then just use {{ p }} in the template.

What is the reason for having '//' in Python?

// is unconditionally "flooring division", e.g:

>>> 4.0//1.5
2.0

As you see, even though both operands are floats, // still floors -- so you always know securely what it's going to do.

Single / may or may not floor depending on Python release, future imports, and even flags on which Python's run, e.g.:

$ python2.6 -Qold -c 'print 2/3'
0
$ python2.6 -Qnew -c 'print 2/3'
0.666666666667

As you see, single / may floor, or it may return a float, based on completely non-local issues, up to and including the value of the -Q flag...;-).

So, if and when you know you want flooring, always use //, which guarantees it. If and when you know you don't want flooring, slap a float() around other operand and use /. Any other combination, and you're at the mercy of version, imports, and flags!-)

CSS ''background-color" attribute not working on checkbox inside <div>

A checkbox does not have background color.

But to add the effect, you may wrap each checkbox with a div that has color:

<div class="evenRow">
    <input type="checkbox" />
</div>
<div class="oddRow">
    <input type="checkbox" />
</div>
<div class="evenRow">
    <input type="checkbox" />
</div>
<div class="oddRow">
    <input type="checkbox" />
</div>

Distribution certificate / private key not installed

This answer is for "One Man" Team to solve this problem quickly without reading through too many information about "Team"

Step 1) Go to web browser, open your developer account. Go to Certificates, Identifiers & Profiles. Select Certificates / Production. You will see the certificate that was missing private key listed there. Click Revoke. And follow the instructions to remove this certificate. enter image description here Step 2) That's it! go back to Xcode to Validate you app. It will now ask you to generate a new certificate. Now you happily uploading your apps.

MemoryStream - Cannot access a closed Stream

Since .net45 you can use the LeaveOpen constructor argument of StreamWriter and still use the using statement. Example:

using (var ms = new MemoryStream())
{
    using (var sw = new StreamWriter(ms, Encoding.UTF8, 1024, true))
    {
        sw.WriteLine("data");
        sw.WriteLine("data 2");    
    }

    ms.Position = 0;
    using (var sr = new StreamReader(ms))
    {
        Console.WriteLine(sr.ReadToEnd());
    }
}

Select All distinct values in a column using LINQ

Interestingly enough I tried both of these in LinqPad and the variant using group from Dmitry Gribkov by appears to be quicker. (also the final distinct is not required as the result is already distinct.

My (somewhat simple) code was:

public class Pair 
{ 
    public int id {get;set;}
    public string Arb {get;set;}
}

void Main()
{

    var theList = new List<Pair>();
    var randomiser = new Random();
    for (int count = 1; count < 10000; count++)
    {
        theList.Add(new Pair 
        {
            id = randomiser.Next(1, 50),
            Arb = "not used"
        });
    }

    var timer = new Stopwatch();
    timer.Start();
    var distinct = theList.GroupBy(c => c.id).Select(p => p.First().id);
    timer.Stop();
    Debug.WriteLine(timer.Elapsed);

    timer.Start();
    var otherDistinct = theList.Select(p => p.id).Distinct();
    timer.Stop();
    Debug.WriteLine(timer.Elapsed);
}

How do I fix the indentation of an entire file in Vi?

:set paste is your friend I use putty and end up copying code between windows. Before I was turned on to :set paste (and :set nopaste) copy/paste gave me fits for that very reason.

How to pass a value from Vue data to href?

Or you can do that with ES6 template literal:

<a :href="`/job/${r.id}`"

How to catch a unique constraint error in a PL/SQL block?

EXCEPTION
      WHEN DUP_VAL_ON_INDEX
      THEN
         UPDATE

Javascript Image Resize

Use JQuery

var scale=0.5;

minWidth=50;
minHeight=100;

if($("#id img").width()*scale>minWidth && $("#id img").height()*scale >minHeight)
{
    $("#id img").width($("#id img").width()*scale);
    $("#id img").height($("#id img").height()*scale);
}

Converting serial port data to TCP/IP in a Linux environment

You don't need to write a program to do this in Linux. Just pipe the serial port through netcat:

netcat www.example.com port </dev/ttyS0 >/dev/ttyS0

Just replace the address and port information. Also, you may be using a different serial port (i.e. change the /dev/ttyS0 part). You can use the stty or setserial commands to change the parameters of the serial port (baud rate, parity, stop bits, etc.).

Python: tf-idf-cosine: to find document similarity

WIth the Help of @excray's comment, I manage to figure it out the answer, What we need to do is actually write a simple for loop to iterate over the two arrays that represent the train data and test data.

First implement a simple lambda function to hold formula for the cosine calculation:

cosine_function = lambda a, b : round(np.inner(a, b)/(LA.norm(a)*LA.norm(b)), 3)

And then just write a simple for loop to iterate over the to vector, logic is for every "For each vector in trainVectorizerArray, you have to find the cosine similarity with the vector in testVectorizerArray."

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from nltk.corpus import stopwords
import numpy as np
import numpy.linalg as LA

train_set = ["The sky is blue.", "The sun is bright."] #Documents
test_set = ["The sun in the sky is bright."] #Query
stopWords = stopwords.words('english')

vectorizer = CountVectorizer(stop_words = stopWords)
#print vectorizer
transformer = TfidfTransformer()
#print transformer

trainVectorizerArray = vectorizer.fit_transform(train_set).toarray()
testVectorizerArray = vectorizer.transform(test_set).toarray()
print 'Fit Vectorizer to train set', trainVectorizerArray
print 'Transform Vectorizer to test set', testVectorizerArray
cx = lambda a, b : round(np.inner(a, b)/(LA.norm(a)*LA.norm(b)), 3)

for vector in trainVectorizerArray:
    print vector
    for testV in testVectorizerArray:
        print testV
        cosine = cx(vector, testV)
        print cosine

transformer.fit(trainVectorizerArray)
print
print transformer.transform(trainVectorizerArray).toarray()

transformer.fit(testVectorizerArray)
print 
tfidf = transformer.transform(testVectorizerArray)
print tfidf.todense()

Here is the output:

Fit Vectorizer to train set [[1 0 1 0]
 [0 1 0 1]]
Transform Vectorizer to test set [[0 1 1 1]]
[1 0 1 0]
[0 1 1 1]
0.408
[0 1 0 1]
[0 1 1 1]
0.816

[[ 0.70710678  0.          0.70710678  0.        ]
 [ 0.          0.70710678  0.          0.70710678]]

[[ 0.          0.57735027  0.57735027  0.57735027]]

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

Using DirectoryIterator and recursion correctly:

function deleteFilesThenSelf($folder) {
    foreach(new DirectoryIterator($folder) as $f) {
        if($f->isDot()) continue; // skip . and ..
        if ($f->isFile()) {
            unlink($f->getPathname());
        } else if($f->isDir()) {
            deleteFilesThenSelf($f->getPathname());
        }
    }
    rmdir($folder);
}

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

Try to this cors npm modules.

var cors = require('cors')

var app = express()
app.use(cors())

This module provides many features to fine tune cors setting such as domain whitelisting, enabling cors for specific apis etc.

What is deserialize and serialize in JSON?

Explanation of Serialize and Deserialize using Python

In python, pickle module is used for serialization. So, the serialization process is called pickling in Python. This module is available in Python standard library.

Serialization using pickle

import pickle

#the object to serialize
example_dic={1:"6",2:"2",3:"f"}

#where the bytes after serializing end up at, wb stands for write byte
pickle_out=open("dict.pickle","wb")
#Time to dump
pickle.dump(example_dic,pickle_out)
#whatever you open, you must close
pickle_out.close()

The PICKLE file (can be opened by a text editor like notepad) contains this (serialized data):

€}q (KX 6qKX 2qKX fqu.

Deserialization using pickle

import pickle

pickle_in=open("dict.pickle","rb")
get_deserialized_data_back=pickle.load(pickle_in)

print(get_deserialized_data_back)

Output:

{1: '6', 2: '2', 3: 'f'}

How to send an HTTPS GET Request in C#

Add ?var1=data1&var2=data2 to the end of url to submit values to the page via GET:

using System.Net;
using System.IO;

string url = "https://www.example.com/scriptname.php?var1=hello";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();

Angular 2 'component' is not a known element

A lot of answers/comments mention components defined in other modules, or that you have to import/declare the component (that you want to use in another component) in its/their containing module.

But in the simple case where you want to use component A from component B when both are defined in the same module, you have to declare both components in the containing module for B to see A, and not only A.

I.e. in my-module.module.ts

import { AComponent } from "./A/A.component";
import { BComponent } from "./B/B.component";

@NgModule({
  declarations: [
    AComponent,   // This is the one that we naturally think of adding ..
    BComponent,   // .. but forget this one and you get a "**'AComponent'** 
                  // is not a known element" error.
  ],
})

Calculate the execution time of a method

StopWatch will use the high-resolution counter

The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time. Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.

If you're measuring IO then your figures will likely be impacted by external events, and I would worry so much re. exactness (as you've indicated above). Instead I'd take a range of measurements and consider the mean and distribution of those figures.

What are all codecs and formats supported by FFmpeg?

You can see the list of supported codecs in the official documentation:

Supported video codecs

Supported audio codecs

Inserting code in this LaTeX document with indentation

Minted, whether from GitHub or CTAN, the Comprehensive TeX Archive Network, works in Overleaf, TeX Live and MiKTeX.

It requires the installation of the Python package Pygments; this is explained in the documentation in either source above. Although Pygments brands itself as a Python syntax highlighter, Minted guarantees the coverage of hundreds of other languages.

Example:

\documentclass{article}
\usepackage{minted}
\begin{document}

\begin{minted}[mathescape, linenos]{python}

# Note: $\pi=\lim_{n\to\infty}\frac{P_n}{d}$
title = "Hello World"

sum = 0
for i in range(10):
 sum += i

\end{minted}

\end{document}

Output:

enter image description here

AngularJS : Clear $watch

Ideally, every custom watch should be removed when you leave the scope.

It helps in better memory management and better app performance.

// call to $watch will return a de-register function
var listener = $scope.$watch(someVariableToWatch, function(....));

$scope.$on('$destroy', function() {
    listener(); // call the de-register function on scope destroy
});

Get cookie by name

Use object.defineProperty

With this, you can easily access cookies

Object.defineProperty(window, "Cookies", {
    get: function() {
        return document.cookie.split(';').reduce(function(cookies, cookie) {
            cookies[cookie.split("=")[0]] = unescape(cookie.split("=")[1]);
            return cookies
        }, {});
    }
});

From now on you can just do:

alert( Cookies.obligations );

This will automatically update too, so if you change a cookie, the Cookies will change too.

Stored procedure - return identity as output parameter or scalar

Either as recordset or output parameter. The latter has less overhead and I'd tend to use that rather than a single column/row recordset.

If I expected to >1 row I'd use the OUTPUT clause and a recordset

Return values would normally be used for error handling.

How can I obtain the element-wise logical NOT of a pandas Series?

NumPy is slower because it casts the input to boolean values (so None and 0 becomes False and everything else becomes True).

import pandas as pd
import numpy as np
s = pd.Series([True, None, False, True])
np.logical_not(s)

gives you

0    False
1     True
2     True
3    False
dtype: object

whereas ~s would crash. In most cases tilde would be a safer choice than NumPy.

Pandas 0.25, NumPy 1.17

The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

Remove the standard.jar. It's apparently of old JSTL 1.0 version when the TLD URIs were without the /jsp path. With JSTL 1.2 as available here you don't need a standard.jar at all. Just the jstl-1.2.jar in /WEB-INF/lib is sufficient.

See also:

DateTime.MinValue and SqlDateTime overflow

Very simple avoid using DateTime.MinValue use System.Data.SqlTypes.SqlDateTime.MinValue instead.

Anaconda export Environment file

I find exporting the packages in string format only is more portable than exporting the whole conda environment. As the previous answer already suggested:

$ conda list -e > requirements.txt

However, this requirements.txt contains build numbers which are not portable between operating systems, e.g. between Mac and Ubuntu. In conda env export we have the option --no-builds but not with conda list -e, so we can remove the build number by issuing the following command:

$ sed -i -E "s/^(.*\=.*)(\=.*)/\1/" requirements.txt 

And recreate the environment on another computer:

conda create -n recreated_env --file requirements.txt 

How to solve static declaration follows non-static declaration in GCC C code?

I have had this issue in a case where the static function was called before it was declared. Moving the function declaration to anywhere above the call solved my problem.

Selecting fields from JSON output

Assume you stored that dictionary in a variable called values. To get id in to a variable, do:

idValue = values['criteria'][0]['id']

If that json is in a file, do the following to load it:

import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()

If that json is from a URL, do the following to load it:

import urllib, json
f = urllib.urlopen("http://domain/path/jsonPage")
values = json.load(f)
f.close()

To print ALL of the criteria, you could:

for criteria in values['criteria']:
    for key, value in criteria.iteritems():
        print key, 'is:', value
    print ''

C# if/then directives for debug vs release

Since the purpose of these COMPILER directives are to tell the compiler NOT to include code, debug code,beta code, or perhaps code that is needed by all of your end users, except say those the advertising department, i.e. #Define AdDept you want to be able include or remove them based on your needs. Without having to change your source code if for example a non AdDept merges into the AdDept. Then all that needs to be done is to include the #AdDept directive in the compiler options properties page of an existing version of the program and do a compile and wa la! the merged program's code springs alive!.

You might also want to use a declarative for a new process that is not ready for prime time or that can not be active in the code until it's time to release it.

Anyhow, that's the way I do it.

SqlServer: Login failed for user

I faced with same problem. I've used Entity Framework and thought that DB will be created automatically. Please make sure your DB exists and has a correct name.

What's the difference between RANK() and DENSE_RANK() functions in oracle?

Rank(), Dense_rank(), row_number() These all are window functions that means they act as window over some ordered input set at first. These windows have different functionality attached to it based on the requirement. Heres the above 3 :

row_number()

Starting by row_number() as this forms the basis of these related window functions. row_number() as the name suggests gives a unique number to the set of rows over which its been applied. Similar to giving a serial number to each row.

Rank()

A subversion of row_number() can be said as rank(). Rank() is used to give same serial number to those ordered set rows which are duplicates but it still keeps the count mantained as similar to a row_number() for all those after duplicates rank() meaning as from below eg. For data 2 row_number() =rank() meaning both just differs in the form of duplicates.

Data row_number() rank() dense_rank() 
    1         1                    1       1
    1         2                    1       1
    1         3                    1       1
    2         4                    4       2

Finally,

Dense_rank() is an extended version of rank() as the name suggests its dense because as you can see from the above example rank() = dense_rank() for all data 1 but just that for data 2 it differs in the form that it mantains the order of rank() from previous rank() not the actual data

Splitting String and put it on int array

Something like this:

  public static void main(String[] args) {
   String N = "ABCD";
   char[] array = N.toCharArray();

   // and as you can see:
    System.out.println(array[0]);
    System.out.println(array[1]);
    System.out.println(array[2]);
  }

Build a basic Python iterator

This question is about iterable objects, not about iterators. In Python, sequences are iterable too so one way to make an iterable class is to make it behave like a sequence, i.e. give it __getitem__ and __len__ methods. I have tested this on Python 2 and 3.

class CustomRange:

    def __init__(self, low, high):
        self.low = low
        self.high = high

    def __getitem__(self, item):
        if item >= len(self):
            raise IndexError("CustomRange index out of range")
        return self.low + item

    def __len__(self):
        return self.high - self.low


cr = CustomRange(0, 10)
for i in cr:
    print(i)

How to globally replace a forward slash in a JavaScript string?

You need to wrap the forward slash to avoid cross browser issues or //commenting out.

str = 'this/that and/if';

var newstr = str.replace(/[/]/g, 'ForwardSlash');

Increasing Heap Size on Linux Machines

You can use the following code snippet :

java -XX:+PrintFlagsFinal -Xms512m -Xmx1024m -Xss512k -XX:PermSize=64m -XX:MaxPermSize=128m
    -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'

In my pc I am getting following output :

    uintx InitialHeapSize                          := 536870912       {product}
    uintx MaxHeapSize                              := 1073741824      {product}
    uintx PermSize                                 := 67108864        {pd product}
    uintx MaxPermSize                              := 134217728       {pd product}
     intx ThreadStackSize                          := 512             {pd product}

How can I install Python's pip3 on my Mac?

To install or upgrade pip, download get-pip.py from the official site. Then run the following command:

sudo python get-pip.py 

and it will install pip for your python version which runs the script.

gnuplot - adjust size of key/legend

To adjust the length of the samples:

set key samplen X

(default is 4)

To adjust the vertical spacing of the samples:

set key spacing X

(default is 1.25)

and (for completeness), to adjust the fontsize:

set key font "<face>,<size>"

(default depends on the terminal)

And of course, all these can be combined into one line:

set key samplen 2 spacing .5 font ",8"

Note that you can also change the position of the key using set key at <position> or any one of the pre-defined positions (which I'll just defer to help key at this point)

Unfortunately Launcher3 has stopped working error in android studio?

I didn't found any particular answer to this question but i deleted the emulator and create a new one and increase the Ram size of the new emulator.Then the emulator works fine.

Find and replace in file and overwrite file doesn't work, it empties the file

use sed's -i option, e.g.

sed -i bak -e s/STRING_TO_REPLACE/REPLACE_WITH/g index.html

Display an image with Python

In a much simpler way, you can do the same using

from PIL import Image

image = Image.open('image.jpg')
image.show()

Can you test google analytics on a localhost address?

Answer for 2019

The best practice is to setup two separate properties for your development/staging, and your production servers. You do not want to pollute your Analytics data with test, and setting up filters is not pleasant if you are forced to do that.

That being said, Google Analytics now has real time tracking, and if you want to track Campaigns or Transactions, the lag is around 1 minute until the data is shown on the page, as long as you select the current day.

For example, you create Site and Site Test, and each one ha UA-XXXX-Y code.

In your application logic, where you serve the analytics JavaScript, check your environment and for production use your Site UA-XXXX-Y, and for staging/development use the Site Test one.

You can have this setup until you learn the ins and outs of GA, and then remove it, or keep it if you need to make constant changes (which you will test on development/staging first).

Source: personal experience, various articles.

How do I filter an array with TypeScript in Angular 2?

You can check an example in Plunker over here plunker example filters

filter() {

    let storeId = 1;
    this.bookFilteredList = this.bookList
                                .filter((book: Book) => book.storeId === storeId);
    this.bookList = this.bookFilteredList; 
}

How to download/upload files from/to SharePoint 2013 using CSOM?

A little late this comment but I will leave here my results working with the library of SharePoin Online and it is very easy to use and implement in your project, just go to the NuGet administrator of .Net and Add Microsoft.SharePoint.CSOM to your project .

https://developer.microsoft.com/en-us/office/blogs/new-sharepoint-csom-version-released-for-office-365-may-2017/

The following code snippet will help you connect your credentials to your SharePoint site, you can also read and download files from a specific site and folder.

using System;
using System.IO;
using System.Linq;
using System.Web;
using Microsoft.SharePoint.Client;
using System.Security;

using ClientOM = Microsoft.SharePoint.Client;

namespace MvcApplication.Models.Home
{
    public class SharepointModel
    {
        public ClientContext clientContext { get; set; }
        private string ServerSiteUrl = "https://somecompany.sharepoint.com/sites/ITVillahermosa";
        private string LibraryUrl = "Shared Documents/Invoices/";
        private string UserName = "[email protected]";
        private string Password = "********";
        private Web WebClient { get; set; }

        public SharepointModel()
        {
            this.Connect();
        }

        public void Connect()
        {
            try
            {
                using (clientContext = new ClientContext(ServerSiteUrl))
                {
                    var securePassword = new SecureString();
                    foreach (char c in Password)
                    {
                        securePassword.AppendChar(c);
                    }

                    clientContext.Credentials = new SharePointOnlineCredentials(UserName, securePassword);
                    WebClient = clientContext.Web;
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        public string UploadMultiFiles(HttpRequestBase Request, HttpServerUtilityBase Server)
        {
            try
            {
                HttpPostedFileBase file = null;
                for (int f = 0; f < Request.Files.Count; f++)
                {
                    file = Request.Files[f] as HttpPostedFileBase;

                    string[] SubFolders = LibraryUrl.Split('/');
                    string filename = System.IO.Path.GetFileName(file.FileName);
                    var path = System.IO.Path.Combine(Server.MapPath("~/App_Data/uploads"), filename);
                    file.SaveAs(path);

                    clientContext.Load(WebClient, website => website.Lists, website => website.ServerRelativeUrl);
                    clientContext.ExecuteQuery();

                    //https://somecompany.sharepoint.com/sites/ITVillahermosa/Shared Documents/
                    List documentsList = clientContext.Web.Lists.GetByTitle("Documents"); //Shared Documents -> Documents
                    clientContext.Load(documentsList, i => i.RootFolder.Folders, i => i.RootFolder);
                    clientContext.ExecuteQuery();

                    string SubFolderName = SubFolders[1];//Get SubFolder 'Invoice'
                    var folderToBindTo = documentsList.RootFolder.Folders;
                    var folderToUpload = folderToBindTo.Where(i => i.Name == SubFolderName).First();

                    var fileCreationInformation = new FileCreationInformation();
                    //Assign to content byte[] i.e. documentStream
                    fileCreationInformation.Content = System.IO.File.ReadAllBytes(path);
                    //Allow owerwrite of document
                    fileCreationInformation.Overwrite = true;
                    //Upload URL
                    fileCreationInformation.Url = ServerSiteUrl + LibraryUrl + filename;

                    Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(fileCreationInformation);

                    //Update the metadata for a field having name "DocType"
                    uploadFile.ListItemAllFields["Title"] = "UploadedCSOM";

                    uploadFile.ListItemAllFields.Update();
                    clientContext.ExecuteQuery();
                }

                return "";
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        public string DownloadFiles()
        {
            try
            {
                string tempLocation = @"c:\Downloads\Sharepoint\";
                System.IO.DirectoryInfo di = new DirectoryInfo(tempLocation);
                foreach (FileInfo file in di.GetFiles())
                {
                    file.Delete();
                }

                FileCollection files = WebClient.GetFolderByServerRelativeUrl(this.LibraryUrl).Files;
                clientContext.Load(files);
                clientContext.ExecuteQuery();

                if (clientContext.HasPendingRequest)
                    clientContext.ExecuteQuery();

                foreach (ClientOM.File file in files)
                {
                    FileInformation fileInfo = ClientOM.File.OpenBinaryDirect(clientContext, file.ServerRelativeUrl);
                    clientContext.ExecuteQuery();

                    var filePath = tempLocation + file.Name;
                    using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
                    {
                        fileInfo.Stream.CopyTo(fileStream);
                    }
                }

                return "";
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

    }
}

Then to invoke the functions from the controller in this case MVC ASP.NET is done in the following way.


using MvcApplication.Models.Home;
using System;
using System.Web.Mvc;

namespace MvcApplication.Controllers
{
    public class SharepointController : MvcBoostraBaseController
    {
        [HttpPost]
        public ActionResult Upload(FormCollection form)
        {
            try
            {
                SharepointModel sharepointModel = new SharepointModel();
                return Json(sharepointModel.UploadMultiFiles(Request, Server), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return ThrowJSONError(ex);
            }
        }

        public ActionResult Download(string ServerUrl, string RelativeUrl)
        {
            try
            {
                SharepointModel sharepointModel = new SharepointModel();
                return Json(sharepointModel.DownloadFiles(), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return ThrowJSONError(ex);
            }
        }
    }
}

If you need the source code of this project you can request it to [email protected]

When to use async false and async true in ajax function in jquery

  1. When async setting is set to false, a Synchronous call is made instead of an Asynchronous call.
  2. When the async setting of the jQuery AJAX function is set to true then a jQuery Asynchronous call is made. AJAX itself means Asynchronous JavaScript and XML and hence if you make it Synchronous by setting async setting to false, it will no longer be an AJAX call.
  3. for more information please refer this link

Sleep function in C++

The simplest way I found for C++ 11 was this:

Your includes:

#include <chrono>
#include <thread>

Your code (this is an example for sleep 1000 millisecond):

std::chrono::duration<int, std::milli> timespan(1000);
std::this_thread::sleep_for(timespan);

The duration could be configured to any of the following:

std::chrono::nanoseconds   duration</*signed integer type of at least 64 bits*/, std::nano>
std::chrono::microseconds  duration</*signed integer type of at least 55 bits*/, std::micro>
std::chrono::milliseconds  duration</*signed integer type of at least 45 bits*/, std::milli>
std::chrono::seconds       duration</*signed integer type of at least 35 bits*/, std::ratio<1>>  
std::chrono::minutes       duration</*signed integer type of at least 29 bits*/, std::ratio<60>>
std::chrono::hours         duration</*signed integer type of at least 23 bits*/, std::ratio<3600>>

Rails: Why "sudo" command is not recognized?

sudo is used for Linux. It looks like you are running this in Windows.

IE8 issue with Twitter Bootstrap 3

Just as a heads up. I had the same problem and none of the above fixed it for me. Eventually I found out that respond.js doesn't parse CSS referenced via @import. I had the whole bootstrap.min.css imported via @import into my main.css.

So make sure you don't have any CSS that contains your media queries referenced via @import.

Java string split with "." (dot)

You need to escape the dot if you want to split on a literal dot:

String extensionRemoved = filename.split("\\.")[0];

Otherwise you are splitting on the regex ., which means "any character".
Note the double backslash needed to create a single backslash in the regex.


You're getting an ArrayIndexOutOfBoundsException because your input string is just a dot, ie ".", which is an edge case that produces an empty array when split on dot; split(regex) removes all trailing blanks from the result, but since splitting a dot on a dot leaves only two blanks, after trailing blanks are removed you're left with an empty array.

To avoid getting an ArrayIndexOutOfBoundsException for this edge case, use the overloaded version of split(regex, limit), which has a second parameter that is the size limit for the resulting array. When limit is negative, the behaviour of removing trailing blanks from the resulting array is disabled:

".".split("\\.", -1) // returns an array of two blanks, ie ["", ""]

ie, when filename is just a dot ".", calling filename.split("\\.", -1)[0] will return a blank, but calling filename.split("\\.")[0] will throw an ArrayIndexOutOfBoundsException.

Get the last day of the month in SQL

For SQL server 2012 or above use EOMONTH to get the last date of month

SQL query to display end date of current month

DECLARE @currentDate DATE = GETDATE()
SELECT EOMONTH (@currentDate) AS CurrentMonthED

SQL query to display end date of Next month

DECLARE @currentDate DATE = GETDATE()
SELECT EOMONTH (@currentDate, 1 ) AS NextMonthED

assign value using linq

Be aware that it only updates the first company it found with company id 1. For multiple

 (from c in listOfCompany where c.id == 1 select c).First().Name = "Whatever Name";

For Multiple updates

 from c in listOfCompany where c.id == 1 select c => {c.Name = "Whatever Name";  return c;}

How to get week number of the month from the date in sql server 2008

select @DateCreated, DATEDIFF(WEEK, @DateCreated, GETDATE())

JavaScript backslash (\) in variables is causing an error

The jsfiddle link to where i tried out your query http://jsfiddle.net/A8Dnv/1/ its working fine @Imrul as mentioned you are using C# on server side and you dont mind that either: http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape.aspx

Disable Buttons in jQuery Mobile

UPDATE:

Since this question still gets a lot of hits I'm also adding the current jQM Docs on how to disable the button:

Updated Examples:

enable enable a disabled form button

$('[type="submit"]').button('enable');  

disable disable a form button

$('[type="submit"]').button('disable'); 

refresh update the form button
If you manipulate a form button via JavaScript, you must call the refresh method on it to update the visual styling.

$('[type="submit"]').button('refresh');

Original Post Below:

Live Example: http://jsfiddle.net/XRjh2/2/

UPDATE:

Using @naugtur example below: http://jsfiddle.net/XRjh2/16/

UPDATE #2:

Link button example:

JS

var clicked = false;

$('#myButton').click(function() {
    if(clicked === false) {
        $(this).addClass('ui-disabled');
        clicked = true;
        alert('Button is now disabled');
    } 
});

$('#enableButton').click(function() {
    $('#myButton').removeClass('ui-disabled');
    clicked = false; 
});

HTML

<div data-role="page" id="home">
    <div data-role="content">

        <a href="#" data-role="button" id="myButton">Click button</a>
        <a href="#" data-role="button" id="enableButton">Enable button</a>

    </div>
</div>

NOTE: - http://jquerymobile.com/demos/1.0rc2/docs/buttons/buttons-types.html

Links styled like buttons have all the same visual options as true form-based buttons below, but there are a few important differences. Link-based buttons aren't part of the button plugin and only just use the underlying buttonMarkup plugin to generate the button styles so the form button methods (enable, disable, refresh) aren't supported. If you need to disable a link-based button (or any element), it's possible to apply the disabled class ui-disabled yourself with JavaScript to achieve the same effect.

How to sum all column values in multi-dimensional array?

Here you have how I usually do this kind of operations.

// We declare an empty array in wich we will store the results
$sumArray = array();

// We loop through all the key-value pairs in $myArray
foreach ($myArray as $k=>$subArray) {

   // Each value is an array, we loop through it
   foreach ($subArray as $id=>$value) {

       // If $sumArray has not $id as key we initialize it to zero  
       if(!isset($sumArray[$id])){
           $sumArray[$id] = 0;
       }

       // If the array already has a key named $id, we increment its value
       $sumArray[$id]+=$value;
    }
 }

 print_r($sumArray);

ORA-01036: illegal variable name/number when running query through C#

The root cause

In Oracle you have three kinds of SQL statements (and additionally there are PL/SQL blocks):

  • Statements in the Data Definiton Language (DDL). These statements modify the structure of the database. They begin usually with the verbs "ALTER" or "CREATE"
  • Statements in the Data Modification Langugage (DML). There statements modify the content inside of tables, leaving the structure of each table unmodified. These statements usually begin with "INSERT", "MERGE" or "DELETE".
  • Statements in what I call "query language" (there seems to be no canonical name for these). This statements start with the verb "SELECT".

Bind variables in Oracle are only allowed in some special places in DML and query statements. You are trying to use bind variables in a places where they are not allowed. Hence the error.

Solution

Build your statement without bind variables. Build the complete query string instead using string concatenation.

If you want to sanitize the input before concatenating the string, use the DBMS_ASSERT package.

Background

Bind variables can only be used when Oracle can build a query plan without knowing the value of the variable. For DDL statements, there is no query plan. Hence bind variables are not allowed.

In DML and query statements, bind variables are only allowed, when they are used inside a tuple (regarding the underlying set theory), i.e. when the value will be compared with the value in a table or when the value will be inserted in a table. They are not allowed to change the structure of the execution plan (e.g. to change the target table or to change the number of comparisons).

How to debug Ruby scripts

To easily debug Ruby shell script, just change its first line from:

#!/usr/bin/env ruby

to:

#!/usr/bin/env ruby -rdebug

Then every time when debugger console is shown, you can choose:

  • c for Continue (to the next Exception, breakpoint or line with: debugger),
  • n for Next line,
  • w/where to Display frame/call stack,
  • l to Show the current code,
  • cat to show catchpoints.
  • h for more Help.

See also: Debugging with ruby-debug, Key shortcuts for ruby-debug gem.


In case the script just hangs and you need a backtrace, try using lldb/gdb like:

echo 'call (void)rb_backtrace()' | lldb -p $(pgrep -nf ruby)

and then check your process foreground.

Replace lldb with gdb if works better. Prefix with sudo to debug non-owned process.

How can I listen to the form submit event in javascript?

Based on your requirements you can also do the following without libraries like jQuery:

Add this to your head:

window.onload = function () {
    document.getElementById("frmSubmit").onsubmit = function onSubmit(form) {
        var isValid = true;
        //validate your elems here
        isValid = false;

        if (!isValid) {
            alert("Please check your fields!");
            return false;
        }
        else {
            //you are good to go
            return true;
        }
    }
}

And your form may still look something like:

    <form id="frmSubmit" action="/Submit">
        <input type="submit" value="Submit" />
    </form>

WPF global exception handler

You can handle the AppDomain.UnhandledException event

EDIT: actually, this event is probably more adequate: Application.DispatcherUnhandledException

How to change the port of Tomcat from 8080 to 80?

Just goto conf folder of tomcat

open the server.xml file

Goto one of the connector node which look like the following

<Connector port="8080" protocol="HTTP/1.1" 
           connectionTimeout="20000" 
           redirectPort="8443" />

Simply change the port

save and restart tomcat