Programs & Examples On #Defaultstyleddocument

How to implement WiX installer upgrade?

I used this site to help me understand the basics about WiX Upgrade:

http://wix.tramontana.co.hu/tutorial/upgrades-and-modularization

Afterwards I created a sample Installer, (installed a test file), then created the Upgrade installer (installed 2 sample test files). This will give you a basic understanding of how the mechanism works.

And as Mike said in the book from Apress, "The Definitive Guide to Windows Installer", it will help you out to understand, but it is not written using WiX.

Another site that was pretty helpful was this one:

http://www.wixwiki.com/index.php?title=Main_Page

How to trigger SIGUSR1 and SIGUSR2?

They are user-defined signals, so they aren't triggered by any particular action. You can explicitly send them programmatically:

#include <signal.h>

kill(pid, SIGUSR1);

where pid is the process id of the receiving process. At the receiving end, you can register a signal handler for them:

#include <signal.h>

void my_handler(int signum)
{
    if (signum == SIGUSR1)
    {
        printf("Received SIGUSR1!\n");
    }
}

signal(SIGUSR1, my_handler);

PHPExcel set border and format for all sheets in spreadsheet

You can set a default style for the entire workbook (all worksheets):

$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getTop()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getBottom()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getLeft()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getRight()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);

or

  $styleArray = array(
      'borders' => array(
          'allborders' => array(
              'style' => PHPExcel_Style_Border::BORDER_THIN
          )
      )
  );
$objPHPExcel->getDefaultStyle()->applyFromArray($styleArray);

And this can be used for all style properties, not just borders.

But column autosizing is structural rather than stylistic, and has to be set for each column on each worksheet individually.

EDIT

Note that default workbook style only applies to Excel5 Writer

How do you pull first 100 characters of a string in PHP

$small = substr($big, 0, 100);

For String Manipulation here is a page with a lot of function that might help you in your future work.

.htaccess, order allow, deny, deny from all: confused?

This is a quite confusing way of using Apache configuration directives.

Technically, the first bit is equivalent to

Allow From All

This is because Order Deny,Allow makes the Deny directive evaluated before the Allow Directives. In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.

Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.

The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.

Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.

It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.

The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):

#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>

which forbids access to any file beginning by ".ht".

The equivalent Apache 2.4 configuration should look like:

<Files ~ "^\.ht">
    Require all denied
</Files>

ASP.net vs PHP (What to choose)

You can have great success and great performance either way. MSDN runs off of ASP.NET so you know it can perform well. PHP runs a lot of the top websites in the world. The same can be said of the databases as well. You really need to choose based upon your skills, the skills of your team, possible specific features that you need/want that one does better than the other, and even the servers that you want to run this site.

If I were building it, I would lean towards PHP because probably everything you want to do has been done before (with code examples how) and because hosting is so much easier to get (and cheaper because you don't have the licensing issues to deal with compared to Windows hosting). For the same reason, I would choose MySQL as well. It is a great database platform and the price is right.

HTML email in outlook table width issue - content is wider than the specified table width

I guess problem is in width attributes in table and td remove 'px' for example

<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">

Should be

<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">

How can I stream webcam video with C#?

Another option to stream images from a webcam to a browser is via mjpeg. This is just a series of jpeg images that most modern browsers support as part of the tag. Here's a sample server written in c#:

https://www.codeproject.com/articles/371955/motion-jpeg-streaming-server

This works well over a LAN, but not as well over the internet as mjpeg is not as effcient as other video codecs (h264, VP8 etc..)

Troubleshooting BadImageFormatException

For anyone who may arrive here at a later time....Nothing worked for me. All my assemblies were fine. I had an app config in one of my Visual Studio Projects that shouldn't have been there. So make sure your app config file is needed.

I deleted the extra app config and it worked.

How to select multiple files with <input type="file">?

HTML5 has provided new attribute multiple for input element whose type attribute is file. So you can select multiple files and IE9 and previous versions does not support this.

NOTE: be carefull with the name of the input element. when you want to upload multiple file you should use array and not string as the value of the name attribute.

ex:

input type="file" name="myPhotos[]" multiple="multiple"

and if you are using php then you will get the data in $_FILES and use var_dump($_FILES) and see output and do processing Now you can iterate over and do the rest

How to use a table type in a SELECT FROM statement?

Thanks for all help at this issue. I'll post here my solution:

Package Header

CREATE OR REPLACE PACKAGE X IS
  TYPE exch_row IS RECORD(
    currency_cd VARCHAR2(9),
    exch_rt_eur NUMBER,
    exch_rt_usd NUMBER);
  TYPE exch_tbl IS TABLE OF X.exch_row;

  FUNCTION GetExchangeRate RETURN X.exch_tbl PIPELINED;
END X;

Package Body

CREATE OR REPLACE PACKAGE BODY X IS
  FUNCTION GetExchangeRate RETURN X.exch_tbl
    PIPELINED AS
    exch_rt_usd NUMBER := 1.0; --todo
    rw exch_row;
  BEGIN

    FOR rw IN (SELECT c.currency_cd AS currency_cd, e.exch_rt AS exch_rt_eur, (e.exch_rt / exch_rt_usd) AS exch_rt_usd
                 FROM exch e, currency c
                WHERE c.currency_key = e.currency_key
                  ) LOOP
      PIPE ROW(rw);
    END LOOP;
  END;


  PROCEDURE DoIt IS
  BEGIN
    DECLARE
      CURSOR c0 IS
        SELECT i.DOC,
               i.doc_currency,
               i.net_value,
               i.net_value / rt.exch_rt_usd AS net_value_in_usd,
               i.net_value / rt.exch_rt_eur AS net_value_in_euro,
          FROM item i, (SELECT * FROM TABLE(X.GetExchangeRate())) rt
         WHERE i.doc_currency = rt.currency_cd;

      TYPE c0_type IS TABLE OF c0%ROWTYPE;

      items c0_type;
    BEGIN
      OPEN c0;

      LOOP
        FETCH c0 BULK COLLECT
          INTO items LIMIT batchsize;

        EXIT WHEN items.COUNT = 0;
        FORALL i IN items.FIRST .. items.LAST SAVE EXCEPTIONS
          INSERT INTO detail_items VALUES items (i);

      END LOOP;

      CLOSE c0;

      COMMIT;

    EXCEPTION
      WHEN OTHERS THEN
        RAISE;
    END;
  END;

END X;

Please review.

Filtering array of objects with lodash based on property value

Use lodash _.filter method:

_.filter(collection, [predicate=_.identity])

Iterates over elements of collection, returning an array of all elements predicate returns truthy for. The predicate is invoked with three arguments: (value, index|key, collection).

with predicate as custom function

 _.filter(myArr, function(o) { 
    return o.name == 'john'; 
 });

with predicate as part of filtered object (the _.matches iteratee shorthand)

_.filter(myArr, {name: 'john'});

with predicate as [key, value] array (the _.matchesProperty iteratee shorthand.)

_.filter(myArr, ['name', 'John']);

Docs reference: https://lodash.com/docs/4.17.4#filter

Boolean vs boolean in Java

Basically boolean represent a primitive data type where Boolean represent a reference data type. this story is started when Java want to become purely object oriented it's provided wrapper class concept to over come to use of primitive data type.

boolean b1;
Boolean b2;

b1 and b2 are not same.

Getting NetworkCredential for current user (C#)

You can get the user name using System.Security.Principal.WindowsIdentity.GetCurrent() but there is not way to get current user password!

Internal and external fragmentation

First of all the term fragmentation cues there's an entity divided into parts — fragments.

  • Internal fragmentation: Typical paper book is a collection of pages (text divided into pages). When a chapter's end isn't located at the end of page and new chapter starts from new page, there's a gap between those chapters and it's a waste of space — a chunk (page for a book) has unused space inside (internally) — "white space"

  • External fragmentation: Say you have a paper diary and you didn't write your thoughts sequentially page after page, but, rather randomly. You might end up with a situation when you'd want to write 3 pages in row, but you can't since there're no 3 clean pages one-by-one, you might have 15 clean pages in the diary totally, but they're not contiguous

How do I know which version of Javascript I'm using?

In chrome you can find easily not only your JS version but also a flash version. All you need is to type chrome://version/ in a command line and you will get something like this:

enter image description here

MySQL error: key specification without a key length

Also, if you want to use index in this field, you should use the MyISAM storage engine and the FULLTEXT index type.

How to properly overload the << operator for an ostream?

Just telling you about one other possibility: I like using friend definitions for that:

namespace Math
{
    class Matrix
    {
    public:

        [...]

        friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix) {
            [...]
        }
    };
}

The function will be automatically targeted into the surrounding namespace Math (even though its definition appears within the scope of that class) but will not be visible unless you call operator<< with a Matrix object which will make argument dependent lookup find that operator definition. That can sometimes help with ambiguous calls, since it's invisible for argument types other than Matrix. When writing its definition, you can also refer directly to names defined in Matrix and to Matrix itself, without qualifying the name with some possibly long prefix and providing template parameters like Math::Matrix<TypeA, N>.

Extending from two classes

Why Not Use an Inner Class (Nesting)

class A extends B {
    private class C extends D {
        //Classes A , B , C , D accessible here 
    }
}

How to send PUT, DELETE HTTP request in HttpURLConnection?

public  HttpURLConnection getHttpConnection(String url, String type){
        URL uri = null;
        HttpURLConnection con = null;
        try{
            uri = new URL(url);
            con = (HttpURLConnection) uri.openConnection();
            con.setRequestMethod(type); //type: POST, PUT, DELETE, GET
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setConnectTimeout(60000); //60 secs
            con.setReadTimeout(60000); //60 secs
            con.setRequestProperty("Accept-Encoding", "Your Encoding");
            con.setRequestProperty("Content-Type", "Your Encoding");
        }catch(Exception e){
            logger.info( "connection i/o failed" );
        }
        return con;
}

Then in your code :

public void yourmethod(String url, String type, String reqbody){
    HttpURLConnection con = null;
    String result = null;
    try {
        con = conUtil.getHttpConnection( url , type);
    //you can add any request body here if you want to post
         if( reqbody != null){  
                con.setDoInput(true);
                con.setDoOutput(true);
                DataOutputStream out = new  DataOutputStream(con.getOutputStream());
                out.writeBytes(reqbody);
                out.flush();
                out.close();
            }
        con.connect();
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String temp = null;
        StringBuilder sb = new StringBuilder();
        while((temp = in.readLine()) != null){
            sb.append(temp).append(" ");
        }
        result = sb.toString();
        in.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        logger.error(e.getMessage());
    }
//result is the response you get from the remote side
}

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

For me it was a browser issue, since my requests were working fine in Postman.

Turns out that for some reason, Firefox and Chrome blocked requests going to port 6000, once I changed the ASP.NET API port to 4000, the error changed to a known CORS error which I could fix.

Chrome at least showed me ERR_UNSAFE_PORT which gave me a clue about what could be wrong.

JavaFX "Location is required." even though it is in the same package

In my case all of the above were not the problem at all.

My problem was solved when I replaced :

getClass().getResource("ui_layout.fxml")

with :

getClass().getClassLoader().getResource("ui_layout.fxml")

What is Unicode, UTF-8, UTF-16?

Originally, Unicode was intended to have a fixed-width 16-bit encoding (UCS-2). Early adopters of Unicode, like Java and Windows NT, built their libraries around 16-bit strings.

Later, the scope of Unicode was expanded to include historical characters, which would require more than the 65,536 code points a 16-bit encoding would support. To allow the additional characters to be represented on platforms that had used UCS-2, the UTF-16 encoding was introduced. It uses "surrogate pairs" to represent characters in the supplementary planes.

Meanwhile, a lot of older software and network protocols were using 8-bit strings. UTF-8 was made so these systems could support Unicode without having to use wide characters. It's backwards-compatible with 7-bit ASCII.

Java JDBC - How to connect to Oracle using Service Name instead of SID

http://download.oracle.com/docs/cd/B28359_01/java.111/b31224/urls.htm#BEIDHCBA

Thin-style Service Name Syntax

Thin-style service names are supported only by the JDBC Thin driver. The syntax is:

@//host_name:port_number/service_name

For example:

jdbc:oracle:thin:scott/tiger@//myhost:1521/myservicename

So I would try:

jdbc:oracle:thin:@//oracle.hostserver2.mydomain.ca:1522/ABCD

Also, per Robert Greathouse's answer, you can also specify the TNS name in the JDBC URL as below:

jdbc:oracle:thin:@(DESCRIPTION =(ADDRESS_LIST =(ADDRESS =(PROTOCOL=TCP)(HOST=blah.example.com)(PORT=1521)))(CONNECT_DATA=(SID=BLAHSID)(GLOBAL_NAME=BLAHSID.WORLD)(SERVER=DEDICATED)))

Generate HTML table from 2D JavaScript array

If you don't mind jQuery, I am using this:

<table id="metaConfigTable">
    <caption>This is your target table</caption>
    <tr>
        <th>Key</th>
        <th>Value</th>
    </tr>
</table>

<script>

    function tabelajzing(a){ 
    // takes (key, value) pairs from and array and returns
    // corresponding html, i.e. [ [1,2], [3,4], [5,6] ] 
      return [
        "<tr>\n<th>",
        a.map(function (e, i) {
          return e.join("</th>\n<td>")
        }).join("</td></tr>\n<tr>\n<th>"),
        "</td>\n</tr>\n"
      ].join("")
    }

  $('#metaConfigTable').find("tr").after(
      tabelajzing( [ [1,2],[3,4],[5,6] ])
  );
</script>

How to redirect the output of an application in background to /dev/null

You use:

yourcommand  > /dev/null 2>&1

If it should run in the Background add an &

yourcommand > /dev/null 2>&1 &

>/dev/null 2>&1 means redirect stdout to /dev/null AND stderr to the place where stdout points at that time

If you want stderr to occur on console and only stdout going to /dev/null you can use:

yourcommand 2>&1 > /dev/null

In this case stderr is redirected to stdout (e.g. your console) and afterwards the original stdout is redirected to /dev/null

If the program should not terminate you can use:

nohup yourcommand &

Without any parameter all output lands in nohup.out

How to display image from URL on Android

For simple example,
http://www.helloandroid.com/tutorials/how-download-fileimage-url-your-device

You will have to use httpClient and download the image (cache it if required) ,

solution offered for displaying images in listview, essentially same code(check the code where imageview is set from url) for displaying.

Lazy load of images in ListView

Local file access with JavaScript

if you are using angularjs & aspnet/mvc, to retrieve json files, you have to allow mime type at web config

<staticContent>
    <remove fileExtension=".json" />
    <mimeMap fileExtension=".json" mimeType="application/json" />
  </staticContent>

Using iFrames In ASP.NET

try this

<iframe name="myIframe" id="myIframe" width="400px" height="400px" runat="server"></iframe>

Expose this iframe in the master page's codebehind:

public HtmlControl iframe
{
get
{
return this.myIframe;
}
}

Add the MasterType directive for the content page to strongly typed Master Page.

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits=_Default" Title="Untitled Page" %>
<%@ MasterType VirtualPath="~/MasterPage.master" %>

In code behind

protected void Page_Load(object sender, EventArgs e)
{
this.Master.iframe.Attributes.Add("src", "some.aspx");
}

Sum a list of numbers in Python

Thanks to Karl Knechtel i was able to understand your question. My interpretation:

  1. You want a new list with the average of the element i and i+1.
  2. You want to sum each element in the list.

First question using anonymous function (aka. Lambda function):

s = lambda l: [(l[0]+l[1])/2.] + s(l[1:]) if len(l)>1 else []  #assuming you want result as float
s = lambda l: [(l[0]+l[1])//2] + s(l[1:]) if len(l)>1 else []  #assuming you want floor result

Second question also using anonymous function (aka. Lambda function):

p = lambda l: l[0] + p(l[1:]) if l!=[] else 0

Both questions combined in a single line of code :

s = lambda l: (l[0]+l[1])/2. + s(l[1:]) if len(l)>1 else 0  #assuming you want result as float
s = lambda l: (l[0]+l[1])/2. + s(l[1:]) if len(l)>1 else 0  #assuming you want floor result

use the one that fits best your needs

1052: Column 'id' in field list is ambiguous

You would do that by providing a fully qualified name, e.g.:

SELECT tbl_names.id as id, name, section FROM tbl_names, tbl_section WHERE tbl_names.id = tbl_section.id

Which would give you the id of tbl_names

Eclipse does not highlight matching variables

There is a bug in Eclipse Juno (and probably others) but I have a workaround!

If you have already checked all the configurations mentioned in the top answers here and it's STILL not working try this.

To confirm the problem:

  1. Select a variable
  2. Notice the highlight didn't work
  3. Click away from eclipse so the editor loses focus.
  4. Click on eclipse's title bar so it regains focus, your variable should be highlighted.

If this is happening for you, you must close ALL of your open files and reopen them. This bug seems to also make weird things happen with Ctrl+S saving of an individual file. My guess is that something is happening whereby internally eclipse believes a certain file has focus but it actually doesn't, and the UI's state is rendered as though a different file is being edited.

Edit: If it's STILL not working, you might need to restart eclipse, but if you don't want to, try selecting the item you want to see occurrences of then disable and re-enable the Mark Occurences Toggle button.

Which looks like this

How to convert latitude or longitude to meters?

If its sufficiently close you can get away with treating them as coordinates on a flat plane. This works on say, street or city level if perfect accuracy isnt required and all you need is a rough guess on the distance involved to compare with an arbitrary limit.

How to copy static files to build directory with Webpack?

The webpack config file (in webpack 2) allows you to export a promise chain, so long as the last step returns a webpack config object. See promise configuration docs. From there:

webpack now supports returning a Promise from the configuration file. This allows to do async processing in you configuration file.

You could create a simple recursive copy function that copies your file, and only after that triggers webpack. E.g.:

module.exports = function(){
    return copyTheFiles( inpath, outpath).then( result => {
        return { entry: "..." } // Etc etc
    } )
}

Nginx: stat() failed (13: permission denied)

This is usually the privilege problem... For me, its because i use the /root/** as the nginx root, it need higher privilege. An easy way is just move the project into a directory created by yourself.

Compilation error: stray ‘\302’ in program etc

I noticed an issue in using the above tr command. The tr command COMPLETELY removes the "smart quotes". It would be better to replace the "smart quotes" with something like this.

This will give you a quick preview of what will be replaced.

sed s/[”“]/'"'/g File.txt

This will do the replacements and put the replacement in a new file called WithoutSmartQuotes.txt.

sed s/[”“]/'"'/g File.txt > WithoutSmartQuotes.txt

This will overwrite the original file.

sed -i ".bk" s/[”“]/'"'/g File.txt

http://developmentality.wordpress.com/2010/10/11/how-to-remove-smart-quotes-from-a-text-file/

How to remove trailing and leading whitespace for user-provided input in a batch file?

Just came up with this:

set sString=" hello|123(4) "
call :trimMENew %sString%
echo "%sString%"
exit /b 0

:trimMeNew
set "sString=%~1"
if "%sString:~0,1%" == " " set "sString=%sString:~1%"
if "%sString:~-1%" == " " set "sString=%sString:~0,-1%"
exit /b 0

Entity Framework : How do you refresh the model when the db changes?

Double click on the .edmx file then right_click anywhere on the screen and choose "Update Modle From DB". In the new window go to the "Refresh" tab and choose the changed table/view and click Finish.

Pytorch tensor to numpy array

You can use this syntax if some grads are attached with your variables.

y=torch.Tensor.cpu(x).detach().numpy()[:,:,:,-1]

Is it possible to capture the stdout from the sh DSL command in the pipeline

Note: The linked Jenkins issue has since been solved.

As mention in JENKINS-26133 it was not possible to get shell output as a variable. As a workaround suggested using of writ-read from temporary file. So, your example would have looked like:

sh "echo foo > result";
def output=readFile('result').trim()
echo "output=$output";

Excel SUMIF between dates

To SUMIFS between dates, use the following:

=SUMIFS(B:B,A:A,">="&DATE(2012,1,1),A:A,"<"&DATE(2012,6,1))

Installing Google Protocol Buffers on mac

This is not via brew, but the end result is the same.

  1. Download the protobuf-2.4.1 from https://protobuf.googlecode.com/files/protobuf-2.4.1.tar.gz
  2. Extract the tar.gz file.
  3. $cd ~/Downloads/protobuf-2.4.1
  4. $./configure
  5. $make
  6. $make check
  7. $sudo make install
  8. $which protoc
  9. $protoc --version

Steps 4-7 are from the README.txt file from the protobuf tarball.

Maven Modules + Building a Single Specific Module

Take a look at my answer Maven and dependent modules.

The Maven Reactor plugin is designed to deal with building part of a project.

The particular goal you'll want to use it reactor:make.

How to select into a variable in PL/SQL when the result might be null?

I use this syntax for flexibility and speed -

    begin
    --
    with KLUJ as
    ( select 0 ROES from dual
       union 
      select count(*) from MY_TABLE where rownum = 1
    ) select max(ROES) into has_rows from KLUJ;
    --
    end;

Dual returns 1 row, rownum adds 0 or 1 rows, and max() groups to exactly 1. This gives 0 for no rows in a table and 1 for any other number of rows.

I extend the where clause to count rows by condition, remove rownum to count rows meeting a condition, and increase rownum to count rows meeting the condition up to a limit.

Catching multiple exception types in one catch block

Update:

As of PHP 7.1, this is available.

The syntax is:

try
{
    // Some code...
}
catch(AError | BError $e)
{
    // Handle exceptions
}
catch(Exception $e)
{
    // Handle the general case
}

Docs: https://www.php.net/manual/en/language.exceptions.php#example-294

RFC: https://wiki.php.net/rfc/multiple-catch

Commit: https://github.com/php/php-src/commit/0aed2cc2a440e7be17552cc669d71fdd24d1204a


For PHP before 7.1:

Despite what these other answers say, you can catch AError and BError in the same block (it is somewhat easier if you are the one defining the exceptions). Even given that there are exceptions you want to "fall through", you should still be able to define a hierarchy to match your needs.

abstract class MyExceptions extends Exception {}

abstract class LetterError extends MyExceptions {}

class AError extends LetterError {}

class BError extends LetterError {}

Then:

catch(LetterError $e){
    //voodoo
}

As you can see here and here, even the SPL default exceptions have a hierarchy you can leverage. Additionally, as stated in the PHP Manual:

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block.

This means you could also have

class CError extends LetterError {}

which you need to handle differently than AError or BError, so your catch statement would look like this:

catch(CError $e){
    //voodoo
}
catch(LetterError $e){
    //voodoo
}

If you had the case where there were twenty or more exceptions that legitimately belonged under the same superclass, and you needed to handle five (or whatever large-ish group) of them one way and the rest the other, you can STILL do this.

interface Group1 {}

class AError extends LetterError implements Group1 {}

class BError extends LetterError implements Group1 {}

And then:

catch (Group1 $e) {}

Using OOP when it comes to exceptions is very powerful. Using things like get_class or instanceof are hacks, and should be avoided if possible.

Another solution I would like to add is putting the exception handling functionality in its own method.

You could have

function handleExceptionMethod1(Exception $e)
{
    //voodoo
}

function handleExceptionMethod2(Exception $e)
{
    //voodoo
}

Assuming there is absolutely no way you can control exception class hierarchies or interfaces (and there almost always will be a way), you can do the following:

try
{
    stuff()
}
catch(ExceptionA $e)
{
    $this->handleExceptionMethod1($e);
}
catch(ExceptionB $e)
{
    $this->handleExceptionMethod1($e);
}
catch(ExceptionC $e)
{
    $this->handleExceptionMethod1($e);
}
catch(Exception $e)
{
    $this->handleExceptionMethod2($e);
}

In this way, you are still have a only single code location you have to modify if your exception handling mechanism needs to change, and you are working within the general constructs of OOP.

Limit the height of a responsive image with css

You can use inline styling to limit the height:

<img src="" class="img-responsive" alt="" style="max-height: 400px;">

json_encode function: special characters

you should add charset=UTF-8 in meta tag and use json_encode for special characters

$json = json_encode($arr);

json_encode function converts special characters in UTF8 standard

Android Service needs to run always (Never pause or stop)

"Is it possible to run this service always as when the application pause and anything else?"

Yes.

  1. In the service onStartCommand method return START_STICKY.

    public int onStartCommand(Intent intent, int flags, int startId) {
            return START_STICKY;
    }
    
  2. Start the service in the background using startService(MyService) so that it always stays active regardless of the number of bound clients.

    Intent intent = new Intent(this, PowerMeterService.class);
    startService(intent);
    
  3. Create the binder.

    public class MyBinder extends Binder {
            public MyService getService() {
                    return MyService.this;
            }
    }
    
  4. Define a service connection.

    private ServiceConnection m_serviceConnection = new ServiceConnection() {
            public void onServiceConnected(ComponentName className, IBinder service) {
                    m_service = ((MyService.MyBinder)service).getService();
            }
    
            public void onServiceDisconnected(ComponentName className) {
                    m_service = null;
            }
    };
    
  5. Bind to the service using bindService.

            Intent intent = new Intent(this, MyService.class);
            bindService(intent, m_serviceConnection, BIND_AUTO_CREATE);
    
  6. For your service you may want a notification to launch the appropriate activity once it has been closed.

    private void addNotification() {
            // create the notification
            Notification.Builder m_notificationBuilder = new Notification.Builder(this)
                    .setContentTitle(getText(R.string.service_name))
                    .setContentText(getResources().getText(R.string.service_status_monitor))
                    .setSmallIcon(R.drawable.notification_small_icon);
    
            // create the pending intent and add to the notification
            Intent intent = new Intent(this, MyService.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
            m_notificationBuilder.setContentIntent(pendingIntent);
    
            // send the notification
            m_notificationManager.notify(NOTIFICATION_ID, m_notificationBuilder.build());
    }
    
  7. You need to modify the manifest to launch the activity in single top mode.

              android:launchMode="singleTop"
    
  8. Note that if the system needs the resources and your service is not very active it may be killed. If this is unacceptable bring the service to the foreground using startForeground.

            startForeground(NOTIFICATION_ID, m_notificationBuilder.build());
    

Getting scroll bar width using JavaScript

Assuming container is only on page once and you are using jQuery, then:

var containerEl = $('.container')[0];
var scrollbarWidth = containerEl.offsetWidth - containerEl.clientWidth;

Also see this answer for more details.

Get the system date and split day, month and year

You can do like follow:

 String date = DateTime.Now.Date.ToString();
    String Month = DateTime.Now.Month.ToString();
    String Year = DateTime.Now.Year.ToString();

On the place of datetime you can use your column..

Disable Chrome strict MIME type checking

The server should respond with the correct MIME Type for JSONP application/javascript and your request should tell jQuery you are loading JSONP dataType: 'jsonp'

Please see this answer for further details ! You can also have a look a this one as it explains why loading .js file with text/plain won't work.

Accessing MVC's model property from Javascript

You could take your entire server-side model and turn it into a Javascript object by doing the following:

var model = @Html.Raw(Json.Encode(Model));

In your case if you just want the FloorPlanSettings object, simply pass the Encode method that property:

var floorplanSettings = @Html.Raw(Json.Encode(Model.FloorPlanSettings));

how do you insert null values into sql server

If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.

Delete keychain items when an app is uninstalled

You can take advantage of the fact that NSUserDefaults are cleared by uninstallation of an app. For example:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //Clear keychain on first run in case of reinstallation
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"FirstRun"]) {
        // Delete values from keychain here
        [[NSUserDefaults standardUserDefaults] setValue:@"1strun" forKey:@"FirstRun"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }

    //...Other stuff that usually happens in didFinishLaunching
}

This checks for and sets a "FirstRun" key/value in NSUserDefaults on the first run of your app if it's not already set. There's a comment where you should put code to delete values from the keychain. Synchronize can be called to make sure the "FirstRun" key/value is immediately persisted in case the user kills the app manually before the system persists it.

Find location of a removable SD card

Like Richard I also use /proc/mounts file to get the list of available storage options

public class StorageUtils {

    private static final String TAG = "StorageUtils";

    public static class StorageInfo {

        public final String path;
        public final boolean internal;
        public final boolean readonly;
        public final int display_number;

        StorageInfo(String path, boolean internal, boolean readonly, int display_number) {
            this.path = path;
            this.internal = internal;
            this.readonly = readonly;
            this.display_number = display_number;
        }

        public String getDisplayName() {
            StringBuilder res = new StringBuilder();
            if (internal) {
                res.append("Internal SD card");
            } else if (display_number > 1) {
                res.append("SD card " + display_number);
            } else {
                res.append("SD card");
            }
            if (readonly) {
                res.append(" (Read only)");
            }
            return res.toString();
        }
    }

    public static List<StorageInfo> getStorageList() {

        List<StorageInfo> list = new ArrayList<StorageInfo>();
        String def_path = Environment.getExternalStorageDirectory().getPath();
        boolean def_path_internal = !Environment.isExternalStorageRemovable();
        String def_path_state = Environment.getExternalStorageState();
        boolean def_path_available = def_path_state.equals(Environment.MEDIA_MOUNTED)
                                    || def_path_state.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
        boolean def_path_readonly = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);
        BufferedReader buf_reader = null;
        try {
            HashSet<String> paths = new HashSet<String>();
            buf_reader = new BufferedReader(new FileReader("/proc/mounts"));
            String line;
            int cur_display_number = 1;
            Log.d(TAG, "/proc/mounts");
            while ((line = buf_reader.readLine()) != null) {
                Log.d(TAG, line);
                if (line.contains("vfat") || line.contains("/mnt")) {
                    StringTokenizer tokens = new StringTokenizer(line, " ");
                    String unused = tokens.nextToken(); //device
                    String mount_point = tokens.nextToken(); //mount point
                    if (paths.contains(mount_point)) {
                        continue;
                    }
                    unused = tokens.nextToken(); //file system
                    List<String> flags = Arrays.asList(tokens.nextToken().split(",")); //flags
                    boolean readonly = flags.contains("ro");

                    if (mount_point.equals(def_path)) {
                        paths.add(def_path);
                        list.add(0, new StorageInfo(def_path, def_path_internal, readonly, -1));
                    } else if (line.contains("/dev/block/vold")) {
                        if (!line.contains("/mnt/secure")
                            && !line.contains("/mnt/asec")
                            && !line.contains("/mnt/obb")
                            && !line.contains("/dev/mapper")
                            && !line.contains("tmpfs")) {
                            paths.add(mount_point);
                            list.add(new StorageInfo(mount_point, false, readonly, cur_display_number++));
                        }
                    }
                }
            }

            if (!paths.contains(def_path) && def_path_available) {
                list.add(0, new StorageInfo(def_path, def_path_internal, def_path_readonly, -1));
            }

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (buf_reader != null) {
                try {
                    buf_reader.close();
                } catch (IOException ex) {}
            }
        }
        return list;
    }    
}

Use string value from a cell to access worksheet of same name

Guess @user3010492 tested it but I used this with fixed cell A5 --> $A$5 and fixed element of G7 --> $G7

=INDIRECT("'"&$A$5&"'!$G7")

Also works nested nicely in other formula if you enclose it in brackets.

Return Max Value of range that is determined by an Index & Match lookup

You can easily change the match-type to 1 when you are looking for the greatest value or to -1 when looking for the smallest value.

django import error - No module named core.management

Store the python python path in a variable and execute.This would include the otherwise missing packages.

python_path= `which python` 
$python_path manage.py runserver

Apache HttpClient Android (Gradle)

I resolved problem by adding following to my build.gradle file

android {
useLibrary 'org.apache.http.legacy'}

However this only works if you are using gradle 1.3.0-beta2 or greater, so you will have to add this to buildscript dependencies if you are on a lower version:

classpath 'com.android.tools.build:gradle:1.3.0-beta2'

Step-by-step debugging with IPython

One option is to use an IDE like Spyder which should allow you to interact with your code while debugging (using an IPython console, in fact). In fact, Spyder is very MATLAB-like, which I presume was intentional. That includes variable inspectors, variable editing, built-in access to documentation, etc.

How do write IF ELSE statement in a MySQL query

according to the mySQL reference manual this the syntax of using if and else statement :

IF search_condition THEN statement_list
[ELSEIF search_condition THEN statement_list] ...
[ELSE statement_list]
END IF

So regarding your query :

x = IF((action=2)&&(state=0),1,2);

or you can use

IF ((action=2)&&(state=0)) then 
state = 1;
ELSE 
state = 2;
END IF;

There is good example in this link : http://easysolutionweb.com/sql-pl-sql/how-to-use-if-and-else-in-mysql/

How to use paginator from material angular?

After spending few hours on this i think this is best way to apply pagination. And more importantly it works. This is my paginator code <mat-paginator #paginatoR [length]="length" [pageSize]="pageSize" [pageSizeOptions]="pageSizeOptions">

Inside my component @ViewChild(MatPaginator) paginator: MatPaginator; to view child and finally you have to bind paginator to table dataSource and this is how it is done ngAfterViewInit() {this.dataSource.paginator = this.paginator;} Easy right? if it works for you then mark this as answer.

jQuery - checkbox enable/disable

_x000D_
_x000D_
$jQuery(function() {_x000D_
  enable_cb();_x000D_
  jQuery("#group1").click(enable_cb);_x000D_
});_x000D_
_x000D_
function enable_cb() {_x000D_
  if (this.checked) {_x000D_
    jQuery("input.group1").removeAttr("disabled");_x000D_
  } else {_x000D_
    jQuery("input.group1").attr("disabled", true);_x000D_
  }_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form name="frmChkForm" id="frmChkForm">_x000D_
  <input type="checkbox" name="chkcc9" id="group1">Check Me <br>_x000D_
  <input type="checkbox" name="chk9[120]" class="group1"><br>_x000D_
  <input type="checkbox" name="chk9[140]" class="group1"><br>_x000D_
  <input type="checkbox" name="chk9[150]" class="group1"><br>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Spring - applicationContext.xml cannot be opened because it does not exist

In Spring all source files are inside src/main/java. Similarly, the resources are generally kept inside src/main/resources. So keep your spring configuration file inside resources folder.

Make sure you have the ClassPath entry for your files inside src/main/resources as well.

In .classpath check for the following 2 lines. If they are missing add them.

<classpathentry path="src/main/java" kind="src"/>
<classpathentry path="src/main/resources" kind="src" />

So, if you have everything in place the below code should work.

ApplicationContext ctx = new ClassPathXmlApplicationContext("Spring-Module.xml");

How to regex in a MySQL query

I think you can use REGEXP instead of LIKE

SELECT trecord FROM `tbl` WHERE (trecord REGEXP '^ALA[0-9]')

Truncate (not round) decimal places in SQL Server

Mod(x,1) is the easiest way I think.

How many values can be represented with n bits?

The thing you are missing is which encoding scheme is being used. There are different ways to encode binary numbers. Look into signed number representations. For 9 bits, the ranges and the amount of numbers that can be represented will differ depending on the system used.

preventDefault() on an <a> tag

Try something like:

$('div.toggle').hide();
$('ul.product-info li a').click(function(event) {
    event.preventDefault();
    $(this).next('div').slideToggle(200);
});

Here is the page about that in the jQuery documentation

document.getElementById(id).focus() is not working for firefox or chrome

One thing to check that I just found is that it won't work if there are multiple elements with the same ID. It doesn't error if you try to do this, it just fails silently

subtract time from date - moment js

Moment.subtract does not support an argument of type Moment - documentation:

moment().subtract(String, Number);
moment().subtract(Number, String); // 2.0.0
moment().subtract(String, String); // 2.7.0
moment().subtract(Duration); // 1.6.0
moment().subtract(Object);

The simplest solution is to specify the time delta as an object:

// Assumes string is hh:mm:ss
var myString = "03:15:00",
    myStringParts = myString.split(':'),
    hourDelta: +myStringParts[0],
    minuteDelta: +myStringParts[1];


date.subtract({ hours: hourDelta, minutes: minuteDelta});
date.toString()
// -> "Sat Jun 07 2014 06:07:06 GMT+0100"

How do I do a multi-line string in node.js?

node v4 and current versions of node

As of ES6 (and so versions of Node greater than v4), a new "template literal" intrinsic type was added to Javascript (denoted by back-ticks "`") which can also be used to construct multi-line strings, as in:

`this is a 
single string`

which evaluates to: 'this is a\nsingle string'.

Note that the newline at the end of the first line is included in the resulting string.

Template literals were added to allow programmers to construct strings where values or code could be directly injected into a string literal without having to use util.format or other templaters, as in:

let num=10;

console.log(`the result of ${num} plus ${num} is ${num + num}.`);

which will print "the result of 10 plus 10 is 20." to the console.

Older versions of node

Older version of node can use a "line continuation" character allowing you to write multi-line strings such as:

'this is a \
single string'

which evaluates to: 'this is a single string'.

Note that the newline at the end of the first line is not included in the resulting string.

Is it .yaml or .yml?

After reading a bunch of people's comments online about this, my first reaction was that this is basically one of those really unimportant debates. However, my initial interest was to find out the right format so I could be consistent with my file naming practice.

Long story short, the creator of YAML are saying .yaml, but personally I keep doing .yml. That just makes more sense to me. So I went on the journey to find affirmation and soon enough, I realise that docker uses .yml everywhere. I've been writing docker-compose.yml files all this time, while you keep seeing in kubernetes' docs kubectl apply -f *.yaml...

So, in conclusion, both formats are obviously accepted and if you are on the other end, (ie: writing systems that receive a YAML file as input) you should allow for both. That seems like another snake case versus camel case thingy...

JQuery Number Formatting

If you need to handle multiple currencies, various number formats etc. I can recommend autoNumeric. Works a treat. Have been using it successfully for several years now.

Get original URL referer with PHP?

Store it in a cookie that only lasts for the current browsing session

Pass variables between two PHP pages without using a form or the URL of page

<?php
session_start();

$message1 = "A message";
$message2 = "Another message";

$_SESSION['firstMessage'] = $message1;
$_SESSION['secondMessage'] = $message2; 
?>

Stores the sessions on page 1 then on page 2 do

<?php
session_start();

echo $_SESSION['firstMessage'];
echo $_SESSION['secondMessage'];
?>

Normalization in DOM parsing with java - how does it work?

In simple, Normalisation is Reduction of Redundancies.
Examples of Redundancies:
a) white spaces outside of the root/document tags(...<document></document>...)
b) white spaces within start tag (<...>) and end tag (</...>)
c) white spaces between attributes and their values (ie. spaces between key name and =")
d) superfluous namespace declarations
e) line breaks/white spaces in texts of attributes and tags
f) comments etc...

Creating a triangle with for loops

A fun, simple solution:

for (int i = 0; i < 5; i++) 
  System.out.println("    *********".substring(i, 5 + 2*i));

How do I clone a specific Git branch?

git checkout -b <branch-name> <origin/branch_name>

for example in my case:

 git branch -a
* master
  origin/HEAD
  origin/enum-account-number
  origin/master
  origin/rel_table_play
  origin/sugarfield_customer_number_show_c

So to create a new branch based on my enum-account-number branch I do:

git checkout -b enum-account-number origin/enum-account-number

After you hit return the following happens:

Branch enum-account-number set up to track remote branch refs/remotes/origin/enum-account-number.
Switched to a new branch "enum-account-number"

Write HTML to string

You're probably better off using an HtmlTextWriter or an XMLWriter than a plain StringWriter. They will take care of escaping for you, as well as making sure the document is well-formed.

This page shows the basics of using the HtmlTextWriter class, the gist of which being:

StringWriter stringWriter = new StringWriter();

using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
{
    writer.AddAttribute(HtmlTextWriterAttribute.Class, classValue);
    writer.RenderBeginTag(HtmlTextWriterTag.Div); // Begin #1

    writer.AddAttribute(HtmlTextWriterAttribute.Href, urlValue);
    writer.RenderBeginTag(HtmlTextWriterTag.A); // Begin #2

    writer.AddAttribute(HtmlTextWriterAttribute.Src, imageValue);
    writer.AddAttribute(HtmlTextWriterAttribute.Width, "60");
    writer.AddAttribute(HtmlTextWriterAttribute.Height, "60");
    writer.AddAttribute(HtmlTextWriterAttribute.Alt, "");

    writer.RenderBeginTag(HtmlTextWriterTag.Img); // Begin #3
    writer.RenderEndTag(); // End #3

    writer.Write(word);

    writer.RenderEndTag(); // End #2
    writer.RenderEndTag(); // End #1
}
// Return the result.
return stringWriter.ToString();

Laravel assets url

You have to put all your assets in app/public folder, and to access them from your views you can use asset() helper method.

Ex. you can retrieve assets/images/image.png in your view as following:

<img src="{{asset('assets/images/image.png')}}">

How to get css background color on <tr> tag to span entire row

This worked for me, even within a div:

      div.cntrblk tr:hover td {
        line-height: 150%;
        background-color: rgb(255,0,0);
        font-weight: bold;
        font-size: 150%;
        border: 0;
      }

It selected the entire row, but I'd like it to not do the header, haven't looked at that yet. It also partially fixed the fonts that wouldn't scale-up with the hover??? Apparently you to have apply settings to the cell not the row, but select all the component cells with the tr:hover. On to tracking down the in-consistent font scaling problem. Sweet that CSS will do this.

Formula px to dp, dp to px android

Efficient way ever

DP to Pixel:

private int dpToPx(int dp)
{
    return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}

Pixel to DP:

private int pxToDp(int px)
{
    return (int) (px / Resources.getSystem().getDisplayMetrics().density);
}

Hope this will help you.

SQL Server Script to create a new user

If you want to create a generic script you can do it with an Execute statement with a Replace with your username and database name

Declare @userName as varchar(50); 
Declare @defaultDataBaseName as varchar(50);
Declare @LoginCreationScript as varchar(max);
Declare @UserCreationScript as varchar(max);
Declare @TempUserCreationScript as varchar(max);
set @defaultDataBaseName = 'data1';
set @userName = 'domain\userName';
set @LoginCreationScript ='CREATE LOGIN [{userName}]
FROM WINDOWS 
WITH DEFAULT_DATABASE ={dataBaseName}'

set @UserCreationScript ='
USE {dataBaseName}
CREATE User [{userName}] for LOGIN [{userName}];
EXEC sp_addrolemember ''db_datareader'', ''{userName}'';
EXEC sp_addrolemember ''db_datawriter'', ''{userName}'';
Grant Execute on Schema :: dbo TO [{userName}];'
/*Login creation*/
set @LoginCreationScript=Replace(Replace(@LoginCreationScript, '{userName}', @userName), '{dataBaseName}', @defaultDataBaseName)
set @UserCreationScript =Replace(@UserCreationScript, '{userName}', @userName)
Execute(@LoginCreationScript)

/*User creation and role assignment*/
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', @defaultDataBaseName)
Execute(@TempUserCreationScript)
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', 'db2')
Execute(@TempUserCreationScript)
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', 'db3')
Execute(@TempUserCreationScript)

Get absolute path of initially run script

`realpath(dirname(__FILE__))` 

it gives you current script(the script inside which you placed this code) directory without trailing slash. this is important if you want to include other files with the result

Java - Change int to ascii

You can convert a number to ASCII in java. example converting a number 1 (base is 10) to ASCII.

char k = Character.forDigit(1, 10);
System.out.println("Character: " + k);
System.out.println("Character: " + ((int) k));

Output:

Character: 1
Character: 49

bootstrap button shows blue outline when clicked

In Bootstrap 4 they use box-shadow: 0 0 0 0px rgba(0,123,255,0); on :focus, si i solved my problem with

a.active.focus,
a.active:focus,
a.focus,
a:active.focus,
a:active:focus,
a:focus,
button.active.focus,
button.active:focus,
button.focus,
button:active.focus,
button:active:focus,
button:focus,
.btn.active.focus,
.btn.active:focus,
.btn.focus,
.btn:active.focus,
.btn:active:focus,
.btn:focus {
    outline: 0;
    outline-color: transparent;
    outline-width: 0;
    outline-style: none;
    box-shadow: 0 0 0 0 rgba(0,123,255,0);
}

ASP.NET MVC3 - textarea with @Html.EditorFor

You could use the [DataType] attribute on your view model like this:

public class MyViewModel
{
    [DataType(DataType.MultilineText)]
    public string Text { get; set; }
}

and then you could have a controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }
}

and a view which does what you want:

@model AppName.Models.MyViewModel
@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.Text)
    <input type="submit" value="OK" />
}

AngularJS $location not changing the path

In my opinion many of the answers here seem a little bit hacky (e.g. $apply() or $timeout), since messing around with $apply() can lead to unwanted errors.

Usually, when the $location doesn't work it means that something was not implemented the angular way.

In this particular question, the problem seems to be in the non-angular AJAX part. I had a similiar problem, where the redirection using $location should take place after a promise resolved. I would like to illustrate the problem on this example.

The old code:

taskService.createTask(data).then(function(code){
            $location.path("task/" + code);
        }, function(error){});

Note: taskService.createTask returns a promise.

$q - the angular way to use promises:

let dataPromises = [taskService.createTask(data)];
        $q.all(dataPromises).then(function(response) {
                let code = response[0];
                $location.path("task/" + code);
            }, 
            function(error){});

Using $q to resolve the promise solved the redirection problem.

More on the $q service: https://docs.angularjs.org/api/ng/service/$q

JPanel vs JFrame in Java

JFrame is the window; it can have one or more JPanel instances inside it. JPanel is not the window.

You need a Swing tutorial:

http://docs.oracle.com/javase/tutorial/uiswing/

How do I remove all null and empty string values from an object?

Building upon suryaPavan's answer this slight modification can cleanup the empty object after removing the invidival emptys inside the object or array. this ensures that you don't have an empty array or object hanging around.

function removeNullsInObject(obj) {
            if( typeof obj === 'string' || obj === "" ){
                return;
            }
            $.each(obj, function(key, value){
                if (value === "" || value === null){
                    delete obj[key];
                } else if ($.isArray(value)) {
                    if( value.length === 0 ){
                        delete obj[key];
                        return;
                    }
                    $.each(value, function (k,v) {
                        removeNullsInObject(v);
                    });
                    if( value.length === 0 ){
                        delete obj[key];
                    }
                } else if (typeof value === 'object') {
                    if( Object.keys(value).length === 0 ){
                        delete obj[key];
                        return;
                    }
                    removeNullsInObject(value);
                    if( Object.keys(value).length === 0 ){
                        delete obj[key];
                    }
                }
            });
 }

What are the undocumented features and limitations of the Windows FINDSTR command?

/D tip for multiple directories: put your directory list before the search string. These all work:

findstr /D:dir1;dir2 "searchString" *.*
findstr /D:"dir1;dir2" "searchString" *.*
findstr /D:"\path\dir1\;\path\dir2\" "searchString" *.*

As expected, the path is relative to location if you don't start the directories with \. Surrounding the path with " is optional if there are no spaces in the directory names. The ending \ is optional. The output of location will include whatever path you give it. It will work with or without surrounding the directory list with ".

How can I copy network files using Robocopy?

You should be able to use Windows "UNC" paths with robocopy. For example:

robocopy \\myServer\myFolder\myFile.txt \\myOtherServer\myOtherFolder

Robocopy has the ability to recover from certain types of network hiccups automatically.

Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

Windows - set environment variable permanently:

setx ANDROID_HOME "C:\Program Files\Android\android-sdk"

or

setx ANDROID_HOME "C:\Program Files (x86)\Android\android-sdk"

Importing Excel into a DataTable Quickly

 class DataReader
    {
        Excel.Application xlApp;
        Excel.Workbook xlBook;
        Excel.Range xlRange;
        Excel.Worksheet xlSheet;
        public DataTable GetSheetDataAsDataTable(String filePath, String sheetName)
        {
            DataTable dt = new DataTable();
            try
            {
                xlApp = new Excel.Application();
                xlBook = xlApp.Workbooks.Open(filePath);
                xlSheet = xlBook.Worksheets[sheetName];
                xlRange = xlSheet.UsedRange;
                DataRow row=null;
                for (int i = 1; i <= xlRange.Rows.Count; i++)
                {
                    if (i != 1)
                        row = dt.NewRow();
                    for (int j = 1; j <= xlRange.Columns.Count; j++)
                    {
                        if (i == 1)
                            dt.Columns.Add(xlRange.Cells[1, j].value);
                        else
                            row[j-1] = xlRange.Cells[i, j].value;
                    }
                    if(row !=null)
                        dt.Rows.Add(row);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                xlBook.Close();
                xlApp.Quit();
            }
            return dt;
        }
    }

Difference between Hive internal tables and external tables?

INTERNAL : Table is created First and Data is loaded later

EXTERNAL : Data is present and Table is created on top of it.

How to use PHP to connect to sql server

for further investigation: print out the mssql error message:

$dbhandle = mssql_connect($myServer, $myUser, $myPass) or die("Could not connect to database: ".mssql_get_last_message()); 

It is also important to specify the port: On MS SQL Server 2000, separate it with a comma:

$myServer = "10.85.80.229:1443";

or

$myServer = "10.85.80.229,1443";

How do I use cascade delete with SQL Server?

If the one to many relationship is from T1 to T2 then it doesn't represent a function and therefore cannot be used to deduce or infer an inverse function that guarantees the resulting T2 value doesn't omit tuples of T1 join T2 that are deductively valid, because there is no deductively valid inverse function. ( representing functions was the purpose of primary keys. ) The answer in SQL think is yes you can do it. The answer in relational think is no you can't do it. See points of ambiguity in Codd 1970. The relationship would have to be many-to-one from T1 to T2.

Create html documentation for C# code

In 2017, the thing closest to Javadoc would probably DocFx which was developed by Microsoft and comes as a Commmand-Line-Tool as well as a VS2017 plugin.

It's still a little rough around the edges but it looks promising.

Another alternative would be Wyam which has a documentation recipe suitable for net aplications. Look at the cake documentation for an example.

How to scroll to bottom in a ScrollView on activity startup

 scrollView.postDelayed(new Runnable() {
        @Override
        public void run() {
            scrollView.fullScroll(ScrollView.FOCUS_DOWN);
        }
    },1000);

Convert string to symbol-able in ruby

"Book Author Title".parameterize('_').to_sym
=> :book_author_title

http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize

parameterize is a rails method, and it lets you choose what you want the separator to be. It is a dash "-" by default.

How do I check CPU and Memory Usage in Java?

Since Java 1.5 the JDK comes with a new tool: JConsole wich can show you the CPU and memory usage of any 1.5 or later JVM. It can do charts of these parameters, export to CSV, show the number of classes loaded, the number of instances, deadlocks, threads etc...

How do I create a Linked List Data Structure in Java?

Java has a LinkedList implementation, that you might wanna check out. You can download the JDK and it's sources at java.sun.com.

Java : Cannot format given Object as a Date

java.time

I should like to contribute the modern answer. The SimpleDateFormat class is notoriously troublesome, and while it was reasonable to fight one’s way through with it when this question was asked six and a half years ago, today we have much better in java.time, the modern Java date and time API. SimpleDateFormat and its friend Date are now considered long outdated, so don’t use them anymore.

    DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MM/uuuu");
    String dateformat = "2012-11-17T00:00:00.000-05:00";
    OffsetDateTime dateTime = OffsetDateTime.parse(dateformat);
    String monthYear = dateTime.format(monthFormatter);
    System.out.println(monthYear);

Output:

11/2012

I am exploiting the fact that your string is in ISO 8601 format, the international standard, and that the classes of java.time parse this format as their default, that is, without any explicit formatter. It’s stil true what the other answers say, you need to parse the original string first, then format the resulting date-time object into a new string. Usually this requires two formatters, only in this case we’re lucky and can do with just one formatter.

What went wrong in your code

  • As others have said, SimpleDateFormat.format cannot accept a String argument, also when the parameter type is declared to be Object.
  • Because of the exception you didn’t get around to discovering: there is also a bug in your format pattern string, mm/yyyy. Lowercase mm os for minute of the hour. You need uppercase MM for month.
  • Finally the Java naming conventions say to use a lowercase first letter in variable names, so use lowercase m in monthYear (also because java.time includes a MonthYear class with uppercase M, so to avoid confusion).

Links

How to run an android app in background?

You can probably start a Service here if you want your Application to run in Background. This is what Service in Android are used for - running in background and doing longtime operations.

UDPATE

You can use START_STICKY to make your Service running continuously.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    handleCommand(intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
}

How to use particular CSS styles based on screen size / device

Use @media queries. They serve this exact purpose. Here's an example how they work:

@media (max-width: 800px) {
  /* CSS that should be displayed if width is equal to or less than 800px goes here */
}

This would work only on devices whose width is equal to or less than 800px.

Read up more about media queries on the Mozilla Developer Network.

How do I put double quotes in a string in vba?

All double quotes inside double quotes which suround the string must be changed doubled. As example I had one of json file strings : "delivery": "Standard", In Vba Editor I changed it into """delivery"": ""Standard""," and everythig works correctly. If you have to insert a lot of similar strings, my proposal first, insert them all between "" , then with VBA editor replace " inside into "". If you will do mistake, VBA editor shows this line in red and you will correct this error.

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

in the first you should make form like this :

<form method="post" enctype="multipart/form-data" >
   <input type="file" name="file[]" multiple id="file"/>
   <input type="submit" name="ok"  />
</form> 

that is right . now add this code under your form code or on the any page you like

<?php
if(isset($_POST['ok']))
   foreach ($_FILES['file']['name'] as $filename) {
    echo $filename.'<br/>';
}
?>

it's easy... finish

How can I scroll a web page using selenium webdriver in python?

same method as shown here:

in python you can just use

driver.execute_script("window.scrollTo(0, Y)")

(Y is the vertical position you want to scroll to)

How to add Button over image using CSS?

You need to give relative or absolute or fixed positioning to your container (#shop) and set its zIndex to say 100.

You also need to give say relative positioning to your elements with the class content and lower zIndex say 97.

Do the above-mentioned with your images too and set their zIndex to 91.

And then position your button higher by setting its position to absolute and zIndex to 95

See the DEMO

HTML

<div id="shop">

 <div class="content"> Counter-Strike 1.6 Steam 

     <img src="http://www.openvms.org/images/samples/130x130.gif">

         <a href="#"><span class='span'><span></a>

     </div>

 <div class="content"> Counter-Strike 1.6 Steam 

     <img src="http://www.openvms.org/images/samples/130x130.gif">

         <a href="#"><span class='span'><span></a>

     </div>

  </div>

CSS

#shop{
    background-image: url("images/shop_bg.png");
    background-repeat: repeat-x;    
    height:121px;
    width: 984px;
    margin-left: 20px;
    margin-top: 13px;
    position:relative;
    z-index:100
}

#shop .content{    
    width: 182px; /*328 co je 1/3 - 20margin left*/
    height: 121px;
    line-height: 20px;
    margin-top: 0px;
    margin-left: 9px;
    margin-right:0px;
    display:inline-block;
    position:relative;
    z-index:97

}

img{

    position:relative;
    z-index:91

}

.span{

    width:70px;
    height:40px;
    border:1px solid red;
    position:absolute;
    z-index:95;
    right:60px;
    bottom:-20px;

}

How to make the corners of a button round?

Create an XML file like below one. Set it as background for the button. Change the radius attribute to your wish, if you need more curve for the button.

button_background.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@color/primary" />
    <corners android:radius="5dp" />
</shape>

Set background to your button:

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/button_background"/>

How to calculate cumulative normal distribution?

Here's an example:

>>> from scipy.stats import norm
>>> norm.cdf(1.96)
0.9750021048517795
>>> norm.cdf(-1.96)
0.024997895148220435

In other words, approximately 95% of the standard normal interval lies within two standard deviations, centered on a standard mean of zero.

If you need the inverse CDF:

>>> norm.ppf(norm.cdf(1.96))
array(1.9599999999999991)

Oracle SELECT TOP 10 records

If you are using Oracle 12c, use:

FETCH NEXT N ROWS ONLY

SELECT DISTINCT 
  APP_ID, 
  NAME, 
  STORAGE_GB, 
  HISTORY_CREATED, 
  TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') AS HISTORY_DATE  
  FROM HISTORY WHERE 
    STORAGE_GB IS NOT NULL AND 
      APP_ID NOT IN (SELECT APP_ID FROM HISTORY WHERE TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') ='06.02.2009')
  ORDER BY STORAGE_GB DESC
FETCH NEXT 10 ROWS ONLY

More info: http://docs.oracle.com/javadb/10.5.3.0/ref/rrefsqljoffsetfetch.html

Convert String to int array in java

Using Java 8's stream library, we can make this a one-liner (albeit a long line):

String str = "[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]";
int[] arr = Arrays.stream(str.substring(1, str.length()-1).split(","))
    .map(String::trim).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(arr));

substring removes the brackets, split separates the array elements, trim removes any whitespace around the number, parseInt parses each number, and we dump the result in an array. I've included trim to make this the inverse of Arrays.toString(int[]), but this will also parse strings without whitespace, as in the question. If you only needed to parse strings from Arrays.toString, you could omit trim and use split(", ") (note the space).

How to make shadow on border-bottom?

I'm a little late on the party, but its actualy possible to emulate borders using a box-shadow

_x000D_
_x000D_
.border {_x000D_
  background-color: #ededed;_x000D_
  padding: 10px;_x000D_
  margin-bottom: 5px;_x000D_
}_x000D_
_x000D_
.border-top {_x000D_
  box-shadow: inset 0 3px 0 0 cornflowerblue;_x000D_
}_x000D_
_x000D_
.border-right {_x000D_
  box-shadow: inset -3px 0 0 cornflowerblue;_x000D_
}_x000D_
_x000D_
.border-bottom {_x000D_
  box-shadow: inset 0 -3px 0 0 cornflowerblue;_x000D_
}_x000D_
_x000D_
.border-left {_x000D_
  box-shadow: inset 3px 0 0 cornflowerblue;_x000D_
}
_x000D_
<div class="border border-top">border-top</div>_x000D_
<div class="border border-right">border-right</div>_x000D_
<div class="border border-bottom">border-bottom</div>_x000D_
<div class="border border-left">border-left</div>
_x000D_
_x000D_
_x000D_

EDIT: I understood this question wrong, but I will leave the awnser as more people might misunderstand the question and came for the awnser I supplied.

force line break in html table cell

I suggest you use a wrapper div or paragraph:

<td><p style="width:50%;">Text only allowed to extend 50% of the cell.</p></td>

And you can make a class out of it:

<td class="linebreak"><p>Text only allowed to extend 50% of the cell.</p></td>

td.linebreak p {
    width: 50%;
}

All of this assuming that you meant 50% as in 50% of the cell.

Sort objects in an array alphabetically on one property of the array

var DepartmentFactory = function(data) {
    this.id = data.Id;
    this.name = data.DepartmentName;
    this.active = data.Active;
}

// use `new DepartmentFactory` as given below. `new` is imporatant

var objArray = [];
objArray.push(new DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true}));
objArray.push(new DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true}));
objArray.push(new DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true}));
objArray.push(new DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true}));

function sortOn(property){
    return function(a, b){
        if(a[property] < b[property]){
            return -1;
        }else if(a[property] > b[property]){
            return 1;
        }else{
            return 0;   
        }
    }
}

//objArray.sort(sortOn("id")); // because `this.id = data.Id;`
objArray.sort(sortOn("name")); // because `this.name = data.DepartmentName;`
console.log(objArray);

demo: http://jsfiddle.net/diode/hdgeH/

How to run a makefile in Windows?

Here is my quick and temporary way to run a Makefile

  • download make from SourceForge: gnuwin32
  • install it
  • go to the install folder

C:\Program Files (x86)\GnuWin32\bin

  • copy the all files in the bin to the folder that contains Makefile

libiconv2.dll libintl3.dll make.exe

  • open the cmd (you can do it with right click with shift) in the folder that contains Makefile and run

make.exe

done.

Plus, you can add arguments after the command, such as

make.exe skel

SQLAlchemy create_all() does not create tables

You should put your model class before create_all() call, like this:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __repr__(self):
        return '<User %r>' % self.username

db.create_all()
db.session.commit()

admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users

If your models are declared in a separate module, import them before calling create_all().

Say, the User model is in a file called models.py,

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)

# See important note below
from models import User

db.create_all()
db.session.commit()

admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users

Important note: It is important that you import your models after initializing the db object since, in your models.py _you also need to import the db object from this module.

What is the reason for java.lang.IllegalArgumentException: No enum const class even though iterating through values() works just fine?

Enum.valueOf() only checks the constant name, so you need to pass it "COLUMN_HEADINGS" instead of "columnHeadings". Your name property has nothing to do with Enum internals.


To address the questions/concerns in the comments:

The enum's "builtin" (implicitly declared) valueOf(String name) method will look up an enum constant with that exact name. If your input is "columnHeadings", you have (at least) three choices:

  1. Forget about the naming conventions for a bit and just name your constants as it makes most sense: enum PropName { contents, columnHeadings, ...}. This is obviously the most convenient.
  2. Convert your camelCase input into UPPER_SNAKE_CASE before calling valueOf, if you're really fond of naming conventions.
  3. Implement your own lookup method instead of the builtin valueOf to find the corresponding constant for an input. This makes most sense if there are multiple possible mappings for the same set of constants.

Unable to run Java GUI programs with Ubuntu

I would check with another Java implementation/vendor. Preferrably Oracle/Sun Java: http://www.java.com/en/ . The open-source implementations unfortunately differ in weird ways.

How to call function on child component on parent events

you can use key to reload child component using key

<component :is="child1" :filter="filter" :key="componentKey"></component>

If you want to reload component with new filter, if button click filter the child component

reloadData() {            
   this.filter = ['filter1','filter2']
   this.componentKey += 1;  
},

and use the filter to trigger the function

Take nth column in a text file

One more simple variant -

$ while read line
  do
      set $line          # assigns words in line to positional parameters
      echo "$3 $5"
  done < file

Table column sizing

Disclaimer: This answer may be a bit old. Since the bootstrap 4 beta. Bootstrap has changed since then.

The table column size class has been changed from this

<th class="col-sm-3">3 columns wide</th>

to

<th class="col-3">3 columns wide</th>

Jenkins / Hudson environment variables

You can also edit the /etc/sysconfig/jenkins file to make any changes to the environment variables, etc. I simply added source /etc/profile to the end of the file. /etc/profile has all all of the proper PATH variables setup. When you do this, make sure you restart Jenkins

/etc/init.d/jenkins restart

We are running ZendServer CE which installs pear, phing, etc in a different path so this was helpful. Also, we don't get the LD_LIBRARY_PATH errors we used to get with Oracle client and Jenkins.

How can I count text lines inside an DOM element? Can I?

I found a way to calc the line number when I develop a html editor. The primary method is that:

  1. In IE you can call getBoundingClientRects, it returns each line as a rectangle

  2. In webkit or new standard html engine, it returns each element or node's client rectangles, in this case you can compare each rectangles, I mean each there must be a rectangle is the largest, so you can ignore those rectangles that height is smaller(if there is a rectangle's top smaller than it and bottom larger than it, the condition is true.)

so let's see the test result:

enter image description here

The green rectangle is the largest rectangle in each row

The red rectangle is the selection boundary

The blue rectangle is the boundary from start to selection after expanding, we see it may larger than red rectangle, so we have to check each rectangle's bottom to limit it must smaller than red rectangle's bottom.

        var lineCount = "?";
        var rects;
        if (window.getSelection) {
            //Get all client rectangles from body start to selection, count those rectangles that has the max bottom and min top
            var bounding = {};
            var range = window.getSelection().getRangeAt(0);//As this is the demo code, I dont check the range count
            bounding = range.getBoundingClientRect();//!!!GET BOUNDING BEFORE SET START!!!

            //Get bounding and fix it , when the cursor is in the last character of lineCount, it may expand to the next lineCount.
            var boundingTop = bounding.top;
            var boundingBottom = bounding.bottom;
            var node = range.startContainer;
            if (node.nodeType !== 1) {
                node = node.parentNode;
            }
            var style = window.getComputedStyle(node);
            var lineHeight = parseInt(style.lineHeight);
            if (!isNaN(lineHeight)) {
                boundingBottom = boundingTop + lineHeight;
            }
            else {
                var fontSize = parseInt(style.fontSize);
                if (!isNaN(fontSize)) {
                    boundingBottom = boundingTop + fontSize;
                }
            }
            range = range.cloneRange();

            //Now we have enougn datas to compare

            range.setStart(body, 0);
            rects = range.getClientRects();
            lineCount = 0;
            var flags = {};//Mark a flags to avoid of check some repeat lines again
            for (var i = 0; i < rects.length; i++) {
                var rect = rects[i];
                if (rect.width === 0 && rect.height === 0) {//Ignore zero rectangles
                    continue;
                }
                if (rect.bottom > boundingBottom) {//Check if current rectangle out of the real bounding of selection
                    break;
                }
                var top = rect.top;
                var bottom = rect.bottom;
                if (flags[top]) {
                    continue;
                }
                flags[top] = 1;

                //Check if there is no rectangle contains this rectangle in vertical direction.
                var succ = true;
                for (var j = 0; j < rects.length; j++) {
                    var rect2 = rects[j];
                    if (j !== i && rect2.top < top && rect2.bottom > bottom) {
                        succ = false;
                        break;
                    }
                }
                //If succ, add lineCount 1
                if (succ) {
                    lineCount++;
                }
            }
        }
        else if (editor.document.selection) {//IN IE8 getClientRects returns each single lineCount as a rectangle
            var range = body.createTextRange();
            range.setEndPoint("EndToEnd", range);
            rects = range.getClientRects();
            lineCount = rects.length;
        }
        //Now we get lineCount here

How to specify the download location with wget?

"-P" is the right option, please read on for more related information:

wget -nd -np -P /dest/dir --recursive http://url/dir1/dir2

Relevant snippets from man pages for convenience:

   -P prefix
   --directory-prefix=prefix
       Set directory prefix to prefix.  The directory prefix is the directory where all other files and subdirectories will be saved to, i.e. the top of the retrieval tree.  The default is . (the current directory).

   -nd
   --no-directories
       Do not create a hierarchy of directories when retrieving recursively.  With this option turned on, all files will get saved to the current directory, without clobbering (if a name shows up more than once, the
       filenames will get extensions .n).


   -np
   --no-parent
       Do not ever ascend to the parent directory when retrieving recursively.  This is a useful option, since it guarantees that only the files below a certain hierarchy will be downloaded.

How can I loop through a C++ map of maps?

for(std::map<std::string, std::map<std::string, std::string> >::iterator outer_iter=map.begin(); outer_iter!=map.end(); ++outer_iter) {
    for(std::map<std::string, std::string>::iterator inner_iter=outer_iter->second.begin(); inner_iter!=outer_iter->second.end(); ++inner_iter) {
        std::cout << inner_iter->second << std::endl;
    }
}

or nicer in C++0x:

for(auto outer_iter=map.begin(); outer_iter!=map.end(); ++outer_iter) {
    for(auto inner_iter=outer_iter->second.begin(); inner_iter!=outer_iter->second.end(); ++inner_iter) {
        std::cout << inner_iter->second << std::endl;
    }
}

Is it possible to remove the focus from a text input when a page loads?

A jQuery solution would be something like:

$(function () {
    $('input').blur();
});

Interface/enum listing standard mime-type constants

As pointed out by an answer above, you can use javax.ws.rs.core.MediaType which has the required constants.

I also wanted to share a really cool and handy link which I found that gives a reference to all the Javax constants in one place - https://docs.oracle.com/javaee/7/api/constant-values.html.

C++ "Access violation reading location" Error

Vertex *f=(findvertex(from));
if(!f) {
    cerr << "vertex not found" << endl;
    exit(1) // or return;
}

Because findVertex can return NULL if it can't find the vertex.

Otherwise this f->adj; is trying to do

NULL->adj;

Which causes access violation.

How to add/subtract dates with JavaScript?

You can use the native javascript Date object to keep track of dates. It will give you the current date, let you keep track of calendar specific stuff and even help you manage different timezones. You can add and substract days/hours/seconds to change the date you are working with or to calculate new dates.

take a look at this object reference to learn more:

Date

Hope that helps!

How to add image to canvas

You have to use .onload

let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d"); 

const drawImage = (url) => {
    const image = new Image();
    image.src = url;
    image.onload = () => {
       ctx.drawImage(image, 0, 0)
    }
}

Here's Why

If you are loading the image first after the canvas has already been created then the canvas won't be able to pass all the image data to draw the image. So you need to first load all the data that came with the image and then you can use drawImage()

How can I save application settings in a Windows Forms application?

Other options, instead of using a custom XML file, we can use a more user friendly file format: JSON or YAML file.

  • If you use .NET 4.0 dynamic, this library is really easy to use (serialize, deserialize, nested objects support and ordering output as you wish + merging multiple settings to one) JsonConfig (usage is equivalent to ApplicationSettingsBase)
  • For .NET YAML configuration library... I haven't found one that is as easy to use as JsonConfig

You can store your settings file in multiple special folders (for all users and per user) as listed here Environment.SpecialFolder Enumeration and multiple files (default read only, per role, per user, etc.)

If you choose to use multiple settings, you can merge those settings: For example, merging settings for default + BasicUser + AdminUser. You can use your own rules: the last one overrides the value, etc.

UIImageView aspect fit and center

Just pasting the solution:

Just like @manohar said

imageView.contentMode = UIViewContentModeCenter;
if (imageView.bounds.size.width > ((UIImage*)imagesArray[i]).size.width && imageView.bounds.size.height > ((UIImage*)imagesArray[i]).size.height) {
       imageView.contentMode = UIViewContentModeScaleAspectFit;
}

solved my problem

Check if a Windows service exists and delete in PowerShell

One could use Where-Object

if ((Get-Service | Where-Object {$_.Name -eq $serviceName}).length -eq 1) { "Service Exists" }

Change UITableView height dynamically

for resizing my table I went with this solution in my tableview controller witch is perfectly fine:

[objectManager getObjectsAtPath:self.searchURLString
                         parameters:nil
                            success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
                                NSArray* results = [mappingResult array];
                                self.eventArray = results;
                                NSLog(@"Events number at first: %i", [self.eventArray count]);
                                CGRect newFrame = self.activityFeedTableView.frame;
                                newFrame.size.height = self.cellsHeight + 30.0;
                                self.activityFeedTableView.frame = newFrame;

                                self.cellsHeight = 0.0;

                            }
                            failure:^(RKObjectRequestOperation *operation, NSError *error) {
                                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                                message:[error localizedDescription]
                                                                               delegate:nil
                                                                      cancelButtonTitle:@"OK"
                                                                      otherButtonTitles:nil];
                                [alert show];
                                NSLog(@"Hit error: %@", error);
                            }];

The resizing part is in a method but here is just so you can see it. Now the only problem I haveis resizing the scroll view in the other view controller as I have no idea when the tableview has finished resizing. At the moment I'm doing it with performSelector: afterDelay: but this is really not a good way to do it. Any ideas?

HTTP 415 unsupported media type error when calling Web API 2 endpoint

I also experienced this error.

I add into header Content-Type: application/json. Following the change, my submissions succeed!

How to configure postgresql for the first time?

There are two methods you can use. Both require creating a user and a database.

  1. Using createuser and createdb,

    $ sudo -u postgres createuser --superuser $USER
    $ createdb mydatabase
    $ psql -d mydatabase
    
  2. Using the SQL administration commands, and connecting with a password over TCP

    $ sudo -u postgres psql postgres
    

    And, then in the psql shell

    CREATE ROLE myuser LOGIN PASSWORD 'mypass';
    CREATE DATABASE mydatabase WITH OWNER = myuser;
    

    Then you can login,

    $ psql -h localhost -d mydatabase -U myuser -p <port>
    

    If you don't know the port, you can always get it by running the following, as the postgres user,

    SHOW port;
    

    Or,

    $ grep "port =" /etc/postgresql/*/main/postgresql.conf
    

Sidenote: the postgres user

I suggest NOT modifying the postgres user.

  1. It's normally locked from the OS. No one is supposed to "log in" to the operating system as postgres. You're supposed to have root to get to authenticate as postgres.
  2. It's normally not password protected and delegates to the host operating system. This is a good thing. This normally means in order to log in as postgres which is the PostgreSQL equivalent of SQL Server's SA, you have to have write-access to the underlying data files. And, that means that you could normally wreck havoc anyway.
  3. By keeping this disabled, you remove the risk of a brute force attack through a named super-user. Concealing and obscuring the name of the superuser has advantages.

Select All checkboxes using jQuery

Use below code..

        $('#globalCheckbox').click(function(){
            if($(this).prop("checked")) {
                $(".checkBox").prop("checked", true);
            } else {
                $(".checkBox").prop("checked", false);
            }                
        });


        $('.checkBox').click(function(){
            if($(".checkBox").length == $(".checkBox:checked").length) { 
                 //if the length is same then untick 
                $("#globalCheckbox").prop("checked", false);
            }else {
                //vise versa
                $("#globalCheckbox").prop("checked", true);            
            }
        });

Check if not nil and not empty in Rails shortcut?

There's a method that does this for you:

def show
  @city = @user.city.present?
end

The present? method tests for not-nil plus has content. Empty strings, strings consisting of spaces or tabs, are considered not present.

Since this pattern is so common there's even a shortcut in ActiveRecord:

def show
  @city = @user.city?
end

This is roughly equivalent.

As a note, testing vs nil is almost always redundant. There are only two logically false values in Ruby: nil and false. Unless it's possible for a variable to be literal false, this would be sufficient:

if (variable)
  # ...
end

This is preferable to the usual if (!variable.nil?) or if (variable != nil) stuff that shows up occasionally. Ruby tends to wards a more reductionist type of expression.

One reason you'd want to compare vs. nil is if you have a tri-state variable that can be true, false or nil and you need to distinguish between the last two states.

Change Select List Option background colour on hover in html

Currently there is no way to apply a css to get your desired result . Why not use libraries like choosen or select2 . These allow you to style the way you want.

If you don want to use third party libraries then you can make a simple un-ordered list and play with some css.Here is thread you could follow

How to convert <select> dropdown into an unordered list using jquery?

Using grep to help subset a data frame in R

You may also use the stringr package

library(dplyr)
library(stringr)
My.Data %>% filter(str_detect(x, '^G45'))

You may not use '^' (starts with) in this case, to obtain the results you need

How do I install a pip package globally instead of locally?

Where does pip installations happen in python?

I will give a windows solution which I was facing and took a while to solve.

First of all, in windows (I will be taking Windows as the OS here), if you do pip install <package_name>, it will be by default installed globally (if you have not activated a virtual enviroment). Once you activate a virtual enviroment and you are inside it, all pip installations will be inside that virtual enviroment.


pip is installing the said packages but not I cannot use them?

For this pip might be giving you a warning that the pip executables like pip3.exe, pip.exe are not on your path variable. For this you might add this path ( usually - C:\Users\<your_username>\AppData\Roaming\Programs\Python\ ) to your enviromental variables. After this restart your cmd, and now try to use your installed python package. It should work now.

How can I copy a file on Unix using C?

Another variant of the copy function using normal POSIX calls and without any loop. Code inspired from the buffer copy variant of the answer of caf. Warning: Using mmap can easily fail on 32 bit systems, on 64 bit system the danger is less likely.

#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/mman.h>

int cp(const char *to, const char *from)
{
  int fd_from = open(from, O_RDONLY);
  if(fd_from < 0)
    return -1;
  struct stat Stat;
  if(fstat(fd_from, &Stat)<0)
    goto out_error;

  void *mem = mmap(NULL, Stat.st_size, PROT_READ, MAP_SHARED, fd_from, 0);
  if(mem == MAP_FAILED)
    goto out_error;

  int fd_to = creat(to, 0666);
  if(fd_to < 0)
    goto out_error;

  ssize_t nwritten = write(fd_to, mem, Stat.st_size);
  if(nwritten < Stat.st_size)
    goto out_error;

  if(close(fd_to) < 0) {
    fd_to = -1;
    goto out_error;
  }
  close(fd_from);

  /* Success! */
  return 0;
}
out_error:;
  int saved_errno = errno;

  close(fd_from);
  if(fd_to >= 0)
    close(fd_to);

  errno = saved_errno;
  return -1;
}

EDIT: Corrected the file creation bug. See comment in http://stackoverflow.com/questions/2180079/how-can-i-copy-a-file-on-unix-using-c/2180157#2180157 answer.

error opening trace file: No such file or directory (2)

I think this is the problem

A little background

Traceview is a graphical viewer for execution logs that you create by using the Debug class to log tracing information in your code. Traceview can help you debug your application and profile its performance. Enabling it creates a .trace file in the sdcard root folder which can then be extracted by ADB and processed by traceview bat file for processing. It also can get added by the DDMS.

It is a system used internally by the logger. In general unless you are using traceview to extract the trace file this error shouldnt bother you. You should look at error/logs directly related to your application

How do I enable it:

There are two ways to generate trace logs:

  1. Include the Debug class in your code and call its methods such as startMethodTracing() and stopMethodTracing(), to start and stop logging of trace information to disk. This option is very precise because you can specify exactly where to start and stop logging trace data in your code.

  2. Use the method profiling feature of DDMS to generate trace logs. This option is less precise because you do not modify code, but rather specify when to start and stop logging with DDMS. Although you have less control on exactly where logging starts and stops, this option is useful if you don't have access to the application's code, or if you do not need precise log timing.

But the following restrictions exist for the above

If you are using the Debug class, your application must have permission to write to external storage (WRITE_EXTERNAL_STORAGE).

If you are using DDMS: Android 2.1 and earlier devices must have an SD card present and your application must have permission to write to the SD card. Android 2.2 and later devices do not need an SD card. The trace log files are streamed directly to your development machine.

So in essence the traceFile access requires two things

1.) Permission to write a trace log file i.e. WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE for good measure

2.) An emulator with an SDCard attached with sufficient space. The doc doesnt say if this is only for DDMS but also for debug, so I am assuming this is also true for debugging via the application.

What do I do with this error:

Now the error is essentially a fall out of either not having the sdcard path to create a tracefile or not having permission to access it. This is an old thread, but the dev behind the bounty, check if are meeting the two prerequisites. You can then go search for the .trace file in the sdcard folder in your emulator. If it exists it shouldn't be giving you this problem, if it doesnt try creating it by adding the startMethodTracing to your app.
I'm not sure why it automatically looks for this file when the logger kicks in. I think when an error/log event occurs , the logger internally tries to write to trace file and does not find it, in which case it throws the error.Having scoured through the docs, I don't find too many references to why this is automatically on. But in general this doesn't affect you directly, you should check direct application logs/errors. Also as an aside Android 2.2 and later devices do not need an SD card for DDMS trace logging. The trace log files are streamed directly to your development machine.

Additional information on Traceview:

Copying Trace Files to a Host Machine

After your application has run and the system has created your trace files .trace on a device or emulator, you must copy those files to your development computer. You can use adb pull to copy the files. Here's an example that shows how to copy an example file, calc.trace, from the default location on the emulator to the /tmp directory on the emulator host machine:

adb pull /sdcard/calc.trace /tmp Viewing Trace Files in Traceview To run Traceview and view the trace files, enter traceview . For example, to run Traceview on the example files copied in the previous section, use:

traceview /tmp/calc Note: If you are trying to view the trace logs of an application that is built with ProGuard enabled (release mode build), some method and member names might be obfuscated. You can use the Proguard mapping.txt file to figure out the original unobfuscated names. For more information on this file, see the Proguard documentation.

I think any other answer regarding positioning of oncreate statements or removing uses-sdk are not related, but this is Android and I could be wrong. Would be useful to redirect this question to an android engineer or post it as a bug

More in the docs

How to download a file over HTTP?

urlretrieve and requests.get are simple, however the reality not. I have fetched data for couple sites, including text and images, the above two probably solve most of the tasks. but for a more universal solution I suggest the use of urlopen. As it is included in Python 3 standard library, your code could run on any machine that run Python 3 without pre-installing site-package

import urllib.request
url_request = urllib.request.Request(url, headers=headers)
url_connect = urllib.request.urlopen(url_request)

#remember to open file in bytes mode
with open(filename, 'wb') as f:
    while True:
        buffer = url_connect.read(buffer_size)
        if not buffer: break

        #an integer value of size of written data
        data_wrote = f.write(buffer)

#you could probably use with-open-as manner
url_connect.close()

This answer provides a solution to HTTP 403 Forbidden when downloading file over http using Python. I have tried only requests and urllib modules, the other module may provide something better, but this is the one I used to solve most of the problems.

IPython Notebook save location

To run in Windows, copy this *.bat file to each directory you wish to use and run the ipython notebook by executing the batch file. This assumes you have ipython installed in windows.

set "var=%cd%"
cd var
ipython notebook

Dynamically access object property using variable

I asked a question that kinda duplicated on this topic a while back, and after excessive research, and seeing a lot of information missing that should be here, I feel I have something valuable to add to this older post.

  • Firstly I want to address that there are several ways to obtain the value of a property and store it in a dynamic Variable. The first most popular, and easiest way IMHO would be:
let properyValue = element.style['enter-a-property'];

however I rarely go this route because it doesn't work on property values assigned via style-sheets. To give you an example, I'll demonstrate with a bit of pseudo code.

 let elem = document.getElementById('someDiv');
 let cssProp = elem.style['width'];

Using the code example above; if the width property of the div element that was stored in the 'elem' variable was styled in a CSS style-sheet, and not styled inside of its HTML tag, you are without a doubt going to get a return value of undefined stored inside of the cssProp variable. The undefined value occurs because in-order to get the correct value, the code written inside a CSS Style-Sheet needs to be computed in-order to get the value, therefore; you must use a method that will compute the value of the property who's value lies within the style-sheet.

  • Henceforth the getComputedStyle() method!
function getCssProp(){
  let ele = document.getElementById("test");
  let cssProp = window.getComputedStyle(ele,null).getPropertyValue("width");
}

W3Schools getComputedValue Doc This gives a good example, and lets you play with it, however, this link Mozilla CSS getComputedValue doc talks about the getComputedValue function in detail, and should be read by any aspiring developer who isn't totally clear on this subject.

  • As a side note, the getComputedValue method only gets, it does not set. This, obviously is a major downside, however there is a method that gets from CSS style-sheets, as well as sets values, though it is not standard Javascript. The JQuery method...
$(selector).css(property,value)

...does get, and does set. It is what I use, the only downside is you got to know JQuery, but this is honestly one of the very many good reasons that every Javascript Developer should learn JQuery, it just makes life easy, and offers methods, like this one, which is not available with standard Javascript. Hope this helps someone!!!

Display Two <div>s Side-by-Side

Try to Use Flex as that is the new standard of html5.

http://jsfiddle.net/maxspan/1b431hxm/

<div id="row1">
    <div id="column1">I am column one</div>
    <div id="column2">I am column two</div>
</div>

#row1{
    display:flex;
    flex-direction:row;
justify-content: space-around;
}

#column1{
    display:flex;
    flex-direction:column;

}


#column2{
    display:flex;
    flex-direction:column;
}

sscanf in Python

You could install pandas and use pandas.read_fwf for fixed width format files. Example using /proc/net/arp:

In [230]: df = pandas.read_fwf("/proc/net/arp")

In [231]: print(df)
       IP address HW type Flags         HW address Mask Device
0   141.38.28.115     0x1   0x2  84:2b:2b:ad:e1:f4    *   eth0
1   141.38.28.203     0x1   0x2  c4:34:6b:5b:e4:7d    *   eth0
2   141.38.28.140     0x1   0x2  00:19:99:ce:00:19    *   eth0
3   141.38.28.202     0x1   0x2  90:1b:0e:14:a1:e3    *   eth0
4    141.38.28.17     0x1   0x2  90:1b:0e:1a:4b:41    *   eth0
5    141.38.28.60     0x1   0x2  00:19:99:cc:aa:58    *   eth0
6   141.38.28.233     0x1   0x2  90:1b:0e:8d:7a:c9    *   eth0
7    141.38.28.55     0x1   0x2  00:19:99:cc:ab:00    *   eth0
8   141.38.28.224     0x1   0x2  90:1b:0e:8d:7a:e2    *   eth0
9   141.38.28.148     0x1   0x0  4c:52:62:a8:08:2c    *   eth0
10  141.38.28.179     0x1   0x2  90:1b:0e:1a:4b:50    *   eth0

In [232]: df["HW address"]
Out[232]:
0     84:2b:2b:ad:e1:f4
1     c4:34:6b:5b:e4:7d
2     00:19:99:ce:00:19
3     90:1b:0e:14:a1:e3
4     90:1b:0e:1a:4b:41
5     00:19:99:cc:aa:58
6     90:1b:0e:8d:7a:c9
7     00:19:99:cc:ab:00
8     90:1b:0e:8d:7a:e2
9     4c:52:62:a8:08:2c
10    90:1b:0e:1a:4b:50

In [233]: df["HW address"][5]
Out[233]: '00:19:99:cc:aa:58'

By default it tries to figure out the format automagically, but there are options you can give for more explicit instructions (see documentation). There are also other IO routines in pandas that are powerful for other file formats.

Do I really need to encode '&' as '&amp;'?

Could you show us what your title actually is? When I submit

<!DOCTYPE html>
<html>
<title>Dolce & Gabbana</title>
<body>
<p>am i allowed loose & mpersands?</p>
</body>
</html>

to http://validator.w3.org/ - explicitly asking it to use the experimental HTML 5 mode - it has no complaints about the &s...

Vue.js data-bind style backgroundImage not working

I tried @david answer, and it didn't fix my issue. after a lot of hassle, I made a method and return the image with style string.

HTML Code

<div v-for="slide in loadSliderImages" :key="slide.id">
    <div v-else :style="bannerBgImage(slide.banner)"></div>
</div>

Method

bannerBgImage(image){
    return 'background-image: url("' + image + '")';
},

How do I configure modprobe to find my module?

You can make a symbolic link of your module to the standard path, so depmod will see it and you'll be able load it as any other module.

sudo ln -s /path/to/module.ko /lib/modules/`uname -r`
sudo depmod -a
sudo modprobe module

If you add the module name to /etc/modules it will be loaded any time you boot.

Anyway I think that the proper configuration is to copy the module to the standard paths.

Access to build environment variables from a groovy script in a Jenkins build step (Windows)

You might be able to get them like this:

def thr = Thread.currentThread()
def build = thr?.executable
def envVarsMap = build.parent.builds[0].properties.get("envVars")

How to pipe list of files returned by find command to cat to view all the files

This works for me

find _CACHE_* | while read line; do
    cat "$line" | grep "something"
done

Example of AES using Crypto++

Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:

Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.

#include <iostream>
#include <iomanip>

#include "modes.h"
#include "aes.h"
#include "filters.h"

int main(int argc, char* argv[]) {

    //Key and IV setup
    //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-   
    //bit). This key is secretly exchanged between two parties before communication   
    //begins. DEFAULT_KEYLENGTH= 16 bytes
    CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
    memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );

    //
    // String and Sink setup
    //
    std::string plaintext = "Now is the time for all good men to come to the aide...";
    std::string ciphertext;
    std::string decryptedtext;

    //
    // Dump Plain Text
    //
    std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
    std::cout << plaintext;
    std::cout << std::endl << std::endl;

    //
    // Create Cipher Text
    //
    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
    stfEncryptor.MessageEnd();

    //
    // Dump Cipher Text
    //
    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ ) {

        std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
    }

    std::cout << std::endl << std::endl;

    //
    // Decrypt
    //
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();

    //
    // Dump Decrypted Text
    //
    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;

    return 0;
}

For installation details :

sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

How do I raise an exception in Rails so it behaves like other Rails exceptions?

You don't have to do anything special, it should just be working.

When I have a fresh rails app with this controller:

class FooController < ApplicationController
  def index
    raise "error"
  end
end

and go to http://127.0.0.1:3000/foo/

I am seeing the exception with a stack trace.

You might not see the whole stacktrace in the console log because Rails (since 2.3) filters lines from the stack trace that come from the framework itself.

See config/initializers/backtrace_silencers.rb in your Rails project

Typescript: How to define type for a function callback (as any function type, not universal any) used in a method parameter

Typescript: How to define type for a function callback used in a method parameter?

You can declare the callback as 1) function property or 2) method:

interface ParamFnProp {
    callback: (a: Animal) => void; // function property
}

interface ParamMethod {
    callback(a: Animal): void; // method
}

There is an important typing difference since TS 2.6:

You get stronger ("sound") types in --strict or --strictFunctionTypes mode, when a function property is declared. Let's take an example:

const animalCallback = (a: Animal): void => { } // Animal is the base type for Dog
const dogCallback = (d: Dog): void => { } 
// function property variant
const param11: ParamFnProp = { callback: dogCallback } // error: not assignable
const param12: ParamFnProp = { callback: animalCallback } // works

// method variant
const param2: ParamMethod = { callback: dogCallback } // now it works again ...

Technically spoken, methods are bivariant and function properties contravariant in their arguments under strictFunctionTypes. Methods are still checked more permissively (even if not sound) to be a bit more practical in combination with built-in types like Array.

Summary

  • There is a type difference between function property and method declaration
  • Choose a function property for stronger types, if possible

Playground sample code

paint() and repaint() in Java

The paint() method supports painting via a Graphics object.

The repaint() method is used to cause paint() to be invoked by the AWT painting thread.

Center content vertically on Vuetify

Still surprised that no one proposed the shortest solution with align-center justify-center to center content vertically and horizontally. Check this CodeSandbox and code below:

<v-container fluid fill-height>
  <v-layout align-center justify-center>
    <v-flex>
      <!-- Some HTML elements... -->
    </v-flex>
  </v-layout>
</v-container>

Create a hidden field in JavaScript

I've found this to work:

var element1 = document.createElement("input");
element1.type = "hidden";
element1.value = "10";
element1.name = "a";
document.getElementById("chells").appendChild(element1);

did you specify the right host or port? error on Kubernetes

try run with sudo permission mode
example sudo kubectl....

Filename timestamp in Windows CMD batch script getting truncated

The first four lines of this code will give you reliable YY DD MM YYYY HH Min Sec variables in XP Pro and higher, using WMIC.

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"

set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause

Output example:

datestamp: "20200828"
timestamp: "085513"
fullstamp: "2020-08-28_08-55-13"
Press any key to continue . . .

Create a directory if it does not exist and then create the files in that directory as well

Trying to make this as short and simple as possible. Creates directory if it doesn't exist, and then returns the desired file:

/** Creates parent directories if necessary. Then returns file */
private static File fileWithDirectoryAssurance(String directory, String filename) {
    File dir = new File(directory);
    if (!dir.exists()) dir.mkdirs();
    return new File(directory + "/" + filename);
}

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

.any() and .all() are great for the extreme cases, but not when you're looking for a specific number of null values. Here's an extremely simple way to do what I believe you're asking. It's pretty verbose, but functional.

import pandas as pd
import numpy as np

# Some test data frame
df = pd.DataFrame({'num_legs':          [2, 4,      np.nan, 0, np.nan],
                   'num_wings':         [2, 0,      np.nan, 0, 9],
                   'num_specimen_seen': [10, np.nan, 1,     8, np.nan]})

# Helper : Gets NaNs for some row
def row_nan_sums(df):
    sums = []
    for row in df.values:
        sum = 0
        for el in row:
            if el != el: # np.nan is never equal to itself. This is "hacky", but complete.
                sum+=1
        sums.append(sum)
    return sums

# Returns a list of indices for rows with k+ NaNs
def query_k_plus_sums(df, k):
    sums = row_nan_sums(df)
    indices = []
    i = 0
    for sum in sums:
        if (sum >= k):
            indices.append(i)
        i += 1
    return indices

# test
print(df)
print(query_k_plus_sums(df, 2))

Output

   num_legs  num_wings  num_specimen_seen
0       2.0        2.0               10.0
1       4.0        0.0                NaN
2       NaN        NaN                1.0
3       0.0        0.0                8.0
4       NaN        9.0                NaN
[2, 4]

Then, if you're like me and want to clear those rows out, you just write this:

# drop the rows from the data frame
df.drop(query_k_plus_sums(df, 2),inplace=True)
# Reshuffle up data (if you don't do this, the indices won't reset)
df = df.sample(frac=1).reset_index(drop=True)
# print data frame
print(df)

Output:

   num_legs  num_wings  num_specimen_seen
0       4.0        0.0                NaN
1       0.0        0.0                8.0
2       2.0        2.0               10.0

Pandas count(distinct) equivalent

Here an approach to have count distinct over multiple columns. Let's have some data:

data = {'CLIENT_CODE':[1,1,2,1,2,2,3],
        'YEAR_MONTH':[201301,201301,201301,201302,201302,201302,201302],
        'PRODUCT_CODE': [100,150,220,400,50,80,100]
       }
table = pd.DataFrame(data)
table

CLIENT_CODE YEAR_MONTH  PRODUCT_CODE
0   1       201301      100
1   1       201301      150
2   2       201301      220
3   1       201302      400
4   2       201302      50
5   2       201302      80
6   3       201302      100

Now, list the columns of interest and use groupby in a slightly modified syntax:

columns = ['YEAR_MONTH', 'PRODUCT_CODE']
table[columns].groupby(table['CLIENT_CODE']).nunique()

We obtain:

YEAR_MONTH  PRODUCT_CODE CLIENT_CODE        
1           2            3
2           2            3
3           1            1

React - Preventing Form Submission

No JS needed really ... Just add a type attribute to the button with a value of button

<Button type="button" color="primary" onClick={this.onTestClick}>primary</Button>&nbsp;

By default, button elements are of the type "submit" which causes them to submit their enclosing form element (if any). Changing the type to "button" prevents that.

How do you install an APK file in the Android emulator?

06-11-2020

Drag and Drop didn't work for me on Windows 10 Pro.

  1. Put the APK on Google Drive

  2. Access that Google drive using Chrome browser on the Android Emulator

  3. Then install it from there.

Note: You need to enable unknown sources within the Emulator.

How to get changes from another branch

You are almost there :)

All that is left is to

git checkout featurex
git merge our-team

This will merge our-team into featurex.

The above assumes you have already committed/stashed your changes in featurex, if that is not the case you will need to do this first.

Load vs. Stress testing

Load - Test S/W at max Load. Stress - Beyond the Load of S/W.Or To determine the breaking point of s/w.

Execute bash script from URL

source <(curl -s http://mywebsite.com/myscript.txt)

ought to do it. Alternately, leave off the initial redirection on yours, which is redirecting standard input; bash takes a filename to execute just fine without redirection, and <(command) syntax provides a path.

bash <(curl -s http://mywebsite.com/myscript.txt)

It may be clearer if you look at the output of echo <(cat /dev/null)

Passing data through intent using Serializable

You need to create a Bundle and then use putSerializable:

List<Thumbnail> all_thumbs = new ArrayList<Thumbnail>();
all_thumbs.add(new Thumbnail(string,bitmap));
Intent intent = new Intent(getApplicationContext(),SomeClass.class);

Bundle extras = new Bundle();

extras.putSerializable("value",all_thumbs);
intent.putExtras(extras);

Sequence contains no elements?

Please use

.FirstOrDefault()

because if in the first row of the result there is no info this instruction goes to the default info.

How to add months to a date in JavaScript?

I would highly recommend taking a look at datejs. With it's api, it becomes drop dead simple to add a month (and lots of other date functionality):

var one_month_from_your_date = your_date_object.add(1).month();

What's nice about datejs is that it handles edge cases, because technically you can do this using the native Date object and it's attached methods. But you end up pulling your hair out over edge cases, which datejs has taken care of for you.

Plus it's open source!

Calling class staticmethod within the class body?

This is due to staticmethod being a descriptor and requires a class-level attribute fetch to exercise the descriptor protocol and get the true callable.

From the source code:

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()); the instance is ignored except for its class.

But not directly from inside the class while it is being defined.

But as one commenter mentioned, this is not really a "Pythonic" design at all. Just use a module level function instead.

Fixed height and width for bootstrap carousel

Because some images could have less than 500px of height, it's better to keep the auto-adjust, so i recommend the following:

<div class="carousel-inner" role="listbox" style="max-width:900px; max-height:600px !important;">`

Rename Pandas DataFrame Index

You can also use Index.set_names as follows:

In [25]: x = pd.DataFrame({'year':[1,1,1,1,2,2,2,2],
   ....:                   'country':['A','A','B','B','A','A','B','B'],
   ....:                   'prod':[1,2,1,2,1,2,1,2],
   ....:                   'val':[10,20,15,25,20,30,25,35]})

In [26]: x = x.set_index(['year','country','prod']).squeeze()

In [27]: x
Out[27]: 
year  country  prod
1     A        1       10
               2       20
      B        1       15
               2       25
2     A        1       20
               2       30
      B        1       25
               2       35
Name: val, dtype: int64
In [28]: x.index = x.index.set_names('foo', level=1)

In [29]: x
Out[29]: 
year  foo  prod
1     A    1       10
           2       20
      B    1       15
           2       25
2     A    1       20
           2       30
      B    1       25
           2       35
Name: val, dtype: int64

How to downgrade Node version

Determining your Node version

node -v  // or node --version
npm -v   // npm version or long npm --version

Ensure that you have n installed

sudo npm install -g n // -g for global installation 

Upgrading to the latest stable version

sudo n stable

Changing to a specific version

sudo n 10.16.0

Answer inspired by this article.

Pandas left outer join multiple dataframes on multiple columns

One can also do this with a compact version of @TomAugspurger's answer, like so:

df = df1.merge(df2, how='left', on=['Year', 'Week', 'Colour']).merge(df3[['Week', 'Colour', 'Val3']], how='left', on=['Week', 'Colour'])

Bulk Record Update with SQL

You can do this through a regular UPDATE with a JOIN

UPDATE T1
SET Description = T2.Description
   FROM Table1 T1
      JOIN Table2 T2
         ON T2.ID = T1.DescriptionId

Submit form on pressing Enter with AngularJS

Just wanted to point out that in the case of having a hidden submit button, you can just use the ngShow directive and set it to false like so:

HTML

<form ng-submit="myFunc()">
    <input type="text" name="username">
    <input type="submit" value="submit" ng-show="false">
</form>

Check whether IIS is installed or not?

In the menu, go to RUN > services.msc and hit enter to get the services window and check for the IIS ADMIN service. If it is not present, then reinstall IIS using your windows CD.

How do I discover memory usage of my application in Android?

There are a lot of answer above which will definitely help you but (after 2 days of afford and research on adb memory tools) I think i can help with my opinion too.

As Hackbod says : Thus if you were to take all of the physical RAM actually mapped in to each process, and add up all of the processes, you would probably end up with a number much greater than the actual total RAM. so there is no way you can get exact amount of memory per process.

But you can get close to it by some logic..and I will tell how..

There are some API like android.os.Debug.MemoryInfo and ActivityManager.getMemoryInfo() mentioned above which you already might have being read about and used but I will talk about other way

So firstly you need to be a root user to get it work. Get into console with root privilege by executing su in process and get its output and input stream. Then pass id\n (enter) in ouputstream and write it to process output, If will get an inputstream containing uid=0, you are root user.

Now here is the logic which you will use in above process

When you get ouputstream of process pass you command (procrank, dumpsys meminfo etc...) with \n instead of id and get its inputstream and read, store the stream in bytes[ ] ,char[ ] etc.. use raw data..and you are done!!!!!

permission :

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

Check if you are root user :

// su command to get root access
Process process = Runtime.getRuntime().exec("su");         
DataOutputStream dataOutputStream = 
                           new DataOutputStream(process.getOutputStream());
DataInputStream dataInputStream = 
                           new DataInputStream(process.getInputStream());
if (dataInputStream != null && dataOutputStream != null) {
   // write id to console with enter
   dataOutputStream.writeBytes("id\n");                   
   dataOutputStream.flush();
   String Uid = dataInputStream.readLine();
   // read output and check if uid is there
   if (Uid.contains("uid=0")) {                           
      // you are root user
   } 
}

Execute your command with su

Process process = Runtime.getRuntime().exec("su");         
DataOutputStream dataOutputStream = 
                           new DataOutputStream(process.getOutputStream());
if (dataOutputStream != null) {
 // adb command
 dataOutputStream.writeBytes("procrank\n");             
 dataOutputStream.flush();
 BufferedInputStream bufferedInputStream = 
                     new BufferedInputStream(process.getInputStream());
 // this is important as it takes times to return to next line so wait
 // else you with get empty bytes in buffered stream 
 try {
       Thread.sleep(10000);
 } catch (InterruptedException e) {                     
       e.printStackTrace();
 }
 // read buffered stream into byte,char etc.
 byte[] bff = new byte[bufferedInputStream.available()];
 bufferedInputStream.read(bff);
 bufferedInputStream.close();
 }
}

logcat : result

You get a raw data in a single string from console instead of in some instance from any API,which is complex to store as you will need to separate it manually.

This is just a try, please suggest me if I missed something

Create numpy matrix filled with NaNs

Yet another possibility not yet mentioned here is to use NumPy tile:

a = numpy.tile(numpy.nan, (3, 3))

Also gives

array([[ NaN,  NaN,  NaN],
       [ NaN,  NaN,  NaN],
       [ NaN,  NaN,  NaN]])

I don't know about speed comparison.

Trying to start a service on boot on Android

Along with

<action android:name="android.intent.action.BOOT_COMPLETED" />  

also use,

<action android:name="android.intent.action.QUICKBOOT_POWERON" />

HTC devices dont seem to catch BOOT_COMPLETED

How to disable action bar permanently

Below are the steps for hiding the action bar permanently:

  1. Open app/res/values/styles.xml.
  2. Look for the style element that is named "apptheme". Should look similar to <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">.
  3. Now replace the parent with any other theme that contains "NoActionBar" in its name.

    a. You can also check how a theme looks by switching to the design tab of activity_main.xml and then trying out each theme provided in the theme drop-down list of the UI.

  4. If your MainActivity extends AppCompatActivity, make sure you use an AppCompat theme.

Linux command to print directory structure in the form of a tree

Since I was not too happy with the output of other (non-tree) answers (see my comment at Hassou's answer), I tried to mimic trees output a bit more.

It's similar to the answer of Robert but the horizontal lines do not all start at the beginning, but where there are supposed to start. Had to use perl though, but in my case, on the system where I don't have tree, perl is available.

ls -aR | grep ":$" | perl -pe 's/:$//;s/[^-][^\/]*\//    /g;s/^    (\S)/+-- \1/;s/(^    |    (?= ))/¦   /g;s/    (\S)/+-- \1/'

Output (shortened):

.
+-- fd
+-- net
¦   +-- dev_snmp6
¦   +-- nfsfs
¦   +-- rpc
¦   ¦   +-- auth.unix.ip
¦   +-- stat
¦   +-- vlan
+-- ns
+-- task
¦   +-- 1310
¦   ¦   +-- net
¦   ¦   ¦   +-- dev_snmp6
¦   ¦   ¦   +-- rpc
¦   ¦   ¦   ¦   +-- auth.unix.gid
¦   ¦   ¦   ¦   +-- auth.unix.ip
¦   ¦   ¦   +-- stat
¦   ¦   ¦   +-- vlan
¦   ¦   +-- ns

Suggestions to avoid the superfluous vertical lines are welcome :-)

I still like Ben's solution in the comment of Hassou's answer very much, without the (not perfectly correct) lines it's much cleaner. For my use case I additionally removed the global indentation and added the option to also ls hidden files, like so:

ls -aR | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//  /g'

Output (shortened even more):

.
  fd
  net
    dev_snmp6
    nfsfs
    rpc
      auth.unix.ip
    stat
    vlan
  ns

How can I pass a class member function as a callback?

The type of pointer to non-static member function is different from pointer to ordinary function.
Type is void(*)(int) if it’s an ordinary or static member function.
Type is void(CLoggersInfra::*)(int) if it’s a non-static member function.
So you cannot pass a pointer to a non-static member function if it is expecting an ordinary function pointer.

Furthermore, a non-static member function has an implicit/hidden parameter to the object. The this pointer is implicitly passed as an argument to the member function call. So the member functions can be invoked only by providing an object.

If the API Init cannot be changed, a wrapper function (ordinary function or a class static member function) that invokes the member can be used. In the worst case, the object would be a global for the wrapper function to access.

CLoggersInfra* pLoggerInfra;

RedundencyManagerCallBackWrapper(int val)
{
    pLoggerInfra->RedundencyManagerCallBack(val);
}
m_cRedundencyManager->Init(RedundencyManagerCallBackWrapper);

If the API Init can be changed, there are many alternatives - Object non-static member function pointer, Function Object, std::function or Interface Function.

See the post on callbacks for the different variations with C++ working examples.

make a header full screen (width) css

set the body max-width:110%; and the make the width on the header 110% it will leave a small margin on left that you can fiX with margin-left: -8px; margin-top: -10px;

C# List<> Sort by x then y

The trick is to implement a stable sort. I've created a Widget class that can contain your test data:

public class Widget : IComparable
{
    int x;
    int y;
    public int X
    {
        get { return x; }
        set { x = value; }
    }

    public int Y
    {
        get { return y; }
        set { y = value; }
    }

    public Widget(int argx, int argy)
    {
        x = argx;
        y = argy;
    }

    public int CompareTo(object obj)
    {
        int result = 1;
        if (obj != null && obj is Widget)
        {
            Widget w = obj as Widget;
            result = this.X.CompareTo(w.X);
        }
        return result;
    }

    static public int Compare(Widget x, Widget y)
    {
        int result = 1;
        if (x != null && y != null)                
        {                
            result = x.CompareTo(y);
        }
        return result;
    }
}

I implemented IComparable, so it can be unstably sorted by List.Sort().

However, I also implemented the static method Compare, which can be passed as a delegate to a search method.

I borrowed this insertion sort method from C# 411:

 public static void InsertionSort<T>(IList<T> list, Comparison<T> comparison)
        {           
            int count = list.Count;
            for (int j = 1; j < count; j++)
            {
                T key = list[j];

                int i = j - 1;
                for (; i >= 0 && comparison(list[i], key) > 0; i--)
                {
                    list[i + 1] = list[i];
                }
                list[i + 1] = key;
            }
    }

You would put this in the sort helpers class that you mentioned in your question.

Now, to use it:

    static void Main(string[] args)
    {
        List<Widget> widgets = new List<Widget>();

        widgets.Add(new Widget(0, 1));
        widgets.Add(new Widget(1, 1));
        widgets.Add(new Widget(0, 2));
        widgets.Add(new Widget(1, 2));

        InsertionSort<Widget>(widgets, Widget.Compare);

        foreach (Widget w in widgets)
        {
            Console.WriteLine(w.X + ":" + w.Y);
        }
    }

And it outputs:

0:1
0:2
1:1
1:2
Press any key to continue . . .

This could probably be cleaned up with some anonymous delegates, but I'll leave that up to you.

EDIT: And NoBugz demonstrates the power of anonymous methods...so, consider mine more oldschool :P

iPhone App Minus App Store?

It's worth noting that if you go the jailbroken route, it's possible (likely?) that an iPhone OS update would kill your ability to run these apps. I'd go the official route and pay the $99 to get authorized. In addition to not having to worry about your apps being clobbered, you also get the opportunity (should you choose) to release your apps on the store.

How to use target in location.href

If you go with the solution by @qiao, perhaps you would want to remove the appended child since the tab remains open and subsequent clicks would add more elements to the DOM.

// Code by @qiao
var a = document.createElement('a')
a.href = 'http://www.google.com'
a.target = '_blank'
document.body.appendChild(a)
a.click()
// Added code
document.body.removeChild(a)

Maybe someone could post a comment to his post, because I cannot.

Chart.js - Formatting Y axis

As Nevercom said the scaleLable should contain javascript so to manipulate the y value just apply the required formatting.

Note the the value is a string.

var options = {      
    scaleLabel : "<%= value + ' + two = ' + (Number(value) + 2)   %>"
};

jsFiddle example

if you wish to set a manual y scale you can use scaleOverride

var options = {      
    scaleLabel : "<%= value + ' + two = ' + (Number(value) + 2)   %>",

    scaleOverride: true,
    scaleSteps: 10,
    scaleStepWidth: 10,
    scaleStartValue: 0

};

jsFiddle example

Understanding Popen.communicate

Your second bit of code starts the first bit of code as a subprocess with piped input and output. It then closes its input and tries to read its output.

The first bit of code tries to read from standard input, but the process that started it closed its standard input, so it immediately reaches an end-of-file, which Python turns into an exception.

Declaring abstract method in TypeScript

The name property is marked as protected. This was added in TypeScript 1.3 and is now firmly established.

The makeSound method is marked as abstract, as is the class. You cannot directly instantiate an Animal now, because it is abstract. This is part of TypeScript 1.6, which is now officially live.

abstract class Animal {
    constructor(protected name: string) { }

    abstract makeSound(input : string) : string;

    move(meters) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    constructor(name: string) { super(name); }

    makeSound(input : string) : string {
        return "sssss"+input;
    }

    move() {
        alert("Slithering...");
        super.move(5);
    }
}

The old way of mimicking an abstract method was to throw an error if anyone used it. You shouldn't need to do this any more once TypeScript 1.6 lands in your project:

class Animal {
    constructor(public name) { }
    makeSound(input : string) : string {
        throw new Error('This method is abstract');
    }
    move(meters) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    constructor(name) { super(name); }
    makeSound(input : string) : string {
        return "sssss"+input;
    }
    move() {
        alert("Slithering...");
        super.move(5);
    }
}