Programs & Examples On #Custom protocol

Angularjs autocomplete from $http

I made an autocomplete directive and uploaded it to GitHub. It should also be able to handle data from an HTTP-Request.

Here's the demo: http://justgoscha.github.io/allmighty-autocomplete/ And here the documentation and repository: https://github.com/JustGoscha/allmighty-autocomplete

So basically you have to return a promise when you want to get data from an HTTP request, that gets resolved when the data is loaded. Therefore you have to inject the $qservice/directive/controller where you issue your HTTP Request.

Example:

function getMyHttpData(){
  var deferred = $q.defer();
  $http.jsonp(request).success(function(data){
    // the promise gets resolved with the data from HTTP
    deferred.resolve(data);
  });
  // return the promise
  return deferred.promise;
}

I hope this helps.

UITableView - scroll to the top

func scrollToTop() {
        NSIndexPath *topItem = [NSIndexPath indexPathForItem:0 inSection:0];
        [tableView scrollToRowAtIndexPath:topItem atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

call this function wherever you want UITableView scroll to top

Datatables Select All Checkbox

I made a simple implementation of this functionality using fontawesome, also taking advantage of the Select Extension, this covers select all, deselect some items, deselect all. https://codepen.io/pakogn/pen/jJryLo

HTML:

<table id="example" class="display" style="width:100%">
    <thead>
        <tr>
            <th>
                <button style="border: none; background: transparent; font-size: 14px;" id="MyTableCheckAllButton">
                <i class="far fa-square"></i>  
                </button>
            </th>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Salary</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td></td>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>61</td>
            <td>$320,800</td>
        </tr>
        <tr>
            <td></td>
            <td>Garrett Winters</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>63</td>
            <td>$170,750</td>
        </tr>
        <tr>
            <td></td>
            <td>Ashton Cox</td>
            <td>Junior Technical Author</td>
            <td>San Francisco</td>
            <td>66</td>
            <td>$86,000</td>
        </tr>
        <tr>
            <td></td>
            <td>Cedric Kelly</td>
            <td>Senior Javascript Developer</td>
            <td>Edinburgh</td>
            <td>22</td>
            <td>$433,060</td>
        </tr>
        <tr>
            <td></td>
            <td>Airi Satou</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>33</td>
            <td>$162,700</td>
        </tr>
        <tr>
            <td></td>
            <td>Brielle Williamson</td>
            <td>Integration Specialist</td>
            <td>New York</td>
            <td>61</td>
            <td>$372,000</td>
        </tr>
        <tr>
            <td></td>
            <td>Herrod Chandler</td>
            <td>Sales Assistant</td>
            <td>San Francisco</td>
            <td>59</td>
            <td>$137,500</td>
        </tr>
        <tr>
            <td></td>
            <td>Rhona Davidson</td>
            <td>Integration Specialist</td>
            <td>Tokyo</td>
            <td>55</td>
            <td>$327,900</td>
        </tr>
        <tr>
            <td></td>
            <td>Colleen Hurst</td>
            <td>Javascript Developer</td>
            <td>San Francisco</td>
            <td>39</td>
            <td>$205,500</td>
        </tr>
        <tr>
            <td></td>
            <td>Sonya Frost</td>
            <td>Software Engineer</td>
            <td>Edinburgh</td>
            <td>23</td>
            <td>$103,600</td>
        </tr>
        <tr>
            <td></td>
            <td>Jena Gaines</td>
            <td>Office Manager</td>
            <td>London</td>
            <td>30</td>
            <td>$90,560</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <th></th>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Salary</th>
        </tr>
    </tfoot>
</table>

Javascript:

$(document).ready(function() {
    let myTable = $('#example').DataTable({
        columnDefs: [{
            orderable: false,
            className: 'select-checkbox',
            targets: 0,
        }],
        select: {
            style: 'os', // 'single', 'multi', 'os', 'multi+shift'
            selector: 'td:first-child',
        },
        order: [
            [1, 'asc'],
        ],
    });

    $('#MyTableCheckAllButton').click(function() {
        if (myTable.rows({
                selected: true
            }).count() > 0) {
            myTable.rows().deselect();
            return;
        }

        myTable.rows().select();
    });

    myTable.on('select deselect', function(e, dt, type, indexes) {
        if (type === 'row') {
            // We may use dt instead of myTable to have the freshest data.
            if (dt.rows().count() === dt.rows({
                    selected: true
                }).count()) {
                // Deselect all items button.
                $('#MyTableCheckAllButton i').attr('class', 'far fa-check-square');
                return;
            }

            if (dt.rows({
                    selected: true
                }).count() === 0) {
                // Select all items button.
                $('#MyTableCheckAllButton i').attr('class', 'far fa-square');
                return;
            }

            // Deselect some items button.
            $('#MyTableCheckAllButton i').attr('class', 'far fa-minus-square');
        }
    });
});

adding comment in .properties files

According to the documentation of the PropertyFile task, you can append the generated properties to an existing file. You could have a properties file with just the comment line, and have the Ant task append the generated properties.

Is < faster than <=?

At the very least, if this were true a compiler could trivially optimise a <= b to !(a > b), and so even if the comparison itself were actually slower, with all but the most naive compiler you would not notice a difference.

convert double to int

if you use cast, that is, (int)SomeDouble you will truncate the fractional part. That is, if SomeDouble were 4.9999 the result would be 4, not 5. Converting to int doesn't round the number. If you want rounding use Math.Round

Why is AJAX returning HTTP status code 0?

It is important to note, that ajax calls can fail even within a session which is defined by a cookie with a certain domain prefixed with www. When you then call your php script e.g. without the www. prefix in the url, the call will fail and viceversa, too.

mongodb/mongoose findMany - find all documents with IDs listed in array

Combining Daniel's and snnsnn's answers:

_x000D_
_x000D_
let ids = ['id1','id2','id3']
let data = await MyModel.find(
  {'_id': { $in: ids}}
);
_x000D_
_x000D_
_x000D_

Simple and clean code. It works and tested against:

"mongodb": "^3.6.0", "mongoose": "^5.10.0",

Finding last occurrence of substring in string, replacing that

I would use a regex:

import re
new_list = [re.sub(r"\.(?=[^.]*$)", r". - ", s) for s in old_list]

How to select current date in Hive SQL

According to the LanguageManual, you can use unix_timestamp() to get the "current time stamp using the default time zone." If you need to convert that to something more human-readable, you can use from_unixtime(unix_timestamp()).

Hope that helps.

Android Studio : How to uninstall APK (or execute adb command) automatically before Run or Debug?

A simple three-step process (checked on mac terminal)

  1. Connect your android device (please connect 1 android Device at a time), preferably by a cable & Confirm connection by (this will list Device's ID device ID)

    adb devices
    
  2. Then to list all app packages on the connected device by running, on terminal

    adb shell pm list packages -f -3 
    
  3. Then uninstall as explained earlier

    adb uninstall <package_name> 
    

Copy Paste Values only( xlPasteValues )

you may use this:

Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

Gradient of n colors ranging from color 1 and color 2

colorRampPalette could be your friend here:

colfunc <- colorRampPalette(c("black", "white"))
colfunc(10)
# [1] "#000000" "#1C1C1C" "#383838" "#555555" "#717171" "#8D8D8D" "#AAAAAA"
# [8] "#C6C6C6" "#E2E2E2" "#FFFFFF"

And just to show it works:

plot(rep(1,10),col=colfunc(10),pch=19,cex=3)

enter image description here

hadoop copy a local file system folder to HDFS

In Short

hdfs dfs -put <localsrc> <dest>

In detail with example:

Checking source and target before placing files into HDFS

[cloudera@quickstart ~]$ ll files/
total 132
-rwxrwxr-x 1 cloudera cloudera  5387 Nov 14 06:33 cloudera-manager
-rwxrwxr-x 1 cloudera cloudera  9964 Nov 14 06:33 cm_api.py
-rw-rw-r-- 1 cloudera cloudera   664 Nov 14 06:33 derby.log
-rw-rw-r-- 1 cloudera cloudera 53655 Nov 14 06:33 enterprise-deployment.json
-rw-rw-r-- 1 cloudera cloudera 50515 Nov 14 06:33 express-deployment.json

[cloudera@quickstart ~]$ hdfs dfs -ls
Found 1 items
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 00:45 .sparkStaging

Copy files HDFS using -put or -copyFromLocal command

[cloudera@quickstart ~]$ hdfs dfs -put files/ files

Verify the result in HDFS

[cloudera@quickstart ~]$ hdfs dfs -ls
Found 2 items
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 00:45 .sparkStaging
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 06:34 files

[cloudera@quickstart ~]$ hdfs dfs -ls files
Found 5 items
-rw-r--r--   1 cloudera cloudera       5387 2017-11-14 06:34 files/cloudera-manager
-rw-r--r--   1 cloudera cloudera       9964 2017-11-14 06:34 files/cm_api.py
-rw-r--r--   1 cloudera cloudera        664 2017-11-14 06:34 files/derby.log
-rw-r--r--   1 cloudera cloudera      53655 2017-11-14 06:34 files/enterprise-deployment.json
-rw-r--r--   1 cloudera cloudera      50515 2017-11-14 06:34 files/express-deployment.json

How to call webmethod in Asp.net C#

Necro'ing this Question ;)

You need to change the data being sent as Stringified JSON, that way you can modularize the Ajax call into a single supportable function.

First Step: Extract data construction

/***
 * This helper is used to call WebMethods from the page WebMethods.aspx
 * 
 * @method - String value; the name of the Web Method to execute
 * @data - JSON Object; the JSON structure data to pass, it will be Stringified
 *      before sending
 * @beforeSend - Function(xhr, sett)
 * @success - Function(data, status, xhr)
 * @error - Function(xhr, status, err)
 */
function AddToCartAjax(method, data, beforeSend, success, error) {
    $.ajax({
        url: 'AddToCart.aspx/', + method,
        data: JSON.stringify(data),
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        beforeSend: beforeSend,
        success: success,
        error: error
    })
}

Second Step: Generalize WebMethod

[WebMethod]
public static string AddTo_Cart ( object items ) {
    var js = new JavaScriptSerializer();
    var json = js.ConvertToType<Dictionary<string , int>>( items );

    SpiritsShared.ShoppingCart.AddItem(json["itemId"], json["quantity"]);      
    return "Add";
}

Third Step: Call it where you need it

This can be called just about anywhere, JS-file, HTML-file, or Server-side construction.

var items = { "quantity": total_qty, "itemId": itemId };

AddToCartAjax("AddTo_Cart", items,
    function (xhr, sett) {  // @beforeSend
        alert("Start!!!");
    }, function (data, status, xhr) {   // @success
        alert("a");
    }, function(xhr, status, err){  // @error
        alert("Sorry!!!");
    });

Avoid Adding duplicate elements to a List C#

If you don't want duplicates in a list, use a HashSet. That way it will be clear to anyone else reading your code what your intention was and you'll have less code to write since HashSet already handles what you are trying to do.

SQLite string contains other string query

While LIKE is suitable for this case, a more general purpose solution is to use instr, which doesn't require characters in the search string to be escaped. Note: instr is available starting from Sqlite 3.7.15.

SELECT *
  FROM TABLE  
 WHERE instr(column, 'cats') > 0;

Also, keep in mind that LIKE is case-insensitive, whereas instr is case-sensitive.

SQL Bulk Insert with FIRSTROW parameter skips the following line

I found it easiest to just read the entire line into one column then parse out the data using XML.

IF (OBJECT_ID('tempdb..#data') IS NOT NULL) DROP TABLE #data
CREATE TABLE #data (data VARCHAR(MAX))

BULK INSERT #data FROM 'E:\filefromabove.txt' WITH (FIRSTROW = 2, ROWTERMINATOR = '\n')

IF (OBJECT_ID('tempdb..#dataXml') IS NOT NULL) DROP TABLE #dataXml
CREATE TABLE #dataXml (ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED, data XML)

INSERT #dataXml (data)
SELECT CAST('<r><d>' + REPLACE(data, '|', '</d><d>') + '</d></r>' AS XML)
FROM #data

SELECT  d.data.value('(/r//d)[1]', 'varchar(max)') AS col1,
        d.data.value('(/r//d)[2]', 'varchar(max)') AS col2,
        d.data.value('(/r//d)[3]', 'varchar(max)') AS col3
FROM #dataXml d

Reloading submodules in IPython

Module named importlib allow to access to import internals. Especially, it provide function importlib.reload():

import importlib
importlib.reload(my_module)

In contrary of %autoreload, importlib.reload() also reset global variables set in module. In most cases, it is what you want.

importlib is only available since Python 3.1. For older version, you have to use module imp.

Invalid Host Header when ngrok tries to connect to React dev server

Option 1

If you do not need to use Authentication you can add configs to ngrok commands

ngrok http 9000 --host-header=rewrite

or

ngrok http 9000 --host-header="localhost:9000"

But in this case Authentication will not work on your website because ngrok rewriting headers and session is not valid for your ngrok domain

Option 2

If you are using webpack you can add the following configuration

devServer: {
    disableHostCheck: true
}

In that case Authentication header will be valid for your ngrok domain

Android: How do I prevent the soft keyboard from pushing my view up?

These answers here didn't help me. So I tried this:

android:windowSoftInputMode="adjustResize"

This worked like a charm, Now the header of my app doesn't disappear. Its smoother.

How to make all controls resize accordingly proportionally when window is maximized?

Well, it's fairly simple to do.

On the window resize event handler, calculate how much the window has grown/shrunk, and use that fraction to adjust 1) Height, 2) Width, 3) Canvas.Top, 4) Canvas.Left properties of all the child controls inside the canvas.

Here's the code:

private void window1_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            myCanvas.Width = e.NewSize.Width;
            myCanvas.Height = e.NewSize.Height;

            double xChange = 1, yChange = 1;

            if (e.PreviousSize.Width != 0)
            xChange = (e.NewSize.Width/e.PreviousSize.Width);

            if (e.PreviousSize.Height != 0)
            yChange = (e.NewSize.Height / e.PreviousSize.Height);

            foreach (FrameworkElement fe in myCanvas.Children )
            {   
                /*because I didn't want to resize the grid I'm having inside the canvas in this particular instance. (doing that from xaml) */            
                if (fe is Grid == false)
                {
                    fe.Height = fe.ActualHeight * yChange;
                    fe.Width = fe.ActualWidth * xChange;

                    Canvas.SetTop(fe, Canvas.GetTop(fe) * yChange);
                    Canvas.SetLeft(fe, Canvas.GetLeft(fe) * xChange);

                }
            }
        }

PHP array: count or sizeof?

sizeof() is just an alias of count() as mentioned here

http://php.net/manual/en/function.sizeof.php

How do you specify a debugger program in Code::Blocks 12.11?

For Code::Blocks 17.12.

  1. Visit http://wiki.codeblocks.org/index.php?title=MinGW_installation#TDM-GCC

  2. Follow installation's instructions.

  3. Alternatively I suggest this post.

Regards.

Jquery split function

Try this. It uses the split function which is a core part of javascript, nothing to do with jQuery.

var parts = html.split(":-"),
    i, l
;
for (i = 0, l = parts.length; i < l; i += 2) {
    $("#" + parts[i]).text(parts[i + 1]);
}

Using floats with sprintf() in embedded C

%g can do this:

#include <stdio.h>
int main() {
  float w = 234.567;
  char x[__SIZEOF_FLOAT__];
  sprintf(x, "%g", w);
  puts(x);
}

MySQL - UPDATE query based on SELECT Query

For same table,

UPDATE PHA_BILL_SEGMENT AS PHA,
     (SELECT BILL_ID, COUNT(REGISTRATION_NUMBER) AS REG 
       FROM PHA_BILL_SEGMENT
        GROUP BY REGISTRATION_NUMBER, BILL_DATE, BILL_AMOUNT
        HAVING REG > 1) T
    SET PHA.BILL_DATE = PHA.BILL_DATE + 2
 WHERE PHA.BILL_ID = T.BILL_ID;

Singleton with Arguments in Java

In your example you are not using a singleton. Notice that if you do the following (assuming that the Singleton.getInstance was actually static):

Singleton obj1 = Singleton.getInstance(3);
Singleton obj2 = Singleton.getInstance(4);

Then the obj2.x's values is 3, not 4. If you need to do this, make it a plain class. If the number of values is small and fixed, you can consider using an enum. If you are having problem with excessive object generation (which is usually not the case), then you can consider caching values (and check sources or get help with that, as it is obvious how to build caches without the danger of memory leaks).

You also might want to read this article as singletons can be very easily overused.

how to check if a form is valid programmatically using jQuery Validation Plugin

For Magento, you check validation of form by something like below.

You can try this:

require(["jquery"], function ($) {
    $(document).ready(function () {
        $('#my-button-name').click(function () { // The button type should be "button" and not submit
            if ($('#form-name').valid()) {
                alert("Validation pass");
                return false;
            }else{
                alert("Validation failed");
                return false;
            }
        });
    });
});

Hope this may help you!

Installing SciPy and NumPy using pip

in my case, upgrading pip did the trick. Also, I've installed scipy with -U parameter (upgrade all packages to the last available version)

excel plot against a date time x series

Try using an X-Y Scatter graph with datetime formatted as YYYY-MM-DD HH:MM.

This provides a reasonable graph for me (using Excel 2010).

Excel Datetime XY Scatter

How can I center an image in Bootstrap?

Since the img is an inline element, Just use text-center on it's container. Using mx-auto will center the container (column) too.

<div class="row">
    <div class="col-4 mx-auto text-center">
        <img src="..">
    </div>
</div>

By default, images are display:inline. If you only want the center the image (and not the other column content), make the image display:block using the d-block class, and then mx-auto will work.

<div class="row">
  <div class="col-4">
    <img class="mx-auto d-block" src="..">
  </div>
</div>

Demo: http://codeply.com/go/iakGGLdB8s

Convert UNIX epoch to Date object

With library(lubridate), numeric representations of date and time saved as the number of seconds since 1970-01-01 00:00:00 UTC, can be coerced into dates with as_datetime():

lubridate::as_datetime(1352068320)

[1] "2012-11-04 22:32:00 UTC"

Converting an array to a function arguments list

@bryc - yes, you could do it like this:

Element.prototype.setAttribute.apply(document.body,["foo","bar"])

But that seems like a lot of work and obfuscation compared to:

document.body.setAttribute("foo","bar")

npm ERR! Error: EPERM: operation not permitted, rename

In my case setting typescript.disableAutomaticTypeAcquisition in Visual Studio Code to true seemed to help.

trying to align html button at the center of the my page

For me it worked using flexbox.

Add a css class around the parent div / element with :

.parent {
    display: flex;
}

and for the button use:

.button {
    justify-content: center;
}

You should use a parent div, otherwise the button doesn't 'know' what the middle of the page / element is.

How can one see content of stack with GDB?

Use:

  • bt - backtrace: show stack functions and args
  • info frame - show stack start/end/args/locals pointers
  • x/100x $sp - show stack memory
(gdb) bt
#0  zzz () at zzz.c:96
#1  0xf7d39cba in yyy (arg=arg@entry=0x0) at yyy.c:542
#2  0xf7d3a4f6 in yyyinit () at yyy.c:590
#3  0x0804ac0c in gnninit () at gnn.c:374
#4  main (argc=1, argv=0xffffd5e4) at gnn.c:389

(gdb) info frame
Stack level 0, frame at 0xffeac770:
 eip = 0x8049047 in main (goo.c:291); saved eip 0xf7f1fea1
 source language c.
 Arglist at 0xffeac768, args: argc=1, argv=0xffffd5e4
 Locals at 0xffeac768, Previous frame's sp is 0xffeac770
 Saved registers:
  ebx at 0xffeac75c, ebp at 0xffeac768, esi at 0xffeac760, edi at 0xffeac764, eip at 0xffeac76c

(gdb) x/10x $sp
0xffeac63c: 0xf7d39cba  0xf7d3c0d8  0xf7d3c21b  0x00000001
0xffeac64c: 0xf78d133f  0xffeac6f4  0xf7a14450  0xffeac678
0xffeac65c: 0x00000000  0xf7d3790e

What is the difference between JOIN and UNION?

Remember that union will merge results (SQL Server to be sure)(feature or bug?)

select 1 as id, 3 as value
union
select 1 as id, 3 as value

id,value

1,3

select * from (select 1 as id, 3 as value) t1 inner join (select 1 as id, 3 as value) t2 on t1.id = t2.id

id,value,id,value

1,3,1,3

Get the size of a 2D array

Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:

array.length * array[0].length

Non-numeric Argument to Binary Operator Error in R

Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.

- is the 'binary operator' your error is referencing, and either CurrentDay or MA (or both) are non-numeric.

A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). + is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).

R only knows how to apply + (and other binary operators, such as -) to numeric arguments:

> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator

When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.

EDIT:

Your error lies in the use of [ instead of [[. Because Day is a list, subsetting with [ will return a list, not a numeric vector. [[, however, returns an object of the class of the item contained in the list:

> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator

> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3

Transaction, as you've defined it, returns a list of two vectors. Above, Day is a list contain one vector. Day2, however, is simply a vector.

Spring RestTemplate GET with parameters

In Spring Web 4.3.6 I also see

public <T> T getForObject(String url, Class<T> responseType, Object... uriVariables)

That means you don't have to create an ugly map

So if you have this url

http://my-url/action?param1={param1}&param2={param2}

You can either do

restTemplate.getForObject(url, Response.class, param1, param2)

or

restTemplate.getForObject(url, Response.class, param [])

Creating table variable in SQL server 2008 R2

@tableName Table variables are alive for duration of the script running only i.e. they are only session level objects.

To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.

There is another type of table object which can be created for temporary use. They are #tableName objects declared like similar create statement for physical tables:

Create table #test (Id int, Name varchar(50))

This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.

IF OBJECT_ID('tempdb..#test') IS NOT NULL
  DROP TABLE #test 

Hope this makes sense !

What's the fastest way to read a text file line-by-line?

There's a good topic about this in Stack Overflow question Is 'yield return' slower than "old school" return?.

It says:

ReadAllLines loads all of the lines into memory and returns a string[]. All well and good if the file is small. If the file is larger than will fit in memory, you'll run out of memory.

ReadLines, on the other hand, uses yield return to return one line at a time. With it, you can read any size file. It doesn't load the whole file into memory.

Say you wanted to find the first line that contains the word "foo", and then exit. Using ReadAllLines, you'd have to read the entire file into memory, even if "foo" occurs on the first line. With ReadLines, you only read one line. Which one would be faster?

Suppress Scientific Notation in Numpy When Creating Array From Nested List

I guess what you need is np.set_printoptions(suppress=True), for details see here: http://pythonquirks.blogspot.fr/2009/10/controlling-printing-in-numpy.html

For SciPy.org numpy documentation, which includes all function parameters (suppress isn't detailed in the above link), see here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html

Converting xml to string using C#

There's a much simpler way to convert your XmlDocument to a string; use the OuterXml property. The OuterXml property returns a string version of the xml.

public string GetXMLAsString(XmlDocument myxml)
{
    return myxml.OuterXml;
}

Relative div height

Basically, the problem lies in block12. for the block1/2 to take up the total height of the block12, it must have a defined height. This stack overflow post explains that in really good detail.

So setting a defined height for block12 will allow you to set a proper height. I have created an example on JSfiddle that will show you the the blocks can be floated next to one another if the block12 div is set to a standard height through out the page.

Here is an example including a header and block3 div with some content in for examples.

#header{
   position:absolute;
   top:0;
   left:0;
   width:100%;
   height:20%;
    }

    #block12{
    position:absolute;
    top:20%;
    width:100%;
    left:0;
    height:40%;
    }
    #block1,#block2{
    float:left;
    overflow-y: scroll;
    text-align:center;
    color:red;
    width:50%;
    height:100%;

    }
 #clear{clear:both;}
 #block3{
    position:absolute;
    bottom:0;
    color:blue;
    height:40%;

    }

Is it possible to get an Excel document's row count without loading the entire document into memory?

This might be extremely convoluted and I might be missing the obvious, but without OpenPyXL filling in the column_dimensions in Iterable Worksheets (see my comment above), the only way I can see of finding the column size without loading everything is to parse the xml directly:

from xml.etree.ElementTree import iterparse
from openpyxl import load_workbook
wb=load_workbook("/path/to/workbook.xlsx", use_iterators=True)
ws=wb.worksheets[0]
xml = ws._xml_source
xml.seek(0)

for _,x in iterparse(xml):

    name= x.tag.split("}")[-1]
    if name=="col":
        print "Column %(max)s: Width: %(width)s"%x.attrib # width = x.attrib["width"]

    if name=="cols":
        print "break before reading the rest of the file"
        break

How to convert current date to epoch timestamp?

Short-hand to convert python date/datetime to Epoch (without microseconds)

int(current_date.strftime("%s")) # 2020-01-14  ---> 1578956400
int(current_datetime.strftime("%s")) # 2020-01-14 16:59:30.251176 -----> 1579017570

How to compare strings in sql ignoring case?

You could use the UPPER keyword:

SELECT *
FROM Customers
WHERE UPPER(LastName) = UPPER('AnGel')

how to get param in method post spring mvc?

  1. Spring annotations will work fine if you remove enctype="multipart/form-data".

    @RequestParam(value="txtEmail", required=false)
    
  2. You can even get the parameters from the request object .

    request.getParameter(paramName);
    
  3. Use a form in case the number of attributes are large. It will be convenient. Tutorial to get you started.

  4. Configure the Multi-part resolver if you want to receive enctype="multipart/form-data".

    <bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="250000"/>
    </bean>
    

Refer the Spring documentation.

VBA macro that search for file in multiple subfolders

This sub will populate a Collection with all files matching the filename or pattern you pass in.

Sub GetFiles(StartFolder As String, Pattern As String, _
             DoSubfolders As Boolean, ByRef colFiles As Collection)

    Dim f As String, sf As String, subF As New Collection, s
    
    If Right(StartFolder, 1) <> "\" Then StartFolder = StartFolder & "\"
    
    f = Dir(StartFolder & Pattern)
    Do While Len(f) > 0
        colFiles.Add StartFolder & f
        f = Dir()
    Loop
    
    If DoSubfolders then
        sf = Dir(StartFolder, vbDirectory)
        Do While Len(sf) > 0
            If sf <> "." And sf <> ".." Then
                If (GetAttr(StartFolder & sf) And vbDirectory) <> 0 Then
                        subF.Add StartFolder & sf
                End If
            End If
            sf = Dir()
        Loop
    
        For Each s In subF
            GetFiles CStr(s), Pattern, True, colFiles
        Next s
    End If

End Sub

Usage:

Dim colFiles As New Collection

GetFiles "C:\Users\Marek\Desktop\Makro\", FName & ".xls", True, colFiles
If colFiles.Count > 0 Then
    'work with found files
End If

is there any way to force copy? copy without overwrite prompt, using windows?

MOVE /-Y Source Destination

Note:/-y will make the announcement of yes/no for overwrite

SQL how to check that two tables has exactly the same data?

We can compare data from two tables of DB2 tables using the below simple query,

Step 1:- Select which all columns we need to compare from table (T1) of schema(S)

     SELECT T1.col1,T1.col3,T1.col5 from S.T1

Step 2:- Use 'Minus' keyword for comparing 2 tables.

Step 3:- Select which all columns we need to compare from table (T2) of schema(S)

     SELECT T2.col1,T2.col3,T2.col5 from S.T1

END result:

     SELECT T1.col1,T1.col3,T1.col5 from S.T1
     MINUS 
     SELECT T2.col1,T2.col3,T2.col5 from S.T1;

If the query returns no rows then the data is exactly the same.

Show which git tag you are on?

Edit: Jakub Narebski has more git-fu. The following much simpler command works perfectly:

git describe --tags

(Or without the --tags if you have checked out an annotated tag. My tag is lightweight, so I need the --tags.)

original answer follows:

git describe --exact-match --tags $(git log -n1 --pretty='%h')

Someone with more git-fu may have a more elegant solution...

This leverages the fact that git-log reports the log starting from what you've checked out. %h prints the abbreviated hash. Then git describe --exact-match --tags finds the tag (lightweight or annotated) that exactly matches that commit.

The $() syntax above assumes you're using bash or similar.

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader

Please note that there's a naming convention. Your lib needs to be called libexample.so .

LoadLibrary("example") will look for libexample.so.

The .so library needs to be inside the apk under the lib folder (since you are developing for Android, it needs to be under the lib/armeabi and lib/armeabi-v7a folders - why both folders ? some versions of Android look under lib/armeabi and some look under lib/armeabi-v7a ... se what works for you ).

Other things to look for :

  • make sure you compile for the correct architecture (if you compile for armeabi v5 it won't work on armeabiv7 or armeabiv7s ).

  • make sure your exported prototypes are used in the correct class (check the hello jni example. Your exposed functions need to look something like Java_mypackagename_myjavabridgeclass_myfunction).

For example the function Java_com_example_sample_hello will translate in the java class com.example.sample , function hello.

How to use a TRIM function in SQL Server

TRIM all SPACE's TAB's and ENTER's:

DECLARE @Str VARCHAR(MAX) = '      
          [         Foo    ]       
          '

DECLARE @NewStr VARCHAR(MAX) = ''
DECLARE @WhiteChars VARCHAR(4) =
      CHAR(13) + CHAR(10) -- ENTER
    + CHAR(9) -- TAB
    + ' ' -- SPACE

;WITH Split(Chr, Pos) AS (
    SELECT
          SUBSTRING(@Str, 1, 1) AS Chr
        , 1 AS Pos
    UNION ALL
    SELECT
          SUBSTRING(@Str, Pos, 1) AS Chr
        , Pos + 1 AS Pos
    FROM Split
    WHERE Pos <= LEN(@Str)
)
SELECT @NewStr = @NewStr + Chr
FROM Split
WHERE
    Pos >= (
        SELECT MIN(Pos)
        FROM Split
        WHERE CHARINDEX(Chr, @WhiteChars) = 0
    )
    AND Pos <= (
        SELECT MAX(Pos)
        FROM Split
        WHERE CHARINDEX(Chr, @WhiteChars) = 0
    )

SELECT '"' + @NewStr + '"'

As Function

CREATE FUNCTION StrTrim(@Str VARCHAR(MAX)) RETURNS VARCHAR(MAX) BEGIN
    DECLARE @NewStr VARCHAR(MAX) = NULL

    IF (@Str IS NOT NULL) BEGIN
        SET @NewStr = ''

        DECLARE @WhiteChars VARCHAR(4) =
              CHAR(13) + CHAR(10) -- ENTER
            + CHAR(9) -- TAB
            + ' ' -- SPACE

        IF (@Str LIKE ('%[' + @WhiteChars + ']%')) BEGIN

            ;WITH Split(Chr, Pos) AS (
                SELECT
                      SUBSTRING(@Str, 1, 1) AS Chr
                    , 1 AS Pos
                UNION ALL
                SELECT
                      SUBSTRING(@Str, Pos, 1) AS Chr
                    , Pos + 1 AS Pos
                FROM Split
                WHERE Pos <= LEN(@Str)
            )
            SELECT @NewStr = @NewStr + Chr
            FROM Split
            WHERE
                Pos >= (
                    SELECT MIN(Pos)
                    FROM Split
                    WHERE CHARINDEX(Chr, @WhiteChars) = 0
                )
                AND Pos <= (
                    SELECT MAX(Pos)
                    FROM Split
                    WHERE CHARINDEX(Chr, @WhiteChars) = 0
                )
        END
    END

    RETURN @NewStr
END

Example

-- Test
DECLARE @Str VARCHAR(MAX) = '      
          [         Foo    ]       
              '

SELECT 'Str', '"' + dbo.StrTrim(@Str) + '"'
UNION SELECT 'EMPTY', '"' + dbo.StrTrim('') + '"'
UNION SELECT 'EMTPY', '"' + dbo.StrTrim('      ') + '"'
UNION SELECT 'NULL', '"' + dbo.StrTrim(NULL) + '"'

Result

+-------+----------------+
| Test  | Result         |
+-------+----------------+
| EMPTY | ""             |
| EMTPY | ""             |
| NULL  | NULL           |
| Str   | "[   Foo    ]" |
+-------+----------------+

Visual Studio SignTool.exe Not Found

Here is a solution for Visual Studio 2017. The installer looks a littlebit different from the VS 2015 version and the name of the installation packages are different.

Construct a manual legend for a complicated plot

In case you were struggling to change linetypes, the following answer should be helpful. (This is an addition to the solution by Andy W.)

We will try to extend the learned pattern:

cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
line_types <- c("LINE1"=1,"LINE2"=3)
ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h,fill = "BAR"))+ #green
  geom_line(aes(y=b,group=1, colour="LINE1", linetype="LINE1"),size=0.5) +   #red
  geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=2) +           #red
  geom_line(aes(y=c,group=1,colour="LINE2", linetype="LINE2"),size=0.5) +   #blue 
  geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=2) +           #blue
  scale_colour_manual(name="Error Bars",values=cols, 
                  guide = guide_legend(override.aes=aes(fill=NA))) + 
  scale_linetype_manual(values=line_types)+
  scale_fill_manual(name="Bar",values=cols, guide="none") +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

However, what we get is the following result: manual without name

The problem is that the linetype is not merged in the main legend. Note that we did not give any name to the method scale_linetype_manual. The trick which works here is to give it the same name as what you used for naming scale_colour_manual. More specifically, if we change the corresponding line to the following we get the desired result:

scale_linetype_manual(name="Error Bars",values=line_types)

manual with the same name

Now, it is easy to change the size of the line with the same idea.

Note that the geom_bar has not colour property anymore. (I did not try to fix this issue.) Also, adding geom_errorbar with colour attribute spoils the result. It would be great if somebody can come up with a better solution which resolves these two issues as well.

How to use ng-if to test if a variable is defined

I edited your plunker to include ABOS's solution.

<body ng-controller="MainCtrl">
    <ul ng-repeat='item in items'>
      <li ng-if='item.color'>The color is {{item.color}}</li>
      <li ng-if='item.shipping !== undefined'>The shipping cost is {{item.shipping}}</li>
    </ul>
  </body>

plunkerFork

Oracle Partition - Error ORA14400 - inserted partition key does not map to any partition

select partition_name,column_name,high_value,partition_position
from ALL_TAB_PARTITIONS a , ALL_PART_KEY_COLUMNS b 
where table_name='YOUR_TABLE' and a.table_name = b.name;

This query lists the column name used as key and the allowed values. make sure, you insert the allowed values(high_value). Else, if default partition is defined, it would go there.


EDIT:

I presume, your TABLE DDL would be like this.

CREATE TABLE HE0_DT_INF_INTERFAZ_MES
  (
    COD_PAIS NUMBER,
    FEC_DATA NUMBER,
    INTERFAZ VARCHAR2(100)
  )
  partition BY RANGE(COD_PAIS, FEC_DATA)
  (
    PARTITION PDIA_98_20091023 VALUES LESS THAN (98,20091024)
  );

Which means I had created a partition with multiple columns which holds value less than the composite range (98,20091024);

That is first COD_PAIS <= 98 and Also FEC_DATA < 20091024

Combinations And Result:

98, 20091024     FAIL
98, 20091023     PASS
99, ********     FAIL
97, ********     PASS
 < 98, ********     PASS

So the below INSERT fails with ORA-14400; because (98,20091024) in INSERT is EQUAL to the one in DDL but NOT less than it.

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
                                  VALUES(98, 20091024, 'CTA');  2
INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
            *
ERROR at line 1:
ORA-14400: inserted partition key does not map to any partition

But, we I attempt (97,20091024), it goes through

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
  2                                    VALUES(97, 20091024, 'CTA');

1 row created.

jQuery - Dynamically Create Button and Attach Event Handler

Calling .html() serializes the element to a string, so all event handlers and other associated data is lost. Here's how I'd do it:

$("#myButton").click(function ()
{
    var test = $('<button/>',
    {
        text: 'Test',
        click: function () { alert('hi'); }
    });

    var parent = $('<tr><td></td></tr>').children().append(test).end();

    $("#addNodeTable tr:last").before(parent);
});

Or,

$("#myButton").click(function ()
{    
    var test = $('<button/>',
    {
        text: 'Test',
        click: function () { alert('hi'); }
    }).wrap('<tr><td></td></tr>').closest('tr');

    $("#addNodeTable tr:last").before(test);
});

If you don't like passing a map of properties to $(), you can instead use

$('<button/>')
    .text('Test')
    .click(function () { alert('hi'); });

// or

$('<button>Test</button>').click(function () { alert('hi'); });

What do $? $0 $1 $2 mean in shell script?

These are positional arguments of the script.

Executing

./script.sh Hello World

Will make

$0 = ./script.sh
$1 = Hello
$2 = World

Note

If you execute ./script.sh, $0 will give output ./script.sh but if you execute it with bash script.sh it will give output script.sh.

How to remove numbers from string using Regex.Replace?

As a string extension:

    public static string RemoveIntegers(this string input)
    {
        return Regex.Replace(input, @"[\d-]", string.Empty);
    }

Usage:

"My text 1232".RemoveIntegers(); // RETURNS "My text "

Do C# Timers elapse on a separate thread?

For System.Timers.Timer, on separate thread, if SynchronizingObject is not set.

    static System.Timers.Timer DummyTimer = null;

    static void Main(string[] args)
    {
        try
        {

            Console.WriteLine("Main Thread Id: " + System.Threading.Thread.CurrentThread.ManagedThreadId);

            DummyTimer = new System.Timers.Timer(1000 * 5); // 5 sec interval
            DummyTimer.Enabled = true;
            DummyTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnDummyTimerFired);
            DummyTimer.AutoReset = true;

            DummyTimer.Start();

            Console.WriteLine("Hit any key to exit");
            Console.ReadLine();
        }
        catch (Exception Ex)
        {
            Console.WriteLine(Ex.Message);
        }

        return;
    }

    static void OnDummyTimerFired(object Sender, System.Timers.ElapsedEventArgs e)
    {
        Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);
        return;
    }

Output you'd see if DummyTimer fired on 5 seconds interval:

Main Thread Id: 9
   12
   12
   12
   12
   12
   ... 

So, as seen, OnDummyTimerFired is executed on Workers thread.

No, further complication - If you reduce interval to say 10 ms,

Main Thread Id: 9
   11
   13
   12
   22
   17
   ... 

This is because if prev execution of OnDummyTimerFired isn't done when next tick is fired, then .NET would create a new thread to do this job.

Complicating things further, "The System.Timers.Timer class provides an easy way to deal with this dilemma—it exposes a public SynchronizingObject property. Setting this property to an instance of a Windows Form (or a control on a Windows Form) will ensure that the code in your Elapsed event handler runs on the same thread on which the SynchronizingObject was instantiated."

http://msdn.microsoft.com/en-us/magazine/cc164015.aspx#S2

Error in Python IOError: [Errno 2] No such file or directory: 'data.csv'

Try to give the full path to your csv file

open('/users/gcameron/Desktop/map/data.csv')

The python process is looking for file in the directory it is running from.

How to get a float result by dividing two integer values using T-SQL?

If you came here (just like me) to find the solution for integer value, here is the answer:

CAST(9/2 AS UNSIGNED)

returns 5

store and retrieve a class object in shared preference

Do you need to retrieve the object even after the application shutting donw or just during it's running ?

You can store it into a database.
Or Simply create a custom Application class.

public class MyApplication extends Application {

    private static Object mMyObject;
    // static getter & setter
    ...
}

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application ... android:name=".MyApplication">
        <activity ... />
        ...
    </application>
    ...
</manifest>

And then from every activities do :

((MyApplication) getApplication).getMyObject();

Not really the best way but it works.

PostgreSQL delete with inner join

Another form that works with Postgres 9.1+ is combining a Common Table Expression with the USING statement for the join.

WITH prod AS (select m_product_id, upc from m_product where upc='7094')
DELETE FROM m_productprice B
USING prod C
WHERE B.m_product_id = C.m_product_id 
AND B.m_pricelist_version_id = '1000020';

Why is &#65279; appearing in my HTML?

The character in question &#65279 is the Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF). It may be that you copied it into your code via a copy/paste without realizing it. The fact that it's not visible makes it hard to tell if you're using an editor that displays actual unicode characters.

One option is to open the file in a very basic text editor that doesn't understand unicode, or one that understands it but has the ability to display any non-ascii characters using their actual codes.

Once you locate it, you can delete the small block of text around it and retype that text manually.

Hibernate: "Field 'id' doesn't have a default value"

Please check whether the Default value for the column id in particular table.if not make it as default

Getting text from td cells with jQuery

I would give your tds a specific class, e.g. data-cell, and then use something like this:

$("td.data-cell").each(function () {
    // 'this' is now the raw td DOM element
    var txt = $(this).html();
});

How to stretch children to fill cross-axis?

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

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

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

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

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

What is the difference between declarations, providers, and import in NgModule?

Adding a quick cheat sheet that may help after the long break with Angular:


DECLARATIONS

Example:

declarations: [AppComponent]

What can we inject here? Components, pipes, directives


IMPORTS

Example:

imports: [BrowserModule, AppRoutingModule]

What can we inject here? other modules


PROVIDERS

Example:

providers: [UserService]

What can we inject here? services


BOOTSTRAP

Example:

bootstrap: [AppComponent]

What can we inject here? the main component that will be generated by this module (top parent node for a component tree)


ENTRY COMPONENTS

Example:

entryComponents: [PopupComponent]

What can we inject here? dynamically generated components (for instance by using ViewContainerRef.createComponent())


EXPORT

Example:

export: [TextDirective, PopupComponent, BrowserModule]

What can we inject here? components, directives, modules or pipes that we would like to have access to them in another module (after importing this module)

Java: how do I check if a Date is within a certain range?

  public class TestDate {

    public static void main(String[] args) {
    // TODO Auto-generated method stub

    String fromDate = "18-FEB-2018";
    String toDate = "20-FEB-2018";

    String requestDate = "19/02/2018";  
    System.out.println(checkBetween(requestDate,fromDate, toDate));
}

public static boolean checkBetween(String dateToCheck, String startDate, String endDate) {
    boolean res = false;
    SimpleDateFormat fmt1 = new SimpleDateFormat("dd-MMM-yyyy"); //22-05-2013
    SimpleDateFormat fmt2 = new SimpleDateFormat("dd/MM/yyyy"); //22-05-2013
    try {
     Date requestDate = fmt2.parse(dateToCheck);
     Date fromDate = fmt1.parse(startDate);
     Date toDate = fmt1.parse(endDate);
     res = requestDate.compareTo(fromDate) >= 0 && requestDate.compareTo(toDate) <=0;
    }catch(ParseException pex){
        pex.printStackTrace();
    }
    return res;
   }
 }

Minimum and maximum date

From the spec, §15.9.1.1:

A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number is called a time value. A time value may also be NaN, indicating that the Date object does not represent a specific instant of time.

Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. In time values leap seconds are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values can represent all integers from –9,007,199,254,740,992 to 9,007,199,254,740,992; this range suffices to measure times to millisecond precision for any instant that is within approximately 285,616 years, either forward or backward, from 01 January, 1970 UTC.

The actual range of times supported by ECMAScript Date objects is slightly smaller: exactly –100,000,000 days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.

The exact moment of midnight at the beginning of 01 January, 1970 UTC is represented by the value +0.

The third paragraph being the most relevant. Based on that paragraph, we can get the precise earliest date per spec from new Date(-8640000000000000), which is Tuesday, April 20th, 271,821 BCE (BCE = Before Common Era, e.g., the year -271,821).

How to open adb and use it to send commands

The adb tool can be found in sdk/platform-tools/

If you don't see this directory in your SDK, launch the SDK Manager and install "Android SDK Platform-tools"

Also update your PATH environment variable to include the platform-tools/ directory, so you can execute adb from any location.

Integer division with remainder in JavaScript?

I'm no expert in bitwise operators, but here's another way to get the whole number:

var num = ~~(a / b);

This will work properly for negative numbers as well, while Math.floor() will round in the wrong direction.

This seems correct as well:

var num = (a / b) >> 0;

Relationship between hashCode and equals method in Java

A contract is: If two objects are equal then they should have the same hashcode and if two objects are not equal then they may or may not have same hash code.

Try using your object as key in HashMap (edited after comment from joachim-sauer), and you will start facing trouble. A contract is a guideline, not something forced upon you.

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

This is possible with a bit of format conversion.

To extract the private key in a format openssh can use:

openssl pkcs12 -in pkcs12.pfx -nocerts -nodes | openssl rsa > id_rsa

To convert the private key to a public key:

openssl rsa -in id_rsa -pubout | ssh-keygen -f /dev/stdin -i -m PKCS8

To extract the public key in a format openssh can use:

openssl pkcs12 -in pkcs12.pfx -clcerts -nokeys | openssl x509 -pubkey -noout | ssh-keygen -f /dev/stdin -i -m PKCS8

How can javascript upload a blob?

I tried all the solutions above and in addition, those in related answers as well. Solutions including but not limited to passing the blob manually to a HTMLInputElement's file property, calling all the readAs* methods on FileReader, using a File instance as second argument for a FormData.append call, trying to get the blob data as a string by getting the values at URL.createObjectURL(myBlob) which turned out nasty and crashed my machine.

Now, if you happen to attempt those or more and still find you're unable to upload your blob, it could mean the problem is server-side. In my case, my blob exceeded the http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize and post_max_size limit in PHP.INI so the file was leaving the front end form but getting rejected by the server. You could either increase this value directly in PHP.INI or via .htaccess

Pass all variables from one shell script to another?

Adding to the answer of Fatal Error, There is one more way to pass the variables to another shell script.

The above suggested solution have some drawbacks:

  1. using Export : It will cause the variable to be present out of their scope which is not a good design practice.
  2. using Source : It may cause name collisions or accidental overwriting of a predefined variable in some other shell script file which have sourced another file.

There is another simple solution avaiable for us to use. Considering the example posted by you,

test.sh

#!/bin/bash

TESTVARIABLE=hellohelloheloo
./test2.sh "$TESTVARIABLE"

test2.sh

#!/bin/bash

echo $1

output

hellohelloheloo

Also it is important to note that "" are necessary if we pass multiword strings. Taking one more example

master.sh

#!/bin/bash
echo in master.sh
var1="hello world"
sh slave1.sh $var1
sh slave2.sh "$var1"
echo back to master

slave1.sh

#!/bin/bash
echo in slave1.sh
echo value :$1

slave2.sh

#!/bin/bash
echo in slave2.sh
echo value : $1

output

in master.sh
in slave1.sh
value :"hello
in slave2.sh
value :"hello world"

It happens because of the reasons aptly described in this link

How do I specify "not equals to" when comparing strings in an XSLT <xsl:if>?

As Filburt says; but also note that it's usually better to write

test="not(Count = 'N/A')"

If there's exactly one Count element they mean the same thing, but if there's no Count, or if there are several, then the meanings are different.

6 YEARS LATER

Since this answer seems to have become popular, but may be a little cryptic to some readers, let me expand it.

The "=" and "!=" operator in XPath can compare two sets of values. In general, if A and B are sets of values, then "=" returns true if there is any pair of values from A and B that are equal, while "!=" returns true if there is any pair that are unequal.

In the common case where A selects zero-or-one nodes, and B is a constant (say "NA"), this means that not(A = "NA") returns true if A is either absent, or has a value not equal to "NA". By contrast, A != "NA" returns true if A is present and not equal to "NA". Usually you want the "absent" case to be treated as "not equal", which means that not(A = "NA") is the appropriate formulation.

remove attribute display:none; so the item will be visible

If you are planning to hide show some span based on click event which is initially hidden with style="display:none" then .toggle() is best option to go with.

$("span").toggle();

Reasons : Each time you don't need to check whether the style is already there or not. .toggle() will take care of that automatically and hide/show span based on current state.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="button" value="Toggle" onclick="$('#hiddenSpan').toggle();"/>_x000D_
<br/>_x000D_
<br/>_x000D_
<span id="hiddenSpan" style="display:none">Just toggle me</span>
_x000D_
_x000D_
_x000D_

How can I convert my Java program to an .exe file?

You can convert jar to exe using jar2exe. However you need to purchase the software. If you need a open source software i would suggest JSmooth.

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

How to put scroll bar only for modal-body?

You have to set the height of the .modal-body in and give it overflow-y: auto. Also reset .modal-dialog overflow value to initial.

See the working sample:

http://www.bootply.com/T0yF2ZNTUd

.modal{
    display: block !important; /* I added this to see the modal, you don't need this */
}

/* Important part */
.modal-dialog{
    overflow-y: initial !important
}
.modal-body{
    height: 80vh;
    overflow-y: auto;
}

How to print variables in Perl

print "Number of lines: $nids\n";
print "Content: $ids\n";

How did Perl complain? print $ids should work, though you probably want a newline at the end, either explicitly with print as above or implicitly by using say or -l/$\.

If you want to interpolate a variable in a string and have something immediately after it that would looks like part of the variable but isn't, enclose the variable name in {}:

print "foo${ids}bar";

Is there an API to get bank transaction and bank balance?

Just a helpful hint, there is a company called Yodlee.com who provides this data. They do charge for the API. Companies like Mint.com use this API to gather bank and financial account data.

Also, checkout https://plaid.com/, they are a similar company Yodlee.com and provide both authentication API for several banks and REST-based transaction fetching endpoints.

How to make an inline-block element fill the remainder of the line?

You can use calc (100% - 100px) on the fluid element, along with display:inline-block for both elements.

Be aware that there should not be any space between the tags, otherwise you will have to consider that space in your calc too.

.left{
    display:inline-block;
    width:100px;
}
.right{
    display:inline-block;
    width:calc(100% - 100px);
}


<div class=“left”></div><div class=“right”></div>

Quick example: http://jsfiddle.net/dw689mt4/1/

List all of the possible goals in Maven 2?

The goal you indicate in the command line is linked to the lifecycle of Maven. For example, the build lifecycle (you also have the clean and site lifecycles which are different) is composed of the following phases:

  • validate: validate the project is correct and all necessary information is available.
  • compile: compile the source code of the project.
  • test: test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed.
  • package: take the compiled code and package it in its distributable format, such as a JAR.
  • integration-test: process and deploy the package if necessary into an environment where integration tests can be run.
  • verify: run any checks to verify the package is valid and meets quality criteria
  • install: install the package into the local repository, for use as a dependency in other projects locally.
  • deploy: done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

You can find the list of "core" plugins here, but there are plenty of others plugins, such as the codehaus ones, here.

Hiding an Excel worksheet with VBA

To hide from the UI, use Format > Sheet > Hide

To hide programatically, use the Visible property of the Worksheet object. If you do it programatically, you can set the sheet as "very hidden", which means it cannot be unhidden through the UI.

ActiveWorkbook.Sheets("Name").Visible = xlSheetVeryHidden 
' or xlSheetHidden or xlSheetVisible

You can also set the Visible property through the properties pane for the worksheet in the VBA IDE (ALT+F11).

C++ IDE for Linux?

For me Ultimate++ seems to be the best solution to write cross-os program

Force flex item to span full row width

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100%, and enable wrap on the container.

The item now consumes all available space. Siblings are forced on to other rows.

_x000D_
_x000D_
.parent {
  display: flex;
  flex-wrap: wrap;
}

#range, #text {
  flex: 1;
}

.error {
  flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
  border: 1px dashed black;
}
_x000D_
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message (takes full width)</label>
</div>
_x000D_
_x000D_
_x000D_

More info: The initial value of the flex-wrap property is nowrap, which means that all items will line up in a row. MDN

How get the base URL via context path in JSF?

URLs are not resolved based on the file structure in the server side. URLs are resolved based on the real public web addresses of the resources in question. It's namely the webbrowser who has got to invoke them, not the webserver.

There are several ways to soften the pain:

JSF EL offers a shorthand to ${pageContext.request} in flavor of #{request}:

<li><a href="#{request.contextPath}/index.xhtml">Home</a></li>
<li><a href="#{request.contextPath}/about_us.xhtml">About us</a></li>

You can if necessary use <c:set> tag to make it yet shorter. Put it somewhere in the master template, it'll be available to all pages:

<c:set var="root" value="#{request.contextPath}/" />
...
<li><a href="#{root}index.xhtml">Home</a></li>
<li><a href="#{root}about_us.xhtml">About us</a></li>

JSF 2.x offers the <h:link> which can take a view ID relative to the context root in outcome and it will append the context path and FacesServlet mapping automatically:

<li><h:link value="Home" outcome="index" /></li>
<li><h:link value="About us" outcome="about_us" /></li>

HTML offers the <base> tag which makes all relative URLs in the document relative to this base. You could make use of it. Put it in the <h:head>.

<base href="#{request.requestURL.substring(0, request.requestURL.length() - request.requestURI.length())}#{request.contextPath}/" />
...
<li><a href="index.xhtml">Home</a></li>
<li><a href="about_us.xhtml">About us</a></li>

(note: this requires EL 2.2, otherwise you'd better use JSTL fn:substring(), see also this answer)

This should end up in the generated HTML something like as

<base href="http://example.com/webname/" />

Note that the <base> tag has a caveat: it makes all jump anchors in the page like <a href="#top"> relative to it as well! See also Is it recommended to use the <base> html tag? In JSF you could solve it like <a href="#{request.requestURI}#top">top</a> or <h:link value="top" fragment="top" />.

How to generate the whole database script in MySQL Workbench?

there is data export option in MySQL workbech

enter image description here

jQuery - Add ID instead of Class

if you want to 'add to the id' rather than replace it

capture the current id first, then append your new id. especially useful for twitter bootstrap which uses input states on their forms.

    new_id = '{{old_id}} inputSuccess';
    old_id = that.attr('id');
    that.attr('id', new_id.replace( /{{old_id}}/ig,old_id));

if you do not - you will lose any properties you previous set.

hth,

Using Google maps API v3 how do I get LatLng with a given address?

If you need to do this on the backend you can use the following URL structure:

https://maps.googleapis.com/maps/api/geocode/json?address=[STREET_ADDRESS]&key=[YOUR_API_KEY]

Sample PHP code using curl:

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, 'https://maps.googleapis.com/maps/api/geocode/json?address=' . rawurlencode($address) . '&key=' . $api_key);

curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);

$json = curl_exec($curl);

curl_close ($curl);

$obj = json_decode($json);

See additional documentation for more details and expected json response.

The docs provide sample output and will assist you in getting your own API key in order to be able to make requests to the Google Maps Geocoding API.

How to convert a date string to different format

I assume I have import datetime before running each of the lines of code below

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

prints "01/25/13".

If you can't live with the leading zero, try this:

dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month, dt.day, dt.year % 100)

This prints "1/25/13".

EDIT: This may not work on every platform:

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

Keystore change passwords

If the keystore contains other key-entries with different password you have to change them also or you can isolate your key to different keystore using below command,

keytool -importkeystore  -srckeystore mystore.jck -destkeystore myotherstore.jks -srcstoretype jceks
-deststoretype jks -srcstorepass mystorepass -deststorepass myotherstorepass -srcalias myserverkey
-destalias myotherserverkey -srckeypass mykeypass -destkeypass myotherkeypass

How to get single value of List<object>

Define a class like this :

public class myclass {
       string id ;
       string title ;
       string content;
 }

 public class program {
        public void Main () {
               List<myclass> objlist = new List<myclass> () ;
               foreach (var value in objlist)  {
                       TextBox1.Text = value.id ;
                       TextBox2.Text= value.title;
                       TextBox3.Text= value.content ;
                }
         }
  }

I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.

Python match a string with regex

r stands for a raw string, so things like \ will be automatically escaped by Python.

Normally, if you wanted your pattern to include something like a backslash you'd need to escape it with another backslash. raw strings eliminate this problem.

short explanation

In your case, it does not matter much but it's a good habit to get into early otherwise something like \b will bite you in the behind if you are not careful (will be interpreted as backspace character instead of word boundary)

As per re.match vs re.search here's an example that will clarify it for you:

>>> import re
>>> testString = 'hello world'
>>> re.match('hello', testString)
<_sre.SRE_Match object at 0x015920C8>
>>> re.search('hello', testString)
<_sre.SRE_Match object at 0x02405560>
>>> re.match('world', testString)
>>> re.search('world', testString)
<_sre.SRE_Match object at 0x015920C8>

So search will find a match anywhere, match will only start at the beginning

Eclipse reports rendering library more recent than ADT plug-in

Please try once uninstalling from Help-->Installation details

and try again installing using http://dl-ssl.google.com/android/eclipse/

How to disable scrolling in UITableView table when the content fits on the screen

// Enable scrolling based on content height self.tableView.scrollEnabled = table.contentSize.height > table.frame.size.height;

how to transfer a file through SFTP in java?

Try this code.

public void send (String fileName) {
    String SFTPHOST = "host:IP";
    int SFTPPORT = 22;
    String SFTPUSER = "username";
    String SFTPPASS = "password";
    String SFTPWORKINGDIR = "file/to/transfer";

    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    System.out.println("preparing the host information for sftp.");

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
        session.setPassword(SFTPPASS);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        System.out.println("Host connected.");
        channel = session.openChannel("sftp");
        channel.connect();
        System.out.println("sftp channel opened and connected.");
        channelSftp = (ChannelSftp) channel;
        channelSftp.cd(SFTPWORKINGDIR);
        File f = new File(fileName);
        channelSftp.put(new FileInputStream(f), f.getName());
        log.info("File transfered successfully to host.");
    } catch (Exception ex) {
        System.out.println("Exception found while tranfer the response.");
    } finally {
        channelSftp.exit();
        System.out.println("sftp Channel exited.");
        channel.disconnect();
        System.out.println("Channel disconnected.");
        session.disconnect();
        System.out.println("Host Session disconnected.");
    }
}   

What is the difference between const and readonly in C#?

Constants

  • Constants are static by default
  • They must have a value at compilation-time (you can have e.g. 3.14 * 2, but cannot call methods)
  • Could be declared within functions
  • Are copied into every assembly that uses them (every assembly gets a local copy of values)
  • Can be used in attributes

Readonly instance fields

  • Must have set value, by the time constructor exits
  • Are evaluated when instance is created

Static readonly fields

  • Are evaluated when code execution hits class reference (when new instance is created or a static method is executed)
  • Must have an evaluated value by the time the static constructor is done
  • It's not recommended to put ThreadStaticAttribute on these (static constructors will be executed in one thread only and will set the value for its thread; all other threads will have this value uninitialized)

How to get index of an item in java.util.Set

One solution (though not very pretty) is to use Apache common List/Set mutation

import org.apache.commons.collections.list.SetUniqueList;

final List<Long> vertexes=SetUniqueList.setUniqueList(new LinkedList<>());

it is a list without duplicates

https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.2/index.html?org/apache/commons/collections/list/SetUniqueList.html

image processing to improve tesseract OCR accuracy

As a rule of thumb, I usually apply the following image pre-processing techniques using OpenCV library:

  1. Rescaling the image (it's recommended if you’re working with images that have a DPI of less than 300 dpi):

    img = cv2.resize(img, None, fx=1.2, fy=1.2, interpolation=cv2.INTER_CUBIC)
    
  2. Converting image to grayscale:

    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
  3. Applying dilation and erosion to remove the noise (you may play with the kernel size depending on your data set):

    kernel = np.ones((1, 1), np.uint8)
    img = cv2.dilate(img, kernel, iterations=1)
    img = cv2.erode(img, kernel, iterations=1)
    
  4. Applying blur, which can be done by using one of the following lines (each of which has its pros and cons, however, median blur and bilateral filter usually perform better than gaussian blur.):

    cv2.threshold(cv2.GaussianBlur(img, (5, 5), 0), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
    
    cv2.threshold(cv2.bilateralFilter(img, 5, 75, 75), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
    
    cv2.threshold(cv2.medianBlur(img, 3), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
    
    cv2.adaptiveThreshold(cv2.GaussianBlur(img, (5, 5), 0), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)
    
    cv2.adaptiveThreshold(cv2.bilateralFilter(img, 9, 75, 75), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)
    
    cv2.adaptiveThreshold(cv2.medianBlur(img, 3), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)
    

I've recently written a pretty simple guide to Tesseract but it should enable you to write your first OCR script and clear up some hurdles that I experienced when things were less clear than I would have liked in the documentation.

In case you'd like to check them out, here I'm sharing the links with you:

href="tel:" and mobile numbers

It's the same. Your international format is already correct, and is recommended for use in all cases, where possible.

How to change DataTable columns order

I know this is a really old question.. and it appears it was answered.. But I got here with the same question but a different reason for the question, and so a slightly different answer worked for me. I have a nice reusable generic datagridview that takes the datasource supplied to it and just displays the columns in their default order. I put aliases and column order and selection at the dataset's tableadapter level in designer. However changing the select query order of columns doesn't seem to impact the columns returned through the dataset. I have found the only way to do this in the designer, is to remove all the columns selected within the tableadapter, adding them back in the order you want them selected.

.NET unique object identifier

.NET 4 and later only

Good news, everyone!

The perfect tool for this job is built in .NET 4 and it's called ConditionalWeakTable<TKey, TValue>. This class:

  • can be used to associate arbitrary data with managed object instances much like a dictionary (although it is not a dictionary)
  • does not depend on memory addresses, so is immune to the GC compacting the heap
  • does not keep objects alive just because they have been entered as keys into the table, so it can be used without making every object in your process live forever
  • uses reference equality to determine object identity; moveover, class authors cannot modify this behavior so it can be used consistently on objects of any type
  • can be populated on the fly, so does not require that you inject code inside object constructors

What are best practices that you use when writing Objective-C and Cocoa?

Declared Properties

You should typically use the Objective-C 2.0 Declared Properties feature for all your properties. If they are not public, add them in a class extension. Using declared properties makes the memory management semantics immediately clear, and makes it easier for you to check your dealloc method -- if you group your property declarations together you can quickly scan them and compare with the implementation of your dealloc method.

You should think hard before not marking properties as 'nonatomic'. As The Objective C Programming Language Guide notes, properties are atomic by default, and incur considerable overhead. Moreover, simply making all your properties atomic does not make your application thread-safe. Also note, of course, that if you don't specify 'nonatomic' and implement your own accessor methods (rather than synthesising them), you must implement them in an atomic fashion.

Getting URL parameter in java and extract a specific text from that URL

My solution mayble not good

        String url = "https://www.youtube.com/watch?param=test&v=XcHJMiSy_1c&lis=test";
        int start = url.indexOf("v=")+2;
        // int start = url.indexOf("list=")+5; **5 is length of ("list=")**
        int end = url.indexOf("&", start);

        end = (end == -1 ? url.length() : end); 

        System.out.println(url.substring(start, end));
        // result: XcHJMiSy_1c

work fine with:

  • https://www.youtube.com/watch?param=test&v=XcHJMiSy_1c&lis=test
  • https://www.youtube.com/watch?v=XcHJMiSy_1c

Auto expand a textarea using jQuery

For anyone using the plugin posted by Reigel please be aware that this will disable the undo functionality in Internet Explorer (go give the demo a go).

If this is a problem for you then I would suggest using the plugin posted by @richsage instead, as it does not suffer from this problem. See the second bullet point on Searching for the Ultimate Resizing Textarea for more information.

Read the current full URL with React?

To get the current router instance or current location you have to create a Higher order component with withRouter from react-router-dom. otherwise, when you are trying to access this.props.location it will return undefined

Example

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';

class className extends Component {

      render(){
           return(
                ....
                  )
              }
}

export default withRouter(className)

Set left margin for a paragraph in html

<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>

That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em' as the measurement, you may want to use other units, like 'px'.

EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:

In your HTML page, containing the <p> tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:

<head>
  <style type="text/css">
    p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>

So above, all <p> elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:

<head>
  <style type="text/css">
    .container p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <div class="container">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
  </div>
  <p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>

In the example above, only the <p> element inside the div, whose class name is 'container', will have the styles applied - and not the <p> element outside the container.

In addition to the above, you can collect your styles together and remove the style element from the <head> tag, replacing it with a <link> tag, which points to an external CSS file. This external file is where you'd now put your <p> tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.

add scroll bar to table body

If you don't want to wrap a table under any div:

table{
  table-layout: fixed;
}
tbody{
      display: block;
    overflow: auto;
}

Retrieving the text of the selected <option> in <select> element

this.options[this.selectedIndex].innerText

How do I POST with multipart form data using fetch?

I was recently working with IPFS and worked this out. A curl example for IPFS to upload a file looks like this:

curl -i -H "Content-Type: multipart/form-data; boundary=CUSTOM" -d $'--CUSTOM\r\nContent-Type: multipart/octet-stream\r\nContent-Disposition: file; filename="test"\r\n\r\nHello World!\n--CUSTOM--' "http://localhost:5001/api/v0/add"

The basic idea is that each part (split by string in boundary with --) has it's own headers (Content-Type in the second part, for example.) The FormData object manages all this for you, so it's a better way to accomplish our goals.

This translates to fetch API like this:

const formData = new FormData()
formData.append('blob', new Blob(['Hello World!\n']), 'test')

fetch('http://localhost:5001/api/v0/add', {
  method: 'POST',
  body: formData
})
.then(r => r.json())
.then(data => {
  console.log(data)
})

A connection was successfully established with the server, but then an error occurred during the login process. (Error Number: 233)

Here is the solution I found:

Go to SQL Server Management, Disable Memory Shared, TCP/IP and Pipes named.

Restart the server and try again.

LINQ select one field from list of DTO objects to array

This is very simple in LinQ... You can use the select statement to get an Enumerable of properties of the objects.

var mySkus = myLines.Select(x => x.Sku);

Or if you want it as an Array just do...

var mySkus = myLines.Select(x => x.Sku).ToArray();

Capitalize the first letter of string in AngularJs

You can try to split your String into two parts and manage their case separately.

{{ (Name.charAt(0) | uppercase) + "" + (Name.slice(1, element.length) | lowercase) }}

or

{{ Name.charAt(0) | uppercase }} {{ Name.slice(1, element.length) | lowercase  }}

How to upgrade Git on Windows to the latest version?

If you look at the most recent update on Git's website in the "git via git" section you will see an option to update your older version.

Here is the command that git has on their site:

git clone https://github.com/git/git

It worked for my version of git which was a 2.13.0.windows.1.

How to quit android application programmatically

public void quit() {
        int pid = android.os.Process.myPid();
        android.os.Process.killProcess(pid);
        System.exit(0);
    }

How to wait until WebBrowser is completely loaded in VB.NET?

Salvete! I needed, simply, a function I could call to make the code wait for the page to load before it continued. After scouring the web for answers, and fiddling around for several hours, I came up with this to solve for myself, the exact dilemma you present. I know I am late in the game with an answer, but I wish to post this for anyone else who comes along.

usage: just call WaitForPageLoad() just after a call to navigation:

whatbrowser.Navigate("http://www.google.com")
WaitForPageLoad()

another example we don't combine the navigate feature with the page load, because sometimes you need to wait for a load without also navigating, for example, you might need to wait for a page to load that was started with an invokemember event:

whatbrowser.Document.GetElementById("UserName").InnerText = whatusername
whatbrowser.Document.GetElementById("Password").InnerText = whatpassword
whatbrowser.Document.GetElementById("LoginButton").InvokeMember("click")
WaitForPageLoad()

Here is the code: You need both subs plus the accessible variable, pageready. First, make sure to fix the variable called whatbrowser to be your webbrowser control

Now, somewhere in your module or class, place this:

Private Property pageready As Boolean = False

#Region "Page Loading Functions"
    Private Sub WaitForPageLoad()
        AddHandler whatbrowser.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
        While Not pageready
            Application.DoEvents()
        End While
        pageready = False
    End Sub

    Private Sub PageWaiter(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
        If whatbrowser.ReadyState = WebBrowserReadyState.Complete Then
            pageready = True
            RemoveHandler whatbrowser.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
        End If
    End Sub

#End Region

SQL SELECT everything after a certain character

For SQL Management studio I used a variation of BWS' answer. This gets the data to the right of '=', or NULL if the symbol doesn't exist:

   CASE WHEN (RIGHT(supplier_reference, CASE WHEN (CHARINDEX('=',supplier_reference,0)) = 0 THEN
    0 ELSE CHARINDEX('=', supplier_reference) -1 END)) <> '' THEN (RIGHT(supplier_reference, CASE WHEN (CHARINDEX('=',supplier_reference,0)) = 0 THEN
    0 ELSE CHARINDEX('=', supplier_reference) -1 END)) ELSE NULL END

How to use the curl command in PowerShell?

Use splatting.

$CurlArgument = '-u', '[email protected]:yyyy',
                '-X', 'POST',
                'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
                '--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument

Run a script in Dockerfile

WORKDIR /scripts
COPY bootstrap.sh .
RUN ./bootstrap.sh 

TypeError: $(...).on is not a function

In my case this code solved my error :

(function (window, document, $) {
            'use strict';
             var $html = $('html');
             $('input[name="myiCheck"]').on('ifClicked', function (event) {
             alert("You clicked " + this.value);
             });
})(window, document, jQuery);

You don't should put your function inside $(document).ready

How to create a file in Linux from terminal window?

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
    
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist


Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit


There are several possible solutions:

Create an empty file

touch file

>file

echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \
text
END

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

How can I use the $index inside a ng-repeat to enable a class and show a DIV?

The issue here is that ng-repeat creates its own scope, so when you do selected=$index it creates a new a selected property in that scope rather than altering the existing one. To fix this you have two options:

Change the selected property to a non-primitive (ie object or array, which makes javascript look up the prototype chain) then set a value on that:

$scope.selected = {value: 0};

<a ng-click="selected.value = $index">A{{$index}}</a>

See plunker

or

Use the $parent variable to access the correct property. Though less recommended as it increases coupling between scopes

<a ng-click="$parent.selected = $index">A{{$index}}</a>

See plunker

CSS/Javascript to force html table row on a single line

If you don't want the text to wrap and you don't want the size of the column to get bigger then set a width and height on the column and set "overflow: hidden" in your stylesheet.

To do this on only one column you will want to add a class to that column on each row. Otherwise you can set it on all columns, that is up to you.

Html:

<table width="300px">
<tr>
    <td>Column 1</td><td>Column 2</td>
</tr>
<tr>
   <td class="column-1">this is the text in column one which wraps</td>
   <td>this is the column two test</td>
</tr>
</table>

stylsheet:

.column-1
{
  overflow: hidden;
  width: 150px;
  height: 1.2ex; 
}

An ex unit is the relative font size for height, if you are using pixels to set the font size you may wish to use that instead.

Multiple conditions in if statement shell script

if using /bin/sh you can use:

if [ <condition> ] && [ <condition> ]; then
    ...
fi

if using /bin/bash you can use:

if [[ <condition> && <condition> ]]; then
    ...
fi

How to change an Android app's name?

if you want to change app name under launcher icon then change this android:label="@string/app_name" inside your Main Launcher activity tag

        <activity android:name="com.test.app"
                  android:label="@string/app_name" >
                  <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                  </intent-filter>
        </activity>

And if you want to change app name inside

Settings -> Application manager -> downloaded

where you have all installed applications then change this android:label="@string/app_name" inside application tag

<application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

            ........

        <activity android:name="com.test.app" >
        </activity>

             .......

 </application>

Add new value to an existing array in JavaScript

Indeed, you must initialize your array then right after that use array.push() command line.

var array = new Array();
array.push("first value");
array.push("second value");

LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

I got this error while I was trying to turn off precompiled headers in a Console Application Project and removing the header file stdafx.h

To fix this go to your project properties -> Linker -> SubSystem and change the value to Not Set

In your main class, use the standard C++ main function protoype that others have already mentioned :

int main(int argc, char** argv)

Using Tkinter in python to edit the title bar

self.parent is a reference to the actual window, so self.root.title should be self.parent.title, and self.root shouldn't exist.

Exposing the current state name with ui router

this is how I do it

JAVASCRIPT:

var module = angular.module('yourModuleName', ['ui.router']);

module.run( ['$rootScope', '$state', '$stateParams',
                      function ($rootScope,   $state,   $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams; 
}
]);

HTML:

<pre id="uiRouterInfo">
      $state = {{$state.current.name}}
      $stateParams = {{$stateParams}}
      $state full url = {{ $state.$current.url.source }}    
</pre>

EXAMPLE

http://plnkr.co/edit/LGMZnj?p=preview

CSS Input with width: 100% goes outside parent's bound

Padding is essentially added to the width, therefore when you say width:100% and padding: 5px 10px you're actually adding 20px to the 100% width.

Django - how to create a file and save it to a model's FileField?

You want to have a look at FileField and FieldFile in the Django docs, and especially FieldFile.save().

Basically, a field declared as a FileField, when accessed, gives you an instance of class FieldFile, which gives you several methods to interact with the underlying file. So, what you need to do is:

self.license_file.save(new_name, new_contents)

where new_name is the filename you wish assigned and new_contents is the content of the file. Note that new_contents must be an instance of either django.core.files.File or django.core.files.base.ContentFile (see given links to manual for the details).

The two choices boil down to:

from django.core.files.base import ContentFile, File

# Using File
with open('/path/to/file') as f:
    self.license_file.save(new_name, File(f))

# Using ContentFile
self.license_file.save(new_name, ContentFile('A string with the file content'))

Maven Out of Memory Build Failure

Need to install jar files as well so that build can save memory in getting local jars.

Below command work for me after trying all those "MAVEN_OPTS" environment variable.

run "mvn clean install -U" on terminal from the root folder of the project.

Custom UITableViewCell from nib in Swift

With Swift 5 and iOS 12.2, you should try the following code in order to solve your problem:

CustomCell.swift

import UIKit

class CustomCell: UITableViewCell {

    // Link those IBOutlets with the UILabels in your .XIB file
    @IBOutlet weak var middleLabel: UILabel!
    @IBOutlet weak var leftLabel: UILabel!
    @IBOutlet weak var rightLabel: UILabel!

}

TableViewController.swift

import UIKit

class TableViewController: UITableViewController {

    let items = ["Item 1", "Item2", "Item3", "Item4"]

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "CustomCell")
    }

    // MARK: - UITableViewDataSource

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell

        cell.middleLabel.text = items[indexPath.row]
        cell.leftLabel.text = items[indexPath.row]
        cell.rightLabel.text = items[indexPath.row]

        return cell
    }

}

The image below shows a set of constraints that work with the provided code without any constraints ambiguity message from Xcode:

enter image description here

Meaning of Open hashing and Closed hashing

The use of "closed" vs. "open" reflects whether or not we are locked in to using a certain position or data structure (this is an extremely vague description, but hopefully the rest helps).

For instance, the "open" in "open addressing" tells us the index (aka. address) at which an object will be stored in the hash table is not completely determined by its hash code. Instead, the index may vary depending on what's already in the hash table.

The "closed" in "closed hashing" refers to the fact that we never leave the hash table; every object is stored directly at an index in the hash table's internal array. Note that this is only possible by using some sort of open addressing strategy. This explains why "closed hashing" and "open addressing" are synonyms.

Contrast this with open hashing - in this strategy, none of the objects are actually stored in the hash table's array; instead once an object is hashed, it is stored in a list which is separate from the hash table's internal array. "open" refers to the freedom we get by leaving the hash table, and using a separate list. By the way, "separate list" hints at why open hashing is also known as "separate chaining".

In short, "closed" always refers to some sort of strict guarantee, like when we guarantee that objects are always stored directly within the hash table (closed hashing). Then, the opposite of "closed" is "open", so if you don't have such guarantees, the strategy is considered "open".

how to make a cell of table hyperlink

Problems:

(User: Kamal) It's a good way, but you forgot the vertical align problem! using this way, we can't put the link exactly at the center of the TD element! even with vertical-align:middle;

(User: Christ) Your answer is the best answer, because there is no any align problem and also today JavaScript is necessary for every one... it's in every where even in an old smart phone... and it's enable by default...

My Suggestion to complete answer of (User: Christ):

HTML:

<td style="cursor:pointer" onclick="location.href='mylink.html'"><a class="LN1 LN2 LN3 LN4 LN5" href="mylink.html" target="_top">link</a></td>

CSS:

a.LN1 {
  font-style:normal;
  font-weight:bold;
  font-size:1.0em;
}

a.LN2:link {
  color:#A4DCF5;
  text-decoration:none;
}

a.LN3:visited {
  color:#A4DCF5;
  text-decoration:none;
}

a.LN4:hover {
  color:#A4DCF5;
  text-decoration:none;
}

a.LN5:active {
  color:#A4DCF5;
  text-decoration:none;
}

How to create streams from string in Node.Js?

in coffee-script:

class StringStream extends Readable
  constructor: (@str) ->
    super()

  _read: (size) ->
    @push @str
    @push null

use it:

new StringStream('text here').pipe(stream1).pipe(stream2)

How to add dividers and spaces between items in RecyclerView?

Just add

recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),
                DividerItemDecoration.VERTICAL));

Also you may need to add the dependency
implementation 'com.android.support:recyclerview-v7:28.0.0'

For customizing it a little bit you can add a custom drawable:

DividerItemDecoration itemDecorator = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
itemDecorator.setDrawable(ContextCompat.getDrawable(getContext(), R.drawable.divider));

You are free to use any custom drawable, for instance:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <solid android:color="@color/colorPrimary"/>
    <size android:height="0.5dp"/>
</shape>

How to resolve "Error: bad index – Fatal: index file corrupt" when using Git

This is ridiculous but I just have rebooted my machine (mac) and the problem was gone like it has never happened. I hate to sound like a support guy...

There is no tracking information for the current branch

You could specify what branch you want to pull:

git pull origin master

Or you could set it up so that your local master branch tracks github master branch as an upstream:

git branch --set-upstream-to=origin/master master
git pull

This branch tracking is set up for you automatically when you clone a repository (for the default branch only), but if you add a remote to an existing repository you have to set up the tracking yourself. Thankfully, the advice given by git makes that pretty easy to remember how to do.

Matplotlib different size subplots

Another way is to use the subplots function and pass the width ratio with gridspec_kw:

import numpy as np
import matplotlib.pyplot as plt 

# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# plot it
f, (a0, a1) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [3, 1]})
a0.plot(x, y)
a1.plot(y, x)

f.tight_layout()
f.savefig('grid_figure.pdf')

Sort JavaScript object by key

function sortObjectKeys(obj){
    return Object.keys(obj).sort().reduce((acc,key)=>{
        acc[key]=obj[key];
        return acc;
    },{});
}

sortObjectKeys({
    telephone: '069911234124',
    name: 'Lola',
    access: true,
});

Could not complete the operation due to error 80020101. IE

wrap your entire code block in this:

//<![CDATA[

//code here

//]]>

also make sure to specify the type of script to be text/javascript

try that and let me know how it goes

SQL JOIN and different types of JOINs

Definition:


JOINS are way to query the data that combined together from multiple tables simultaneously.

Types of JOINS:


Concern to RDBMS there are 5-types of joins:

  • Equi-Join: Combines common records from two tables based on equality condition. Technically, Join made by using equality-operator (=) to compare values of Primary Key of one table and Foreign Key values of another table, hence result set includes common(matched) records from both tables. For implementation see INNER-JOIN.

  • Natural-Join: It is enhanced version of Equi-Join, in which SELECT operation omits duplicate column. For implementation see INNER-JOIN

  • Non-Equi-Join: It is reverse of Equi-join where joining condition is uses other than equal operator(=) e.g, !=, <=, >=, >, < or BETWEEN etc. For implementation see INNER-JOIN.

  • Self-Join:: A customized behavior of join where a table combined with itself; This is typically needed for querying self-referencing tables (or Unary relationship entity). For implementation see INNER-JOINs.

  • Cartesian Product: It cross combines all records of both tables without any condition. Technically, it returns the result set of a query without WHERE-Clause.

As per SQL concern and advancement, there are 3-types of joins and all RDBMS joins can be achieved using these types of joins.

  1. INNER-JOIN: It merges(or combines) matched rows from two tables. The matching is done based on common columns of tables and their comparing operation. If equality based condition then: EQUI-JOIN performed, otherwise Non-EQUI-Join.

  2. OUTER-JOIN: It merges(or combines) matched rows from two tables and unmatched rows with NULL values. However, can customized selection of un-matched rows e.g, selecting unmatched row from first table or second table by sub-types: LEFT OUTER JOIN and RIGHT OUTER JOIN.

    2.1. LEFT Outer JOIN (a.k.a, LEFT-JOIN): Returns matched rows from two tables and unmatched from the LEFT table(i.e, first table) only.

    2.2. RIGHT Outer JOIN (a.k.a, RIGHT-JOIN): Returns matched rows from two tables and unmatched from the RIGHT table only.

    2.3. FULL OUTER JOIN (a.k.a OUTER JOIN): Returns matched and unmatched from both tables.

  3. CROSS-JOIN: This join does not merges/combines instead it performs Cartesian product.

enter image description here Note: Self-JOIN can be achieved by either INNER-JOIN, OUTER-JOIN and CROSS-JOIN based on requirement but the table must join with itself.

For more information:

Examples:

1.1: INNER-JOIN: Equi-join implementation

SELECT  *
FROM Table1 A 
 INNER JOIN Table2 B ON A.<Primary-Key> =B.<Foreign-Key>;

1.2: INNER-JOIN: Natural-JOIN implementation

Select A.*, B.Col1, B.Col2          --But no B.ForeignKeyColumn in Select
 FROM Table1 A
 INNER JOIN Table2 B On A.Pk = B.Fk;

1.3: INNER-JOIN with NON-Equi-join implementation

Select *
 FROM Table1 A INNER JOIN Table2 B On A.Pk <= B.Fk;

1.4: INNER-JOIN with SELF-JOIN

Select *
 FROM Table1 A1 INNER JOIN Table1 A2 On A1.Pk = A2.Fk;

2.1: OUTER JOIN (full outer join)

Select *
 FROM Table1 A FULL OUTER JOIN Table2 B On A.Pk = B.Fk;

2.2: LEFT JOIN

Select *
 FROM Table1 A LEFT OUTER JOIN Table2 B On A.Pk = B.Fk;

2.3: RIGHT JOIN

Select *
 FROM Table1 A RIGHT OUTER JOIN Table2 B On A.Pk = B.Fk;

3.1: CROSS JOIN

Select *
 FROM TableA CROSS JOIN TableB;

3.2: CROSS JOIN-Self JOIN

Select *
 FROM Table1 A1 CROSS JOIN Table1 A2;

//OR//

Select *
 FROM Table1 A1,Table1 A2;

Permutations between two lists of unequal length

The better answers to this only work for specific lengths of lists that are provided.

Here's a version that works for any lengths of input. It also makes the algorithm clear in terms of the mathematical concepts of combination and permutation.

from itertools import combinations, permutations
list1 = ['1', '2']
list2 = ['A', 'B', 'C']

num_elements = min(len(list1), len(list2))
list1_combs = list(combinations(list1, num_elements))
list2_perms = list(permutations(list2, num_elements))
result = [
  tuple(zip(perm, comb))
  for comb in list1_combs
  for perm in list2_perms
]

for idx, ((l11, l12), (l21, l22)) in enumerate(result):
  print(f'{idx}: {l11}{l12} {l21}{l22}')

This outputs:

0: A1 B2
1: A1 C2
2: B1 A2
3: B1 C2
4: C1 A2
5: C1 B2

Best way to add Activity to an Android project in Eclipse?

The R.* classes are generated dynamically. I leave the "Build automatically" option on in the Project menu so that mine R.* classes are always up-to-date.

Additionally, when creating new Activities, I copy and rename old ones, especially if they are similar to the new Activity that I need because Eclipse renames everything for you.

Otherwise, as others have said, the File->New->Class command works well and will build your file for you including templates for required methods based on your class, its inheritance and interfaces.

Why was the name 'let' chosen for block-scoped variable declarations in JavaScript?

The most likely possibility is that it was the most idiomatic choice. Not only is it easy to speak, but rather intuitive to understand. Some could argue, even more so than var.

But I reckon there's a little more history to this.

From Wikipedia:

Dana Scott's LCF language was a stage in the evolution of lambda calculus into modern functional languages. This language introduced the let expression, which has appeared in most functional languages since that time.

State-full imperative languages such as ALGOL and Pascal essentially implement a let expression, to implement restricted scope of functions, in block structures.

I would like to believe this was an inspiration too, for the let in Javascript.

How to read file with async/await properly?

This is TypeScript version of @Joel's answer. It is usable after Node 11.0:

import { promises as fs } from 'fs';

async function loadMonoCounter() {
    const data = await fs.readFile('monolitic.txt', 'binary');
    return Buffer.from(data);
}

How to fix the session_register() deprecated issue?

I wrote myself a little wrapper, so I don't have to rewrite all of my code from the past decades, which emulates register_globals and the missing session functions.

I've picked up some ideas from different sources and put some own stuff to get a replacement for missing register_globals and missing session functions, so I don't have to rewrite all of my code from the past decades. The code also works with multidimensional arrays and builds globals from a session.

To get the code to work use auto_prepend_file on php.ini to specify the file containing the code below. E.g.: auto_prepend_file = /srv/www/php/.auto_prepend.php.inc

You should have runkit extension from PECL installed and the following entries on your php.ini:

extension_dir = <your extension dir>
extension = runkit.so
runkit.internal_override = On

.auto_prepend.php.inc:

<?php
//Fix for removed session functions
if (!function_exists('session_register'))
{
    function session_register()
    {
        $register_vars = func_get_args();
        foreach ($register_vars as $var_name)
        {
            $_SESSION[$var_name] = $GLOBALS[$var_name];
            if (!ini_get('register_globals'))
            {   $GLOBALS[$var_name] = &$_SESSION[$var_name]; }
        }
    }

    function session_is_registered($var_name)
    {   return isset($_SESSION[$var_name]); }

    function session_unregister($var_name)
    {   unset($_SESSION[$var_name]); }
}

//Fix for removed function register_globals
if (!isset($PXM_REG_GLOB))
{
    $PXM_REG_GLOB=1;
    if (!ini_get('register_globals'))
    {
        if (isset($_REQUEST))   { extract($_REQUEST); }
        if (isset($_SERVER))        { extract($_SERVER); }

        //$_SESSION globals must be registred with call of session_start()
        // Best option - Catch session_start call - Runkit extension from PECL must be present
        if (extension_loaded("runkit"))
        {
            if (!function_exists('session_start_default'))
            {   runkit_function_rename("session_start", "session_start_default"); }
            if (!function_exists('session_start'))
            {
                function session_start($options=null)
                {
                    $return=session_start_default($options);
                    if (isset($_SESSION))
                    {
                        $var_names=array_keys($_SESSION);
                        foreach($var_names as $var_name)
                        {   $GLOBALS[$var_name]=&$_SESSION[$var_name]; }
                    }
                    return $return;
                }
            }
        }
        // Second best option - Will always extract $_SESSION if session cookie is present.
        elseif ($_COOKIE["PHPSESSID"])
        {
            session_start();
            if (isset($_SESSION))
            {
                $var_names=array_keys($_SESSION);
                foreach($var_names as $var_name)
                {   $GLOBALS[$var_name]=&$_SESSION[$var_name]; }
            }
        }
    }
}
?>

How to get a property value based on the name

You want Reflection

Type t = typeof(Car);
PropertyInfo prop = t.GetProperty("Make");
if(null != prop)
return prop.GetValue(this, null);

In MS DOS copying several files to one file

filenames must sort correctly to combine correctly!

file1.bin file2.bin ... file10.bin wont work properly

file01.bin file02.bin ... file10.bin will work properly

c:>for %i in (file*.bin) do type %i >> onebinary.bin

Works for ascii or binary files.

I do not want to inherit the child opacity from the parent in CSS

There is no one size fits-all approach, but one thing that I found particularly helpful is setting opacity for a div's direct children, except for the one that you want to keep fully visible. In code:

<div class="parent">
    <div class="child1"></div>
    <div class="child2"></div>
    <div class="child3"></div>
    <div class="child4"></div>
</div>

and css:

div.parent > div:not(.child1){
    opacity: 0.5;
}

In case you have background colors/images on the parent you fix color opacity with rgba and background-image by applying alpha filters

CSS Div stretch 100% page height

I ran into the same problem as you. I wanted to make a DIV as background, why, because its easy to manipulate div through javascript. Anyways three things I did in the css for that div.

CSS:

{    
position:absolute; 
display:block; 
height:100%; 
width:100%; 
top:0px; 
left:0px; 
z-index:-1;    
}

Google Maps API v3 marker with label

I can't guarantee it's the simplest, but I like MarkerWithLabel. As shown in the basic example, CSS styles define the label's appearance and options in the JavaScript define the content and placement.

 .labels {
   color: red;
   background-color: white;
   font-family: "Lucida Grande", "Arial", sans-serif;
   font-size: 10px;
   font-weight: bold;
   text-align: center;
   width: 60px;     
   border: 2px solid black;
   white-space: nowrap;
 }

JavaScript:

 var marker = new MarkerWithLabel({
   position: homeLatLng,
   draggable: true,
   map: map,
   labelContent: "$425K",
   labelAnchor: new google.maps.Point(22, 0),
   labelClass: "labels", // the CSS class for the label
   labelStyle: {opacity: 0.75}
 });

The only part that may be confusing is the labelAnchor. By default, the label's top left corner will line up to the marker pushpin's endpoint. Setting the labelAnchor's x-value to half the width defined in the CSS width property will center the label. You can make the label float above the marker pushpin with an anchor point like new google.maps.Point(22, 50).

In case access to the links above are blocked, I copied and pasted the packed source of MarkerWithLabel into this JSFiddle demo. I hope JSFiddle is allowed in China :|

Error Dropping Database (Can't rmdir '.test\', errno: 17)

I had the same issue (mysql 5.6 on mac) with 'can't rmdir..'-errors when dropping databases. Leaving an empty database directory not possible to get rid of. Thanks @Framework and @Beel for the solutions.

I first deleted the db directory from the Terminal in (/Applications/XAMPP/xamppfiles/var/mysql).

For further db drops, I also deleted the empty test file. In my case the file was called NOTEMPTY but still containing 0:

sudo ls -al test
total 0
drwxrwx---   3 _mysql  _mysql  102 Mar 26 16:50 .
drwxrwxr-x  18 _mysql  _mysql  612 Apr  7 13:34 ..
-rw-rw----   1 _mysql  _mysql    0 Jun 26  2013 NOTEMPTY

Chmod first and then

sudo rm -rf test/NOTEMPTY

No problems dropping databases after that

How to sort dates from Oldest to Newest in Excel?

I had the same problem and tried all the suggestions above. My dates were formatted mm/dd/yyyy. In desperation I tried the following:

  1. Highlighted the entire column with the dates.
  2. Searched for 2017
  3. Replace All with 2017
  4. The problem was solved (for dates in 2017, repeat for other years).

I hope this helps.

Python IndentationError unindent does not match any outer indentation level

You are mixing tabs and spaces. Don't do that. Specifically, the __init__ function body is indented with tabs while your on_data method is not.

Here is a screenshot of your code in my text editor; I set the tab stop to 8 spaces (which is what Python uses) and selected the text, which causes the editor to display tabs with continuous horizontal lines:

highlighted code with tabs shown as lines

You have your editor set to expanding tabs to every fourth column instead, so the methods appear to line up.

Run your code with:

python -tt scriptname.py

and fix all errors that finds. Then configure your editor to use spaces only for indentation; a good editor will insert 4 spaces every time you use the TAB key.

How to write log file in c#?

This is add new string in the file

using (var file = new StreamWriter(filePath + "log.txt", true))
        {
            file.WriteLine(log);
            file.Close();
        }

Convert string to a variable name

There is another simple solution found there: http://www.r-bloggers.com/converting-a-string-to-a-variable-name-on-the-fly-and-vice-versa-in-r/

To convert a string to a variable:

x <- 42
eval(parse(text = "x"))
[1] 42

And the opposite:

x <- 42
deparse(substitute(x))
[1] "x"

Proper use of const for defining functions in JavaScript

There are some very important benefits to the use of const and some would say it should be used wherever possible because of how deliberate and indicative it is.

It is, as far as I can tell, the most indicative and predictable declaration of variables in JavaScript, and one of the most useful, BECAUSE of how constrained it is. Why? Because it eliminates some possibilities available to var and let declarations.

What can you infer when you read a const? You know all of the following just by reading the const declaration statement, AND without scanning for other references to that variable:

  • the value is bound to that variable (although its underlying object is not deeply immutable)
  • it can’t be accessed outside of its immediately containing block
  • the binding is never accessed before declaration, because of Temporal Dead Zone (TDZ) rules.

The following quote is from an article arguing the benefits of let and const. It also more directly answers your question about the keyword's constraints/limits:

Constraints such as those offered by let and const are a powerful way of making code easier to understand. Try to accrue as many of these constraints as possible in the code you write. The more declarative constraints that limit what a piece of code could mean, the easier and faster it is for humans to read, parse, and understand a piece of code in the future.

Granted, there’s more rules to a const declaration than to a var declaration: block-scoped, TDZ, assign at declaration, no reassignment. Whereas var statements only signal function scoping. Rule-counting, however, doesn’t offer a lot of insight. It is better to weigh these rules in terms of complexity: does the rule add or subtract complexity? In the case of const, block scoping means a narrower scope than function scoping, TDZ means that we don’t need to scan the scope backwards from the declaration in order to spot usage before declaration, and assignment rules mean that the binding will always preserve the same reference.

The more constrained statements are, the simpler a piece of code becomes. As we add constraints to what a statement might mean, code becomes less unpredictable. This is one of the biggest reasons why statically typed programs are generally easier to read than dynamically typed ones. Static typing places a big constraint on the program writer, but it also places a big constraint on how the program can be interpreted, making its code easier to understand.

With these arguments in mind, it is recommended that you use const where possible, as it’s the statement that gives us the least possibilities to think about.

Source: https://ponyfoo.com/articles/var-let-const

How to programmatically set style attribute in a view

Depending on what style attributes you'd like to change you may be able to use the Paris library:

Button view = (Button) LayoutInflater.from(this).inflate(R.layout.section_button, null);
Paris.style(view).apply(R.style.YourStyle);

Many attributes like background, padding, textSize, textColor, etc. are supported.

Disclaimer: I authored the library.

PHP Undefined Index

I don't see php file, but that could be that -
replace in your php file:

$query_age = $_GET['query_age'];

with:

$query_age = (isset($_GET['query_age']) ? $_GET['query_age'] : null);

Most probably, at first time you running your script without ?query_age=[something] and $_GET has no key like query_age.

Bootstrap 4, How do I center-align a button?

Use text-center class in the parent container for Bootstrap 4

What is the documents directory (NSDocumentDirectory)?

Your app only (on a non-jailbroken device) runs in a "sandboxed" environment. This means that it can only access files and directories within its own contents. For example Documents and Library.

See the iOS Application Programming Guide.

To access the Documents directory of your applications sandbox, you can use the following:

iOS 8 and newer, this is the recommended method

+ (NSURL *)applicationDocumentsDirectory
{
     return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

if you need to support iOS 7 or earlier

+ (NSString *) applicationDocumentsDirectory 
{    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = paths.firstObject;
    return basePath;
}

This Documents directory allows you to store files and subdirectories your app creates or may need.

To access files in the Library directory of your apps sandbox use (in place of paths above):

[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]

Printing tuple with string formatting in Python

Note that the % syntax is obsolete. Use str.format, which is simpler and more readable:

t = 1,2,3
print 'This is a tuple {0}'.format(t)

jQuery select change event get selected option

See official API documentation https://api.jquery.com/selected-selector/

This good works:

$( "select" ).on('change',function() {
  var str = "";
  // For multiple choice
  $( "select option:selected" ).each(function() {
    str += $( this ).val() + " "; 
  });
});

and

$( "select" ).on('change',function() {
  // For unique choice
  var selVal = $( "select option:selected" ).val(); 
});

and be easy for unique choice

var SelVal = $( "#idSelect option:selected" ).val();

How to quickly drop a user with existing privileges

Here's what's finally worked for me :

REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA myschem FROM user_mike;
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA myschem FROM user_mike;
REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA myschem FROM user_mike;
REVOKE ALL PRIVILEGES ON SCHEMA myschem FROM user_mike;
ALTER DEFAULT PRIVILEGES IN SCHEMA myschem REVOKE ALL ON SEQUENCES FROM user_mike;
ALTER DEFAULT PRIVILEGES IN SCHEMA myschem REVOKE ALL ON TABLES FROM user_mike;
ALTER DEFAULT PRIVILEGES IN SCHEMA myschem REVOKE ALL ON FUNCTIONS FROM user_mike;
REVOKE USAGE ON SCHEMA myschem FROM user_mike;
REASSIGN OWNED BY user_mike TO masteruser;
DROP USER user_mike ;

How to solve could not create the virtual machine error of Java Virtual Machine Launcher?

  • Tap on Windows-Pause to open the System Control Panel applet. You can alternatively open the control panel manual to go there if you prefer it that way. Click on advanced system settings on the left.
  • Select environmental variables here.
  • Click on new under System Variables.
  • Enter '_JAVA_OPTIONS' as the variable name.
  • Enter '-Xmx1024M' as the variable value.
  • Click ok twice.

How to check for a valid Base64 encoded string

The answer must depend on the usage of the string. There are many strings that may be "valid base64" according to the syntax suggested by several posters, but that may "correctly" decode, without exception, to junk. Example: the 8char string Portland is valid Base64. What is the point of stating that this is valid Base64? I guess that at some point you'd want to know that this string should or should not be Base64 decoded.

In my case, I have Oracle connection strings that may be in plain text like:

Data source=mydb/DBNAME;User Id=Roland;Password=.....`

or in base64 like

VXNlciBJZD1sa.....................................==

I just have to check for the presence of a semicolon, because that proves that it is NOT base64, which is of course faster than any above method.

How to use template module with different set of variables?

- name: copy vhosts
  template: src=site-vhost.conf dest=/etc/apache2/sites-enabled/{{ item }}.conf
  with_items:
    - somehost.local
    - otherhost.local
  notify: restart apache

IMPORTANT: Note that an item does not have to be just a string, it can be an object with as many properties as you like, so that way you can pass any number of variables.

In the template I have:

<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName {{ item }}
    DocumentRoot /vagrant/public


    ErrorLog ${APACHE_LOG_DIR}/error-{{ item }}.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

What is the difference between an annotated and unannotated tag?

The big difference is perfectly explained here.

Basically, lightweight tags are just pointers to specific commits. No further information is saved; on the other hand, annotated tags are regular objects, which have an author and a date and can be referred because they have their own SHA key.

If knowing who tagged what and when is relevant for you, then use annotated tags. If you just want to tag a specific point in your development, no matter who and when did that, then lightweight tags are good enough.

Normally you'd go for annotated tags, but it is really up to the Git master of the project.

Writing BMP image in pure c/c++ without other libraries

If you get strange colors switches in the middle of your image using the above C++ function. Be sure to open the outstream in binary mode: imgFile.open(filename, std::ios_base::out | std::ios_base::binary);
Otherwise windows inserts unwanted characters in the middle of your file! (been banging my head on this issue for hours)

See related question here: Why does ofstream insert a 0x0D byte before 0x0A?

ORA-00904: invalid identifier

Also make sure the user issuing the query has been granted the necessary permissions.

For queries on tables you need to grant SELECT permission.
For queries on other object types (e.g. stored procedures) you need to grant EXECUTE permission.

JavaScript + Unicode regexes

This will do it:

/[A-Za-z\u00C0-\u00FF ]+/.exec('hipopótamo maçã pólen ñ poção água língüa')

It explicitly selects a range of unicode characters. It will work for latin characters, but other strange characters may be out of this range.

Java Refuses to Start - Could not reserve enough space for object heap

ulimit max memory size and virtual memory set to unlimited?

How to enable file upload on React's Material UI simple input?

You can use Material UI's Input and InputLabel components. Here's an example if you were using them to input spreadsheet files.

import { Input, InputLabel } from "@material-ui/core";

const styles = {
  hidden: {
    display: "none",
  },
  importLabel: {
    color: "black",
  },
};

<InputLabel htmlFor="import-button" style={styles.importLabel}>
    <Input
        id="import-button"
        inputProps={{
          accept:
            ".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel",
        }}
        onChange={onInputChange}
        style={styles.hidden}
        type="file"
    />
    Import Spreadsheet
</InputLabel>

Http Servlet request lose params from POST body after read it once

Just overwriting of getInputStream() did not work in my case. My server implementation seems to parse parameters without calling this method. I did not find any other way, but re-implement the all four getParameter* methods as well. Here is the code of getParameterMap (Apache Http Client and Google Guava library used):

@Override
public Map<String, String[]> getParameterMap() {
    Iterable<NameValuePair> params = URLEncodedUtils.parse(getQueryString(), NullUtils.UTF8);

    try {
        String cts = getContentType();
        if (cts != null) {
            ContentType ct = ContentType.parse(cts);
            if (ct.getMimeType().equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
                List<NameValuePair> postParams = URLEncodedUtils.parse(IOUtils.toString(getReader()), NullUtils.UTF8);
                params = Iterables.concat(params, postParams);
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    Map<String, String[]> result = toMap(params);
    return result;
}

public static Map<String, String[]> toMap(Iterable<NameValuePair> body) {
    Map<String, String[]> result = new LinkedHashMap<>();
    for (NameValuePair e : body) {
        String key = e.getName();
        String value = e.getValue();
        if (result.containsKey(key)) {
            String[] newValue = ObjectArrays.concat(result.get(key), value);
            result.remove(key);
            result.put(key, newValue);
        } else {
            result.put(key, new String[] {value});
        }
    }
    return result;
}

Lumen: get URL parameter in a Blade view

You can publicly expose Input facade via an alias in config/app.php:

'aliases' => [
    ...

    'Input' => Illuminate\Support\Facades\Input::class,
]

And access url $_GET parameter values using the facade directly inside Blade view/template:

{{ Input::get('a') }}

How can I save a base64-encoded image to disk?

UPDATE

I found this interesting link how to solve your problem in PHP. I think you forgot to replace space by +as shown in the link.

I took this circle from http://images-mediawiki-sites.thefullwiki.org/04/1/7/5/6204600836255205.png as sample which looks like:

http://images-mediawiki-sites.thefullwiki.org/04/1/7/5/6204600836255205.png

Next I put it through http://www.greywyvern.com/code/php/binary2base64 which returned me:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAAAAACPAi4CAAAAB3RJTUUH1QEHDxEhOnxCRgAAAAlwSFlzAAAK8AAACvABQqw0mAAAAXBJREFUeNrtV0FywzAIxJ3+K/pZyctKXqamji0htEik9qEHc3JkWC2LRPCS6Zh9HIy/AP4FwKf75iHEr6eU6Mt1WzIOFjFL7IFkYBx3zWBVkkeXAUCXwl1tvz2qdBLfJrzK7ixNUmVdTIAB8PMtxHgAsFNNkoExRKA+HocriOQAiC+1kShhACwSRGAEwPP96zYIoE8Pmph9qEWWKcCWRAfA/mkfJ0F6dSoA8KW3CRhn3ZHcW2is9VOsAgoqHblncAsyaCgcbqpUZQnWoGTcp/AnuwCoOUjhIvCvN59UBeoPZ/AYyLm3cWVAjxhpqREVaP0974iVwH51d4AVNaSC8TRNNYDQEFdlzDW9ob10YlvGQm0mQ+elSpcCCBtDgQD7cDFojdx7NIeHJkqi96cOGNkfZOroZsHtlPYoR7TOp3Vmfa5+49uoSSRyjfvc0A1kLx4KC6sNSeDieD1AWhrJLe0y+uy7b9GjP83l+m68AJ72AwSRPN5g7uwUAAAAAElFTkSuQmCC

saved this string to base64 which I read from in my code.

var fs      = require('fs'),
data        = fs.readFileSync('base64', 'utf8'),
base64Data,
binaryData;

base64Data  =   data.replace(/^data:image\/png;base64,/, "");
base64Data  +=  base64Data.replace('+', ' ');
binaryData  =   new Buffer(base64Data, 'base64').toString('binary');

fs.writeFile("out.png", binaryData, "binary", function (err) {
    console.log(err); // writes out file without error, but it's not a valid image
});

I get a circle back, but the funny thing is that the filesize has changed :)...

END

When you read back image I think you need to setup headers

Take for example imagepng from PHP page:

<?php
$im = imagecreatefrompng("test.png");

header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

I think the second line header('Content-Type: image/png');, is important else your image will not be displayed in browser, but just a bunch of binary data is shown to browser.

In Express you would simply just use something like below. I am going to display your gravatar which is located at http://www.gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG and is a jpeg file when you curl --head http://www.gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG. I only request headers because else curl will display a bunch of binary stuff(Google Chrome immediately goes to download) to console:

curl --head "http://www.gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG"
HTTP/1.1 200 OK
Server: nginx
Date: Wed, 03 Aug 2011 12:11:25 GMT
Content-Type: image/jpeg
Connection: keep-alive
Last-Modified: Mon, 04 Oct 2010 11:54:22 GMT
Content-Disposition: inline; filename="cabf735ce7b8b4471ef46ea54f71832d.jpeg"
Access-Control-Allow-Origin: *
Content-Length: 1258
X-Varnish: 2356636561 2352219240
Via: 1.1 varnish
Expires: Wed, 03 Aug 2011 12:16:25 GMT
Cache-Control: max-age=300
Source-Age: 1482

$ mkdir -p ~/tmp/6922728
$ cd ~/tmp/6922728/
$ touch app.js

app.js

var app = require('express').createServer();

app.get('/', function (req, res) {
    res.contentType('image/jpeg');
    res.sendfile('cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG');
});

app.get('/binary', function (req, res) {
    res.sendfile('cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG');
});

app.listen(3000);

$ wget "http://www.gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG"
$ node app.js

laravel the requested url was not found on this server

Make sure you have mod_rewrite enabled.

restart apache

and clear cookies of your browser for read again at .htaccess

Bootstrap: adding gaps between divs

Adding a padding between the divs to simulate a gap might be a hack, but why not use something Bootstrap provides. It's called offsets. But again, you can define a class in your custom.css (you shouldn't edit the core stylesheet anyway) file and add something like .gap. However, .col-md-offset-* does the job most of the times for me, allowing me to precisely leave a gap between the divs.

As for vertical spacing, unfortunately, there isn't anything set built-in like that in Bootstrap 3, so you will have to invent your own custom class to do that. I'd usually do something like .top-buffer { margin-top:20px; }. This does the trick, and obviously, it doesn't have to be 20px, it can be anything you like.

Should each and every table have a primary key?

Short answer: yes.

Long answer:

  • You need your table to be joinable on something
  • If you want your table to be clustered, you need some kind of a primary key.
  • If your table design does not need a primary key, rethink your design: most probably, you are missing something. Why keep identical records?

In MySQL, the InnoDB storage engine always creates a primary key if you didn't specify it explicitly, thus making an extra column you don't have access to.

Note that a primary key can be composite.

If you have a many-to-many link table, you create the primary key on all fields involved in the link. Thus you ensure that you don't have two or more records describing one link.

Besides the logical consistency issues, most RDBMS engines will benefit from including these fields in a unique index.

And since any primary key involves creating a unique index, you should declare it and get both logical consistency and performance.

See this article in my blog for why you should always create a unique index on unique data:

P.S. There are some very, very special cases where you don't need a primary key.

Mostly they include log tables which don't have any indexes for performance reasons.

gcc: undefined reference to

Are you mixing C and C++? One issue that can occur is that the declarations in the .h file for a .c file need to be surrounded by:

#if defined(__cplusplus)
  extern "C" {                 // Make sure we have C-declarations in C++ programs
#endif

and:

#if defined(__cplusplus)
  }
#endif

Note: if unable / unwilling to modify the .h file(s) in question, you can surround their inclusion with extern "C":

extern "C" {
#include <abc.h>
} //extern

How to handle ListView click in Android

Suppose ListView object is lv, do the following-

lv.setClickable(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

  @Override
  public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {

    Object o = lv.getItemAtPosition(position);
    /* write you handling code like...
    String st = "sdcard/";
    File f = new File(st+o.toString());
    // do whatever u want to do with 'f' File object
    */  
  }
});

How to create own dynamic type or dynamic object in C#?

dynamic myDynamic = new { PropertyOne = true, PropertyTwo = false};

To show error message without alert box in Java Script

web masters or web programmers, please insert

<!DOCTYPE html>

at the start of your page. Second you should enclose your attributes with quotes like

type="text" id="fname"

input element should not contain end element, just close it like:

 />

input element dont have innerHTML, it has value sor your javascript line should be:

document.getElementById("fname").value = "this is invalid name";

Please write in organized way and make sure it is convenient to standards.

Can gcc output C code after preprocessing?

I'm using gcc as a preprocessor (for html files.) It does just what you want. It expands "#--" directives, then outputs a readable file. (NONE of the other C/HTML preprocessors I've tried do this- they concatenate lines, choke on special characters, etc.) Asuming you have gcc installed, the command line is:

gcc -E -x c -P -C -traditional-cpp code_before.cpp > code_after.cpp

(Doesn't have to be 'cpp'.) There's an excellent description of this usage at http://www.cs.tut.fi/~jkorpela/html/cpre.html.

The "-traditional-cpp" preserves whitespace & tabs.

When should we implement Serializable interface?

  1. Implement the Serializable interface when you want to be able to convert an instance of a class into a series of bytes or when you think that a Serializable object might reference an instance of your class.

  2. Serializable classes are useful when you want to persist instances of them or send them over a wire.

  3. Instances of Serializable classes can be easily transmitted. Serialization does have some security consequences, however. Read Joshua Bloch's Effective Java.