Programs & Examples On #Serviceconnection

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

You mention the user switching between Activities pretty quickly. Could it be that you're calling unbindService before the service connection has been established? This may have the effect of failing to unbind, then leaking the binding.

Not entirely sure how you could handle this... Perhaps when onServiceConnected is called you could call unbindService if onDestroy has already been called. Not sure if that'll work though.


If you haven't already, you could add an onUnbind method to your service. That way you can see exactly when your classes unbind from it, and it might help with debugging.

@Override
public boolean onUnbind(Intent intent) {
    Log.d(this.getClass().getName(), "UNBIND");
    return true;
}

JavaScript push to array

var array = new Array(); // or the shortcut: = []
array.push ( {"cool":"34.33","also cool":"45454"} );
array.push (  {"cool":"34.39","also cool":"45459"} );

Your variable is a javascript object {} not an array [].

You could do:

var o = {}; // or the longer form: = new Object()
o.SomeNewProperty = "something";
o["SomeNewProperty"] = "something";

and

var o = { SomeNewProperty: "something" };
var o2 = { "SomeNewProperty": "something" };

Later, you add those objects to your array: array.push (o, o2);

Also JSON is simply a string representation of a javascript object, thus:

var json = '{"cool":"34.33","alsocool":"45454"}'; // is JSON
var o = JSON.parse(json); // is a javascript object
json = JSON.stringify(o); // is JSON again

Bind failed: Address already in use

As mentioned above the port is in use already. This could be due to several reasons

  1. some other application is already using it.
  2. The port is in close_wait state when your program is waiting for the other end to close the program.refer (https://unix.stackexchange.com/questions/10106/orphaned-connections-in-close-wait-state).
  3. The program might be in time_wait state. you can wait or use socket option SO_REUSEADDR as mentioned in another post.

Do netstat -a | grep <portno> to check the port state.

C# Telnet Library

I doubt very much a telnet library will ever be part of the .Net BCL, although you do have almost full socket support so it wouldnt be too hard to emulate a telnet client, Telnet in its general implementation is a legacy and dying technology that where exists generally sits behind a nice new modern facade. In terms of Unix/Linux variants you'll find that out the box its SSH and enabling telnet is generally considered poor practice.

You could check out: http://granados.sourceforge.net/ - SSH Library for .Net http://www.tamirgal.com/home/dev.aspx?Item=SharpSsh

You'll still need to put in place your own wrapper to handle events for feeding in input in a scripted manner.

addEventListener not working in IE8

If you use jQuery you can write:

$( _checkbox ).click( function( e ){ /*process event here*/ } )

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block

You are catching the error but then you are re throwing it. You should try and handle it more gracefully, otherwise your user is going to see 500, internal server, errors.

You may want to send back a response telling the user what went wrong as well as logging the error on your server.

I am not sure exactly what errors the request might return, you may want to return something like.

router.get("/emailfetch", authCheck, async (req, res) => {
  try {
    let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
      emailFetch = emailFetch.data
      res.send(emailFetch)
   } catch(error) {
      res.status(error.response.status)
      return res.send(error.message);
    })

})

This code will need to be adapted to match the errors that you get from the axios call.

I have also converted the code to use the try and catch syntax since you are already using async.

Disable cross domain web security in Firefox

For anyone finding this question while using Nightwatch.js (1.3.4), there's an acceptInsecureCerts: true setting in the config file:

_x000D_
_x000D_
firefox: {_x000D_
      desiredCapabilities: {_x000D_
        browserName: 'firefox',_x000D_
        alwaysMatch: {_x000D_
          // Enable this if you encounter unexpected SSL certificate errors in Firefox_x000D_
          acceptInsecureCerts: true,_x000D_
          'moz:firefoxOptions': {_x000D_
            args: [_x000D_
              // '-headless',_x000D_
              // '-verbose'_x000D_
            ],_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
    },
_x000D_
_x000D_
_x000D_

How to multi-line "Replace in files..." in Notepad++

The workaround is

  1. search and replace \r\n to thisismynewlineword

(this will remove all the new lines and there should be whole one line)

  1. now perform your replacements

  2. search and replace thisismynewlineword to \r\n

(to undo the step 1)

Can I have an onclick effect in CSS?

Answer as of 2020:

The best way (actually the only way*) to simulate an actual click event using only CSS (rather than just hovering on an element or making an element active, where you don't have mouseUp) is to use the checkbox hack. It works by attaching a label to an <input type="checkbox"> element via the label's for="" attribute.

This feature has broad browser support (the :checked pseudo-class is IE9+).

Apply the same value to an <input>'s ID attribute and an accompanying <label>'s for="" attribute, and you can tell the browser to re-style the label on click with the :checked pseudo-class, thanks to the fact that clicking a label will check and uncheck the "associated" <input type="checkbox">.

* You can simulate a "selected" event via the :active or :focus pseudo-class in IE7+ (e.g. for a button that's normally 50px wide, you can change its width while active: #btnControl:active { width: 75px; }), but those are not true "click" events. They are "live" the entire time the element is selected (such as by Tabbing with your keyboard), which is a little different from a true click event, which fires an action on - typically - mouseUp.


Basic demo of the checkbox hack (the basic code structure for what you're asking):

_x000D_
_x000D_
label {
    display: block;
    background: lightgrey;
    width: 100px;
    height: 100px;
}

#demo:checked + label {
    background: blue;
    color: white;
}
_x000D_
<input type="checkbox" id="demo"/>
<label for="demo">I'm a square. Click me.</label>
_x000D_
_x000D_
_x000D_

Here I've positioned the label right after the input in my markup. This is so that I can use the adjacent sibling selector (the + key) to select only the label that immediately follows my #demo checkbox. Since the :checked pseudo-class applies to the checkbox, #demo:checked + label will only apply when the checkbox is checked.

Demo for re-sizing an image on click, which is what you're asking:

_x000D_
_x000D_
#btnControl {
    display: none;
}

#btnControl:checked + label > img {
    width: 70px;
    height: 74px;
}
_x000D_
<input type="checkbox" id="btnControl"/>
<label class="btn" for="btnControl"><img src="https://placekitten.com/200/140" id="btnLeft" /></label>
_x000D_
_x000D_
_x000D_

With that being said, there is some bad news. Because a label can only be associated with one form control at a time, that means you can't just drop a button inside the <label></label> tags and call it a day. However, we can use some CSS to make the label look and behave fairly close to how an HTML button looks and behaves.

Demo for imitating a button click effect, above and beyond what you're asking:

_x000D_
_x000D_
#btnControl {
    display: none;
}

.btn {
    width: 60px;
    height: 20px;
    background: silver;
    border-radius: 5px;
    padding: 1px 3px;
    box-shadow: 1px 1px 1px #000;
    display: block;
    text-align: center;
    background-image: linear-gradient(to bottom, #f4f5f5, #dfdddd);
    font-family: arial;
    font-size: 12px;
    line-height:20px;
}

.btn:hover {
    background-image: linear-gradient(to bottom, #c3e3fa, #a5defb);
}


.btn:active {
    margin-left: 1px 1px 0;
    box-shadow: -1px -1px 1px #000;
    outline: 1px solid black;
    -moz-outline-radius: 5px;
    background-image: linear-gradient(to top, #f4f5f5, #dfdddd);
}

#btnControl:checked + label {
    width: 70px;
    height: 74px;
    line-height: 74px;
}
_x000D_
<input type="checkbox" id="btnControl"/>
<label class="btn" for="btnControl">Click me!</label>
_x000D_
_x000D_
_x000D_

Most of the CSS in this demo is just for styling the label element. If you don't actually need a button, and any old element will suffice, then you can remove almost all of the styles in this demo, similar to my second demo above.

You'll also notice I have one prefixed property in there, -moz-outline-radius. A while back, Mozilla added this awesome non-spec property to Firefox, but the folks at WebKit decided they aren't going to add it, unfortunately. So consider that line of CSS just a progressive enhancement for people who use Firefox.

How do I use the lines of a file as arguments of a command?

After editing @Wesley Rice's answer a couple times, I decided my changes were just getting too big to continue changing his answer instead of writing my own. So, I decided I need to write my own!

Read each line of a file in and operate on it line-by-line like this:

#!/bin/bash
input="/path/to/txt/file"
while IFS= read -r line
do
  echo "$line"
done < "$input"

This comes directly from author Vivek Gite here: https://www.cyberciti.biz/faq/unix-howto-read-line-by-line-from-file/. He gets the credit!

Syntax: Read file line by line on a Bash Unix & Linux shell:
1. The syntax is as follows for bash, ksh, zsh, and all other shells to read a file line by line
2. while read -r line; do COMMAND; done < input.file
3. The -r option passed to read command prevents backslash escapes from being interpreted.
4. Add IFS= option before read command to prevent leading/trailing whitespace from being trimmed -
5. while IFS= read -r line; do COMMAND_on $line; done < input.file


And now to answer this now-closed question which I also had: Is it possible to `git add` a list of files from a file? - here's my answer:

Note that FILES_STAGED is a variable containing the absolute path to a file which contains a bunch of lines where each line is a relative path to a file I'd like to do git add on. This code snippet is about to become part of the "eRCaGuy_dotfiles/useful_scripts/sync_git_repo_to_build_machine.sh" file in this project, to enable easy syncing of files in development from one PC (ex: a computer I code on) to another (ex: a more powerful computer I build on): https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles.

while IFS= read -r line
do
    echo "  git add \"$line\""
    git add "$line" 
done < "$FILES_STAGED"

References:

  1. Where I copied my answer from: https://www.cyberciti.biz/faq/unix-howto-read-line-by-line-from-file/
  2. For loop syntax: https://www.cyberciti.biz/faq/bash-for-loop/

Related:

  1. How to read contents of file line-by-line and do git add on it: Is it possible to `git add` a list of files from a file?

How to process POST data in Node.js?

You need to use bodyParser() if you want the form data to be available in req.body. body-parser parses your request and converts it into a format from which you can easily extract relevant information that you may need.

For example, let’s say you have a sign-up form at your frontend. You are filling it, and requesting server to save the details somewhere.

Extracting username and password from your request goes as simple as below if you use body-parser.

…………………………………………………….

var loginDetails = {

username : request.body.username,

password : request.body.password

};

How can I slice an ArrayList out of an ArrayList in Java?

I have found a way if you know startIndex and endIndex of the elements one need to remove from ArrayList

Let al be the original ArrayList and startIndex,endIndex be start and end index to be removed from the array respectively:

al.subList(startIndex, endIndex + 1).clear();

openCV video saving in python

I wasn't having codec issues or dimension issues as the answers above. Instead, my issue was because my output frames were in greyscale.

I had to create a VideoWriter with the parameter isColor=False

out = cv2.VideoWriter(output_path,
                      cv2.VideoWriter_fourcc(*'mp4v'),
                      30,
                      (INPUT_VIDEO_WIDTH,INPUT_VIDEO_HEIGHT),
                      isColor=False
                      )

In the API Docs, it wrongly says that the flag is currently supported on Windows only. I have tested on Ubuntu 20.04, with opencv-python==4.2.0.34, and it finally writes out to file correctly.

Convert a date format in epoch

tl;dr

ZonedDateTime.parse( 
                        "Jun 13 2003 23:11:52.454 UTC" , 
                        DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" ) 
                    )
              .toInstant()
              .toEpochMilli()

1055545912454

java.time

This Answer expands on the Answer by Lockni.

DateTimeFormatter

First define a formatting pattern to match your input string by creating a DateTimeFormatter object.

String input = "Jun 13 2003 23:11:52.454 UTC";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" );

ZonedDateTime

Parse the string as a ZonedDateTime. You can think of that class as: ( Instant + ZoneId ).

ZonedDateTime zdt = ZonedDateTime.parse ( "Jun 13 2003 23:11:52.454 UTC" , f );

zdt.toString(): 2003-06-13T23:11:52.454Z[UTC]

Table of types of date-time classes in modern java.time versus legacy.

Count-from-epoch

I do not recommend tracking date-time values as a count-from-epoch. Doing so makes debugging tricky as humans cannot discern a meaningful date-time from a number so invalid/unexpected values may slip by. Also such counts are ambiguous, in granularity (whole seconds, milli, micro, nano, etc.) and in epoch (at least two dozen in by various computer systems).

But if you insist you can get a count of milliseconds from the epoch of first moment of 1970 in UTC (1970-01-01T00:00:00) through the Instant class. Be aware this means data-loss as you are truncating any nanoseconds to milliseconds.

Instant instant = zdt.toInstant ();

instant.toString(): 2003-06-13T23:11:52.454Z

long millisSinceEpoch = instant.toEpochMilli() ; 

1055545912454


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

how to check if string contains '+' character

Why not just:

int plusIndex = s.indexOf("+");
if (plusIndex != -1) {
    String before = s.substring(0, plusIndex);
    // Use before
}

It's not really clear why your original version didn't work, but then you didn't say what actually happened. If you want to split not using regular expressions, I'd personally use Guava:

Iterable<String> bits = Splitter.on('+').split(s);
String firstPart = Iterables.getFirst(bits, "");

If you're going to use split (either the built-in version or Guava) you don't need to check whether it contains + first - if it doesn't there'll only be one result anyway. Obviously there's a question of efficiency, but it's simpler code:

// Calling split unconditionally
String[] parts = s.split("\\+");
s = parts[0];

Note that writing String[] parts is preferred over String parts[] - it's much more idiomatic Java code.

Text on image mouseover?

And if you come from even further in the future you can use the title property on div tags now to provide tooltips:

<div title="Tooltip text">Hover over me</div>

Let's just hope you're not using a browser from the past.

_x000D_
_x000D_
<div title="Tooltip text">Hover over me</div>
_x000D_
_x000D_
_x000D_

Error: Unexpected value 'undefined' imported by the module

This issue of circular dependencies of two module

Module 1:import Module 2
Module 2:import Module 1

OR is not supported with CASE Statement in SQL Server

select id,phno,case gender
when 'G' then 'M'
when 'L' then 'F'
else
'No gender'
end
as gender 
from contacts

How to create User/Database in script for Docker Postgres

You need to have the database running before you create the users. For this you need multiple processes. You can either start postgres in a subshell (&) in the shell script, or use a tool like supervisord to run postgres and then run any initialization scripts.

A guide to supervisord and docker https://docs.docker.com/articles/using_supervisord/

Inserting a blank table row with a smaller height

Just add the CSS rule (and the slightly improved mark-up) posted below and you should get the result that you're after.

CSS

.blank_row
{
    height: 10px !important; /* overwrites any other rules */
    background-color: #FFFFFF;
}

HTML

<tr class="blank_row">
    <td colspan="3"></td>
</tr>

Since I have no idea what your current stylesheet looks like I added the !important property just in case. If possible, though, you should remove it as one rarely wants to rely on !important declarations in a stylesheet considering the big possibility that they will mess it up later on.

Download file from an ASP.NET Web API method using AngularJS

Support for downloading binary files in using ajax is not great, it is very much still under development as working drafts.

Simple download method:

You can have the browser download the requested file simply by using the code below, and this is supported in all browsers, and will obviously trigger the WebApi request just the same.

$scope.downloadFile = function(downloadPath) { 
    window.open(downloadPath, '_blank', '');  
}

Ajax binary download method:

Using ajax to download the binary file can be done in some browsers and below is an implementation that will work in the latest flavours of Chrome, Internet Explorer, FireFox and Safari.

It uses an arraybuffer response type, which is then converted into a JavaScript blob, which is then either presented to save using the saveBlob method - though this is only currently present in Internet Explorer - or turned into a blob data URL which is opened by the browser, triggering the download dialog if the mime type is supported for viewing in the browser.

Internet Explorer 11 Support (Fixed)

Note: Internet Explorer 11 did not like using the msSaveBlob function if it had been aliased - perhaps a security feature, but more likely a flaw, So using var saveBlob = navigator.msSaveBlob || navigator.webkitSaveBlob ... etc. to determine the available saveBlob support caused an exception; hence why the code below now tests for navigator.msSaveBlob separately. Thanks? Microsoft

// Based on an implementation here: web.student.tuwien.ac.at/~e0427417/jsdownload.html
$scope.downloadFile = function(httpPath) {
    // Use an arraybuffer
    $http.get(httpPath, { responseType: 'arraybuffer' })
    .success( function(data, status, headers) {

        var octetStreamMime = 'application/octet-stream';
        var success = false;

        // Get the headers
        headers = headers();

        // Get the filename from the x-filename header or default to "download.bin"
        var filename = headers['x-filename'] || 'download.bin';

        // Determine the content type from the header or default to "application/octet-stream"
        var contentType = headers['content-type'] || octetStreamMime;

        try
        {
            // Try using msSaveBlob if supported
            console.log("Trying saveBlob method ...");
            var blob = new Blob([data], { type: contentType });
            if(navigator.msSaveBlob)
                navigator.msSaveBlob(blob, filename);
            else {
                // Try using other saveBlob implementations, if available
                var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob;
                if(saveBlob === undefined) throw "Not supported";
                saveBlob(blob, filename);
            }
            console.log("saveBlob succeeded");
            success = true;
        } catch(ex)
        {
            console.log("saveBlob method failed with the following exception:");
            console.log(ex);
        }

        if(!success)
        {
            // Get the blob url creator
            var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
            if(urlCreator)
            {
                // Try to use a download link
                var link = document.createElement('a');
                if('download' in link)
                {
                    // Try to simulate a click
                    try
                    {
                        // Prepare a blob URL
                        console.log("Trying download link method with simulated click ...");
                        var blob = new Blob([data], { type: contentType });
                        var url = urlCreator.createObjectURL(blob);
                        link.setAttribute('href', url);

                        // Set the download attribute (Supported in Chrome 14+ / Firefox 20+)
                        link.setAttribute("download", filename);

                        // Simulate clicking the download link
                        var event = document.createEvent('MouseEvents');
                        event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
                        link.dispatchEvent(event);
                        console.log("Download link method with simulated click succeeded");
                        success = true;

                    } catch(ex) {
                        console.log("Download link method with simulated click failed with the following exception:");
                        console.log(ex);
                    }
                }

                if(!success)
                {
                    // Fallback to window.location method
                    try
                    {
                        // Prepare a blob URL
                        // Use application/octet-stream when using window.location to force download
                        console.log("Trying download link method with window.location ...");
                        var blob = new Blob([data], { type: octetStreamMime });
                        var url = urlCreator.createObjectURL(blob);
                        window.location = url;
                        console.log("Download link method with window.location succeeded");
                        success = true;
                    } catch(ex) {
                        console.log("Download link method with window.location failed with the following exception:");
                        console.log(ex);
                    }
                }

            }
        }

        if(!success)
        {
            // Fallback to window.open method
            console.log("No methods worked for saving the arraybuffer, using last resort window.open");
            window.open(httpPath, '_blank', '');
        }
    })
    .error(function(data, status) {
        console.log("Request failed with status: " + status);

        // Optionally write the error out to scope
        $scope.errorDetails = "Request failed with status: " + status;
    });
};

Usage:

var downloadPath = "/files/instructions.pdf";
$scope.downloadFile(downloadPath);

Notes:

You should modify your WebApi method to return the following headers:

  • I have used the x-filename header to send the filename. This is a custom header for convenience, you could however extract the filename from the content-disposition header using regular expressions.

  • You should set the content-type mime header for your response too, so the browser knows the data format.

I hope this helps.

How to read all of Inputstream in Server Socket JAVA

The problem you have is related to TCP streaming nature.

The fact that you sent 100 Bytes (for example) from the server doesn't mean you will read 100 Bytes in the client the first time you read. Maybe the bytes sent from the server arrive in several TCP segments to the client.

You need to implement a loop in which you read until the whole message was received. Let me provide an example with DataInputStream instead of BufferedinputStream. Something very simple to give you just an example.

Let's suppose you know beforehand the server is to send 100 Bytes of data.

In client you need to write:

byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";

try 
{
    DataInputStream in = new DataInputStream(clientSocket.getInputStream());

    while(!end)
    {
        int bytesRead = in.read(messageByte);
        dataString += new String(messageByte, 0, bytesRead);
        if (dataString.length == 100)
        {
            end = true;
        }
    }
    System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
    e.printStackTrace();
}

Now, typically the data size sent by one node (the server here) is not known beforehand. Then you need to define your own small protocol for the communication between server and client (or any two nodes) communicating with TCP.

The most common and simple is to define TLV: Type, Length, Value. So you define that every message sent form server to client comes with:

  • 1 Byte indicating type (For example, it could also be 2 or whatever).
  • 1 Byte (or whatever) for length of message
  • N Bytes for the value (N is indicated in length).

So you know you have to receive a minimum of 2 Bytes and with the second Byte you know how many following Bytes you need to read.

This is just a suggestion of a possible protocol. You could also get rid of "Type".

So it would be something like:

byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";

try 
{
    DataInputStream in = new DataInputStream(clientSocket.getInputStream());
    int bytesRead = 0;

    messageByte[0] = in.readByte();
    messageByte[1] = in.readByte();

    int bytesToRead = messageByte[1];

    while(!end)
    {
        bytesRead = in.read(messageByte);
        dataString += new String(messageByte, 0, bytesRead);
        if (dataString.length == bytesToRead )
        {
            end = true;
        }
    }
    System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
    e.printStackTrace();
}

The following code compiles and looks better. It assumes the first two bytes providing the length arrive in binary format, in network endianship (big endian). No focus on different encoding types for the rest of the message.

import java.nio.ByteBuffer;
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;

class Test
{
    public static void main(String[] args)
    {
        byte[] messageByte = new byte[1000];
        boolean end = false;
        String dataString = "";

        try 
        {
            Socket clientSocket;
            ServerSocket server;

            server = new ServerSocket(30501, 100);
            clientSocket = server.accept();

            DataInputStream in = new DataInputStream(clientSocket.getInputStream());
            int bytesRead = 0;

            messageByte[0] = in.readByte();
            messageByte[1] = in.readByte();
            ByteBuffer byteBuffer = ByteBuffer.wrap(messageByte, 0, 2);

            int bytesToRead = byteBuffer.getShort();
            System.out.println("About to read " + bytesToRead + " octets");

            //The following code shows in detail how to read from a TCP socket

            while(!end)
            {
                bytesRead = in.read(messageByte);
                dataString += new String(messageByte, 0, bytesRead);
                if (dataString.length() == bytesToRead )
                {
                    end = true;
                }
            }

            //All the code in the loop can be replaced by these two lines
            //in.readFully(messageByte, 0, bytesToRead);
            //dataString = new String(messageByte, 0, bytesToRead);

            System.out.println("MESSAGE: " + dataString);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

JavaScript/jQuery: replace part of string?

You need to set the text after the replace call:

_x000D_
_x000D_
$('.element span').each(function() {_x000D_
  console.log($(this).text());_x000D_
  var text = $(this).text().replace('N/A, ', '');_x000D_
  $(this).text(text);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="element">_x000D_
  <span>N/A, Category</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Here's another cool way you can do it (hat tip @Felix King):

$(".element span").text(function(index, text) {
    return text.replace("N/A, ", "");
});

Best way to simulate "group by" from bash?

The canonical solution is the one mentioned by another respondent:

sort | uniq -c

It is shorter and more concise than what can be written in Perl or awk.

You write that you don't want to use sort, because the data's size is larger than the machine's main memory size. Don't underestimate the implementation quality of the Unix sort command. Sort was used to handle very large volumes of data (think the original AT&T's billing data) on machines with 128k (that's 131,072 bytes) of memory (PDP-11). When sort encounters more data than a preset limit (often tuned close to the size of the machine's main memory) it sorts the data it has read in main memory and writes it into a temporary file. It then repeats the action with the next chunks of data. Finally, it performs a merge sort on those intermediate files. This allows sort to work on data many times larger than the machine's main memory.

Open and write data to text file using Bash?

this is my answer. $ cat file > copy_file

Add CSS to <head> with JavaScript?

Here's a simple way.

/**
 * Add css to the document
 * @param {string} css
 */
function addCssToDocument(css){
  var style = document.createElement('style')
  style.innerText = css
  document.head.appendChild(style)
}

ADB Driver and Windows 8.1

The most complete answer I have found is here: http://blog.kikicode.com/2013/10/installing-android-adb-driver-in.html

I'm copying the complete answer below.


Installing Android ADB driver in Windows 8.1 64-bit when all else fails

For some reason I just couldn't get my machine to recognize Xperia J in Windows 8.1 64-bit. Even after installing latest Sony PC Companion (2.10.174). Device Manager kept showing yellow exclamation mark to an 'Android'.

Here's the solution, but I don't promise it will work on your device!

1. Find out your device's VID and PID

Open Device Manager, right-click that Android with yellow exclamation mark and click Properties. Go to Details tab. In Property, select Hardware Ids. Right-click the value and click Copy. Paste the value somewhere.

2. Download Android USB Driver

Run Android SDK Manager. Expand Extras, tick Google USB Driver, click Install packages. After installation, look for the driver location by hovering mouse over Google USB Driver. The location will appear in the tooltip.

3. Modify android_winusb.inf

Go to the usb driver location, for example in the above picture it is c:\Android\android-studio\sdk\extras\google\usb_driver Make a backup copy of android_winusb.inf Open android_winusb.inf with a text editor. Notepad is fine but Notepad++ is better, it will syntax highlight the inf file! Look for [Google.NTx86], and insert a line with your device's hardware ID that you copied above, for example

[Google.NTx86]

; ... other existing lines

;SONY Sony Xperia J
%CompositeAdbInterface% = USB_Install, USB\VID_0FCE&PID_6188&MI_01

Look for [Google.NTamd86], and insert the same lines, for example:

[Google.NTamd64]

; ... other existing lines

;SONY Sony Xperia J
%CompositeAdbInterface% = USB_Install, USB\VID_0FCE&PID_6188&MI_01

Save the file.

4. Disable driver signing

Run Command Prompt as an administrator Paste and run the following commands:

bcdedit -set loadoptions DISABLE_INTEGRITY_CHECKS
bcdedit -set TESTSIGNING ON

Restart Windows.

5. Install driver

Open Device Manager, right-click that Android with yellow exclamation mark and click Update Driver Software. Click Browse my computer for driver software. Enter or browse to the folder containing android_winusb.inf, eg: C:\Android\android-studio\sdk\extras\google\usb_driver Click Next. The driver will install. Run adb devices to confirm your device is working fine.

6. Re-enable driver signing

Run Command Prompt as an administrator Paste and run the following commands:

bcdedit -set loadoptions ENABLE_INTEGRITY_CHECKS
bcdedit -set TESTSIGNING OFF

Restart Windows. Run adb devices to reconfirm!

How to force garbage collector to run?

GC.Collect();

Keep in mind, though, that the Garbage Collector might not always clean up what you expect...

rails simple_form - hidden field - create?

= f.input_field :title, as: :hidden, value: "some value"

Is also an option. Note, however, that it skips any wrapper defined for your form builder.

Parsing HTML using Python

I recommend lxml for parsing HTML. See "Parsing HTML" (on the lxml site).

In my experience Beautiful Soup messes up on some complex HTML. I believe that is because Beautiful Soup is not a parser, rather a very good string analyzer.

Extract a substring using PowerShell

PS> $a = "-----start-------Hello World------end-------"
PS> $a.substring(17, 11)
         or
PS> $a.Substring($a.IndexOf('H'), 11)

$a.Substring(argument1, argument2) --> Here argument1 = Starting position of the desired alphabet and argument2 = Length of the substring you want as output.

Here 17 is the index of the alphabet 'H' and since we want to Print till Hello World, we provide 11 as the second argument

Get ID of element that called a function

You can use 'this' in event handler:

document.getElementById("preview").onmouseover = function() {
    alert(this.id);
}

Or pass event object to handler as follows:

document.getElementById("preview").onmouseover = function(evt) {
    alert(evt.target.id);
}

It's recommended to use attachEvent(for IE < 9)/addEventListener(IE9 and other browsers) to attach events. Example above is for brevity.

function myHandler(evt) {
    alert(evt.target.id);
}

var el = document.getElementById("preview");
if (el.addEventListener){
    el.addEventListener('click', myHandler, false); 
} else if (el.attachEvent){
    el.attachEvent('onclick', myHandler);
}

Java: Unresolved compilation problem

Make sure you have removed unavailable libraries (jar files) from build path

What is this weird colon-member (" : ") syntax in the constructor?

It's an initialization list for the constructor. Instead of default constructing x, y and z and then assigning them the values received in the parameters, those members will be initialized with those values right off the bat. This may not seem terribly useful for floats, but it can be quite a timesaver with custom classes that are expensive to construct.

How to rollback everything to previous commit

If you have pushed the commits upstream...

Select the commit you would like to roll back to and reverse the changes by clicking Reverse File, Reverse Hunk or Reverse Selected Lines. Do this for all the commits after the commit you would like to roll back to also.

reverse stuff reverse commit

If you have not pushed the commits upstream...

Right click on the commit and click on Reset current branch to this commit.

reset branch to commit

How do I add my bot to a channel?

This is how I've added a bot to my channel and set up notifications:

  1. Make sure the channel is public (you can set it private later)
  2. Add administrators > Type the bot username and make it administrator
  3. Your bot will join your channel
  4. set a channel id by setting the channel url like

telegram.me/whateverIWantAndAvailable

the channel id will be @whateverIWantAndAvailable

Now set up your bot to send notifications by pusshing the messages here:

https://api.telegram.org/botTOKENOFTHEBOT/sendMessage?chat_id=@whateverIWantAndAvailable&text=Test

the message which bot will notify is: Test

I strongly suggest an urlencode of the message like

https://api.telegram.org/botTOKENOFTHEBOT/sendMessage?chat_id=@whateverIWantAndAvailable&text=Testing%20if%20this%20works

in php you can use urlencode("Test if this works"); in js you can encodeURIComponent("Test if this works");

I hope it helps

Notification bar icon turns white in Android 5 Lollipop

According to the documentation, notification icon must be white since Android 3.0 (API Level 11) :

https://developer.android.com/guide/practices/ui_guidelines/icon_design_status_bar

"Status bar icons are composed simply of white pixels on a transparent backdrop, with alpha blending used for smooth edges and internal texture where appropriate."

JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

Thanks to the talk with Sarfraz we could figure out the solution.

The problem was that I was passing an HTML element instead of its value, which is actually what I wanted to do (in fact in my php code I need that value as a foreign key for querying my cities table and filter correct entries).

So, instead of:

var data = {
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex]
};

it should be:

var data = {
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex].value
};

Note: check Jason Kulatunga's answer, it quotes JQuery doc to explain why passing an HTML element was causing troubles.

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

Here is an online converter with an article after explaining all the algorithms for color conversion.

You probably would prefer a ready-made C version but it should not be long to apply and it could help other people trying to do the same in another language or with another color space.

Is there a Java API that can create rich Word documents?

I have developed pure XML based word files in the past. I used .NET, but the language should not matter since it's truely XML. It was not the easiest thing to do (had a project that required it a couple years ago.) These do only work in Word 2007 or above - but all you need is Microsoft's white paper that describe what each tag does. You can accomplish all you want with the tags the same way as if you were using Word (of course a little more painful initially.)

Changing CSS for last <li>

If you know there are three li's in the list you're looking at, for example, you could do this:

li + li + li { /* Selects third to last li */
}

In IE6 you can use expressions:

li {
    color: expression(this.previousSibling ? 'red' : 'green'); /* 'green' if last child */
}

I would recommend using a specialized class or Javascript (not IE6 expressions), though, until the :last-child selector gets better support.

Changing project port number in Visual Studio 2013

The Visual Studio Development Server option applies only when you are running (testing) the Web project in Visual Studio. Production Web applications always run under IIS.


To specify the Web server for a Web site project

  1. In Solution Explorer, right-click the name of the Web site project for which you want to specify a Web server, and then click Property Pages.
  2. In the Property Pages dialog box, click the Start Options tab.
  3. Under Server, click Use custom server.
  4. In the Base URL box, type the URL that Visual Studio should start when running the current project.

    Note: If you specify the URL of a remote server (for example, an IIS Web application on another computer), be sure that the remote server is running at least the .NET Framework version 2.0.

To specify the Web server for a Web application project

  1. In Solution Explorer, right-click the name of the Web application project for which you want to specify a Web server, and then click Properties.
  2. In the Properties window, click the Web tab.
  3. Under Servers, click Use Visual Studio Development Server or Use Local IIS Web server or Use Custom Web server.
  4. If you clicked Local IIS Web server or Use Custom Web Server, in the Base URL box, type the URL that Visual Studio should start when running the current project.

    Note: If you clicked Use Custom Web Server and specify the URL of a remote server (for example, an IIS Web application on another computer), be sure that the remote server is running at least the .NET Framework version 2.0.

(Source: https://msdn.microsoft.com/en-us/library/ms178108.aspx)

SQL query to get most recent row for each instance of a given key

Both of the above answers assume that you only have one row for each user and time_stamp. Depending on the application and the granularity of your time_stamp this may not be a valid assumption. If you need to deal with ties of time_stamp for a given user, you'd need to extend one of the answers given above.

To write this in one query would require another nested sub-query - things will start getting more messy and performance may suffer.

I would have loved to have added this as a comment but I don't yet have 50 reputation so sorry for posting as a new answer!

How to make matrices in Python?

you can also use append function

b = [ ]

for x in range(0, 5):
    b.append(["O"] * 5)

def print_b(b):
    for row in b:
        print " ".join(row)

SQL to Query text in access with an apostrophe in it

Escape the apostrophe in O'Neal by writing O''Neal (two apostrophes).

Complex numbers usage in python

In python, you can put ‘j’ or ‘J’ after a number to make it imaginary, so you can write complex literals easily:

>>> 1j
1j
>>> 1J
1j
>>> 1j * 1j
(-1+0j)

The ‘j’ suffix comes from electrical engineering, where the variable ‘i’ is usually used for current. (Reasoning found here.)

The type of a complex number is complex, and you can use the type as a constructor if you prefer:

>>> complex(2,3)
(2+3j)

A complex number has some built-in accessors:

>>> z = 2+3j
>>> z.real
2.0
>>> z.imag
3.0
>>> z.conjugate()
(2-3j)

Several built-in functions support complex numbers:

>>> abs(3 + 4j)
5.0
>>> pow(3 + 4j, 2)
(-7+24j)

The standard module cmath has more functions that handle complex numbers:

>>> import cmath
>>> cmath.sin(2 + 3j)
(9.15449914691143-4.168906959966565j)

Set Locale programmatically

For those who tried everything but not not working. Please check that if you set darkmode with AppCompatDelegate.setDefaultNightMode and the system is not dark, then Configuration.setLocale will not work above Andorid 7.0.

Add this code in your every activity to solve this issue:

override fun applyOverrideConfiguration(overrideConfiguration: Configuration?) {
  if (overrideConfiguration != null) {
    val uiMode = overrideConfiguration.uiMode
    overrideConfiguration.setTo(baseContext.resources.configuration)
    overrideConfiguration.uiMode = uiMode
  }
  super.applyOverrideConfiguration(overrideConfiguration)
}

Environment Variable with Maven

in your code add:

System.getProperty("WSNSHELL_HOME")

Modify or add value property from maven command:

mvn clean test -DargLine=-DWSNSHELL_HOME=yourvalue

If you want to run it in Eclipse, add VM arguments in your Debug/Run configurations

  • Go to Run -> Run configurations
  • Select Tab Arguments
  • Add in section VM Arguments

-DWSNSHELL_HOME=yourvalue

See image example

you don't need to modify the POM

import sun.misc.BASE64Encoder results in error compiled in Eclipse

This error is because of you are importing below two classes import sun.misc.BASE64Encoder; import sun.misc.BASE64Decoder;. Maybe you are using encode and decode of that library like below.

new BASE64Encoder().encode(encVal);
newBASE64Decoder().decodeBuffer(encryptedData);

Yeah instead of sun.misc.BASE64Encoder you can import java.util.Base64 class.Now change the previous encode method as below:

encryptedData=Base64.getEncoder().encodeToString(encryptedByteArray);

Now change the previous decode method as below

byte[] base64DecodedData = Base64.getDecoder().decode(base64EncodedData);

Now everything is done , you can save your program and run. It will run without showing any error.

How to get these two divs side-by-side?

I found the below code very useful, it might help anyone who comes searching here

_x000D_
_x000D_
<html>_x000D_
<body>_x000D_
    <div style="width: 50%; height: 50%; background-color: green; float:left;">-</div>_x000D_
    <div style="width: 50%; height: 50%; background-color: blue; float:right;">-</div>_x000D_
    <div style="width: 100%; height: 50%; background-color: red; clear:both">-</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Regular vs Context Free Grammars

A grammar is context-free if all production rules have the form: A (that is, the left side of a rule can only be a single variable; the right side is unrestricted and can be any sequence of terminals and variables). We can define a grammar as a 4-tuple where V is a finite set (variables), _ is a finite set (terminals), S is the start variable, and R is a finite set of rules, each of which is a mapping V
regular grammar is either right or left linear, whereas context free grammar is basically any combination of terminals and non-terminals. hence we can say that regular grammar is a subset of context-free grammar. After these properties we can say that Context Free Languages set also contains Regular Languages set

Is it possible to forward-declare a function in Python?

Sometimes an algorithm is easiest to understand top-down, starting with the overall structure and drilling down into the details.

You can do so without forward declarations:

def main():
  make_omelet()
  eat()

def make_omelet():
  break_eggs()
  whisk()
  fry()

def break_eggs():
  for egg in carton:
    break(egg)

# ...

main()

Why use @PostConstruct?

  • because when the constructor is called, the bean is not yet initialized - i.e. no dependencies are injected. In the @PostConstruct method the bean is fully initialized and you can use the dependencies.

  • because this is the contract that guarantees that this method will be invoked only once in the bean lifecycle. It may happen (though unlikely) that a bean is instantiated multiple times by the container in its internal working, but it guarantees that @PostConstruct will be invoked only once.

How do you set the document title in React?

Since React 16.8. you can build a custom hook to do so (similar to the solution of @Shortchange):

export function useTitle(title) {
  useEffect(() => {
    const prevTitle = document.title
    document.title = title
    return () => {
      document.title = prevTitle
    }
  })
}

this can be used in any react component, e.g.:

const MyComponent = () => {
  useTitle("New Title")
  return (
    <div>
     ...
    </div>
  )
}

It will update the title as soon as the component mounts and reverts it to the previous title when it unmounts.

Display Parameter(Multi-value) in Report

Hopefully someone else finds this useful:

Using the Join is the best way to use a multi-value parameter. But what if you want to have an efficient 'Select All'? If there are 100s+ then the query will be very inefficient.

To solve this instead of using a SQL Query as is, change it to using an expression (click the Fx button top right) then build your query something like this (speech marks are necessary):

= "Select * from tProducts Where 1 = 1 " 
IIF(Parameters!ProductID.Value(0)=-1,Nothing," And ProductID In (" & Join(Parameters!ProductID.Value,"','") & ")")

In your Parameter do the following:

    SELECT -1 As ProductID, 'All' as ProductName Union All
    Select  
    tProducts.ProductID,tProducts.ProductName
    FROM
    tProducts

By building the query as an expression means you can make the SQL Statement more efficient but also handle the difficulty SQL Server has with handling values in an 'In' statement.

Alternate background colors for list items

Since you using standard HTML you will need to define separate class for and manual set the rows to the classes.

Percentage width in a RelativeLayout

You are looking for the android:layout_weight attribute. It will allow you to use percentages to define your layout.

In the following example, the left button uses 70% of the space, and the right button 30%.

<LinearLayout
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:text="left" 
        android:layout_width="0dp" 
        android:layout_height="wrap_content" 
        android:layout_weight=".70" /> 

    <Button
        android:text="right" 
        android:layout_width="0dp" 
        android:layout_height="wrap_content" 
        android:layout_weight=".30" />

</LinearLayout>

It works the same with any kind of View, you can replace the buttons with some EditText to fit your needs.

Be sure to set the layout_width to 0dp or your views may not be scaled properly.

Note that the weight sum doesn't have to equal 1, I just find it easier to read like this. You can set the first weight to 7 and the second to 3 and it will give the same result.

Python: json.loads returns items prefixing with 'u'

Everything is cool, man. The 'u' is a good thing, it indicates that the string is of type Unicode in python 2.x.

http://docs.python.org/2/howto/unicode.html#the-unicode-type

Cross-browser custom styling for file upload button

It's also easy to style the label if you are working with Bootstrap and LESS:

label {
    .btn();
    .btn-primary();

    > input[type="file"] {
        display: none;
    }
}

git push rejected

First use

git pull https://github.com/username/repository master

and then try

git push -u origin master

How to SELECT the last 10 rows of an SQL table which has no ID field?

Select from the table, use the ORDER BY __ DESC to sort in reverse order, then limit your results to 10.

SELECT * FROM big_table ORDER BY A DESC LIMIT 10

how to use php DateTime() function in Laravel 5

I didn't mean to copy the same answer, that is why I didn't accept my own answer.

Actually when I add use DateTime in top of the controller solves this problem.

What do parentheses surrounding an object/function/class declaration mean?

The first parentheses are for, if you will, order of operations. The 'result' of the set of parentheses surrounding the function definition is the function itself which, indeed, the second set of parentheses executes.

As to why it's useful, I'm not enough of a JavaScript wizard to have any idea. :P

Converts scss to css

Install Ruby-sass using below command
sudo apt-get -y update
sudo apt-get -y install ruby-full
sudo apt install ruby-sass
gem install bundler

Example
sass SCSS_FILE_PATH:CSS_FILE_PATH;

e.g sass mda/at-md-black.scss:css/at-md-black.css;

Two div blocks on same line

What I would first is make the following CSS code:

#bloc1 {
   float: left
}

This will make #bloc2 be inline with #bloc1.

To make it central, I would add #bloc1 and #bloc2 in a separate div. For example:

<style type="text/css">
    #wrapper { margin: 0 auto; }
</style>
<div id="wrapper">
    <div id="bloc1"> ... </div>
    <div id="bloc2"> ... </div>
</div>

Disable text input history

<input type="text" autocomplete="off"/>

Should work. Alternatively, use:

<form autocomplete="off" … >

for the entire form (see this related question).

JSON and escaping characters

hmm, well here's a workaround anyway:

function JSON_stringify(s, emit_unicode)
{
   var json = JSON.stringify(s);
   return emit_unicode ? json : json.replace(/[\u007f-\uffff]/g,
      function(c) { 
        return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
      }
   );
}

test case:

js>s='15\u00f8C 3\u0111';
15°C 3?
js>JSON_stringify(s, true)
"15°C 3?"
js>JSON_stringify(s, false)
"15\u00f8C 3\u0111"

How to convert a DataFrame back to normal RDD in pyspark?

Use the method .rdd like this:

rdd = df.rdd

How can I clear the NuGet package cache using the command line?

dotnet nuget locals all --clear

If you're using .NET Core.

WaitAll vs WhenAll

Task.WaitAll blocks the current thread until everything has completed.

Task.WhenAll returns a task which represents the action of waiting until everything has completed.

That means that from an async method, you can use:

await Task.WhenAll(tasks);

... which means your method will continue when everything's completed, but you won't tie up a thread to just hang around until that time.

What is the most compatible way to install python modules on a Mac?

If you use Python from MacPorts, it has it's own easy_install located at: /opt/local/bin/easy_install-2.6 (for py26, that is). It's not the same one as simply calling easy_install directly, even if you used python_select to change your default python command.

Start and stop a timer PHP

For your purpose, this simple class should be all you need:

class Timer {
    private $time = null;
    public function __construct() {
        $this->time = time();
        echo 'Working - please wait..<br/>';
    }

    public function __destruct() {
        echo '<br/>Job finished in '.(time()-$this->time).' seconds.';
    }
}


$t = new Timer(); // echoes "Working, please wait.."

[some operations]

unset($t);  // echoes "Job finished in n seconds." n = seconds elapsed

What is the purpose of the word 'self'?

I would say for Python at least, the self parameter can be thought of as a placeholder. Take a look at this:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)

Self in this case and a lot of others was used as a method to say store the name value. However, after that, we use the p1 to assign it to the class we're using. Then when we print it we use the same p1 keyword.

Hope this helps for Python!

How to create a laravel hashed password

ok, this is a extract from the make function in hash.php

    $work = str_pad(8, 2, '0', STR_PAD_LEFT);

    // Bcrypt expects the salt to be 22 base64 encoded characters including
    // dots and slashes. We will get rid of the plus signs included in the
    // base64 data and replace them with dots.
    if (function_exists('openssl_random_pseudo_bytes'))
    {
        $salt = openssl_random_pseudo_bytes(16);
    }
    else
    {
        $salt = Str::random(40);
    }

    $salt = substr(strtr(base64_encode($salt), '+', '.'), 0 , 22);

    echo crypt('yourpassword', '$2a$'.$work.'$'.$salt);

Just copy/paste it into a php file and run it.

ImportError: No module named Crypto.Cipher

I solve this problem by change the first letter case to upper. Make sure ''from Crypto.Cipher import AES'' not ''from crypto.Cipher import AES''.

Can I create a One-Time-Use Function in a Script or Stored Procedure?

You can call CREATE Function near the beginning of your script and DROP Function near the end.

How can I verify a Google authentication API access token?

I need to somehow query Google and ask: Is this access token valid for [email protected]?

No. All you need is request standard login with Federated Login for Google Account Users from your API domain. And only after that you could compare "persistent user ID" with one you have from 'public interface'.

The value of realm is used on the Google Federated Login page to identify the requesting site to the user. It is also used to determine the value of the persistent user ID returned by Google.

So you need be from same domain as 'public interface'.

And do not forget that user needs to be sure that your API could be trusted ;) So Google will ask user if it allows you to check for his identity.

Difference between two dates in years, months, days in JavaScript

Time span in full Days, Hours, Minutes, Seconds, Milliseconds:

// Extension for Date
Date.difference = function (dateFrom, dateTo) {
  var diff = { TotalMs: dateTo - dateFrom };
  diff.Days = Math.floor(diff.TotalMs / 86400000);

  var remHrs = diff.TotalMs % 86400000;
  var remMin = remHrs % 3600000;
  var remS   = remMin % 60000;

  diff.Hours        = Math.floor(remHrs / 3600000);
  diff.Minutes      = Math.floor(remMin / 60000);
  diff.Seconds      = Math.floor(remS   / 1000);
  diff.Milliseconds = Math.floor(remS % 1000);
  return diff;
};

// Usage
var a = new Date(2014, 05, 12, 00, 5, 45, 30); //a: Thu Jun 12 2014 00:05:45 GMT+0400 
var b = new Date(2014, 02, 12, 00, 0, 25, 0);  //b: Wed Mar 12 2014 00:00:25 GMT+0400
var diff = Date.difference(b, a);
/* diff: {
  Days: 92
  Hours: 0
  Minutes: 5
  Seconds: 20
  Milliseconds: 30
  TotalMs: 7949120030
} */

Browse for a directory in C#

or even more better, you can put this code in a class file

using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows.Forms;

internal class OpenFolderDialog : IDisposable {

    /// <summary>
    /// Gets/sets folder in which dialog will be open.
    /// </summary>
    public string InitialFolder { get; set; }

    /// <summary>
    /// Gets/sets directory in which dialog will be open if there is no recent directory available.
    /// </summary>
    public string DefaultFolder { get; set; }

    /// <summary>
    /// Gets selected folder.
    /// </summary>
    public string Folder { get; private set; }


    internal DialogResult ShowDialog(IWin32Window owner) {
        if (Environment.OSVersion.Version.Major >= 6) {
            return ShowVistaDialog(owner);
        } else {
            return ShowLegacyDialog(owner);
        }
    }

    private DialogResult ShowVistaDialog(IWin32Window owner) {
        var frm = (NativeMethods.IFileDialog)(new NativeMethods.FileOpenDialogRCW());
        uint options;
        frm.GetOptions(out options);
        options |= NativeMethods.FOS_PICKFOLDERS | NativeMethods.FOS_FORCEFILESYSTEM | NativeMethods.FOS_NOVALIDATE | NativeMethods.FOS_NOTESTFILECREATE | NativeMethods.FOS_DONTADDTORECENT;
        frm.SetOptions(options);
        if (this.InitialFolder != null) {
            NativeMethods.IShellItem directoryShellItem;
            var riid = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"); //IShellItem
            if (NativeMethods.SHCreateItemFromParsingName(this.InitialFolder, IntPtr.Zero, ref riid, out directoryShellItem) == NativeMethods.S_OK) {
                frm.SetFolder(directoryShellItem);
            }
        }
        if (this.DefaultFolder != null) {
            NativeMethods.IShellItem directoryShellItem;
            var riid = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"); //IShellItem
            if (NativeMethods.SHCreateItemFromParsingName(this.DefaultFolder, IntPtr.Zero, ref riid, out directoryShellItem) == NativeMethods.S_OK) {
                frm.SetDefaultFolder(directoryShellItem);
            }
        }

        if (frm.Show(owner.Handle) == NativeMethods.S_OK) {
            NativeMethods.IShellItem shellItem;
            if (frm.GetResult(out shellItem) == NativeMethods.S_OK) {
                IntPtr pszString;
                if (shellItem.GetDisplayName(NativeMethods.SIGDN_FILESYSPATH, out pszString) == NativeMethods.S_OK) {
                    if (pszString != IntPtr.Zero) {
                        try {
                            this.Folder = Marshal.PtrToStringAuto(pszString);
                            return DialogResult.OK;
                        } finally {
                            Marshal.FreeCoTaskMem(pszString);
                        }
                    }
                }
            }
        }
        return DialogResult.Cancel;
    }

    private DialogResult ShowLegacyDialog(IWin32Window owner) {
        using (var frm = new SaveFileDialog()) {
            frm.CheckFileExists = false;
            frm.CheckPathExists = true;
            frm.CreatePrompt = false;
            frm.Filter = "|" + Guid.Empty.ToString();
            frm.FileName = "any";
            if (this.InitialFolder != null) { frm.InitialDirectory = this.InitialFolder; }
            frm.OverwritePrompt = false;
            frm.Title = "Select Folder";
            frm.ValidateNames = false;
            if (frm.ShowDialog(owner) == DialogResult.OK) {
                this.Folder = Path.GetDirectoryName(frm.FileName);
                return DialogResult.OK;
            } else {
                return DialogResult.Cancel;
            }
        }
    }


    public void Dispose() { } //just to have possibility of Using statement.

}

internal static class NativeMethods {

    #region Constants

    public const uint FOS_PICKFOLDERS = 0x00000020;
    public const uint FOS_FORCEFILESYSTEM = 0x00000040;
    public const uint FOS_NOVALIDATE = 0x00000100;
    public const uint FOS_NOTESTFILECREATE = 0x00010000;
    public const uint FOS_DONTADDTORECENT = 0x02000000;

    public const uint S_OK = 0x0000;

    public const uint SIGDN_FILESYSPATH = 0x80058000;

    #endregion


    #region COM

    [ComImport, ClassInterface(ClassInterfaceType.None), TypeLibType(TypeLibTypeFlags.FCanCreate), Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")]
    internal class FileOpenDialogRCW { }


    [ComImport(), Guid("42F85136-DB7E-439C-85F1-E4075D135FC8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    internal interface IFileDialog {
        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        [PreserveSig()]
        uint Show([In, Optional] IntPtr hwndOwner); //IModalWindow 


        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFileTypes([In] uint cFileTypes, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr rgFilterSpec);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFileTypeIndex([In] uint iFileType);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetFileTypeIndex(out uint piFileType);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint Advise([In, MarshalAs(UnmanagedType.Interface)] IntPtr pfde, out uint pdwCookie);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint Unadvise([In] uint dwCookie);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetOptions([In] uint fos);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetOptions(out uint fos);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        void SetDefaultFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetFolder([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetCurrentSelection([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFileName([In, MarshalAs(UnmanagedType.LPWStr)] string pszName);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetTitle([In, MarshalAs(UnmanagedType.LPWStr)] string pszTitle);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetOkButtonLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszText);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFileNameLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetResult([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint AddPlace([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, uint fdap);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetDefaultExtension([In, MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint Close([MarshalAs(UnmanagedType.Error)] uint hr);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetClientGuid([In] ref Guid guid);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint ClearClientData();

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFilter([MarshalAs(UnmanagedType.Interface)] IntPtr pFilter);
    }


    [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    internal interface IShellItem {
        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint BindToHandler([In] IntPtr pbc, [In] ref Guid rbhid, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IntPtr ppvOut);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetParent([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetDisplayName([In] uint sigdnName, out IntPtr ppszName);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetAttributes([In] uint sfgaoMask, out uint psfgaoAttribs);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint Compare([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In] uint hint, out int piOrder);
    }

    #endregion


    [DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    internal static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv);

}

And use it like this

using (var frm = new OpenFolderDialog()) {
                if (frm.ShowDialog(this)== DialogResult.OK) {
                    MessageBox.Show(this, frm.Folder);
                }
            }

Regular expression for checking if capital letters are found consecutively in a string?

Aside from tchrists excellent post concerning unicode, I think you don't need the complex solution with a negative lookahead... Your definition requires an Uppercase-letter followed by at least one group of (a lowercase letter optionally followed by an Uppercase-letter)

^
[A-Z]    // Start with an uppercase Letter
(        // A Group of:
  [a-z]  // mandatory lowercase letter
  [A-Z]? // an optional Uppercase Letter at the end
         // or in between lowercase letters
)+       // This group at least one time
$

Just a bit more compact and easier to read I think...

What does \u003C mean?

It is a unicode char \u003C = <

How to open a second activity on click of button in android app

From Activity : where you are currently ?

To Activity : where you want to go ?

Intent i = new Intent( MainActivity.this, SendPhotos.class); startActivity(i);

Both Activity must be included in manifest file otherwise it will not found the class file and throw Force close.

Edit your Mainactivity.java

crate button's object;

now Write code for click event.

        Button btn = (button)findViewById(R.id.button1);
         btn.LoginButton.setOnClickListener(new View.OnClickListener() 
       {

                @Override
                public void onClick(View v) 
                {
                 //put your intent code here
                }
   });

Hope it will work for you.

mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab

Besides the solution of m79lkm above, my 2 cents on this topic is not to directly pipe the result in gzip but first dump it as a .sql file, and then gzip it. (Use && instead of | )

The dump itself will be faster. (for what I tested it was double as fast)

Otherwise you tables will be locked longer and the downtime/slow-responding of your application can bother the users. The mysqldump command is taking a lot of resources from your server.

So I would go for "&& gzip" instead of "| gzip"

Important: check for free disk space first with df -h since you will need more then piping | gzip.

mysqldump -u user -p[user_password] [database_name] > dumpfilename.sql && gzip dumpfilename.sql

-> which will also result in 1 file called dumpfilename.sql.gz

Furthermore the option --single-transaction prevents the tables being locked but still result in a solid backup. So you might consider to use that option. See docs here

mysqldump --single-transaction -u user -p[user_password] [database_name] > dumpfilename.sql && gzip dumpfilename.sql

Default SecurityProtocol in .NET 4.5

Create a text file with a .reg extension and the following contents:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

Or download it from the following source:

https://tls1test.salesforce.com/s/NET40-Enable-TLS-1_2.reg

Double-click to install...

How to get the mobile number of current sim card in real device?

Hi Actually this is my same question but I didn't get anything.Now I got mobile number and his email-Id from particular Android real device(Android Mobile).Now a days 90% people using what's App application on Android Mobile.And now I am getting Mobile no and email-ID Through this What's app API.Its very simple to use see this below code.

            AccountManager am = AccountManager.get(this);
            Account[] accounts = am.getAccounts();
      for (Account ac : accounts) 
       {
        acname = ac.name;

        if (acname.startsWith("91")) {
            mobile_no = acname;
        }else if(acname.endsWith("@gmail.com")||acname.endsWith("@yahoo.com")||acname.endsWith("@hotmail.com")){
            email = acname;
        }

        // Take your time to look at all available accounts
        Log.i("Accounts : ", "Accounts : " + acname);
    }

and import this API

    import android.accounts.Account;
    import android.accounts.AccountManager;

How to remove all the null elements inside a generic list in one go?

I do not know of any in-built method, but you could just use linq:

parameterList = parameterList.Where(x => x != null).ToList();

How do you show animated GIFs on a Windows Form (c#)

I had the same issue and came across different solutions by implementing which I used to face several different issues. Finally, below is what I put some pieces from different posts together which worked for me as expected.

private void btnCompare_Click(object sender, EventArgs e)
{
    ThreadStart threadStart = new ThreadStart(Execution);
    Thread thread = new Thread(threadStart);
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
}

Here is the Execution method that also carries invoking the PictureBox control:

private void Execution()
{
    btnCompare.Invoke((MethodInvoker)delegate { pictureBox1.Visible = true; });
    Application.DoEvents();

    // Your main code comes here . . .

    btnCompare.Invoke((MethodInvoker)delegate { pictureBox1.Visible = false; });
}

Keep in mind, the PictureBox is invisible from Properties Window or do below:

private void ComparerForm_Load(object sender, EventArgs e)
{
    pictureBox1.Visible = false;
}

What is the cleanest way to disable CSS transition effects temporarily?

You can disable animation, transition, trasforms for all of element in page with this css code

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '* {' +
'/*CSS transitions*/' +
' -o-transition-property: none !important;' +
' -moz-transition-property: none !important;' +
' -ms-transition-property: none !important;' +
' -webkit-transition-property: none !important;' +
'  transition-property: none !important;' +
'/*CSS transforms*/' +
'  -o-transform: none !important;' +
' -moz-transform: none !important;' +
'   -ms-transform: none !important;' +
'  -webkit-transform: none !important;' +
'   transform: none !important;' +
'  /*CSS animations*/' +
'   -webkit-animation: none !important;' +
'   -moz-animation: none !important;' +
'   -o-animation: none !important;' +
'   -ms-animation: none !important;' +
'   animation: none !important;}';
   document.getElementsByTagName('head')[0].appendChild(style);

Set transparent background of an imageview on Android

Use the following for complete transparency:

#00000000

When I tried with #80000000 I got a black transparent overlay which I don't want. Try to change the first two digits; it controls the level of transparency, like

#00000000
#10000000
#20000000
#30000000

Difference between JSONObject and JSONArray

When a JSON start's with {} it is a ObjectJSON object and when it start's with [] it is an Array JOSN Array

An JSON array can consist of a/many objects and that is called an array of objects

How to check string length with JavaScript

The quick and dirty way would be to simple bind to the keyup event.

_x000D_
_x000D_
$('#mytxt').keyup(function(){_x000D_
    $('#divlen').text('you typed ' + this.value.length + ' characters');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input type=text id=mytxt >_x000D_
<div id=divlen></div>
_x000D_
_x000D_
_x000D_

But better would be to bind a reusable function to several events. For example also to the change(), so you can also anticipate text changes such as pastes (with the context menu, shortcuts would also be caught by the keyup )

XPath Query: get attribute href from a tag

For the following HTML document:

<html>
  <body>
    <a href="http://www.example.com">Example</a> 
    <a href="http://www.stackoverflow.com">SO</a> 
  </body>
</html>

The xpath query /html/body//a/@href (or simply //a/@href) will return:

    http://www.example.com
    http://www.stackoverflow.com

To select a specific instance use /html/body//a[N]/@href,

    $ /html/body//a[2]/@href
    http://www.stackoverflow.com

To test for strings contained in the attribute and return the attribute itself place the check on the tag not on the attribute:

    $ /html/body//a[contains(@href,'example')]/@href
    http://www.example.com

Mixing the two:

    $ /html/body//a[contains(@href,'com')][2]/@href
    http://www.stackoverflow.com

Sublime Text 2 - Show file navigation in sidebar

Instead of opening a folder, try adding a folder by going to "Project" -> "Add Folder to Project..." which opens a Folder choosing dialog. This way the folder won't open in a new window and will be added to your current workspace.

If you then go to "Project" -> "Save Project As..." you can even save your current setup (cells setup, opened files, unsaved changes, etc...), this makes it easy to hotswitch between multiple projects without loosing control and unsaved changes which could be unsafe to be saved right now, but would be a loss if you just ditched them. (Just be sure to have the "hot_exit" setting set to true.)

And Ctrl + Alt + P (Linux and Windows) / Super + Ctrl + P (Mac) lets you switch between the saved projects.

This way you don't have to setup your editor every time you want to work on one of your projects.

Hint: Try http://sublime-text-unofficial-documentation.readthedocs.org/en/sublime-text-2/ which is a wonderful resource for beginners, it teaches you the ropes and shows you the power of your "new" editor, just start with the "Editing" chapter.

Bootstrap Dropdown menu is not working

For Bootstrap 4 you need an additional library. If you read your browser console, Bootstrap will actually print an error message telling you that you need it for drop down to work.

Error: Bootstrap dropdown require Popper.js (https://popper.js.org)

How do you write multiline strings in Go?

From String literals:

  • raw string literal supports multiline (but escaped characters aren't interpreted)
  • interpreted string literal interpret escaped characters, like '\n'.

But, if your multi-line string has to include a backquote (`), then you will have to use an interpreted string literal:

`line one
  line two ` +
"`" + `line three
line four`

You cannot directly put a backquote (`) in a raw string literal (``xx\).
You have to use (as explained in "how to put a backquote in a backquoted string?"):

 + "`" + ...

ASP.NET: Session.SessionID changes between requests

My issue was with a Microsoft MediaRoom IPTV application. It turns out that MPF MRML applications don't support cookies; changing to use cookieless sessions in the web.config solved my issue

<sessionState cookieless="true"  />

Here's a REALLY old article about it: Cookieless ASP.NET

Install tkinter for Python

If, like me, you don't have root privileges on your network because of your wonderful friends in I.S., and you are working in a local install you may have some problems with the above approaches.

I spent ages on Google - but in the end, it's easy.

Download the tcl and tk from http://www.tcl.tk/software/tcltk/download.html and install them locally too.

To install locally on Linux (I did it to my home directory), extract the .tar.gz files for tcl and tk. Then open up the readme files inside the ./unix directory. I ran

cd ~/tcl8.5.11/unix
./configure --prefix=/home/cnel711 --exec-prefix=/home/cnel711
make
make install

cd ~/tk8.5.11/unix
./configure --prefix=/home/cnel711 --exec-prefix=/home/cnel711 --with-tcl=/home/cnel711/tcl8.5.11/unix
make
make install

It may seem a pain, but the files are tiny and installation is very fast.

Then re-run python setup.py build and python setup.py install in your python installation directory - and it should work. It worked for me - and I can now import Tkinter etc to my heart's content - yipidy-yay. An entire afternoon spent on this - hope this note saves others from the pain.

jQuery convert line breaks to br (nl2br equivalent)

Another way to insert text from a textarea in the DOM keeping the line breaks is to use the Node.innerText property that represents the rendered text content of a node and its descendants.

As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied to the clipboard.

The property became standard in 2016 and is well supported by modern browsers. Can I Use: 97% global coverage when I posted this answer.

Rounded corner for textview in android

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="5dp" />
            <solid android:color="#ffffff"/>

        </shape>
    </item>
</layer-list>

How do I set log4j level on the command line?

log4j does not support this directly.

As you do not want a configuration file, you most likely use programmatic configuration. I would suggest that you look into scanning all the system properties, and explicitly program what you want based on this.

When should I use h:outputLink instead of h:commandLink?

The <h:outputLink> renders a fullworthy HTML <a> element with the proper URL in the href attribute which fires a bookmarkable GET request. It cannot directly invoke a managed bean action method.

<h:outputLink value="destination.xhtml">link text</h:outputLink>

The <h:commandLink> renders a HTML <a> element with an onclick script which submits a (hidden) POST form and can invoke a managed bean action method. It's also required to be placed inside a <h:form>.

<h:form>
    <h:commandLink value="link text" action="destination" />
</h:form>

The ?faces-redirect=true parameter on the <h:commandLink>, which triggers a redirect after the POST (as per the Post-Redirect-Get pattern), only improves bookmarkability of the target page when the link is actually clicked (the URL won't be "one behind" anymore), but it doesn't change the href of the <a> element to be a fullworthy URL. It still remains #.

<h:form>
    <h:commandLink value="link text" action="destination?faces-redirect=true" />
</h:form>

Since JSF 2.0, there's also the <h:link> which can take a view ID (a navigation case outcome) instead of an URL. It will generate a HTML <a> element as well with the proper URL in href.

<h:link value="link text" outcome="destination" />

So, if it's for pure and bookmarkable page-to-page navigation like the SO username link, then use <h:outputLink> or <h:link>. That's also better for SEO since bots usually doesn't cipher POST forms nor JS code. Also, UX will be improved as the pages are now bookmarkable and the URL is not "one behind" anymore.

When necessary, you can do the preprocessing job in the constructor or @PostConstruct of a @RequestScoped or @ViewScoped @ManagedBean which is attached to the destination page in question. You can make use of @ManagedProperty or <f:viewParam> to set GET parameters as bean properties.

See also:

Multiple rows to one comma-separated value in Sql Server

Test Data

DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)

Query

SELECT  ID
       ,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
         FROM @Table1 
         WHERE ID = t.ID
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

SQL Server 2017 and Later Versions

If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:

DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);


SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

Combine two OR-queries with AND in Mongoose

It's probably easiest to create your query object directly as:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

How to check if an item is selected from an HTML drop down list?

<script>
var card = document.getElementById("cardtype");
if(card.selectedIndex == 0) {
     alert('select one answer');
}
else {
    var selectedText = card.options[card.selectedIndex].text;
    alert(selectedText);
}
</script>

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

This happened for me when my ajax was replacing contents on the page and ending up with two elements the same class for the dialog which meant when my line to close the dialog executed based on the CSS class selector, it found two elements not one and the second one had never been initialised.

$(".dialogClass").dialog("close"); //This line was expecting to find one element but found two where the second had not been initialised.

For anyone on ASP.NET MVC this occured because my controller action was returning a full view including the shared layout page which had the element when it should have been returning a partial view since the javascript was replacing only the main content area.

Double precision floating values in Python?

For some applications you can use Fraction instead of floating-point numbers.

>>> from fractions import Fraction
>>> Fraction(1, 3**54)
Fraction(1, 58149737003040059690390169)

(For other applications, there's decimal, as suggested out by the other responses.)

How to use operator '-replace' in PowerShell to replace strings of texts with special characters and replace successfully

'-replace' does a regex search and you have special characters in that last one (like +) So you might use the non-regex replace version like this:

$c = $c.replace('AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA==')

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

  1. mysql -u root -p
  2. UPDATE mysql.user SET Password=PASSWORD('mypass') WHERE User='root';
  3. Flush the privileges: FLUSH PRIVILEGES;
  4. Exit by typing: Exit
  5. Edited line in the file config.inc.php with the new root password: $cfg['Servers'][$i]['password'] = 'mypass'

  6. be succss

How can I set the font-family & font-size inside of a div?

Append a semicolon to the following line to fix the issue.

font-family:    Arial, Helvetica, sans-serif;

Add comma to numbers every three digits

2016 Answer:

Javascript has this function, so no need for Jquery.

yournumber.toLocaleString("en");

Token Authentication vs. Cookies

Http is stateless. In order to authorize you, you have to "sign" every single request you're sending to server.

Token authentication

  • A request to the server is signed by a "token" - usually it means setting specific http headers, however, they can be sent in any part of the http request (POST body, etc.)

  • Pros:

    • You can authorize only the requests you wish to authorize. (Cookies - even the authorization cookie are sent for every single request.)
    • Immune to XSRF (Short example of XSRF - I'll send you a link in email that will look like <img src="http://bank.com?withdraw=1000&to=myself" />, and if you're logged in via cookie authentication to bank.com, and bank.com doesn't have any means of XSRF protection, I'll withdraw money from your account simply by the fact that your browser will trigger an authorized GET request to that url.) Note there are anti forgery measure you can do with cookie-based authentication - but you have to implement those.
    • Cookies are bound to a single domain. A cookie created on the domain foo.com can't be read by the domain bar.com, while you can send tokens to any domain you like. This is especially useful for single page applications that are consuming multiple services that are requiring authorization - so I can have a web app on the domain myapp.com that can make authorized client-side requests to myservice1.com and to myservice2.com.
  • Cons:
    • You have to store the token somewhere; while cookies are stored "out of the box". The locations that comes to mind are localStorage (con: the token is persisted even after you close browser window), sessionStorage (pro: the token is discarded after you close browser window, con: opening a link in a new tab will render that tab anonymous) and cookies (Pro: the token is discarded after you close the browser window. If you use a session cookie you will be authenticated when opening a link in a new tab, and you're immune to XSRF since you're ignoring the cookie for authentication, you're just using it as token storage. Con: cookies are sent out for every single request. If this cookie is not marked as https only, you're open to man in the middle attacks.)
    • It is slightly easier to do XSS attack against token based authentication (i.e. if I'm able to run an injected script on your site, I can steal your token; however, cookie based authentication is not a silver bullet either - while cookies marked as http-only can't be read by the client, the client can still make requests on your behalf that will automatically include the authorization cookie.)
    • Requests to download a file, which is supposed to work only for authorized users, requires you to use File API. The same request works out of the box for cookie-based authentication.

Cookie authentication

  • A request to the server is always signed in by authorization cookie.
  • Pros:
    • Cookies can be marked as "http-only" which makes them impossible to be read on the client side. This is better for XSS-attack protection.
    • Comes out of the box - you don't have to implement any code on the client side.
  • Cons:
    • Bound to a single domain. (So if you have a single page application that makes requests to multiple services, you can end up doing crazy stuff like a reverse proxy.)
    • Vulnerable to XSRF. You have to implement extra measures to make your site protected against cross site request forgery.
    • Are sent out for every single request, (even for requests that don't require authentication).

Overall, I'd say tokens give you better flexibility, (since you're not bound to single domain). The downside is you have to do quite some coding by yourself.

Could not establish trust relationship for SSL/TLS secure channel -- SOAP

Thoughts (based on pain in the past):

  • do you have DNS and line-of-sight to the server?
  • are you using the correct name from the certificate?
  • is the certificate still valid?
  • is a badly configured load balancer messing things up?
  • does the new server machine have the clock set correctly (i.e. so that the UTC time is correct [ignore local time, it is largely irrelevent]) - this certainly matters for WCF, so may impact regular SOAP?
  • is there a certificate trust chain issue? if you browse from the server to the soap service, can you get SSL?
  • related to the above - has the certificate been installed to the correct location? (you may need a copy in Trusted Root Certification Authorities)
  • is the server's machine-level proxy set correctly? (which different to the user's proxy); see proxycfg for XP / 2003 (not sure about Vista etc)

How to access PHP session variables from jQuery function in a .js file?

You can produce the javascript file via PHP. Nothing says a javascript file must have a .js extention. For example in your HTML:

<script src='javascript.php'></script>

Then your script file:

<?php header("Content-type: application/javascript"); ?>

$(function() {
    $( "#progressbar" ).progressbar({
        value: <?php echo $_SESSION['value'] ?>
    });

    // ... more javascript ...

If this particular method isn't an option, you could put an AJAX request in your javascript file, and have the data returned as JSON from the server side script.

Difference between static and shared libraries?

A static library is like a bookstore, and a shared library is like... a library. With the former, you get your own copy of the book/function to take home; with the latter you and everyone else go to the library to use the same book/function. So anyone who wants to use the (shared) library needs to know where it is, because you have to "go get" the book/function. With a static library, the book/function is yours to own, and you keep it within your home/program, and once you have it you don't care where or when you got it.

How to get duration, as int milli's and float seconds from <chrono>?

Taking a guess at what it is you're asking for. I'm assuming by millisecond frame timer you're looking for something that acts like the following,

double mticks()
{
    struct timeval tv;
    gettimeofday(&tv, 0);
    return (double) tv.tv_usec / 1000 + tv.tv_sec * 1000;
}

but uses std::chrono instead,

double mticks()
{
    typedef std::chrono::high_resolution_clock clock;
    typedef std::chrono::duration<float, std::milli> duration;

    static clock::time_point start = clock::now();
    duration elapsed = clock::now() - start;
    return elapsed.count();
}

Hope this helps.

Best XML parser for Java

I think you should not consider any specific parser implementation. Java API for XML Processing lets you use any conforming parser implementation in a standard way. The code should be much more portable, and when you realise that a specific parser has grown too old, you can replace it with another without changing a line of your code (if you do it correctly).

Basically there are three ways of handling XML in a standard way:

  • SAX This is the simplest API. You read the XML by defining a Handler class that receives the data inside elements/attributes when the XML gets processed in a serial way. It is faster and simpler if you only plan to read some attributes/elements and/or write some values back (your case).
  • DOM This method creates an object tree which lets you modify/access it randomly so it is better for complex XML manipulation and handling.
  • StAX This is in the middle of the path between SAX and DOM. You just write code to pull the data from the parser you are interested in when it is processed.

Forget about proprietary APIs such as JDOM or Apache ones (i.e. Apache Xerces XMLSerializer) because will tie you to a specific implementation that can evolve in time or lose backwards compatibility, which will make you change your code in the future when you want to upgrade to a new version of JDOM or whatever parser you use. If you stick to Java standard API (using factories and interfaces) your code will be much more modular and maintainable.

There is no need to say that all (I haven't checked all, but I'm almost sure) of the parsers proposed comply with a JAXP implementation so technically you can use all, no matter which.

How to put labels over geom_bar in R with ggplot2

To plot text on a ggplot you use the geom_text. But I find it helpful to summarise the data first using ddply

dfl <- ddply(df, .(x), summarize, y=length(x))
str(dfl)

Since the data is pre-summarized, you need to remember to change add the stat="identity" parameter to geom_bar:

ggplot(dfl, aes(x, y=y, fill=x)) + geom_bar(stat="identity") +
    geom_text(aes(label=y), vjust=0) +
    opts(axis.text.x=theme_blank(),
        axis.ticks=theme_blank(),
        axis.title.x=theme_blank(),
        legend.title=theme_blank(),
        axis.title.y=theme_blank()
)

enter image description here

check the null terminating character in char*

To make this complete: while others now solved your problem :) I would like to give you a piece of good advice: don't reinvent the wheel.

size_t forward_length = strlen(forward);

How to take complete backup of mysql database using mysqldump command line utility

If you want to take a full backup i.e., all databases, procedures, routines, and events without interrupting any connections:

mysqldump -u [username] -p -A -R -E --triggers --single-transaction > full_backup.sql
  1. -A For all databases (you can also use --all-databases)
  2. -R For all routines (stored procedures & triggers)
  3. -E For all events
  4. --single-transaction Without locking the tables i.e., without interrupting any connection (R/W).

If you want to take a backup of only specified database(s):

mysqldump -u [username] -p [database_name] [other_database_name] -R -e --triggers --single-transaction > database_backup.sql

If you want to take a backup of only a specific table in a database:

mysqldump -u [username] -p [database_name] [table_name] > table_backup.sql

If you want to take a backup of the database structure only just add --no-data to the previous commands:

mysqldump -u [username] –p[password] –-no-data [database_name] > dump_file.sql

mysqldump has many more options, which are all documented in the mysqldump documentation or by running man mysqldump at the command line.

Typedef function pointer?

Without the typedef word, in C++ the declaration would declare a variable FunctionFunc of type pointer to function of no arguments, returning void.

With the typedef it instead defines FunctionFunc as a name for that type.

Difference between DataFrame, Dataset, and RDD in Spark

Spark RDD (resilient distributed dataset) :

RDD is the core data abstraction API and is available since very first release of Spark (Spark 1.0). It is a lower-level API for manipulating distributed collection of data. The RDD APIs exposes some extremely useful methods which can be used to get very tight control over underlying physical data structure. It is an immutable (read only) collection of partitioned data distributed on different machines. RDD enables in-memory computation on large clusters to speed up big data processing in a fault tolerant manner. To enable fault tolerance, RDD uses DAG (Directed Acyclic Graph) which consists of a set of vertices and edges. The vertices and edges in DAG represent the RDD and the operation to be applied on that RDD respectively. The transformations defined on RDD are lazy and executes only when an action is called

Spark DataFrame :

Spark 1.3 introduced two new data abstraction APIs – DataFrame and DataSet. The DataFrame APIs organizes the data into named columns like a table in relational database. It enables programmers to define schema on a distributed collection of data. Each row in a DataFrame is of object type row. Like an SQL table, each column must have same number of rows in a DataFrame. In short, DataFrame is lazily evaluated plan which specifies the operations needs to be performed on the distributed collection of the data. DataFrame is also an immutable collection.

Spark DataSet :

As an extension to the DataFrame APIs, Spark 1.3 also introduced DataSet APIs which provides strictly typed and object-oriented programming interface in Spark. It is immutable, type-safe collection of distributed data. Like DataFrame, DataSet APIs also uses Catalyst engine in order to enable execution optimization. DataSet is an extension to the DataFrame APIs.

Other Differences -

enter image description here

Difference between Encapsulation and Abstraction

Encapsulate hides variables or some implementation that may be changed so often in a class to prevent outsiders access it directly. They must access it via getter and setter methods.

Abstraction is used to hiding something too but in a higher degree(class, interface). Clients use an abstract class(or interface) do not care about who or which it was, they just need to know what it can do.

Get current directory name (without full path) in a Bash script

There are a lots way of doing that I particularly liked Charles way because it avoid a new process, but before know this I solved it with awk

pwd | awk -F/ '{print $NF}'

How to efficiently count the number of keys/properties of an object in JavaScript?

If you are using Underscore.js you can use _.size (thanks @douwe):
_.size(obj)

Alternatively you can also use _.keys which might be clearer for some:
_.keys(obj).length

I highly recommend Underscore, its a tight library for doing lots of basic things. Whenever possible they match ECMA5 and defer to the native implementation.

Otherwise I support @Avi's answer. I edited it to add a link to the MDC doc which includes the keys() method you can add to non-ECMA5 browsers.

How to correct TypeError: Unicode-objects must be encoded before hashing?

It is probably looking for a character encoding from wordlistfile.

wordlistfile = open(wordlist,"r",encoding='utf-8')

Or, if you're working on a line-by-line basis:

line.encode('utf-8')

EDIT

Per the comment below and this answer.

My answer above assumes that the desired output is a str from the wordlist file. If you are comfortable in working in bytes, then you're better off using open(wordlist, "rb"). But it is important to remember that your hashfile should NOT use rb if you are comparing it to the output of hexdigest. hashlib.md5(value).hashdigest() outputs a str and that cannot be directly compared with a bytes object: 'abc' != b'abc'. (There's a lot more to this topic, but I don't have the time ATM).

It should also be noted that this line:

line.replace("\n", "")

Should probably be

line.strip()

That will work for both bytes and str's. But if you decide to simply convert to bytes, then you can change the line to:

line.replace(b"\n", b"")

Viewing unpushed Git commits

I had a commit done previously, not pushed to any branch, nor remote nor local. Just the commit. Nothing from other answers worked for me, but with:

git reflog

There I found my commit.

How to detect iPhone 5 (widescreen devices)?

In Swift, iOS 8+ project I like to make an extension on UIScreen, like:

extension UIScreen {

    var isPhone4: Bool {
        return self.nativeBounds.size.height == 960;
    }

    var isPhone5: Bool {
        return self.nativeBounds.size.height == 1136;
    }

    var isPhone6: Bool {
        return self.nativeBounds.size.height == 1334;
    }

    var isPhone6Plus: Bool {
        return self.nativeBounds.size.height == 2208;
    }

}

(NOTE: nativeBounds is in pixels).

And then the code will be like:

if UIScreen.mainScreen().isPhone4 {
    // do smth on the smallest screen
}

So the code makes it clear that this is a check for the main screen, not for the device model.

Failed to allocate memory: 8

I change my monitor DPI settings from the launch options of AVD and synchronized it with the original and current setting of my monitor, and it worked.

How to change Vagrant 'default' machine name?

I found the multiple options confusing, so I decided to test all of them to see exactly what they do.

I'm using VirtualBox 4.2.16-r86992 and Vagrant 1.3.3.

I created a directory called nametest and ran

vagrant init precise64 http://files.vagrantup.com/precise64.box

to generate a default Vagrantfile. Then I opened the VirtualBox GUI so I could see what names the boxes I create would show up as.

  1. Default Vagrantfile

    Vagrant.configure('2') do |config|
        config.vm.box = "precise64"
        config.vm.box_url = "http://files.vagrantup.com/precise64.box"
    end
    

    VirtualBox GUI Name: "nametest_default_1386347922"

    Comments: The name defaults to the format DIRECTORY_default_TIMESTAMP.

  2. Define VM

    Vagrant.configure('2') do |config|
        config.vm.box = "precise64"
        config.vm.box_url = "http://files.vagrantup.com/precise64.box"
        config.vm.define "foohost"
    end
    

    VirtualBox GUI Name: "nametest_foohost_1386347922"

    Comments: If you explicitly define a VM, the name used replaces the token 'default'. This is the name vagrant outputs on the console. Simplifying based on zook's (commenter) input

  3. Set Provider Name

    Vagrant.configure('2') do |config|
        config.vm.box = "precise64"
        config.vm.box_url = "http://files.vagrantup.com/precise64.box"
        config.vm.provider :virtualbox do |vb|
            vb.name = "foohost"
        end
    end
    

    VirtualBox GUI Name: "foohost"

    Comments: If you set the name attribute in a provider configuration block, that name will become the entire name displayed in the VirtualBox GUI.

    Combined Example: Define VM -and- Set Provider Name

    Vagrant.configure('2') do |config|
        config.vm.box = "precise64"
        config.vm.box_url = "http://files.vagrantup.com/precise64.box"
        config.vm.define "foohost"
        config.vm.provider :virtualbox do |vb|
            vb.name = "barhost"
        end
    end
    

    VirtualBox GUI Name: "barhost"

    Comments: If you use both methods at the same time, the value assigned to name in the provider configuration block wins. Simplifying based on zook's (commenter) input

  4. Set hostname (BONUS)

    Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
      config.vm.hostname = "buzbar"
    end
    

    Comments: This sets the hostname inside the VM. This would be the output of hostname command in the VM and also this is what's visible in the prompt like vagrant@<hostname>, here it will look like vagrant@buzbar

Final Code

    Vagrant.configure('2') do |config|
        config.vm.box = "precise64"
        config.vm.box_url = "http://files.vagrantup.com/precise64.box"
        config.vm.hostname = "buzbar"
        config.vm.define "foohost"
        config.vm.provider :virtualbox do |vb|
            vb.name = "barhost"
        end
    end

So there it is. You now know 3 different options you can set and the effects they have. I guess it's a matter of preference at this point? (I'm new to Vagrant, so I can't speak to best practices yet.)

How to fix symbol lookup error: undefined symbol errors in a cluster environment

yum update

helped me out. After I had

wget: symbol lookup error: wget: undefined symbol: psl_latest

Why do we not have a virtual constructor in C++?

C++ virtual constructor is not possible.For example you can not mark a constructor as virtual.Try this code

#include<iostream.h>
using namespace std;
class aClass
{
    public:
        virtual aClass()
        {   
        }  
};
int main()
{
    aClass a; 
}

It causes an error.This code is trying to declare a constructor as virtual. Now let us try to understand why we use virtual keyword. Virtual keyword is used to provide run time polymorphism. For example try this code.

#include<iostream.h>
using namespace std;
class aClass
{
    public:
        aClass()
        {
            cout<<"aClass contructor\n";
        }
        ~aClass()
        {
            cout<<"aClass destructor\n";
        }

};
class anotherClass:public aClass
{

    public:
        anotherClass()
        {
            cout<<"anotherClass Constructor\n";
        }
        ~anotherClass()
        {
            cout<<"anotherClass destructor\n";
        }

};
int main()
{
    aClass* a;
    a=new anotherClass;
    delete a;   
    getchar(); 
}

In main a=new anotherClass; allocates a memory for anotherClass in a pointer a declared as type of aClass.This causes both the constructor (In aClass and anotherClass) to call automatically.So we do not need to mark constructor as virtual.Because when an object is created it must follow the chain of creation (i.e first the base and then the derived classes). But when we try to delete a delete a; it causes to call only the base destructor.So we have to handle the destructor using virtual keyword. So virtual constructor is not possible but virtual destructor is.Thanks

ReactJS: "Uncaught SyntaxError: Unexpected token <"

Add type="text/babel" to the script that includes the .jsx file and add this: <script src="https://npmcdn.com/[email protected]/browser.min.js"></script>

Get UTC time and local time from NSDate object

Xcode 9 • Swift 4 (also works Swift 3.x)

extension Formatter {
    // create static date formatters for your date representations
    static let preciseLocalTime: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "HH:mm:ss.SSS"
        return formatter
    }()
    static let preciseGMTTime: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.timeZone = TimeZone(secondsFromGMT: 0)
        formatter.dateFormat = "HH:mm:ss.SSS"
        return formatter
    }()
}

extension Date {
    // you can create a read-only computed property to return just the nanoseconds from your date time
    var nanosecond: Int { return Calendar.current.component(.nanosecond,  from: self)   }
    // the same for your local time
    var preciseLocalTime: String {
        return Formatter.preciseLocalTime.string(for: self) ?? ""
    }
    // or GMT time
    var preciseGMTTime: String {
        return Formatter.preciseGMTTime.string(for: self) ?? ""
    }
}

Playground testing

Date().preciseLocalTime // "09:13:17.385"  GMT-3
Date().preciseGMTTime   // "12:13:17.386"  GMT
Date().nanosecond       // 386268973

This might help you also formatting your dates:

enter image description here

why is plotting with Matplotlib so slow?

Matplotlib makes great publication-quality graphics, but is not very well optimized for speed. There are a variety of python plotting packages that are designed with speed in mind:

What is Type-safe?

Type safety means that the compiler will validate types while compiling, and throw an error if you try to assign the wrong type to a variable.

Some simple examples:

// Fails, Trying to put an integer in a string
String one = 1;
// Also fails.
int foo = "bar";

This also applies to method arguments, since you are passing explicit types to them:

int AddTwoNumbers(int a, int b)
{
    return a + b;
}

If I tried to call that using:

int Sum = AddTwoNumbers(5, "5");

The compiler would throw an error, because I am passing a string ("5"), and it is expecting an integer.

In a loosely typed language, such as javascript, I can do the following:

function AddTwoNumbers(a, b)
{
    return a + b;
}

if I call it like this:

Sum = AddTwoNumbers(5, "5");

Javascript automaticly converts the 5 to a string, and returns "55". This is due to javascript using the + sign for string concatenation. To make it type-aware, you would need to do something like:

function AddTwoNumbers(a, b)
{
    return Number(a) + Number(b);
}

Or, possibly:

function AddOnlyTwoNumbers(a, b)
{
    if (isNaN(a) || isNaN(b))
        return false;
    return Number(a) + Number(b);
}

if I call it like this:

Sum = AddTwoNumbers(5, " dogs");

Javascript automatically converts the 5 to a string, and appends them, to return "5 dogs".

Not all dynamic languages are as forgiving as javascript (In fact a dynamic language does not implicity imply a loose typed language (see Python)), some of them will actually give you a runtime error on invalid type casting.

While its convenient, it opens you up to a lot of errors that can be easily missed, and only identified by testing the running program. Personally, I prefer to have my compiler tell me if I made that mistake.

Now, back to C#...

C# supports a language feature called covariance, this basically means that you can substitute a base type for a child type and not cause an error, for example:

 public class Foo : Bar
 {
 }

Here, I created a new class (Foo) that subclasses Bar. I can now create a method:

 void DoSomething(Bar myBar)

And call it using either a Foo, or a Bar as an argument, both will work without causing an error. This works because C# knows that any child class of Bar will implement the interface of Bar.

However, you cannot do the inverse:

void DoSomething(Foo myFoo)

In this situation, I cannot pass Bar to this method, because the compiler does not know that Bar implements Foo's interface. This is because a child class can (and usually will) be much different than the parent class.

Of course, now I've gone way off the deep end and beyond the scope of the original question, but its all good stuff to know :)

What is the easiest way to get current GMT time in Unix timestamp format?

Python 3 seconds with microsecond decimal resolution:

from datetime import datetime
print(datetime.now().timestamp())

Python 3 integer seconds:

print(int(datetime.now().timestamp()))

WARNING on datetime.utcnow().timestamp()!

datetime.utcnow() is a non-timezone aware object. See reference: https://docs.python.org/3/library/datetime.html#aware-and-naive-objects

For something like 1am UTC:

from datetime import timezone
print(datetime(1970,1,1,1,0,tzinfo=timezone.utc).timestamp())

or

print(datetime.fromisoformat('1970-01-01T01:00:00+00:00').timestamp())

if you remove the tzinfo=timezone.utc or +00:00, you'll get results dependent on your current local time. Ex: 1am on Jan 1st 1970 in your current timezone - which could be legitimate - for example, if you want the timestamp of the instant when you were born, you should use the timezone you were born in. However, the timestamp from datetime.utcnow().timestamp() is neither the current instant in local time nor UTC. For example, I'm in GMT-7:00 right now, and datetime.utcnow().timestamp() gives a timestamp from 7 hours in the future!

Git Pull vs Git Rebase

git-pull - Fetch from and integrate with another repository or a local branch GIT PULL

Basically you are pulling remote branch to your local, example:

git pull origin master

Will pull master branch into your local repository

git-rebase - Forward-port local commits to the updated upstream head GIT REBASE

This one is putting your local changes on top of changes done remotely by other users. For example:

  • You have committed some changes on your local branch for example called SOME-FEATURE
  • Your friend in the meantime was working on other features and he merged his branch into master

Now you want to see his and your changes on your local branch. So then you checkout master branch:

git checkout master

then you can pull:

git pull origin master

and then you go to your branch:

git checkout SOME-FEATURE

and you can do rebase master to get lastest changes from it and put your branch commits on top:

git rebase master

I hope now it's a bit more clear for you.

TypeError: cannot perform reduce with flexible type

It looks like your 'trainData' is a list of strings:

['-214' '-153' '-58' ..., '36' '191' '-37']

Change your 'trainData' to a numeric type.

 import numpy as np
 np.array(['1','2','3']).astype(np.float)

jQuery/JavaScript: accessing contents of an iframe

Have you tried the classic, waiting for the load to complete using jQuery's builtin ready function?

$(document).ready(function() {
    $('some selector', frames['nameOfMyIframe'].document).doStuff()
} );

K

Where is the syntax for TypeScript comments documented?

TypeScript is a strict syntactical superset of JavaScript hence

  • Single line comments start with //
  • Multi-line comments start with /* and end with */

Cannot make a static reference to the non-static method

Since getText() is non-static you cannot call it from a static method.

To understand why, you have to understand the difference between the two.

Instance (non-static) methods work on objects that are of a particular type (the class). These are created with the new like this:

SomeClass myObject = new SomeClass();

To call an instance method, you call it on the instance (myObject):

myObject.getText(...)

However a static method/field can be called only on the type directly, say like this: The previous statement is not correct. One can also refer to static fields with an object reference like myObject.staticMethod() but this is discouraged because it does not make it clear that they are class variables.

... = SomeClass.final

And the two cannot work together as they operate on different data spaces (instance data and class data)

Let me try and explain. Consider this class (psuedocode):

class Test {
     string somedata = "99";
     string getText() { return somedata; } 
     static string TTT = "0";
}

Now I have the following use case:

Test item1 = new Test();
 item1.somedata = "200";

 Test item2 = new Test();

 Test.TTT = "1";

What are the values?

Well

in item1 TTT = 1 and somedata = 200
in item2 TTT = 1 and somedata = 99

In other words, TTT is a datum that is shared by all the instances of the type. So it make no sense to say

class Test {
         string somedata = "99";
         string getText() { return somedata; } 
  static string TTT = getText(); // error there is is no somedata at this point 
}

So the question is why is TTT static or why is getText() not static?

Remove the static and it should get past this error - but without understanding what your type does it's only a sticking plaster till the next error. What are the requirements of getText() that require it to be non-static?

How to redirect to an external URL in Angular2?

I think you need à target="_blank", so then you can use window.open :

gotoGoogle() : void {
     window.open("https://www.google.com", "_blank");
}

Finding repeated words on a string and counting the repetitions

Use Function.identity() inside Collectors.groupingBy and store everything in a MAP.

String a  = "Gini Gina Gina Gina Gina Protijayi Protijayi "; 
        Map<String, Long> map11 = Arrays.stream(a.split(" ")).collect(Collectors
                .groupingBy(Function.identity(),Collectors.counting()));
        System.out.println(map11);

// output => {Gina=4, Gini=1, Protijayi=2}

In Python we can use collections.Counter()

a = "Roopa Roopi  loves green color Roopa Roopi"
words = a.split()

wordsCount = collections.Counter(words)
for word,count in sorted(wordsCount.items()):
    print('"%s" is repeated %d time%s.' % (word,count,"s" if count > 1 else "" ))

Output :

"Roopa" is repeated 2 times. "Roopi" is repeated 2 times. "color" is repeated 1 time. "green" is repeated 1 time. "loves" is repeated 1 time.

What exactly is Apache Camel?

In plain English, camel gets (many) things done without much of boiler plate code.

Just to give you a perspective, the Java DSL given below will create a REST endpoint which will be able to accept an XML consisting of List of Products and splits it into multiple products and invoke Process method of BrandProcessor with it. And just by adding .parallelProcessing (note the commented out part) it will parallel process all the Product Objects. (Product class is JAXB/XJC generated Java stub from the XSD which the input xml is confined to.) This much code (along with few Camel dependencies) will get the job done which used to take 100s of lines of Java code.

from("servlet:item-delta?matchOnUriPrefix=true&httpMethodRestrict=POST")
.split(stax(Product.class))
/*.parallelProcessing()*/
.process(itemDeltaProcessor);

After adding the route ID and logging statement

from("servlet:item-delta?matchOnUriPrefix=true&httpMethodRestrict=POST")
.routeId("Item-DeltaRESTRoute")
.log(LoggingLevel.INFO, "Item Delta received on Item-DeltaRESTRoute")
.split(stax(Product.class))
.parallelProcessing()
.process(itemDeltaProcessor);

This is just a sample, Camel is much more than just REST end point. Just take a look the pluggable component list http://camel.apache.org/components.html

PHP Echo text Color

this works for me every time try this.

echo "<font color='blue'>".$myvariable."</font>";

since font is not supported in html5 you can do this

echo "<p class="variablecolor">".$myvariable."</p>";

then in css do

.variablecolor{
color: blue;}

How to compare two dates in php

benchmark comparison date_create, strtotime, DateTime, and direct

direct is faster

$f1="2014-12-12";
$f2="2014-12-13";
$diff=false;


$this->bench('a');
for ($i=0; $i < 20000; $i++) { 
    $date1=date_create($f1);
    $date2=date_create($f2);
    $diff=date_diff($date1,$date2);
}
$this->bench('a','b');
for ($i=0; $i < 20000; $i++) { 
     $date1=strtotime($f1);
     $date2=strtotime($f2);
     if ($date1>$date2) {
        $diff=true;
    }
}
$this->bench('b','c');
for ($i=0; $i < 20000; $i++) { 
    $date1 = new DateTime($f1);
    $date2 = new DateTime($f2);
    if ($date1>$date2) {
        $diff=true;
     }
}
$diff=false;
$this->bench('c','d');
for ($i=0; $i < 20000; $i++) { 
     if ($f1>$f2) {
        $diff=true;
     }
}
$this->bench('d','e');
var_dump($diff);

$this->dumpr($this->benchs);

results:

    [a] => 1610415241.4687
    [b] => 1610415242.8759
    [a-b] => 1.407194852829
    [c] => 1610415243.5672
    [b-c] => 0.69137716293335
    [d] => 1610415244.7036
    [c-d] => 1.1363649368286
    [e] => 1610415244.7109
    [d-e] => 0.0073208808898926

Converting a JToken (or string) to a given Type

System.Convert.ChangeType(jtoken.ToString(), targetType);

or

JsonConvert.DeserializeObject(jtoken.ToString(), targetType);

--EDIT--

Uzair, Here is a complete example just to show you they work

string json = @"{
        ""id"" : 77239923,
        ""username"" : ""UzEE"",
        ""email"" : ""[email protected]"",
        ""name"" : ""Uzair Sajid"",
        ""twitter_screen_name"" : ""UzEE"",
        ""join_date"" : ""2012-08-13T05:30:23Z05+00"",
        ""timezone"" : 5.5,
        ""access_token"" : {
            ""token"" : ""nkjanIUI8983nkSj)*#)(kjb@K"",
            ""scope"" : [ ""read"", ""write"", ""bake pies"" ],
            ""expires"" : 57723
        },
        ""friends"" : [{
            ""id"" : 2347484,
            ""name"" : ""Bruce Wayne""
        },
        {
            ""id"" : 996236,
            ""name"" : ""Clark Kent""
        }]
    }";

var obj = (JObject)JsonConvert.DeserializeObject(json);
Type type = typeof(int);
var i1 = System.Convert.ChangeType(obj["id"].ToString(), type);
var i2 = JsonConvert.DeserializeObject(obj["id"].ToString(), type);

Excel 2007: How to display mm:ss format not as a DateTime (e.g. 73:07)?

One convenient trick to entering elapsed times into Excel is to have two zeros and a colon before the number of minutes, details follow. For copy and paste operations into Excel without have to worry about formatting at all one can use the format 00:XX:XX where XX are two digits totaling < 60. In that case, Excel will echo 0:XX:XX in the cell contents displayed and store the data as 12:XX:XX AM. If one pastes data in a 00:XXX:XX format into Excel, or 00:XX:XX where either XX > 59 this will be converted into a fraction of a day.

For example, 00:121:12 becomes 0.0841666666666667, which if multiplied by the number of seconds in a day, 86,400, becomes 7272 s. Next, 00:21:12 would by default show 0:21:12 stored as 12:21:12 AM. Finally, 00:21:60 becomes 0.0152777777777778, also a fraction of a day.

This suggestion is made merely to avoid having to worry about specific formatting in Excel, and letting the program worry about it. Note, for Excel data internally formatted as 12:XX:XX AM one can only use certain Excel commands, for example, one can take an average. However, subtraction will only work when the result is a positive number. Such that converting times into seconds, fractions of a day, or other real number is suggested for access to more complete arithmetic operation coverage.

For example, if one has a column of mixed time formats, or times that are negative and will not display, if one changes the number formatting to General, all the times will be converted to fractions of a day.

"relocation R_X86_64_32S against " linking Error

I've got a similar error when installing FCL that needs CCD lib(libccd) like this:

/usr/bin/ld: /usr/local/lib/libccd.a(ccd.o): relocation R_X86_64_32S against `a local symbol' can not be used when making a shared object; recompile with -fPIC

I find that there is two different files named "libccd.a" :

  1. /usr/local/lib/libccd.a
  2. /usr/local/lib/x86_64-linux-gnu/libccd.a

I solved the problem by removing the first file.

Set default value of javascript object attributes

I'm surprised nobody has mentioned ternary operator yet.

var emptyObj = {a:'123', b:'234', c:0};
var defaultValue = 'defaultValue';
var attr = 'someNonExistAttribute';
emptyObj.hasOwnProperty(attr) ? emptyObj[attr] : defaultValue;//=> 'defaultValue'


attr = 'c'; // => 'c'
emptyObj.hasOwnProperty(attr) ? emptyObj[attr] : defaultValue; // => 0

In this way, even if the value of 'c' is 0, it will still get the correct value.

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

TypeError: 'str' object cannot be interpreted as an integer

Or you can also use eval(input('prompt')).

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

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

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

Go to IIS 6 Manager

Go to IIS 6 Manager

Select properties of SMTP server

Select properties of SMTP server

On tab Access, select Relays

On tab Access, select Relays

Add your public IP address

Add your public IP address

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

Add Integrated Windows Authentication

Add Integrated Windows Authentication

Maybe some step is not needed, but it works.

Create a branch in Git from another branch

For creating a branch from another one can use this syntax as well:

git push origin refs/heads/<sourceBranch>:refs/heads/<targetBranch>

It is a little shorter than "git checkout -b " + "git push origin "

How can I pass a list as a command-line argument with argparse?

If you have a nested list where the inner lists have different types and lengths and you would like to preserve the type, e.g.,

[[1, 2], ["foo", "bar"], [3.14, "baz", 20]]

then you can use the solution proposed by @sam-mason to this question, shown below:

from argparse import ArgumentParser
import json

parser = ArgumentParser()
parser.add_argument('-l', type=json.loads)
parser.parse_args(['-l', '[[1,2],["foo","bar"],[3.14,"baz",20]]'])

which gives:

Namespace(l=[[1, 2], ['foo', 'bar'], [3.14, 'baz', 20]])

An unhandled exception was generated during the execution of the current web request

In my case, I created a new project and when I ran it the first time, it gave me the following error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

So my solution was to go to the Package Manager Console inside the Visual Studio and run:Update-Package

Problem solved!!

show all tables in DB2 using the LIST command

To get a list of tables for the current database in DB2 -->

Connect to the database:

db2 connect to DATABASENAME user USER using PASSWORD

Run this query:

db2 LIST TABLES

This is the equivalent of SHOW TABLES in MySQL.

You may need to execute 'set schema myschema' to the correct schema before you run the list tables command. By default upon login your schema is the same as your username - which often won't contain any tables. You can use 'values current schema' to check what schema you're currently set to.

How to run Java program in command prompt

javac is the Java compiler. java is the JVM and what you use to execute a Java program. You do not execute .java files, they are just source files. Presumably there is .jar somewhere (or a directory containing .class files) that is the product of building it in Eclipse:

java/src/com/mypackage/Main.java
java/classes/com/mypackage/Main.class
java/lib/mypackage.jar

From directory java execute:

java -cp lib/mypackage.jar Main arg1 arg2

How do I correctly detect orientation change using Phonegap on iOS?

While working with the orientationchange event, I needed a timeout to get the correct dimensions of the elements in the page, but matchMedia worked fine. My final code:

var matchMedia = window.msMatchMedia || window.MozMatchMedia || window.WebkitMatchMedia || window.matchMedia;

if (typeof(matchMedia) !== 'undefined') {
  // use matchMedia function to detect orientationchange
  window.matchMedia('(orientation: portrait)').addListener(function() {
    // your code ...
  });
} else {
  // use orientationchange event with timeout (fires to early)
  $(window).on('orientationchange', function() {
    window.setTimeout(function() {
      // your code ...
    }, 300)
  });
}

How do I initialize an empty array in C#?

In .NET 4.6 the preferred way is to use a new method, Array.Empty:

String[] a = Array.Empty<string>();

The implementation is succinct, using how static members in generic classes behave in .Net:

public static T[] Empty<T>()
{
    return EmptyArray<T>.Value;
}

// Useful in number of places that return an empty byte array to avoid
// unnecessary memory allocation.
internal static class EmptyArray<T>
{
    public static readonly T[] Value = new T[0];
}

(code contract related code removed for clarity)

See also:

Way to get number of digits in an int?

Can I try? ;)

based on Dirk's solution

final int digits = number==0?1:(1 + (int)Math.floor(Math.log10(Math.abs(number))));

pip install: Please check the permissions and owner of that directory

basic info

  • system: mac os 18.0.0
  • current user: yutou

the key

  1. add the current account to wheel group
sudo dscl . -append /Groups/wheel wheel $(whoami)
  1. modify python package mode to 775.
chmod -R 775 ${this_is_your_python_package_path}

the whole thing

  • when python3 compiled well, the infomation is just like the question said.
  • I try to use pip3 install requests and got:
File "/usr/local/python3/lib/python3.6/os.py", line 220, in makedirs
    mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: 
'/usr/local/python3/lib/python3.6/site-packages/requests'
  • so i cd /usr/local/python3/lib/python3.6/site-packages, then ls -al and got:
drwxr-xr-x    6 root   wheel   192B  2 27 18:06 requests/

when i saw this, i understood, makedirs is an action of write, but the requests mode drwxrwxr-x displaied only user root can write the requests file. If add yutou(whoami) to the group wheel, and modify the package to the group wheel can write, then i can write, and the problem solved.

How to add yutou to group wheel? + detect group wheel, sudo dscl . -list /groups GroupMembership, you will find:

wheel                    root

the group wheel only one member root. + add yutou to group wheel, sudo dscl . -append /Groups/wheel wheel yutou. + check, sudo dscl . -list /groups GroupMembership:

wheel                    root yutou

modify the python package mode

chmod -R 775 /usr/local/python3/lib/python3.6

How to set the maxAllowedContentLength to 500MB while running on IIS7?

According to MSDN maxAllowedContentLength has type uint, its maximum value is 4,294,967,295 bytes = 3,99 gb

So it should work fine.

See also Request Limits article. Does IIS return one of these errors when the appropriate section is not configured at all?

See also: Maximum request length exceeded

How can I import a database with MySQL from terminal?

After struggling for sometime I found the information in https://tommcfarlin.com/importing-a-large-database/

  1. Connect to Mysql (let's use root for both username and password):

    mysql -uroot -proot
    
  2. Connect to the database (let's say it is called emptyDatabase (your should get a confirmation message):

    connect emptyDatabase
    

3 Import the source code, lets say the file is called mySource.sql and it is in a folder called mySoureDb under the profile of a user called myUser:

source /Users/myUser/mySourceDB/mySource.sql

EditText onClickListener in Android

Why did not anyone mention setOnTouchListener? Using setOnTouchListener is easy and all right, and just return true if the listener has consumed the event, false otherwise.

Java: How to convert List to Map

You can leverage the streams API of Java 8.

public class ListToMap {

  public static void main(String[] args) {
    List<User> items = Arrays.asList(new User("One"), new User("Two"), new User("Three"));

    Map<String, User> map = createHashMap(items);
    for(String key : map.keySet()) {
      System.out.println(key +" : "+map.get(key));
    }
  }

  public static Map<String, User> createHashMap(List<User> items) {
    Map<String, User> map = items.stream().collect(Collectors.toMap(User::getId, Function.identity()));
    return map;
  }
}

For more details visit: http://codecramp.com/java-8-streams-api-convert-list-map/

Android Studio doesn't see device

If you still have this problem (later than summer 2015) maybe you should:

  1. Go here: http://developer.android.com/sdk/win-usb.html#top
  2. Download the driver
  3. Reinstall it

I recently installed Windows 10 (not an upgrade, a clean installation) and I forgot the ADB USB driver

Git says remote ref does not exist when I delete remote branch

A handy one-liner to delete branches other than 'master' from origin:

git branch --remotes | grep -v 'origin/master' | sed "s/origin\///" | xargs -i{foo} git push origin --delete {foo}

Be sure you understand the implications of running this before doing so!

How do I pass the this context to a function?

Javascripts .call() and .apply() methods allow you to set the context for a function.

var myfunc = function(){
    alert(this.name);
};

var obj_a = {
    name:  "FOO"
};

var obj_b = {
    name:  "BAR!!"
};

Now you can call:

myfunc.call(obj_a);

Which would alert FOO. The other way around, passing obj_b would alert BAR!!. The difference between .call() and .apply() is that .call() takes a comma separated list if you're passing arguments to your function and .apply() needs an array.

myfunc.call(obj_a, 1, 2, 3);
myfunc.apply(obj_a, [1, 2, 3]);

Therefore, you can easily write a function hook by using the apply() method. For instance, we want to add a feature to jQuerys .css() method. We can store the original function reference, overwrite the function with custom code and call the stored function.

var _css = $.fn.css;
$.fn.css = function(){
   alert('hooked!');
   _css.apply(this, arguments);
};

Since the magic arguments object is an array like object, we can just pass it to apply(). That way we guarantee, that all parameters are passed through to the original function.

How to get the absolute coordinates of a view

First Way:

In Kotlin we can create a simple extension for view:

fun View.getLocationOnScreen(): Point
{
    val location = IntArray(2)
    this.getLocationOnScreen(location)
    return Point(location[0],location[1])
}

And simply get coordinates:

val location = yourView.getLocationOnScreen()
val absX = location.x
val absY = location.y

Second Way:

The Second way is more simple :

fun View.absX(): Int
{
    val location = IntArray(2)
    this.getLocationOnScreen(location)
    return location[0]
}

fun View.absY(): Int
{
    val location = IntArray(2)
    this.getLocationOnScreen(location)
    return location[1]
}

and simply get absolute X by view.absX() and Y by view.absY()

How to initialize static variables

Here is a hopefully helpful pointer, in a code example. Note how the initializer function is only called once.

Also, if you invert the calls to StaticClass::initializeStStateArr() and $st = new StaticClass() you'll get the same result.

$ cat static.php
<?php

class StaticClass {

  public static  $stStateArr = NULL;

  public function __construct() {
    if (!isset(self::$stStateArr)) {
      self::initializeStStateArr();
    }
  }

  public static function initializeStStateArr() {
    if (!isset(self::$stStateArr)) {
      self::$stStateArr = array('CA' => 'California', 'CO' => 'Colorado',);
      echo "In " . __FUNCTION__. "\n";
    }
  }

}

print "Starting...\n";
StaticClass::initializeStStateArr();
$st = new StaticClass();

print_r (StaticClass::$stStateArr);

Which yields :

$ php static.php
Starting...
In initializeStStateArr
Array
(
    [CA] => California
    [CO] => Colorado
)

How to detect chrome and safari browser (webkit)

Most of the answers here are obsolete, there is no more jQuery.browser, and why would anyone even use jQuery or would sniff the User Agent is beyond me.

Instead of detecting a browser, you should rather detect a feature
(whether it's supported or not).

The following is false in Mozilla Firefox, Microsoft Edge; it is true in Google Chrome.

"webkitLineBreak" in document.documentElement.style

Note this is not future-proof. A browser could implement the -webkit-line-break property at any time in the future, thus resulting in false detection. Then you can just look at the document object in Chrome and pick anything with webkit prefix and check for that to be missing in other browsers.

Spring Bean Scopes

The Spring documentation describes the following standard scopes:

singleton: (Default) Scopes a single bean definition to a single object instance per Spring IoC container.

prototype: Scopes a single bean definition to any number of object instances.

request: Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session: Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

global session: Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

Additional custom scopes can also be created and configured using a CustomScopeConfigurer. An example would be the flow scope added by Spring Webflow.

By the way, you argues that you always used prototype what I find strange. The standard scope is singleton and in the application I develop, I rarely need the prototype scope. You should maybe take a look at this.

Scale iFrame css width 100% like an image

@Anachronist is closest here, @Simone not far off. The caveat with percentage padding on an element is that it's based on its parent's width, so if different to your container, the proportions will be off.

The most reliable, simplest answer is:

_x000D_
_x000D_
body {_x000D_
  /* for demo */_x000D_
  background: lightgray;_x000D_
}_x000D_
.fixed-aspect-wrapper {_x000D_
  /* anything or nothing, it doesn't matter */_x000D_
  width: 60%;_x000D_
  /* only need if other rulesets give this padding */_x000D_
  padding: 0;_x000D_
}_x000D_
.fixed-aspect-padder {_x000D_
  height: 0;_x000D_
  /* last padding dimension is (100 * height / width) of item to be scaled */_x000D_
  padding: 0 0 56.25%;_x000D_
  position: relative;_x000D_
  /* only need next 2 rules if other rulesets change these */_x000D_
  margin: 0;_x000D_
  width: auto;_x000D_
}_x000D_
.whatever-needs-the-fixed-aspect {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  /* for demo */_x000D_
  border: 0;_x000D_
  background: white;_x000D_
}
_x000D_
<div class="fixed-aspect-wrapper">_x000D_
  <div class="fixed-aspect-padder">_x000D_
    <iframe class="whatever-needs-the-fixed-aspect" src="/"></iframe>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get time (hour, minute, second) in Swift 3 using NSDate?

Swift 5+

extension Date {
    
    func get(_ type: Calendar.Component)-> String {
        let calendar = Calendar.current
        let t = calendar.component(type, from: self)
        return (t < 10 ? "0\(t)" : t.description)
    }
}

Usage:

print(Date().get(.year)) // => 2020
print(Date().get(.month)) // => 08
print(Date().get(.day)) // => 18 

How to deserialize a JObject to .NET object

From the documentation I found this

JObject o = new JObject(
   new JProperty("Name", "John Smith"),
   new JProperty("BirthDate", new DateTime(1983, 3, 20))
);

JsonSerializer serializer = new JsonSerializer();
Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person));

Console.WriteLine(p.Name);

The class definition for Person should be compatible to the following:

class Person {
    public string Name { get; internal set; }
    public DateTime BirthDate { get; internal set; }
}

Edit

If you are using a recent version of JSON.net and don't need custom serialization, please see TienDo's answer above (or below if you upvote me :P ), which is more concise.

Python: create dictionary using dict() with integer keys?

There are also these 'ways':

>>> dict.fromkeys(range(1, 4))
{1: None, 2: None, 3: None}
>>> dict(zip(range(1, 4), range(1, 4)))
{1: 1, 2: 2, 3: 3}

warning: implicit declaration of function

You need to declare the desired function before your main function:

#include <stdio.h>
int yourfunc(void);

int main(void) {

   yourfunc();
 }

Fatal Error :1:1: Content is not allowed in prolog

It could be not supported file encoding. Change it to UTF-8 for example.

I've done this using Sublime

Get operating system info

If you want very few info like a class in your html for common browsers for instance, you could use:

function get_browser()
{
    $browser = '';
    $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
    if (preg_match('~(?:msie ?|trident.+?; ?rv: ?)(\d+)~', $ua, $matches)) $browser = 'ie ie'.$matches[1];
    elseif (preg_match('~(safari|chrome|firefox)~', $ua, $matches)) $browser = $matches[1];

    return $browser;
}

which will return 'safari' or 'firefox' or 'chrome', or 'ie ie8', 'ie ie9', 'ie ie10', 'ie ie11'.

How do I find the size of a struct?

Contrary to what some of the other answers have said, on most systems, in the absence of a pragma or compiler option, the size of the structure will be at least 6 bytes and, on most 32-bit systems, 8 bytes. For 64-bit systems, the size could easily be 16 bytes. Alignment does come into play; always. The sizeof a single struct has to be such that an array of those sizes can be allocated and the individual members of the array are sufficiently aligned for the processor in question. Consequently, if the size of the struct was 5 as others have hypothesized, then an array of two such structures would be 10 bytes long, and the char pointer in the second array member would be aligned on an odd byte, which would (on most processors) cause a major bottleneck in the performance.

How to set the id attribute of a HTML element dynamically with angularjs (1.x)?

You could just simply do the following

In your js

$scope.id = 0;

In your template

<div id="number-{{$scope.id}}"></div>

which will render

<div id="number-0"></div>

It is not necessary to concatenate inside double curly brackets.

Python Iterate Dictionary by Index

Since you want to iterate in order, you can use sorted:

for k, v in sorted(dict.items()):
    print k,v

LAST_INSERT_ID() MySQL

If you need to have from mysql, after your query, the last auto-incremental id without another query, put in your code:

mysql_insert_id();

java.io.FileNotFoundException: the system cannot find the file specified

Your file should directly be under the project folder, and not inside any other sub-folder.

If the folder of your project is named for e.g. AProject, it should be in the same place as your src folder.

Aproject
        src
        word.txt

Rownum in postgresql

I have just tested in Postgres 9.1 a solution which is close to Oracle ROWNUM:

select row_number() over() as id, t.*
from information_schema.tables t;

How to format string to money

you can also do :

string.Format("{0:C}", amt)

What is the string concatenation operator in Oracle?

It is ||, for example:

select 'Mr ' || ename from emp;

The only "interesting" feature I can think of is that 'x' || null returns 'x', not null as you might perhaps expect.

how to git commit a whole folder?

You don't "commit the folder" - you add the folder, as you have done, and then simply commit all changes. The command should be:

git add foldername
git commit -m "commit operation"

Can I assume (bool)true == (int)1 for any C++ compiler?

I've found different compilers return different results on true. I've also found that one is almost always better off comparing a bool to a bool instead of an int. Those ints tend to change value over time as your program evolves and if you assume true as 1, you can get bitten by an unrelated change elsewhere in your code.

Howto? Parameters and LIKE statement SQL

Your visual basic code would look something like this:

Dim cmd as New SqlCommand("SELECT * FROM compliance_corner WHERE (body LIKE '%' + @query + '%') OR (title LIKE '%' + @query + '%')")

cmd.Parameters.Add("@query", searchString)

How to add scroll bar to the Relative Layout?

hi see the following sample code of xml file.

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ScrollView01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <RelativeLayout
        android:id="@+id/RelativeLayout01"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <LinearLayout
            android:id="@+id/LinearLayout01"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/TextView01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dip"
                android:text="@+id/TextView01" >
            </TextView>

            <TextView
                android:id="@+id/TextView01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dip"
                android:text="@+id/TextView01" >
            </TextView>

            <TextView
                android:id="@+id/TextView01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dip"
                android:text="@+id/TextView01" >
            </TextView>

            <TextView
                android:id="@+id/TextView01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dip"
                android:text="@+id/TextView01" >
            </TextView>

            <TextView
                android:id="@+id/TextView01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dip"
                android:text="@+id/TextView01" >
            </TextView>

            <TextView
                android:id="@+id/TextView01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dip"
                android:text="@+id/TextView01" >
            </TextView>

            <TextView
                android:id="@+id/TextView01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dip"
                android:text="@+id/TextView01" >
            </TextView>

            <TextView
                android:id="@+id/TextView01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dip"
                android:text="@+id/TextView01" >
            </TextView>

            <TextView
                android:id="@+id/TextView01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dip"
                android:text="@+id/TextView01" >
            </TextView>
        </LinearLayout>
    </RelativeLayout>

</ScrollView>

How can I see the raw SQL queries Django is running?

If you make sure your settings.py file has:

  1. django.core.context_processors.debug listed in CONTEXT_PROCESSORS
  2. DEBUG=True
  3. your IP in the INTERNAL_IPS tuple

Then you should have access to the sql_queries variable. I append a footer to each page that looks like this:

{%if sql_queries %}
  <div class="footNav">
    <h2>Queries</h2>
    <p>
      {{ sql_queries|length }} Quer{{ sql_queries|pluralize:"y,ies" }}, {{sql_time_sum}} Time
    {% ifnotequal sql_queries|length 0 %}
      (<span style="cursor: pointer;" onclick="var s=document.getElementById('debugQueryTable').style;s.disp\
lay=s.display=='none'?'':'none';this.innerHTML=this.innerHTML=='Show'?'Hide':'Show';">Show</span>)
    {% endifnotequal %}
    </p>
    <table id="debugQueryTable" style="display: none;">
      <col width="1"></col>
      <col></col>
      <col width="1"></col>
      <thead>
        <tr>
          <th scope="col">#</th>
          <th scope="col">SQL</th>
          <th scope="col">Time</th>
        </tr>
      </thead>
      <tbody>
        {% for query in sql_queries %}
          <tr class="{% cycle odd,even %}">
            <td>{{ forloop.counter }}</td>
            <td>{{ query.sql|escape }}</td>
            <td>{{ query.time }}</td>
          </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
{% endif %}

I got the variable sql_time_sum by adding the line

context_extras['sql_time_sum'] = sum([float(q['time']) for q in connection.queries])

to the debug function in django_src/django/core/context_processors.py.

How do I Merge two Arrays in VBA?

My preferred way is a bit long, but has some advantages over the other answers:

  • It can combine an indefinite number of arrays at once
  • It can combine arrays with non-arrays (objects, strings, integers, etc.)
  • It accounts for the possibility that one or more of the arrays may contain objects
  • It allows the user to choose the base of the new array (0, 1, etc.)

Here it is:

Function combineArrays(ByVal toCombine As Variant, Optional ByVal newBase As Long = 1)
'Combines an array of one or more 1d arrays, objects, or values into a single 1d array
'newBase parameter indicates start position of new array (0, 1, etc.)
'Example usage:
    'combineArrays(Array(Array(1,2,3),Array(4,5,6),Array(7,8))) -> Array(1,2,3,4,5,6,7,8)
    'combineArrays(Array("Cat",Array(2,3,4))) -> Array("Cat",2,3,4)
    'combineArrays(Array("Cat",ActiveSheet)) -> Array("Cat",ActiveSheet)
    'combineArrays(Array(ThisWorkbook)) -> Array(ThisWorkbook)
    'combineArrays("Cat") -> Array("Cat")

    Dim tempObj As Object
    Dim tempVal As Variant

    If Not IsArray(toCombine) Then
        If IsObject(toCombine) Then
            Set tempObj = toCombine
            ReDim toCombine(newBase To newBase)
            Set toCombine(newBase) = tempObj
        Else
            tempVal = toCombine
            ReDim toCombine(newBase To newBase)
            toCombine(newBase) = tempVal
        End If
        combineArrays = toCombine
        Exit Function
    End If

    Dim i As Long
    Dim tempArr As Variant
    Dim newMax As Long
    newMax = 0

    For i = LBound(toCombine) To UBound(toCombine)
        If Not IsArray(toCombine(i)) Then
            If IsObject(toCombine(i)) Then
                Set tempObj = toCombine(i)
                ReDim tempArr(1 To 1)
                Set tempArr(1) = tempObj
                toCombine(i) = tempArr
            Else
                tempVal = toCombine(i)
                ReDim tempArr(1 To 1)
                tempArr(1) = tempVal
                toCombine(i) = tempArr
            End If
            newMax = newMax + 1
        Else
            newMax = newMax + (UBound(toCombine(i)) + LBound(toCombine(i)) - 1)
        End If
    Next
    newMax = newMax + (newBase - 1)

    ReDim newArr(newBase To newMax)
    i = newBase
    Dim j As Long
    Dim k As Long
    For j = LBound(toCombine) To UBound(toCombine)
        For k = LBound(toCombine(j)) To UBound(toCombine(j))
            If IsObject(toCombine(j)(k)) Then
                Set newArr(i) = toCombine(j)(k)
            Else
                newArr(i) = toCombine(j)(k)
            End If
            i = i + 1
        Next
    Next

    combineArrays = newArr

End Function