Programs & Examples On #Legacy app

CSS selector last row from main table

Your tables should have as immediate children just tbody and thead elements, with the rows within*. So, amend the HTML to be:

<table border="1" width="100%" id="test">
  <tbody>
    <tr>
     <td>
      <table border="1" width="100%">
        <tbody>
          <tr>
            <td>table 2</td>
          </tr>
        </tbody>
      </table>
     </td>
    </tr> 
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
  </tbody>
</table>

Then amend your selector slightly to this:

#test > tbody > tr:last-child { background:#ff0000; }

See it in action here. That makes use of the child selector, which:

...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.

So, you are targeting only direct children of tbody elements that are themselves direct children of your #test table.

Alternative solution

The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:

#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }

* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:

...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

I had naively added junit-4.12.jar from poi.apache.org to my Build Path in Eclipse. I deleted it (Project, Properties, Java Build Path, Libraries, junit-4.12.jar, Remove) then in my test class allowed Eclipse to "Fix Project Setup" after pressing Ctrl-1. No more problems! :-)

How can I make a horizontal ListView in Android?

Have you looked into the ViewFlipper component? Maybe it can help you.

http://developer.android.com/reference/android/widget/ViewFlipper.html

With this component, you can attach two or more view childs. If you add some translate animation and capture Gesture detection, you can have a nicely horizontal scroll.

Rotate label text in seaborn factorplot

Any seaborn plots suported by facetgrid won't work with (e.g. catplot)

g.set_xticklabels(rotation=30) 

however barplot, countplot, etc. will work as they are not supported by facetgrid. Below will work for them.

g.set_xticklabels(g.get_xticklabels(), rotation=30)

Also, in case you have 2 graphs overlayed on top of each other, try set_xticklabels on graph which supports it.

Get remote registry value

another option ... needs remoting ...

(invoke-command -ComputerName mymachine -ScriptBlock {Get-ItemProperty HKLM:\SOFTWARE\VanDyke\VShell\License -Name Version }).version

In Subversion can I be a user other than my login name?

If you need to specify a username other than your logged in user for use with svn+ssh just add an entry to your .ssh/config file:

Host example.com
User jdoe

How I can check whether a page is loaded completely or not in web driver?

Recently, when I was dealing with an AJAX application/RIA, I was having the same issue! And I used implicit wait, with a time of around 90 seconds. It waits, till the element is available...So, what we can do to make sure, that page gets loaded completely is,

add a boolean statement, checking for whether the condition(a particular part of the element), is present and assign it to a variable, check for the condition and only when it is true, " do the necessary actions!"...In this way, I figured out, both waits could be used...

Ex:

@Before

{ implicit wait statement}

@Test

{

boolean tr1=Driver.findElement(By.xpath("xx")).isEnabled/isDisplayed;

if (tr1==true && ____)//as many conditions, to make sure, the page is loaded

{

//do the necessary set of actions...
driver.findElement(By.xpath("yy")).click();

}

}

Hope this helps!! It is in implementation stage, for me too...

How can I get the current date and time in UTC or GMT in Java?

java.util.Date has no specific time zone, although its value is most commonly thought of in relation to UTC. What makes you think it's in local time?

To be precise: the value within a java.util.Date is the number of milliseconds since the Unix epoch, which occurred at midnight January 1st 1970, UTC. The same epoch could also be described in other time zones, but the traditional description is in terms of UTC. As it's a number of milliseconds since a fixed epoch, the value within java.util.Date is the same around the world at any particular instant, regardless of local time zone.

I suspect the problem is that you're displaying it via an instance of Calendar which uses the local timezone, or possibly using Date.toString() which also uses the local timezone, or a SimpleDateFormat instance, which, by default, also uses local timezone.

If this isn't the problem, please post some sample code.

I would, however, recommend that you use Joda-Time anyway, which offers a much clearer API.

What is the main difference between PATCH and PUT request?

I spent couple of hours with google and found the answer here

PUT => If user can update all or just a portion of the record, use PUT (user controls what gets updated)

PUT /users/123/email
[email protected]

PATCH => If user can only update a partial record, say just an email address (application controls what can be updated), use PATCH.

PATCH /users/123
[description of changes]

Why Patch

PUT method need more bandwidth or handle full resources instead on partial. So PATCH was introduced to reduce the bandwidth.

Explanation about PATCH

PATCH is a method that is not safe, nor idempotent, and allows full and partial updates and side-effects on other resources.

PATCH is a method which enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version.

PATCH /users/123
[
  { "op": "replace", "path": "/email", "value": "[email protected]" }
]

Here more information about put and patch

Rounding integer division (instead of truncating)

try using math ceil function that makes rounding up. Math Ceil !

Capitalize only first character of string and leave others alone? (Rails)

Note that if you need to deal with multi-byte characters, i.e. if you have to internationalize your site, the s[0] = ... solution won't be adequate. This Stack Overflow question suggests using the unicode-util gem

Ruby 1.9: how can I properly upcase & downcase multibyte strings?

EDIT

Actually an easier way to at least avoid strange string encodings is to just use String#mb_chars:

s = s.mb_chars
s[0] = s.first.upcase
s.to_s

Git with SSH on Windows

Since this keeps coming up in search results for making git and github work with SSH on Windows (and because I didn't need anything from the guides above), I'm adding the following, simple solution.

(Microsoft says they are working on adding SSH to Visual Studio, and GitHub for Windows still doesn't support SSH...)

1. I installed "git for Windows" (which includes ssh and a bash shell)

https://git-scm.com/download/win

2. From the included bash shell (which, for me, was installed at: C:\Program Files\Git\git-bash.exe)

cd to the root level of where you want your repo saved (something like: C:\code\github\), and

Type:

eval $(ssh-agent -s) && ssh-add "C:\Users\YOURNAMEHERE\.ssh\github_rsa"

3. Type: (the SSH link from the repo)

git clone [email protected]:RepoName/Project.git

Responsive image map

I found a no-JS way to address this if you are okay with rectangular hit areas.

First of all, make sure your image is in a div that's relatively positioned. Then put the image inside this div, which means it'll take up all the space in the div. Finally, add absolutely positioned div's under the image, within the main div, and use percentages for top, left, width, and height to get the link hit areas the size and position you want.

I find it's easiest to give the div a black background color (ideally with some alpha fading so you can see the linked content underneath) when you're first working, and to use a code inspector in your browser to adjust the percentages in real time, so that you can get it just right.

Here's the basic outline you can work with. By doing everything with percentages, you ensure the elements all stay the same relative size and position as the image scales.

<div style="position: relative;">
  <img src="background-image.png" style="width: 100%; height: auto;">
  <a href="/link1"><div style="position: absolute; left: 15%; top: 20%; width: 12%; height: 8%; background-color: rgba(0, 0, 0, .25);"></div></a>
  <a href="/link2"><div style="position: absolute; left: 52%; top: 38%; width: 14%; height: 20%; background-color: rgba(0, 0, 0, .25);"></div></a>
</div>

Use this code with your code inspector in Chrome or your browser of choice, and adjust the percentages (you can use decimal percentages to be more exact) until the boxes are just right. Also choose a background-color of transparent when you're ready to use it since you want your hit areas to be invisible.

How can I stop redis-server?

Try killall redis-server. You may also use ps aux to find the name and pid of your server, and then kill it with kill -9 here_pid_number.

add scroll bar to table body

This is because you are adding your <tbody> tag before <td> in table you cannot print any data without <td>.

So for that you have to make a <div> say #header with position: fixed;

 header
 {
      position: fixed;
 }

make another <div> which will act as <tbody>

tbody
{
    overflow:scroll;
}

Now your header is fixed and the body will scroll. And the header will remain there.

Disable Required validation attribute under certain circumstances

I know this question has been answered a long time ago and the accepted answer will actually do the work. But there's one thing that bothers me: having to copy 2 models only to disable a validation.

Here's my suggestion:

public class InsertModel
{
    [Display(...)]
    public virtual string ID { get; set; }

    ...Other properties
}

public class UpdateModel : InsertModel
{
    [Required]
    public override string ID
    {
        get { return base.ID; }
        set { base.ID = value; }
    }
}

This way, you don't have to bother with client/server side validations, the framework will behave the way it's supposed to. Also, if you define a [Display] attribute on the base class, you don't have to redefine it in your UpdateModel.

And you can still use these classes the same way:

[HttpPost]
public ActionResult Update(UpdateModel model)
{
    ...
}

[HttpPost]
public ActionResult Insert(InsertModel model)
{
    ...
}

Trigger a keypress/keydown/keyup event in JS/jQuery?

First of all, I need to say that sample from Sionnach733 worked flawlessly. Some users complain about absent of actual examples. Here is my two cents. I've been working on mouse click simulation when using this site: https://www.youtube.com/tv. You can open any video and try run this code. It performs switch to next video.

function triggerEvent(el, type, keyCode) {
    if ('createEvent' in document) {
            // modern browsers, IE9+
            var e = document.createEvent('HTMLEvents');
            e.keyCode = keyCode;
            e.initEvent(type, false, true);
            el.dispatchEvent(e);
    } else {
        // IE 8
        var e = document.createEventObject();
        e.keyCode = keyCode;
        e.eventType = type;
        el.fireEvent('on'+e.eventType, e);
    }
}

var nextButton = document.getElementsByClassName('icon-player-next')[0];
triggerEvent(nextButton, 'keyup', 13); // simulate mouse/enter key press

How to vertically align text with icon font?

To expand on Marian Udrea's answer: In my scenario, I was trying to align the text with a material icon. There's something weird about material icons that prevented it from being aligned. None of the answers were working, until I added the vertical-align to the icon element, instead of the parent element.

So, if the icon is 24px in height:

.parent {
    line-height: 24px; // Same as icon height

    i.material-icons {  // Only if you're using material icons
      display: inline-flex;
      vertical-align: top;
    }
}

How do I test if a variable does not equal either of two values?

May I suggest trying to use in else if statement in your if/else statement. And if you don't want to run any code that not under any conditions you want you can just leave the else out at the end of the statement. else if can also be used for any number of diversion paths that need things to be a certain condition for each.

if(condition 1){

} else if (condition 2) {

}else {

}

How to update fields in a model without creating a new record in django?

In my scenario, I want to update the status of status based on his id

student_obj = StudentStatus.objects.get(student_id=101)
student_obj.status= 'Enrolled'
student_obj.save()

Or If you want the last id from Student_Info table you can use the following.

student_obj = StudentStatus.objects.get(student_id=StudentInfo.objects.last().id)
student_obj.status= 'Enrolled'
student_obj.save()

Simple C example of doing an HTTP POST and consuming the response

Handle added.
Added Host header.
Added linux / windows support, tested (XP,WIN7).
WARNING: ERROR : "segmentation fault" if no host,path or port as argument.

#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit, atoi, malloc, free */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#ifdef __linux__ 
    #include <sys/socket.h> /* socket, connect */
    #include <netdb.h> /* struct hostent, gethostbyname */
    #include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#elif _WIN32
    #include <winsock2.h>
    #include <ws2tcpip.h>
    #include <windows.h>
    #pragma comment(lib,"ws2_32.lib") //Winsock Library

#else

#endif

void error(const char *msg) { perror(msg); exit(0); }

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

    int i;
    struct hostent *server;
    struct sockaddr_in serv_addr;
    int bytes, sent, received, total, message_size;
    char *message, response[4096];
    int portno = atoi(argv[2])>0?atoi(argv[2]):80;
    char *host = strlen(argv[1])>0?argv[1]:"localhost";
    char *path = strlen(argv[4])>0?argv[4]:"/";
    if (argc < 5) { puts("Parameters: <host> <port> <method> <path> [<data> [<headers>]]"); exit(0); }
    /* How big is the message? */
    message_size=0;
    if(!strcmp(argv[3],"GET"))
    {
                printf("Process 1\n");
        message_size+=strlen("%s %s%s%s HTTP/1.0\r\nHost: %s\r\n");        /* method         */
        message_size+=strlen(argv[3]);                         /* path           */
        message_size+=strlen(path);                         /* headers        */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* query string   */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        message_size+=strlen("\r\n");                          /* blank line     */
    }
    else
    {
                printf("Process 2\n");
        message_size+=strlen("%s %s HTTP/1.0\r\nHost: %s\r\n");
        message_size+=strlen(argv[3]);                         /* method         */
        message_size+=strlen(path);                            /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        if(argc>5)
            message_size+=strlen("Content-Length: %d\r\n")+10; /* content length */
        message_size+=strlen("\r\n");                          /* blank line     */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* body           */
    }
            printf("Allocating...\n");
    /* allocate space for the message */
    message=malloc(message_size);

    /* fill in the parameters */
    if(!strcmp(argv[3],"GET"))
    {
        if(argc>5)
            sprintf(message,"%s %s%s%s HTTP/1.0\r\nHost: %s\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                path,                                          /* path           */
                strlen(argv[5])>0?"?":"",                      /* ?              */
                strlen(argv[5])>0?argv[5]:"",host);            /* query string   */
        else
            sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                path,host);                                    /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        strcat(message,"\r\n");                                /* blank line     */
    }
    else
    {
        sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
            strlen(argv[3])>0?argv[3]:"POST",                  /* method         */
            path,host);                                        /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        if(argc>5)
            sprintf(message+strlen(message),"Content-Length: %d\r\n",(int)strlen(argv[5]));
        strcat(message,"\r\n");                                /* blank line     */
        if(argc>5)
            strcat(message,argv[5]);                           /* body           */
    }
    printf("Processed\n");
    /* What are we going to send? */
    printf("Request:\n%s\n",message);
        /* lookup the ip address */

    total = strlen(message);
    /* create the socket */
    #ifdef _WIN32
WSADATA wsa;
SOCKET s;

printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
    printf("Failed. Error Code : %d",WSAGetLastError());
    return 1;
}

printf("Initialised.\n");

//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
    printf("Could not create socket : %d" , WSAGetLastError());
}

printf("Socket created.\n");

server = gethostbyname(host);
serv_addr.sin_addr.s_addr = inet_addr(server->h_addr);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
//Connect to remote server
if (connect(s , (struct sockaddr *)&serv_addr , sizeof(serv_addr)) < 0)
{
    printf("connect failed with error code : %d" , WSAGetLastError());
    return 1;
}

puts("Connected");
if( send(s , message , strlen(message) , 0) < 0)
{
    printf("Send failed with error code : %d" , WSAGetLastError());
    return 1;
}
puts("Data Send\n");

//Receive a reply from the server
if((received = recv(s , response , 2000 , 0)) == SOCKET_ERROR)
{
    printf("recv failed with error code : %d" , WSAGetLastError());
}

puts("Reply received\n");

//Add a NULL terminating character to make it a proper string before printing
response[received] = '\0';
puts(response);

closesocket(s);
WSACleanup();
    #endif
    #ifdef __linux__ 
    int sockfd;
    server = gethostbyname(host);
    if (server == NULL) error("ERROR, no such host");
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0) error("ERROR opening socket");
        /* fill in the structure */
        memset(&serv_addr,0,sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_port = htons(portno);
        memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
                /* connect the socket */
        if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
            error("ERROR connecting");
                /* send the request */

    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);
    /* receive the response */
    memset(response, 0, sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    printf("Response: \n");
    do {
       printf("%s", response);
       memset(response, 0, sizeof(response));
       bytes = recv(sockfd, response, 1024, 0);
        if (bytes < 0)
           printf("ERROR reading response from socket");
       if (bytes == 0)
           break;
       received+=bytes;
    } while (1);

    if (received == total)
        error("ERROR storing complete response from socket");

    /* close the socket */
    close(sockfd);
    #endif


    free(message);

    return 0;
}

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

How to draw a filled circle in Java?

/***Your Code***/
public void paintComponent(Graphics g){
/***Your Code***/
    g.setColor(Color.RED);
    g.fillOval(50,50,20,20);
}

g.fillOval(x-axis,y-axis,width,height);

SMTP server response: 530 5.7.0 Must issue a STARTTLS command first

First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

I got the same error {AttributeError: 'bytes' object has no attribute 'read'} in python3. This worked for me later without using json:

from urllib.request import urlopen
from bs4 import BeautifulSoup

url = 'https://someurl/'
page = urlopen(url)
html = page.read()
soup = BeautifulSoup(html)
print(soup.prettify('latin-1'))

Finish all previous activities

If you log in the user in screen 1 and from there you go to the other screens, use

Intent intent = new Intent(this, Screen1.class);
intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

Keyboard shortcut to change font size in Eclipse?

Here's a quicker way than multi-layer menus without resorting to plug-ins:

Use the Quick Access tool at the upper left corner.

Type in "font", then, from the list that drops down, click on the link for "Preferences->Colors and Fonts->General->Appearance".

One click replaces the 4 needed to get there through menus. I do it so often, my Quick Access tool pulls it up as a previous choice right at the top of the list so I can just type "font" with a tap on the enter key and Boom!, I'm there.

If you want a keyboard shortcut, Ctrl+3 sets the focus to the Quick Access tool. Better yet, this even automatically brings up a list with your previous choices. The last one you chose will be on top, in which case a simple Ctrl+3 followed by enter would bring you straight there! I use this all the time to make it bigger during long typing or reading sessions to ease eye strain, or to make it smaller if I need more text on the screen at one time to make it easier to find something.

It's not quite as nice as zooming with the scroll wheel or with a simple Ctrl+ or Ctrl-, but it's a lot better than navigating through the menus every time!

Boolean operators ( &&, -a, ||, -o ) in Bash

-a and -o are the older and/or operators for the test command. && and || are and/or operators for the shell. So (assuming an old shell) in your first case,

[ "$1" = 'yes' ] && [ -r $2.txt ]

The shell is evaluating the and condition. In your second case,

[ "$1" = 'yes' -a $2 -lt 3 ]

The test command (or builtin test) is evaluating the and condition.

Of course in all modern or semi-modern shells, the test command is built in to the shell, so there really isn't any or much difference. In modern shells, the if statement can be written:

[[ $1 == yes && -r $2.txt ]]

Which is more similar to modern programming languages and thus is more readable.

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

This is working code for your query,you can use it.

Controler

    [HttpPost]
    public ActionResult save(List<ListName> listObject)
    {
    //operation return
    Json(new { istObject }, JsonRequestBehavior.AllowGet); }
    }

javascript

  $("#btnSubmit").click(function () {
    var myColumnDefs = [];
    $('input[type=checkbox]').each(function () {
        if (this.checked) {
            myColumnDefs.push({ 'Status': true, 'ID': $(this).data('id') })
        } else {
            myColumnDefs.push({ 'Status': false, 'ID': $(this).data('id') })
        }
    });
   var data1 = { 'listObject': myColumnDefs};
   var data = JSON.stringify(data1)
   $.ajax({
   type: 'post',
   url: '/Controller/action',
   data:data ,
   contentType: 'application/json; charset=utf-8',
   success: function (response) {
    //do your actions
   },
   error: function (response) {
    alert("error occured");
   }
   });

Reference - What does this regex mean?

The Stack Overflow Regular Expressions FAQ

See also a lot of general hints and useful links at the tag details page.


Online tutorials

Quantifiers

Character Classes

Escape Sequences

Anchors

(Also see "Flavor-Specific Information ? Java ? The functions in Matcher")

Groups

Lookarounds

Modifiers

Other:

Common Tasks

Advanced Regex-Fu

Flavor-Specific Information

(Except for those marked with *, this section contains non-Stack Overflow links.)

General information

(Links marked with * are non-Stack Overflow links.)

Examples of regex that can cause regex engine to fail

Tools: Testers and Explainers

(This section contains non-Stack Overflow links.)

How to match "anything up until this sequence of characters" in a regular expression?

You didn't specify which flavor of regex you're using, but this will work in any of the most popular ones that can be considered "complete".

/.+?(?=abc)/

How it works

The .+? part is the un-greedy version of .+ (one or more of anything). When we use .+, the engine will basically match everything. Then, if there is something else in the regex it will go back in steps trying to match the following part. This is the greedy behavior, meaning as much as possible to satisfy.

When using .+?, instead of matching all at once and going back for other conditions (if any), the engine will match the next characters by step until the subsequent part of the regex is matched (again if any). This is the un-greedy, meaning match the fewest possible to satisfy.

/.+X/  ~ "abcXabcXabcX"        /.+/  ~ "abcXabcXabcX"
          ^^^^^^^^^^^^                  ^^^^^^^^^^^^

/.+?X/ ~ "abcXabcXabcX"        /.+?/ ~ "abcXabcXabcX"
          ^^^^                          ^

Following that we have (?={contents}), a zero width assertion, a look around. This grouped construction matches its contents, but does not count as characters matched (zero width). It only returns if it is a match or not (assertion).

Thus, in other terms the regex /.+?(?=abc)/ means:

Match any characters as few as possible until a "abc" is found, without counting the "abc".

Why does Boolean.ToString output "True" and not "true"

It's simple code to convert that to all lower case.

Not so simple to convert "true" back to "True", however.

true.ToString().ToLower() 

is what I use for xml output.

Read/Write String from/to a File in Android

For those looking for a general strategy for reading and writing a string to file:

First, get a file object

You'll need the storage path. For the internal storage, use:

File path = context.getFilesDir();

For the external storage (SD card), use:

File path = context.getExternalFilesDir(null);

Then create your file object:

File file = new File(path, "my-file-name.txt");

Write a string to the file

FileOutputStream stream = new FileOutputStream(file);
try {
    stream.write("text-to-write".getBytes());
} finally {
    stream.close();
}

Or with Google Guava

String contents = Files.toString(file, StandardCharsets.UTF_8);

Read the file to a string

int length = (int) file.length();

byte[] bytes = new byte[length];

FileInputStream in = new FileInputStream(file);
try {
    in.read(bytes);
} finally {
    in.close();
}

String contents = new String(bytes);   

Or if you are using Google Guava

String contents = Files.toString(file,"UTF-8");

For completeness I'll mention

String contents = new Scanner(file).useDelimiter("\\A").next();

which requires no libraries, but benchmarks 50% - 400% slower than the other options (in various tests on my Nexus 5).

Notes

For each of these strategies, you'll be asked to catch an IOException.

The default character encoding on Android is UTF-8.

If you are using external storage, you'll need to add to your manifest either:

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

or

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

Write permission implies read permission, so you don't need both.

How to get the first non-null value in Java?

Following on from LES2's answer, you can eliminate some repetition in the efficient version, by calling the overloaded function:

public static <T> T coalesce(T a, T b) {
    return a != null ? a : b;
}
public static <T> T coalesce(T a, T b, T c) {
    return a != null ? a : coalesce(b,c);
}
public static <T> T coalesce(T a, T b, T c, T d) {
    return a != null ? a : coalesce(b,c,d);
}
public static <T> T coalesce(T a, T b, T c, T d, T e) {
    return a != null ? a : coalesce(b,c,d,e);
}

Python - Create list with numbers between 2 values?

If you are looking for range like function which works for float type, then here is a very good article.

def frange(start, stop, step=1.0):
    ''' "range()" like function which accept float type''' 
    i = start
    while i < stop:
        yield i
        i += step
# Generate one element at a time.
# Preferred when you don't need all generated elements at the same time. 
# This will save memory.
for i in frange(1.0, 2.0, 0.5):
    print i   # Use generated element.
# Generate all elements at once.
# Preferred when generated list ought to be small.
print list(frange(1.0, 10.0, 0.5))    

Output:

1.0
1.5
[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5]

Stripping everything but alphanumeric chars from a string in Python

You could try:

print ''.join(ch for ch in some_string if ch.isalnum())

How can I use external JARs in an Android project?

I'm currently using SDK 20.0.3 and none of the previous solutions worked for me.

The reason that hessdroid works where hess failed is because the two jar files contain java that is compiled for different virtual machines. The byte code created by the Java compiler is not guaranteed to run on the Dalvik virtual machine. The byte code created by the Android compiler is not guaranteed to run on the Java virtual machine.

In my case I had access to the source code and was able to create an Android jar file for it using the method that I described here: https://stackoverflow.com/a/13144382/545064

C# binary literals

Update

C# 7.0 now has binary literals, which is awesome.

[Flags]
enum Days
{
    None = 0,
    Sunday    = 0b0000001,
    Monday    = 0b0000010,   // 2
    Tuesday   = 0b0000100,   // 4
    Wednesday = 0b0001000,   // 8
    Thursday  = 0b0010000,   // 16
    Friday    = 0b0100000,   // etc.
    Saturday  = 0b1000000,
    Weekend = Saturday | Sunday,
    Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday
}

Original Post

Since the topic seems to have turned to declaring bit-based flag values in enums, I thought it would be worth pointing out a handy trick for this sort of thing. The left-shift operator (<<) will allow you to push a bit to a specific binary position. Combine that with the ability to declare enum values in terms of other values in the same class, and you have a very easy-to-read declarative syntax for bit flag enums.

[Flags]
enum Days
{
    None        = 0,
    Sunday      = 1,
    Monday      = 1 << 1,   // 2
    Tuesday     = 1 << 2,   // 4
    Wednesday   = 1 << 3,   // 8
    Thursday    = 1 << 4,   // 16
    Friday      = 1 << 5,   // etc.
    Saturday    = 1 << 6,
    Weekend     = Saturday | Sunday,
    Weekdays    = Monday | Tuesday | Wednesday | Thursday | Friday
}

How can I get a favicon to show up in my django app?

In template file

{% load static %}

Then within <head> tag

<link rel="shortcut icon" href="{%  static 'favicon.ico' %}">

This assumes that you have static files configured appropiately in settings.py.


Note: older versions of Django use load staticfiles, not load static.

Best practices for SQL varchar column length

I haven't checked this lately, but I know in the past with Oracle that the JDBC driver would reserve a chunk of memory during query execution to hold the result set coming back. The size of the memory chunk is dependent on the column definitions and the fetch size. So the length of the varchar2 columns affects how much memory is reserved. This caused serious performance issues for me years ago as we always used varchar2(4000) (the max at the time) and garbage collection was much less efficient than it is today.

What is the fastest factorial function in JavaScript?

This will return the factorial of n

function f(n) {
    var e = n;
    if (e == 1 | e == 0) return 1;
    while (n--) {
        if (n < 1)
            break;
        e *= n;
    }
    return e
}

typeof !== "undefined" vs. != null

You shouldn't really worry about undefined being renamed. If someone renames undefined, you will be in a lot more trouble than just a few if checks failing. If you really want to protect your code, wrap it in an IFFE (immediately invoked function expression) like this:

(function($, Backbone, _, undefined) {
    //undefined is undefined here.
})(jQuery, Backbone, _);

If you're working with global variables (which is wrong already) in a browser enviroment, I'd check for undefined like this:

if(window.neverDefined === undefined) {
    //Code works
}

Since global variables are a part of the window object, you can simply check against undefined instead of casting to a string and comparing strings.

On top of that, why are your variables not defined? I've seen a lot of code where they check a variables existence and perform some action based on that. Not once have I seen where this approach has been correct.

Markdown and image alignment

You can embed HTML in Markdown, so you can do something like this:

<img style="float: right;" src="whatever.jpg">

Continue markdown text...

Access denied for user 'root'@'localhost' (using password: YES) after new installation on Ubuntu

TL;DR: To access newer versions of mysql/mariadb after as the root user, after a new install, you need to be in a root shell (ie sudo mysql -u root, or mysql -u root inside a shell started by su - or sudo -i first)


Having just done the same upgrade, on Ubuntu, I had the same issue.

What was odd was that

sudo /usr/bin/mysql_secure_installation

Would accept my password, and allow me to set it, but I couldn't log in as root via the mysql client

I had to start mariadb with

sudo mysqld_safe --skip-grant-tables

to get access as root, whilst all the other users could still access fine.

Looking at the mysql.user table I noticed for root the plugin column is set to unix_socket whereas all other users it is set to 'mysql_native_password'. A quick look at this page: https://mariadb.com/kb/en/mariadb/unix_socket-authentication-plugin/ explains that the Unix Socket enables logging in by matching uid of the process running the client with that of the user in the mysql.user table. In other words to access mariadb as root you have to be logged in as root.

Sure enough restarting my mariadb daemon with authentication required I can login as root with

sudo mysql -u root -p

or

sudo su -
mysql -u root -p

Having done this I thought about how to access without having to do the sudo, which is just a matter of running these mysql queries

GRANT ALL PRIVILEGES on *.* to 'root'@'localhost' IDENTIFIED BY '<password>';
FLUSH PRIVILEGES;

(replacing <password> with your desired mysql root password). This enabled password logins for the root user.

Alternatively running the mysql query:

UPDATE mysql.user SET plugin = 'mysql_native_password' WHERE user = 'root' AND plugin = 'unix_socket';
FLUSH PRIVILEGES;

Will change the root account to use password login without changing the password, but this may leave you with a mysql/mariadb install with no root password on it.

After either of these you need to restarting mysql/mariadb:

sudo service mysql restart

And voila I had access from my personal account via mysql -u root -p

PLEASE NOTE THAT DOING THIS IS REDUCING SECURITY Presumably the MariaDB developers have opted to have root access work like this for a good reason.

Thinking about it I'm quite happy to have to sudo mysql -u root -p so I'm switching back to that, but I thought I'd post my solution as I couldn't find one elsewhere.

How to give a Blob uploaded as FormData a file name?

Are you using Google App Engine? You could use cookies (made with JavaScript) to maintain a relationship between filenames and the name received from the server.

Sort array by firstname (alphabetically) in Javascript

in simply words you can use this method

users.sort(function(a,b){return a.firstname < b.firstname ? -1 : 1});

How to display HTML in TextView?

May I suggest a somewhat hacky but still genius solution! I got the idea from this article and adapted it for Android. Basically you use a WebView and insert the HTML you want to show and edit in an editable div tag. This way when the user taps the WebView the keyboard appears and allows editing. They you just add some JavaScript to get back the edited HTML and voila!

Here is the code:

public class HtmlTextEditor extends WebView {

    class JsObject {
        // This field always keeps the latest edited text
        public String text;
        @JavascriptInterface
        public void textDidChange(String newText) {
            text = newText.replace("\n", "");
        }
    }

    private JsObject mJsObject;

    public HtmlTextEditor(Context context, AttributeSet attrs) {
        super(context, attrs);

        getSettings().setJavaScriptEnabled(true);
        mJsObject = new JsObject();
        addJavascriptInterface(mJsObject, "injectedObject");
        setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                loadUrl(
                        "javascript:(function() { " +
                            "    var editor = document.getElementById(\"editor\");" +
                            "    editor.addEventListener(\"input\", function() {" +
                            "        injectedObject.textDidChange(editor.innerHTML);" +
                            "    }, false)" +
                            "})()");
            }
        });
    }

    public void setText(String text) {
        if (text == null) { text = ""; }

        String editableHtmlTemplate = "<!DOCTYPE html>" + "<html>" + "<head>" + "<meta name=\"viewport\" content=\"initial-scale=1.0\" />" + "</head>" + "<body>" + "<div id=\"editor\" contenteditable=\"true\">___REPLACE___</div>" + "</body>" + "</html>";
        String editableHtml = editableHtmlTemplate.replace("___REPLACE___", text);
        loadData(editableHtml, "text/html; charset=utf-8", "UTF-8");
        // Init the text field in case it's read without editing the text before
        mJsObject.text = text;
    }

    public String getText() {
        return mJsObject.text;
    }
}

And here is the component as a Gist.

Note: I didn't need the height change callback from the original solution so that's missing here but you can easily add it if needed.

Replace whitespaces with tabs in linux

better tr command:

tr [:blank:] \\t

This will clean up the output of say, unzip -l , for further processing with grep, cut, etc.

e.g.,

unzip -l some-jars-and-textfiles.zip | tr [:blank:] \\t | cut -f 5 | grep jar

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

EDIT 2

After three months we can say: no more official Google Apps in Genymotion and CyanogenMod-like method is only way to get Google Apps. However, you can still use the previous project of the Genymotion team: AndroVM (download mirror).


EDIT

Google apps will be removed from Genymotion in November. You can find more information on the Genymotion Google Plus page.


Choose virtual device with Google Apps:

Done:

Clearing <input type='file' /> using jQuery

What? In your validation function, just put

document.onlyform.upload.value="";

Assuming upload is the name:

<input type="file" name="upload" id="csv_doc"/>

I'm using JSP, not sure if that makes a difference...

Works for me, and I think it's way easier.

ERROR 2003 (HY000): Can't connect to MySQL server (111)

I had the same problem trying to connect to a remote mysql db.

I fixed it by opening the firewall on the db server to allow traffic through:

sudo ufw allow mysql

How to allow CORS in react.js?

Suppose you want to hit https://yourwebsitedomain/app/getNames from http://localhost:3000 then just make the following changes:

packagae.json :

   "name": "version-compare-app",
   "proxy": "https://yourwebsitedomain/",
   ....
   "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
     ...

In your component use it as follows:

import axios from "axios";

componentDidMount() {
const getNameUrl =
  "app/getNames";

axios.get(getChallenge).then(data => {
  console.log(data);
});

}

Stop your local server and re run npm start. You should be able to see the data in browser's console logged

How to disable a ts rule for a specific line?

@ts-expect-error

TS 3.9 introduces a new magic comment. @ts-expect-error will:

  • have same functionality as @ts-ignore
  • trigger an error, if actually no compiler error has been suppressed (= indicates useless flag)
if (false) {
  // @ts-expect-error: Let's ignore a single compiler error like this unreachable code 
  console.log("hello"); // compiles
}

// If @ts-expect-error didn't suppress anything at all, we now get a nice warning 
let flag = true;
// ...
if (flag) {
  // @ts-expect-error
  // ^~~~~~~~~~~~~~~^ error: "Unused '@ts-expect-error' directive.(2578)"
  console.log("hello"); 
}

Alternatives

@ts-ignore and @ts-expect-error can be used for all sorts of compiler errors. For type issues (like in OP), I recommend one of the following alternatives due to narrower error suppression scope:

? Use any type

// type assertion for single expression
delete ($ as any).summernote.options.keyMap.pc.TAB;

// new variable assignment for multiple usages
const $$: any = $
delete $$.summernote.options.keyMap.pc.TAB;
delete $$.summernote.options.keyMap.mac.TAB;

? Augment JQueryStatic interface

// ./global.d.ts
interface JQueryStatic {
  summernote: any;
}

// ./main.ts
delete $.summernote.options.keyMap.pc.TAB; // works

In other cases, shorthand module declarations or module augmentations for modules with no/extendable types are handy utilities. A viable strategy is also to keep not migrated code in .js and use --allowJs with checkJs: false.

How to get Bitmap from an Uri?

It seems that MediaStore.Images.Media.getBitmap was deprecated in API 29. The recommended way is to use ImageDecoder.createSource which was added in API 28.

Here's how getting the bitmap would be done:

val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
    ImageDecoder.decodeBitmap(ImageDecoder.createSource(requireContext().contentResolver, imageUri))
} else {
    MediaStore.Images.Media.getBitmap(requireContext().contentResolver, imageUri)
}

How do I download the Android SDK without downloading Android Studio?

Well the folks who are trying to download either on *ix or Ec2 machine would suggest to clean approach in below steps:

$ mkdir android-sdk
$ cd android-sdk
$ mkdir cmdline-tools
$ cd cmdline-tools
$ wget https://dl.google.com/android/repository/commandlinetools-linux-*.zip
$ unzip commandlinetools-linux-*.zip

The king - sdkmanager lives inside

cmdline-tools/tools/bin

, you'd better set in PATH environment variable.

but cmdline-tools should not be set as ANDROID_HOME. Because later, when updating Android SDK, or installing more packages, the other packages will be placed under ANDROID_HOME, but not under cmdline-tools.

The final, complete ANDROID_HOME directory structure should look like below, consist of quite a few sub-directories:

build-tools, cmdline-tools, emulator, licenses, patcher, platform-tools, platforms, tools. You can easily point out that build-tools and cmdline-tools are siblings, all resides inside the parent ANDROID_HOME.

Add SDK tools directory in PATH environment variable to make executable available globally. Add below line either in ~/.bashrc or ~/.profile file to make it permanent.

In order to edit the ~/.bashrc simply can be editable in vim mode

$ vim .bashrc

Now set your preferred ANDROID_HOME in .bashrc file :

export ANDROID_HOME=/home/<user>/android-sdk
export PATH=${PATH}:$ANDROID_HOME/cmdline-tools/tools/bin:$ANDROID_HOME/platform-tools

here strange thing that we haven't download the platform-tools directory as of now but mentoning it under path but let it be as it will help you avoid remodification on the same file later.

Now go inside the same directory:

$ cd android-sdk

NOTE: well in first attempt sdkmanager command didnt found for me so I close the terminal and again created the connection or you can also refresh the same if it works for you.

after that use the sdkmanager to list and install the packages needed:

$ sdkmanager "platform-tools" "platforms;android-27" "build-tools;27.0.3"

Hence Sdkmanager path is already set it will be accessible from anywhere:

$ sdkmanager --update


$ sdkmanager --list
Installed packages:=====================] 100% Computing updates...             
  Path                 | Version | Description                    | Location             
  -------              | ------- | -------                        | -------              
  build-tools;27.0.3   | 27.0.3  | Android SDK Build-Tools 27.0.3 | build-tools/27.0.3/  
  emulator             | 30.0.12 | Android Emulator               | emulator/            
  patcher;v4           | 1       | SDK Patch Applier v4           | patcher/v4/          
  platform-tools       | 30.0.1  | Android SDK Platform-Tools     | platform-tools/      
  platforms;android-27 | 3       | Android SDK Platform 27        | platforms/android-27/

How to upgrade scikit-learn package in anaconda

Anaconda comes with the conda package manager which is designed to handle these kinds of upgrades. Start by updating conda itself to get the most recent package lists:

conda update conda

And then install the version of scikit-learn you want

conda install scikit-learn=0.17

All necessary dependencies will be upgraded as well. If you have trouble with conda on Windows, there are some relevant FAQ here: http://docs.continuum.io/anaconda/faq

Why ModelState.IsValid always return false in mvc

As Brad Wilson states in his answer here:

ModelState.IsValid tells you if any model errors have been added to ModelState.

The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.

Try using :-

if (!ModelState.IsValid)
{
    var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));

    // Breakpoint, Log or examine the list with Exceptions.
}

If it helps catching you the error. Courtesy this and this

How can I insert new line/carriage returns into an element.textContent?

You could use regular expressions to replace the '\n' or '\n\r' characters with '<br />'.

you have this:

var h1 = document.createElement("h1");

h1.textContent = "This is a very long string and I would like to insert a carriage return HERE...
moreover, I would like to insert another carriage return HERE... 
so this text will display in a new line";

you can replace your characters like this:

h1.innerHTML = h1.innerHTML.replace(/\n\r?/g, '<br />');

check the javascript reference for the String and Regex objects:

http://www.w3schools.com/jsref/jsref_replace.asp

http://www.w3schools.com/jsref/jsref_obj_regexp.asp

Android; Check if file exists without creating a new one

if(new File("/sdcard/your_filename.txt").exists())){

// Your code goes here...

}

Default SecurityProtocol in .NET 4.5

Following code will:

  • print enabled protocols
  • print available protocols
  • enable TLS1.2 if platform supports it and if it is not enabled to begin with
  • disable SSL3 if it is enabled
  • print end result

Constants:

  • 48 is SSL3
  • 192 is TLS1
  • 768 is TLS1.1
  • 3072 is TLS1.2

Other protocols will not be affected. This makes this compatible with future protocols (Tls1.3, etc).

Code

// print initial status
    Console.WriteLine("Runtime: " + System.Diagnostics.FileVersionInfo.GetVersionInfo(typeof(int).Assembly.Location).ProductVersion);
    Console.WriteLine("Enabled protocols:   " + ServicePointManager.SecurityProtocol);
    Console.WriteLine("Available protocols: ");
    Boolean platformSupportsTls12 = false;
    foreach (SecurityProtocolType protocol in Enum.GetValues(typeof(SecurityProtocolType))) {                
        Console.WriteLine(protocol.GetHashCode());
        if (protocol.GetHashCode() == 3072){
            platformSupportsTls12 = true;
        }
    }
    Console.WriteLine("Is Tls12 enabled: " + ServicePointManager.SecurityProtocol.HasFlag((SecurityProtocolType)3072));    


// enable Tls12, if possible
    if (!ServicePointManager.SecurityProtocol.HasFlag((SecurityProtocolType)3072)){
        if (platformSupportsTls12){
            Console.WriteLine("Platform supports Tls12, but it is not enabled. Enabling it now.");
            ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072;
        } else {
            Console.WriteLine("Platform does not supports Tls12.");
        }
    }

// disable ssl3
   if (ServicePointManager.SecurityProtocol.HasFlag(SecurityProtocolType.Ssl3)) { 
      Console.WriteLine("Ssl3SSL3 is enabled. Disabling it now.");
      // disable SSL3. Has no negative impact if SSL3 is already disabled. The enclosing "if" if just for illustration.
      System.Net.ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3;                      
   }
    Console.WriteLine("Enabled protocols:   " + ServicePointManager.SecurityProtocol);

Output

Runtime: 4.7.2114.0
Enabled protocols:   Ssl3, Tls
Available protocols: 
0
48
192
768
3072
Is Tls12 enabled: False
Platform supports Tls12, but it is not enabled. Enabling it now.
Ssl3 is enabled. Disabling it now.
Enabled protocols:   Tls, Tls12

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

I've encountered this problem when copying a git repo with working files from an old hard drive a couple times. The problem stems from the fact that the owner and permissions changed from the old drive/machine to the new one. The long and short of it is, run the following commands to straighten things out (thanks to this superuser answer):

sudo chmod -R -x . # remove the executable bit from all files

The former command will actually resolve the differences that git diff reported, but will revoke your ability to list the directories, so ls ./ fails with ls: .: Permission denied. To fix that:

sudo chmod -R +X . # add the executable bit only for directories

The bad news is that if you do have any files you want to keep executable, such as .sh scripts, you'll need to revert those. You can do that with the following command for each file:

chmod +x ./build.sh # where build.sh is the file you want to make executable again

Vertical (rotated) text in HTML table

Here is one that works for plain-text with some server side processing:

public string RotateHtmltext(string innerHtml)
{
   const string TRANSFORMTEXT = "transform: rotate(90deg);";
   const string EXTRASTYLECSS = "<style type='text/css'>.r90 {"
                                 + "-webkit-" + TRANSFORMTEXT
                                 + "-moz-" + TRANSFORMTEXT
                                 + "-o-" + TRANSFORMTEXT
                                 + "-ms-" + TRANSFORMTEXT
                                 + "" + TRANSFORMTEXT
                                 + "width:1em;line-height:1ex}</style>";
   const string WRAPPERDIV = "<div style='display: table-cell; vertical-align: middle;'>";

   var newinnerHtml = string.Join("</div>"+WRAPPERDIV, Regex.Split(innerHtml, @"<br */?>").Reverse());

   newinnerHtml = Regex.Replace(newinnerHtml, @"((?:<[^>]*>)|(?:[^<]+))",
                                 match => match.Groups[1].Value.StartsWith("<")
                                             ? match.Groups[1].Value
                                             : string.Join("", match.Groups[1].Value.ToCharArray().Select(x=>"<div class='r90'>"+x+"</div>")),
                                 RegexOptions.Singleline);
   return EXTRASTYLECSS + WRAPPERDIV + newinnerHtml + "</div>";
}

which gives something like:

<style type="text/css">.r90 {
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
width: 1em;
line-height: 1ex; 
}</style>
<div style="display: table-cell; vertical-align: middle;">
<div class="r90">p</div>
<div class="r90">o</div>
<div class="r90">s</div>
</div><div style="display: table-cell; vertical-align: middle;">
<div class="r90">(</div>
<div class="r90">A</div>
<div class="r90">b</div>
<div class="r90">s</div>
<div class="r90">)</div>
</div>

http://jsfiddle.net/TzzHy/

Difference between IsNullOrEmpty and IsNullOrWhiteSpace in C#

The first method checks if a string is null or a blank string. In your example you can risk a null reference since you are not checking for null before trimming

1- string.IsNullOrEmpty(text.Trim())

The second method checks if a string is null or an arbitrary number of spaces in the string (including a blank string)

2- string .IsNullOrWhiteSpace(text)

The method IsNullOrWhiteSpace covers IsNullOrEmpty, but it also returns true if the string contains white space.

In your concrete example you should use 2) as you run the risk of a null reference exception in approach 1) since you're calling trim on a string that may be null

WPF: Setting the Width (and Height) as a Percentage Value

I use two methods for relative sizing. I have a class called Relative with three attached properties To, WidthPercent and HeightPercent which is useful if I want an element to be a relative size of an element anywhere in the visual tree and feels less hacky than the converter approach - although use what works for you, that you're happy with.

The other approach is rather more cunning. Add a ViewBox where you want relative sizes inside, then inside that, add a Grid at width 100. Then if you add a TextBlock with width 10 inside that, it is obviously 10% of 100.

The ViewBox will scale the Grid according to whatever space it has been given, so if its the only thing on the page, then the Grid will be scaled out full width and effectively, your TextBlock is scaled to 10% of the page.

If you don't set a height on the Grid then it will shrink to fit its content, so it'll all be relatively sized. You'll have to ensure that the content doesn't get too tall, i.e. starts changing the aspect ratio of the space given to the ViewBox else it will start scaling the height as well. You can probably work around this with a Stretch of UniformToFill.

Playing .mp3 and .wav in Java?

I wrote a pure java mp3 player: mp3transform.

How To Get Selected Value From UIPickerView

This is my answer

- (IBAction)Result:(id)sender 
{
   self.statusLabel.text = DataSource[[pickerViewTool selectedRowInComponent:0]];

}

Git push requires username and password

As many users has said, you just have to change your Git repository URL from HTTPS to SSH.

If you haven't generated a SSH key in your machine, then your are going to have to do it.

Just as an additional information, after doing this change I still was getting the same error:

Permission Denied.

In my case, the problem was that I was using the Windows Shell to execute the ngh command; since this command should open a prompt to request the SSH phrase and the Windows Shell doesn't open these kinds of prompts, the authentication just failed.

So, I just had to open the Git shell and execute the ngh command there, put the SSH phrase in the prompt every time it asked for it and "voilà"... It just worked fine!

How do I make a new line in swift

You can do this

textView.text = "Name: \(string1) \n" + "Phone Number: \(string2)"

The output will be

Name: output of string1 Phone Number: output of string2

How to generate a random String in Java

Random ran = new Random();
int top = 3;
char data = ' ';
String dat = "";

for (int i=0; i<=top; i++) {
  data = (char)(ran.nextInt(25)+97);
  dat = data + dat;
}

System.out.println(dat);

JavaScript closure inside loops – simple practical example

This is a problem often encountered with asynchronous code, the variable i is mutable and at the time at which the function call is made the code using i will be executed and i will have mutated to its last value, thus meaning all functions created within the loop will create a closure and i will be equal to 3 (the upper bound + 1 of the for loop.

A workaround to this, is to create a function that will hold the value of i for each iteration and force a copy i (as it is a primitive, think of it as a snapshot if it helps you).

How get data from material-ui TextField, DropDownMenu components?

flson's code did not work for me. For those in the similar situation, here is my slightly different code:

<TextField ref='myTextField'/>

get its value using

this.refs.myTextField.input.value

How to create a simple map using JavaScript/JQuery

This is an old question, but because the existing answers could be very dangerous, I wanted to leave this answer for future folks who might stumble in here...

The answers based on using an Object as a HashMap are broken and can cause extremely nasty consequences if you use anything other than a String as the key. The problem is that Object properties are coerced to Strings using the .toString method. This can lead to the following nastiness:

function MyObject(name) {
  this.name = name;
};
var key1 = new MyObject("one");
var key2 = new MyObject("two");

var map = {};
map[key1] = 1;
map[key2] = 2;

If you were expecting that Object would behave in the same way as a Java Map here, you would be rather miffed to discover that map only contains one entry with the String key [object Object]:

> JSON.stringify(map);
{"[object Object]": 2}

This is clearly not a replacement for Java's HashMap. Bizarrely, given it's age, Javascript does not currently have a general purpose map object. There is hope on the horizon, though: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map although a glance at the Browser Compatability table there will show that this isn't ready to used in general purpose web apps yet.

In the meantime, the best you can do is:

  • Deliberately use Strings as keys. I.e. use explicit strings as keys rather than relying on the implicit .toString-ing of the keys you use.
  • Ensure that the objects you are using as keys have a well-defined .toString() method that suits your understanding of uniqueness for these objects.
  • If you cannot/don't want to change the .toString of the key Objects, when storing and retrieving the entries, convert the objects to a string which represents your understanding of uniqueness. E.g. map[toUniqueString(key1)] = 1

Sometimes, though, that is not possible. If you want to map data based on, for example File objects, there is no reliable way to do this because the attributes that the File object exposes are not enough to ensure its uniqueness. (You may have two File objects that represent different files on disk, but there is no way to distinguish between them in JS in the browser). In these cases, unfortunately, all that you can do is refactor your code to eliminate the need for storing these in a may; perhaps, by using an array instead and referencing them exclusively by index.

getch and arrow codes

for a solution that uses ncurses with working code and initialization of ncurses see getchar() returns the same value (27) for up and down arrow keys

Color text in terminal applications in UNIX

Use ANSI escape sequences. This article goes into some detail about them. You can use them with printf as well.

How to escape % in String.Format?

To escape %, you will need to double it up: %%.

Iterate through pairs of items in a Python list

From the itertools recipes:

from itertools import tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

for v, w in pairwise(a):
    ...

Can I call a base class's virtual function if I'm overriding it?

Yes you can call it. C++ syntax for calling parent class function in child class is

class child: public parent {
  // ...

  void methodName() {
    parent::methodName(); // calls Parent class' function
  }
};

Read more about function overriding.

How to override the path of PHP to use the MAMP path?

The latest version of MAMP (Version 5+) offers an easy way to make the MAMP PHP version available to the command line. Just select "PHP" in the the side bar menu and check "Make this version available on the command line". Easy peasy! See attached screenshot:)

screenshot

Check if a time is between two times (time DataType)

Let us consider a table which stores the shift details

enter image description here

Please check the SQL queries to generate table and finding the schedule based on an input(time)

Declaring the Table variable

declare @MyShiftTable table(MyShift int,StartTime time,EndTime time)

Adding values to Table variable

insert into @MyShiftTable select 1,'01:17:40.3530000','02:17:40.3530000'
insert into @MyShiftTable select 2,'09:17:40.3530000','03:17:40.3530000'
insert into @MyShiftTable select 3,'10:17:40.3530000','18:17:40.3530000'

Creating another table variable with an additional field named "Flag"

declare @Temp table(MyShift int,StartTime time,EndTime time,Flag int)

Adding values to temporary table with swapping the start and end time

insert into @Temp select MyShift,case when (StartTime>EndTime) then EndTime else StartTime end,case when (StartTime>EndTime) then StartTime else EndTime end,case when (StartTime>EndTime) then 1 else 0 end from @MyShiftTable

Creating input variable to find the Shift

declare @time time=convert(time,'10:12:40.3530000')

Query to find the shift corresponding to the time supplied

select myShift from @Temp where
(@time between StartTime and EndTime and Flag=0) or (@time not between StartTime and EndTime and Flag=1)

how to parse json using groovy

        def jsonFile = new File('File Path');
        JsonSlurper jsonSlurper = new JsonSlurper();
        def parseJson = jsonSlurper.parse(jsonFile)
        String json = JsonOutput.toJson(parseJson)
        def prettyJson = JsonOutput.prettyPrint(json)
        println(prettyJson)

What is the difference between HTML tags and elements?

Tags and Elements are not the same.

Elements


They are the pieces themselves, i.e. a paragraph is an element, or a header is an element, even the body is an element. Most elements can contain other elements, as the body element would contain header elements, paragraph elements, in fact pretty much all of the visible elements of the DOM.

Eg:

<p>This is the <span>Home</span> page</p>

Tags


Tags are not the elements themselves, rather they're the bits of text you use to tell the computer where an element begins and ends. When you 'mark up' a document, you generally don't want those extra notes that are not really part of the text to be presented to the reader. HTML borrows a technique from another language, SGML, to provide an easy way for a computer to determine which parts are "MarkUp" and which parts are the content. By using '<' and '>' as a kind of parentheses, HTML can indicate the beginning and end of a tag, i.e. the presence of '<' tells the browser 'this next bit is markup, pay attention'.

The browser sees the letters '

' and decides 'A new paragraph is starting, I'd better start a new line and maybe indent it'. Then when it sees '

' it knows that the paragraph it was working on is finished, so it should break the line there before going on to whatever is next.

- Opening tag.

- Closing tagenter image description here

SyntaxError: missing ; before statement

Or you might have something like this (redeclaring a variable):

var data = [];
var data = 

Re-run Spring Boot Configuration Annotation Processor to update generated metadata

None of these options worked for me. I've found that the auto detection of annotation processors to be pretty flaky. I ended up creating a plugin section in the pom.xml file that explicitly sets the annotation processors that are used for the project. The advantage of this is that you don't need to rely on any IDE settings.

<plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.7.0</version>
            <configuration>
                <compilerVersion>1.8</compilerVersion>
                <source>1.8</source>
                <target>1.8</target>
                <annotationProcessors>
                    <annotationProcessor>org.springframework.boot.configurationprocessor.ConfigurationMetadataAnnotationProcessor</annotationProcessor>
                    <annotationProcessor>lombok.launch.AnnotationProcessorHider$AnnotationProcessor</annotationProcessor>
                    <annotationProcessor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</annotationProcessor>
                </annotationProcessors>
            </configuration>
        </plugin>

Uncaught SyntaxError: Unexpected token with JSON.parse

When you are using POST or PUT method, make sure to stringify the body part.

I have documented an example here https://gist.github.com/manju16832003/4a92a2be693a8fda7ca84b58b8fa7154

Java generics - ArrayList initialization

A lot of this has to do with polymorphism. When you assign

X = new Y();

X can be much less 'specific' than Y, but not the other way around. X is just the handle you are accessing Y with, Y is the real instantiated thing,

You get an error here because Integer is a Number, but Number is not an Integer.

ArrayList<Integer> a = new ArrayList<Number>(); // compile-time error

As such, any method of X that you call must be valid for Y. Since X is more generally it probably shares some, but not all of Y's methods. Still, any arguments given must be valid for Y.

In your examples with add, an int (small i) is not a valid Object or Integer.

ArrayList<?> a = new ArrayList<?>();

This is no good because you can't actually instantiate an array list containing ?'s. You can declare one as such, and then damn near anything can follow in new ArrayList<Whatever>();

How do you change Background for a Button MouseOver in WPF?

Just want to share my button style from my ResourceDictionary that i've been using. You can freely change the onHover background at the style triggers. "ColorAnimation To = *your desired BG(i.e #FFCEF7A0)". The button BG will also automatically revert to its original BG after the mouseOver state.You can even set how fast the transition.

Resource Dictionary

<Style x:Key="Flat_Button" TargetType="{x:Type Button}">
    <Setter Property="Width" Value="100"/>
    <Setter Property="Height" Value="50"/>
    <Setter Property="Margin" Value="2"/>
    <Setter Property="FontFamily" Value="Arial Narrow"/>
    <Setter Property="FontSize" Value="12px"/>
    <Setter Property="FontWeight" Value="Bold"/>
    <Setter Property="Cursor" Value="Hand"/>
    <Setter Property="Foreground">
        <Setter.Value>
            <SolidColorBrush Opacity="1" Color="White"/>
        </Setter.Value>
    </Setter>
    <Setter Property="Background" >
        <Setter.Value>
            <SolidColorBrush Opacity="1" Color="#28C2FF" />
        </Setter.Value>
    </Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">

                <Border x:Name="border"
                         SnapsToDevicePixels="True"
                         BorderThickness="1"
                         Padding="4,2"
                         BorderBrush="Gray"
                         CornerRadius="3"
                         Background="{TemplateBinding Background}">
                    <Grid>
                        <ContentPresenter 
                        Margin="2"
                        HorizontalAlignment="Center"
                        VerticalAlignment="Center"
                        RecognizesAccessKey="True" />

                    </Grid>
                </Border>

            </ControlTemplate>
        </Setter.Value>
    </Setter>

    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="true">
            <Trigger.EnterActions>
                <BeginStoryboard>
                    <Storyboard>
                        <ColorAnimation To="#D2F898"
                                        Storyboard.TargetProperty="(Control.Background).(SolidColorBrush.Color)" 
                                        FillBehavior="HoldEnd" Duration="0:0:0.25" AutoReverse="False" RepeatBehavior="1x"/>
                    </Storyboard>
                </BeginStoryboard>
            </Trigger.EnterActions>

            <Trigger.ExitActions>
                <BeginStoryboard>
                    <Storyboard>
                        <ColorAnimation
                                            Storyboard.TargetProperty="(Control.Background).(SolidColorBrush.Color)" 
                                            FillBehavior="HoldEnd" Duration="0:0:0.25" AutoReverse="False" RepeatBehavior="1x"/>
                    </Storyboard>
                </BeginStoryboard>
            </Trigger.ExitActions>

        </Trigger>


    </Style.Triggers>
</Style>

all you have to do is call the style.

Example Implementation

<Button Style="{StaticResource Flat_Button}" Height="Auto"Width="Auto">  
     <StackPanel>
     <TextBlock Text="SAVE" FontFamily="Arial" FontSize="10.667"/>
     </StackPanel>
</Button>

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

Try this:

private void txtEntry_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            string trimText;

            trimText = this.txtEntry.Text.Replace("\r\n", "").ToString();
            this.txtEntry.Text = trimText;
            btnEnter.PerformClick();
        }
    }

Can't connect to local MySQL server through socket homebrew

I had some directories left from another mysql(8.0) installation, that were not removed.

I solved this by doing the following:

First uninstall mysql

brew uninstall [email protected]

Delete the folders/files that were not removed

rm -rf /usr/local/var/mysql
rm /usr/local/etc/my.cnf

Reinstall mysql and link it

brew install [email protected]
brew link --force [email protected]

Enable and start the service

brew services start [email protected]

Which websocket library to use with Node.js?

Getting the ball rolling with this community wiki answer. Feel free to edit me with your improvements.

  • ws WebSocket server and client for node.js. One of the fastest libraries if not the fastest one.

  • websocket-node WebSocket server and client for node.js

  • websocket-driver-node WebSocket server and client protocol parser node.js - used in faye-websocket-node

  • faye-websocket-node WebSocket server and client for node.js - used in faye and sockjs

  • socket.io WebSocket server and client for node.js + client for browsers + (v0 has newest to oldest fallbacks, v1 of Socket.io uses engine.io) + channels - used in stack.io. Client library tries to reconnect upon disconnection.

  • sockjs WebSocket server and client for node.js and others + client for browsers + newest to oldest fallbacks

  • faye WebSocket server and client for node.js and others + client for browsers + fallbacks + support for other server-side languages

  • deepstream.io clusterable realtime server that handles WebSockets & TCP connections and provides data-sync, pub/sub and request/response

  • socketcluster WebSocket server cluster which makes use of all CPU cores on your machine. For example, if you were to use an xlarge Amazon EC2 instance with 32 cores, you would be able to handle almost 32 times the traffic on a single instance.

  • primus Provides a common API for most of the libraries above for easy switching + stability improvements for all of them.

When to use:

  • use the basic WebSocket servers when you want to use the native WebSocket implementations on the clientside, beware of the browser incompatabilities

  • use the fallback libraries when you care about browser fallbacks

  • use the full featured libraries when you care about channels

  • use primus when you have no idea about what to use, are not in the mood for rewriting your application when you need to switch frameworks because of changing project requirements or need additional connection stability.

Where to test:

Firecamp is a GUI testing environment for SocketIO, WS and all major real-time technology. Debug the real-time events while you're developing it.

Writing a string to a cell in excel

replace Range("A1") = "Asdf" with Range("A1").value = "Asdf"

How to switch activity without animation in Android?

You can create a style,

 <style name="noAnimTheme" parent="android:Theme">
   <item name="android:windowAnimationStyle">@null</item>
</style>

and set it as theme for your activity in the manifest:

   <activity android:name=".ui.ArticlesActivity" android:theme="@style/noAnimTheme">
    </activity>

You can also define a style to specify custom entry and exit animations. http://developer.android.com/reference/android/R.attr.html#windowEnterAnimation

Resize to fit image in div, and center horizontally and vertically

This is one way to do it:

Fiddle here: http://jsfiddle.net/4Mvan/1/

HTML:

<div class='container'>
    <a href='#'>
    <img class='resize_fit_center'
      src='http://i.imgur.com/H9lpVkZ.jpg' />
    </a>
</div>

CSS:

.container {
    margin: 10px;
    width: 115px;
    height: 115px;
    line-height: 115px;
    text-align: center;
    border: 1px solid red;
}
.resize_fit_center {
    max-width:100%;
    max-height:100%;
    vertical-align: middle;
}

C# Create New T()

Another way is to use reflection:

protected T GetObject<T>(Type[] signature, object[] args)
{
    return (T)typeof(T).GetConstructor(signature).Invoke(args);
}

SQL to find the number of distinct values in a column

SELECT COUNT(DISTINCT column_name) FROM table as column_name_count;

you've got to count that distinct col, then give it an alias.

How can I write output from a unit test?

I think it is still actual.

You can use this NuGet package: Bitoxygen.Testing.Pane

Call the custom WriteLine method from this library. It creates a Testing pane inside the Output window and puts messages there always (during each test, it runs independently of DEBUG and TRACE flags).

To make tracing more easy I can recommend to create a base class:

[TestClass]
public abstract class BaseTest
{
    #region Properties
    public TestContext TestContext { get; set; }

    public string Class
    {
        get { return this.TestContext.FullyQualifiedTestClassName; }
    }
    public string Method
    {
        get { return this.TestContext.TestName; }
    }
    #endregion

    #region Methods
    protected virtual void Trace(string message)
    {
        System.Diagnostics.Trace.WriteLine(message);

        Output.Testing.Trace.WriteLine(message);
    }
    #endregion
}

[TestClass]
public class SomeTest : BaseTest
{
    [TestMethod]
    public void SomeTest1()
    {
        this.Trace(string.Format("Yeah: {0} and {1}", this.Class, this.Method));
    }
}

Custom "confirm" dialog in JavaScript?

To enable you to use the confirm box like the normal confirm dialog, I would use Promises which will enable you to await on the result of the outcome and then act on this, rather than having to use callbacks.

This will allow you to follow the same pattern you have in other parts of your code with code such as...

  const confirm = await ui.confirm('Are you sure you want to do this?');

  if(confirm){
    alert('yes clicked');
  } else{
    alert('no clicked');
  }

See codepen for example, or run the snippet below.

https://codepen.io/larnott/pen/rNNQoNp

enter image description here

_x000D_
_x000D_
const ui = {_x000D_
  confirm: async (message) => createConfirm(message)_x000D_
}_x000D_
_x000D_
const createConfirm = (message) => {_x000D_
  return new Promise((complete, failed)=>{_x000D_
    $('#confirmMessage').text(message)_x000D_
_x000D_
    $('#confirmYes').off('click');_x000D_
    $('#confirmNo').off('click');_x000D_
    _x000D_
    $('#confirmYes').on('click', ()=> { $('.confirm').hide(); complete(true); });_x000D_
    $('#confirmNo').on('click', ()=> { $('.confirm').hide(); complete(false); });_x000D_
    _x000D_
    $('.confirm').show();_x000D_
  });_x000D_
}_x000D_
                     _x000D_
const saveForm = async () => {_x000D_
  const confirm = await ui.confirm('Are you sure you want to do this?');_x000D_
  _x000D_
  if(confirm){_x000D_
    alert('yes clicked');_x000D_
  } else{_x000D_
    alert('no clicked');_x000D_
  }_x000D_
}
_x000D_
body {_x000D_
  margin: 0px;_x000D_
  font-family: "Arial";_x000D_
}_x000D_
_x000D_
.example {_x000D_
  padding: 20px;_x000D_
}_x000D_
_x000D_
input[type=button] {_x000D_
  padding: 5px 10px;_x000D_
  margin: 10px 5px;_x000D_
  border-radius: 5px;_x000D_
  cursor: pointer;_x000D_
  background: #ddd;_x000D_
  border: 1px solid #ccc;_x000D_
}_x000D_
input[type=button]:hover {_x000D_
  background: #ccc;_x000D_
}_x000D_
_x000D_
.confirm {_x000D_
  display: none;_x000D_
}_x000D_
.confirm > div:first-of-type {_x000D_
  position: fixed;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background: rgba(0, 0, 0, 0.5);_x000D_
  top: 0px;_x000D_
  left: 0px;_x000D_
}_x000D_
.confirm > div:last-of-type {_x000D_
  padding: 10px 20px;_x000D_
  background: white;_x000D_
  position: absolute;_x000D_
  width: auto;_x000D_
  height: auto;_x000D_
  left: 50%;_x000D_
  top: 50%;_x000D_
  transform: translate(-50%, -50%);_x000D_
  border-radius: 5px;_x000D_
  border: 1px solid #333;_x000D_
}_x000D_
.confirm > div:last-of-type div:first-of-type {_x000D_
  min-width: 150px;_x000D_
  padding: 10px;_x000D_
}_x000D_
.confirm > div:last-of-type div:last-of-type {_x000D_
  text-align: right;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="example">_x000D_
  <input type="button" onclick="saveForm()" value="Save" />_x000D_
</div>_x000D_
_x000D_
<!-- Hidden confirm markup somewhere at the bottom of page -->_x000D_
_x000D_
<div class="confirm">_x000D_
  <div></div>_x000D_
  <div>_x000D_
    <div id="confirmMessage"></div>_x000D_
    <div>_x000D_
      <input id="confirmYes" type="button" value="Yes" />_x000D_
      <input id="confirmNo" type="button" value="No" />_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Show git diff on file in staging area

In order to see the changes that have been staged already, you can pass the -–staged option to git diff (in pre-1.6 versions of Git, use –-cached).

git diff --staged
git diff --cached

How to use python numpy.savetxt to write strings and float number to an ASCII file?

You have to specify the format (fmt) of you data in savetxt, in this case as a string (%s):

num.savetxt('test.txt', DAT, delimiter=" ", fmt="%s") 

The default format is a float, that is the reason it was expecting a float instead of a string and explains the error message.

How do I get a reference to the app delegate in Swift?

In my case, I was missing import UIKit on top of my NSManagedObject subclass. After importing it, I could remove that error as UIApplication is the part of UIKit

Hope it helps others !!!

SVN "Already Locked Error"

I got similar error msgs. I run svn clean-up, and then tried "get clock" for a few times. Then this error was gone.

Getting the filenames of all files in a folder

Here's how to look in the documentation.

First, you're dealing with IO, so look in the java.io package.

There are two classes that look interesting: FileFilter and FileNameFilter. When I clicked on the first, it showed me that there was a a listFiles() method in the File class. And the documentation for that method says:

Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.

Scrolling up in the File JavaDoc, I see the constructors. And that's really all I need to be able to create a File instance and call listFiles() on it. Scrolling still further, I can see some information about how files are named in different operating systems.

Javascript ES6/ES5 find in array and change

You can use findIndex to find the index in the array of the object and replace it as required:

var item = {...}
var items = [{id:2}, {id:2}, {id:2}];

var foundIndex = items.findIndex(x => x.id == item.id);
items[foundIndex] = item;

This assumes unique IDs. If your IDs are duplicated (as in your example), it's probably better if you use forEach:

items.forEach((element, index) => {
    if(element.id === item.id) {
        items[index] = item;
    }
});

How to debug a stored procedure in Toad?

Basic Steps to Debug a Procedure in Toad

  1. Load your Procedure in Toad Editor.
  2. Put debug point on the line where you want to debug.See the first screenshot.
  3. Right click on the editor Execute->Execute PLSQL(Debugger).See the second screeshot.
  4. A window opens up,you need to select the procedure from the left side and pass parameters for that procedure and then click Execute.See the third screenshot.
  5. Now start your debugging check Debug-->Step Over...Add Watch etc.

Reference:Toad Debugger

Debug

Execute In Debug

parameter

Effective swapping of elements of an array in Java

If you want to swap string. it's already the efficient way to do that.

However, if you want to swap integer, you can use XOR to swap two integers more efficiently like this:

int a = 1; int b = 2; a ^= b; b ^= a; a ^= b;

Cannot ignore .idea/workspace.xml - keeps popping up

Just tell git to not assume it is changed never matter what:

git update-index --assume-unchanged src/file/to/ignore

yes, you can remove the files from the git repository. But if your team all use the same IDE or you are by yourself, you probably don't want to do that. For yourself, you want to have an ok starting point to resume working, for your teammates as well.

How to make a Bootstrap accordion collapse when clicking the header div?

Another way is make your <a> full fill all the space of the panel-heading. Use this style to do so:

.panel-title a {
    display: block;
    padding: 10px 15px;
    margin: -10px -15px;
}

Check this demo (http://jsfiddle.net/KbQyx/).

Then when you clicking on the heading, you are actually clicking on the <a>.

SQL: How do I SELECT only the rows with a unique value on certain column?

Assuming your table of data is called ProjectInfo:

SELECT DISTINCT Contract, Activity
    FROM ProjectInfo
    WHERE Contract = (SELECT Contract
                          FROM (SELECT DISTINCT Contract, Activity
                                    FROM ProjectInfo) AS ContractActivities
                          GROUP BY Contract
                          HAVING COUNT(*) = 1);

The innermost query identifies the contracts and the activities. The next level of the query (the middle one) identifies the contracts where there is just one activity. The outermost query then pulls the contract and activity from the ProjectInfo table for the contracts that have a single activity.

Tested using IBM Informix Dynamic Server 11.50 - should work elsewhere too.

How can I reuse a navigation bar on multiple pages?

A very old but simple enough technique is to use "Server-Side Includes", to include HTML pages into a top-level page that has the .shtml extension. For instance this would be your index.shtml file:

<html>
<head>...</head>
<body>
<!-- repeated header: note that the #include is in a HTML comment -->
<!--#include file="header.html" -->
<!-- unique content here... -->
</body>
</html>

Yes, it is lame, but it works. Remember to enable SSI support in your HTTP server configuration (this is how to do it for Apache).

Python: Is there an equivalent of mid, right, and left from BASIC?

This is Andy's solution. I just addressed User2357112's concern and gave it meaningful variable names. I'm a Python rookie and preferred these functions.

def left(aString, howMany):
    if howMany <1:
        return ''
    else:
        return aString[:howMany]

def right(aString, howMany):
    if howMany <1:
        return ''
    else:
        return aString[-howMany:]

def mid(aString, startChar, howMany):
    if howMany < 1:
        return ''
    else:
        return aString[startChar:startChar+howMany]

Unable to install gem - Failed to build gem native extension - cannot load such file -- mkmf (LoadError)

I found that I needed to install another version of ruby. So running the command

$ sudo apt-get install ruby1.9.1-dev

and then attempt to install the extension

If you run into issues where it is telling you that you don't have g++ you can run the following command to install it

$ sudo apt-get install g++

Getting multiple values with scanf()

int a,b,c,d;
if(scanf("%d %d %d %d",&a,&b,&c,&d) == 4) {
   //read the 4 integers
} else {
   puts("Error. Please supply 4 integers");
}

A simple explanation of Naive Bayes Classification

I try to explain the Bayes rule with an example.

What is the chance that a random person selected from the society is a smoker?

You may reply 10%, and let's assume that's right.

Now, what if I say that the random person is a man and is 15 years old?

You may say 15 or 20%, but why?.

In fact, we try to update our initial guess with new pieces of evidence ( P(smoker) vs. P(smoker | evidence) ). The Bayes rule is a way to relate these two probabilities.

P(smoker | evidence) = P(smoker)* p(evidence | smoker)/P(evidence)

Each evidence may increase or decrease this chance. For example, this fact that he is a man may increase the chance provided that this percentage (being a man) among non-smokers is lower.

In the other words, being a man must be an indicator of being a smoker rather than a non-smoker. Therefore, if an evidence is an indicator of something, it increases the chance.

But how do we know that this is an indicator?

For each feature, you can compare the commonness (probability) of that feature under the given conditions with its commonness alone. (P(f | x) vs. P(f)).

P(smoker | evidence) / P(smoker) = P(evidence | smoker)/P(evidence)

For example, if we know that 90% of smokers are men, it's not still enough to say whether being a man is an indicator of being smoker or not. For example if the probability of being a man in the society is also 90%, then knowing that someone is a man doesn't help us ((90% / 90%) = 1. But if men contribute to 40% of the society, but 90% of the smokers, then knowing that someone is a man increases the chance of being a smoker (90% / 40%) = 2.25, so it increases the initial guess (10%) by 2.25 resulting 22.5%.

However, if the probability of being a man was 95% in the society, then regardless of the fact that the percentage of men among smokers is high (90%)! the evidence that someone is a man decreases the chance of him being a smoker! (90% / 95%) = 0.95).

So we have:

P(smoker | f1, f2, f3,... ) = P(smoker) * contribution of f1* contribution of f2 *... 
=
P(smoker)* 
(P(being a man | smoker)/P(being a man))*
(P(under 20 | smoker)/ P(under 20))

Note that in this formula we assumed that being a man and being under 20 are independent features so we multiplied them, it means that knowing that someone is under 20 has no effect on guessing that he is man or woman. But it may not be true, for example maybe most adolescence in a society are men...

To use this formula in a classifier

The classifier is given with some features (being a man and being under 20) and it must decide if he is an smoker or not (these are two classes). It uses the above formula to calculate the probability of each class under the evidence (features), and it assigns the class with the highest probability to the input. To provide the required probabilities (90%, 10%, 80%...) it uses the training set. For example, it counts the people in the training set that are smokers and find they contribute 10% of the sample. Then for smokers checks how many of them are men or women .... how many are above 20 or under 20....In the other words, it tries to build the probability distribution of the features for each class based on the training data.

How to install older version of node.js on Windows?

You can use Nodist for this purpose. Download it from here.

Usage:

nodist                         List all installed node versions.
nodist list
nodist ls

nodist <version>               Use the specified node version globally (downloads the executable, if necessary).
nodist latest                  Use the latest available node version globally (downloads the executable, if necessary).

nodist add <version>           Download the specified node version.

More Nodist commands here

If Browser is Internet Explorer: run an alternative script instead

You can do something like this to include IE-specific javascript:

<!--[IF IE]>
    <script type="text/javascript">
        // IE stuff
    </script>
<![endif]-->

Pass by pointer & Pass by reference

Pass by pointer is the only way you could pass "by reference" in C, so you still see it used quite a bit.

The NULL pointer is a handy convention for saying a parameter is unused or not valid, so use a pointer in that case.

References can't be updated once they're set, so use a pointer if you ever need to reassign it.

Prefer a reference in every case where there isn't a good reason not to. Make it const if you can.

Technically what is the main difference between Oracle JDK and OpenJDK?

OpenJDK is a reference model and open source, while Oracle JDK is an implementation of the OpenJDK and is not open source. Oracle JDK is more stable than OpenJDK.

OpenJDK is released under GPL v2 license whereas Oracle JDK is licensed under Oracle Binary Code License Agreement.

OpenJDK and Oracle JDK have almost the same code, but Oracle JDK has more classes and some bugs fixed.

So if you want to develop enterprise/commercial software I would suggest to go for Oracle JDK, as it is thoroughly tested and stable.

I have faced lot of problems with application crashes using OpenJDK, which are fixed just by switching to Oracle JDK

HTML Input Box - Disable

The syntax to disable an HTML input is as follows:

<input type="text" id="input_id" DISABLED />

How to reliably open a file in the same directory as a Python script

I always use:

__location__ = os.path.realpath(
    os.path.join(os.getcwd(), os.path.dirname(__file__)))

The join() call prepends the current working directory, but the documentation says that if some path is absolute, all other paths left of it are dropped. Therefore, getcwd() is dropped when dirname(__file__) returns an absolute path.

Also, the realpath call resolves symbolic links if any are found. This avoids troubles when deploying with setuptools on Linux systems (scripts are symlinked to /usr/bin/ -- at least on Debian).

You may the use the following to open up files in the same folder:

f = open(os.path.join(__location__, 'bundled-resource.jpg'))
# ...

I use this to bundle resources with several Django application on both Windows and Linux and it works like a charm!

Remove all subviews?

Use the Following code to remove all subviews.

for (UIView *view in [self.view subviews]) 
{
 [view removeFromSuperview];
}

SQL Server: Filter output of sp_who2

Similar to KyleMit answer, its possible to select directly the tables used by SP_WHO2, although I think it's only need dbo.sysprocesses table.

If someone open this SP, it can understand what it does. This is my best select to have a similar output as SP_WHO2

select convert(char(5),sp.spid) as SPID
        ,  CASE lower(sp.status)
                 When 'sleeping' Then lower(sp.status)
                 Else  upper(sp.status)
              END as Status
        , convert(sysname, rtrim(sp.loginame)) as LOGIN
        , CASE sp.hostname
                 When Null  Then '  .'
                 When ' ' Then '  .'
                 Else    rtrim(sp.hostname)
              END as HostName
        , CASE isnull(convert(char(5),sp.blocked),'0')
                 When '0' Then '  .'
                 Else isnull(convert(char(5),sp.blocked),'0')
              END as BlkBy
        , case when sp.dbid = 0 then null when sp.dbid <> 0 then db_name(sp.dbid) end as DBName
        , sp.cmd as Command
        , sp.cpu as CPUTime
        , sp.physical_io as DiskIO
        , sp.last_batch as LastBatch
        , sp.program_name as ProgramName 
        from master.dbo.sysprocesses sp (nolock)
  ;

Over this select, you can select the fields you need and have the order you want.

Overlay a background-image with an rgba background-color

The solution by PeterVR has the disadvantage that the additional color displays on top of the entire HTML block - meaning that it also shows up on top of div content, not just on top of the background image. This is fine if your div is empty, but if it is not using a linear gradient might be a better solution:

<div class="the-div">Red text</div>

<style type="text/css">
  .the-div
  {
    background-image: url("the-image.png");
    color: #f00;
    margin: 10px;
    width: 200px;
    height: 80px;
  }
  .the-div:hover
  {
    background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
    background-image: -moz-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
    background-image: -o-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
    background-image: -ms-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
    background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(0, 0, 0, 0.1)), to(rgba(0, 0, 0, 0.1))), url("the-image.png");
    background-image: -webkit-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
  }
</style>

See fiddle. Too bad that gradient specifications are currently a mess. See compatibility table, the code above should work in any browser with a noteworthy market share - with the exception of MSIE 9.0 and older.

Edit (March 2017): The state of the web got far less messy by now. So the linear-gradient (supported by Firefox and Internet Explorer) and -webkit-linear-gradient (supported by Chrome, Opera and Safari) lines are sufficient, additional prefixed versions are no longer necessary.

Python Save to file

You need to open the file again using open(), but this time passing 'w' to indicate that you want to write to the file. I would also recommend using with to ensure that the file will be closed when you are finished writing to it.

with open('Failed.txt', 'w') as f:
    for ip in [k for k, v in ips.iteritems() if v >=5]:
        f.write(ip)

Naturally you may want to include newlines or other formatting in your output, but the basics are as above.

The same issue with closing your file applies to the reading code. That should look like this:

ips = {}
with open('today','r') as myFile:
    for line in myFile:
        parts = line.split(' ')
        if parts[1] == 'Failure':
            if parts[0] in ips:
                ips[pars[0]] += 1
            else:
                ips[parts[0]] = 0

Accessing @attribute from SimpleXML

$xml = <<<XML
<root>
<elem attrib="value" />
</root>
XML;

$sxml = simplexml_load_string($xml);
$attrs = $sxml->elem->attributes();
echo $attrs["attrib"]; //or just $sxml->elem["attrib"]

Use SimpleXMLElement::attributes.

Truth is, the SimpleXMLElement get_properties handler lies big time. There's no property named "@attributes", so you can't do $sxml->elem->{"@attributes"}["attrib"].

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

Python 3.6+ provides built-in convenience methods to find and decode the plain text body as in @Todor Minakov's answer. You can use the EMailMessage.get_body() and get_content() methods:

msg = email.message_from_string(s, policy=email.policy.default)
body = msg.get_body(('plain',))
if body:
    body = body.get_content()
print(body)

Note this will give None if there is no (obvious) plain text body part.

If you are reading from e.g. an mbox file, you can give the mailbox constructor an EmailMessage factory:

mbox = mailbox.mbox(mboxfile, factory=lambda f: email.message_from_binary_file(f, policy=email.policy.default), create=False)
for msg in mbox:
    ...

Note you must pass email.policy.default as the policy, since it's not the default...

What's the difference between struct and class in .NET?

Structs are the actual value - they can be empty but never null

This is true, however also note that as of .NET 2 structs support a Nullable version and C# supplies some syntactic sugar to make it easier to use.

int? value = null;
value  = 1;

How to set a text box for inputing password in winforms?

The best way to solve your problem is to set the UseSystemPasswordChar property to true. Then, the Caps-lock message is shown when the user enters the field and the Caps-Lock is on (at least for Vista and Windows 7).

Another alternative is to set the PasswordChar property to a character value (* for example). This also triggers the automatic Caps-Lock handling.

MySQL "Group By" and "Order By"

Here's one approach:

SELECT cur.textID, cur.fromEmail, cur.subject, 
     cur.timestamp, cur.read
FROM incomingEmails cur
LEFT JOIN incomingEmails next
    on cur.fromEmail = next.fromEmail
    and cur.timestamp < next.timestamp
WHERE next.timestamp is null
and cur.toUserID = '$userID' 
ORDER BY LOWER(cur.fromEmail)

Basically, you join the table on itself, searching for later rows. In the where clause you state that there cannot be later rows. This gives you only the latest row.

If there can be multiple emails with the same timestamp, this query would need refining. If there's an incremental ID column in the email table, change the JOIN like:

LEFT JOIN incomingEmails next
    on cur.fromEmail = next.fromEmail
    and cur.id < next.id

SELECT FOR UPDATE with SQL Server

Question - is this case proven to be the result of lock escalation (i.e. if you trace with profiler for lock escalation events, is that definitely what is happening to cause the blocking)? If so, there is a full explanation and a (rather extreme) workaround by enabling a trace flag at the instance level to prevent lock escalation. See http://support.microsoft.com/kb/323630 trace flag 1211

But, that will likely have unintended side effects.

If you are deliberately locking a row and keeping it locked for an extended period, then using the internal locking mechanism for transactions isn't the best method (in SQL Server at least). All the optimization in SQL Server is geared toward short transactions - get in, make an update, get out. That's the reason for lock escalation in the first place.

So if the intent is to "check out" a row for a prolonged period, instead of transactional locking it's best to use a column with values and a plain ol' update statement to flag the rows as locked or not.

Set the value of an input field

The simple answer is not in Javascript the simplest way to get the placeholder is through the place holder attribute

<input type="text" name="text_box_1" placeholder="My Default Value" />

Object of class DateTime could not be converted to string

$Date = $row['Received_date']->format('d/m/Y');

then it cast date object from given in database

SELECT using 'CASE' in SQL

which platform ?

SELECT 
  CASE 
    WHEN FRUIT = 'A' THEN 'APPLE' 
    ELSE FRUIT ='B' THEN 'BANANA' 
   END AS FRUIT     
FROM FRUIT_TABLE;

In python, what is the difference between random.uniform() and random.random()?

The difference is in the arguments. It's very common to generate a random number from a uniform distribution in the range [0.0, 1.0), so random.random() just does this. Use random.uniform(a, b) to specify a different range.

PHP display current server path

php can call command line operations so

echo exec("pwd");

How to align a div to the top of its parent but keeping its inline-block behaviour?

Use vertical-align:top; for the element you want at the top, as I have demonstrated on your jsfiddle.

http://www.brunildo.org/test/inline-block.html

What is the regex for "Any positive integer, excluding 0"

This should only allow decimals > 0

^([0-9]\.\d+)|([1-9]\d*\.?\d*)$

How can I check for NaN values?

Well I entered this post, because i've had some issues with the function:

math.isnan()

There are problem when you run this code:

a = "hello"
math.isnan(a)

It raises exception. My solution for that is to make another check:

def is_nan(x):
    return isinstance(x, float) and math.isnan(x)

jquery: get value of custom attribute

You need some form of iteration here, as val (except when called with a function) only works on the first element:

$("input[placeholder]").val($("input[placeholder]").attr("placeholder"));

should be:

$("input[placeholder]").each( function () {
    $(this).val( $(this).attr("placeholder") );
});

or

$("input[placeholder]").val(function() {
    return $(this).attr("placeholder");
});

Accessing private member variables from prototype-defined functions

In current JavaScript, I'm fairly certain that there is one and only one way to have private state, accessible from prototype functions, without adding anything public to this. The answer is to use the "weak map" pattern.

To sum it up: The Person class has a single weak map, where the keys are the instances of Person, and the values are plain objects that are used for private storage.

Here is a fully functional example: (play at http://jsfiddle.net/ScottRippey/BLNVr/)

var Person = (function() {
    var _ = weakMap();
    // Now, _(this) returns an object, used for private storage.
    var Person = function(first, last) {
        // Assign private storage:
        _(this).firstName = first;
        _(this).lastName = last;
    }
    Person.prototype = {
        fullName: function() {
            // Retrieve private storage:
            return _(this).firstName + _(this).lastName;
        },
        firstName: function() {
            return _(this).firstName;
        },
        destroy: function() {
            // Free up the private storage:
            _(this, true);
        }
    };
    return Person;
})();

function weakMap() {
    var instances=[], values=[];
    return function(instance, destroy) {
        var index = instances.indexOf(instance);
        if (destroy) {
            // Delete the private state:
            instances.splice(index, 1);
            return values.splice(index, 1)[0];
        } else if (index === -1) {
            // Create the private state:
            instances.push(instance);
            values.push({});
            return values[values.length - 1];
        } else {
            // Return the private state:
            return values[index];
        }
    };
}

Like I said, this is really the only way to achieve all 3 parts.

There are two caveats, however. First, this costs performance -- every time you access the private data, it's an O(n) operation, where n is the number of instances. So you won't want to do this if you have a large number of instances. Second, when you're done with an instance, you must call destroy; otherwise, the instance and the data will not be garbage collected, and you'll end up with a memory leak.

And that's why my original answer, "You shouldn't", is something I'd like to stick to.

Open source face recognition for Android

macgyver offers face detection programs via a simple to use API.

The program below takes a reference to a public image and will return an array of the coordinates and dimensions of any faces detected in the image.

https://askmacgyver.com/explore/program/face-location/5w8J9u4z

Change UITableView height dynamically

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

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

                                self.cellsHeight = 0.0;

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

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

Mark error in form using Bootstrap

Bootstrap V3:

Official Doc Link 1
Official Doc Link 2

<div class="form-group has-success">
  <label class="control-label" for="inputSuccess">Input with success</label>
  <input type="text" class="form-control" id="inputSuccess" />
  <span class="help-block">Woohoo!</span>
</div>
<div class="form-group has-warning">
  <label class="control-label" for="inputWarning">Input with warning</label>
  <input type="text" class="form-control" id="inputWarning">
  <span class="help-block">Something may have gone wrong</span>
</div>
<div class="form-group has-error">
  <label class="control-label" for="inputError">Input with error</label>
  <input type="text" class="form-control" id="inputError">
  <span class="help-block">Please correct the error</span>
</div>

Does Spring @Transactional attribute work on a private method?

Same way as @loonis suggested to use TransactionTemplate one may use this helper component (Kotlin):

@Component
class TransactionalUtils {
    /**
     * Execute any [block] of code (even private methods)
     * as if it was effectively [Transactional]
     */
    @Transactional
    fun <R> executeAsTransactional(block: () -> R): R {
        return block()
    }
}

Usage:

@Service
class SomeService(private val transactionalUtils: TransactionalUtils) {

    fun foo() {
        transactionalUtils.executeAsTransactional { transactionalFoo() }
    }

    private fun transactionalFoo() {
        println("This method is executed within transaction")
    }
}

Don't know whether TransactionTemplate reuse existing transaction or not but this code definitely do.

Adding Text to DataGridView Row Header

make sure the Enable Column Recording is checked.

Custom Input[type="submit"] style not working with jquerymobile button

I'm assume you cannot get css working for your button using anchor tag. So you need to override the css styles which are being overwritten by other elements using !important property.

HTML

<a href="#" class="selected_btn" data-role="button">Button name</a>

CSS

.selected_btn
{
    border:1px solid red;
    text-decoration:none;
    font-family:helvetica;
    color:red !important;            
    background:url('http://www.lessardstephens.com/layout/images/slideshow_big.png') repeat-x;
}

Here is the demo

Conditionally displaying JSF components

In addition to previous post you can have

<h:form rendered="#{!bean.boolvalue}" />
<h:form rendered="#{bean.textvalue == 'value'}" />

Jsf 2.0

How can I copy a file from a remote server to using Putty in Windows?

One of the putty tools is pscp.exe; it will allow you to copy files from your remote host.

Is the size of C "int" 2 bytes or 4 bytes?

I know it's equal to sizeof(int). The size of an int is really compiler dependent. Back in the day, when processors were 16 bit, an int was 2 bytes. Nowadays, it's most often 4 bytes on a 32-bit as well as 64-bit systems.

Still, using sizeof(int) is the best way to get the size of an integer for the specific system the program is executed on.

EDIT: Fixed wrong statement that int is 8 bytes on most 64-bit systems. For example, it is 4 bytes on 64-bit GCC.

Intro to GPU programming

Check out CUDA by NVidia, IMO it's the easiest platform to do GPU programming. There are tons of cool materials to read. http://www.nvidia.com/object/cuda_home.html

Hello world would be to do any kind of calculation using GPU.

Hope that helps.

Control flow in T-SQL SP using IF..ELSE IF - are there other ways?

CASE expression
      WHEN value1 THEN result1
      WHEN value2 THEN result2
      ...
      WHEN valueN THEN resultN

      [
        ELSE elseResult
      ]
END

http://www.4guysfromrolla.com/webtech/102704-1.shtml For more information.

Make footer stick to bottom of page using Twitter Bootstrap

http://bootstrapfooter.codeplex.com/

This should solve your problem.

<div id="wrap">
<div id="main" class="container clear-top">
<div class="row">
<div class="span12">
Your content here.
</div>
</div>
</div>
</div>
<footer class="footer" style="background-color:#c2c2c2">
</footer>

CSS:

html,body
{
height:100%;
}

#wrap
{
min-height: 100%;
}

#main
{
overflow:auto;
padding-bottom:150px; /* this needs to be bigger than footer height*/
}

.footer
{
position: relative;
margin-top: -150px; /* negative value of footer height */
height: 150px;
clear:both;
padding-top:20px;
color:#fff;
}

Is there a simple, elegant way to define singletons?

Here's my own implementation of singletons. All you have to do is decorate the class; to get the singleton, you then have to use the Instance method. Here's an example:

@Singleton
class Foo:
   def __init__(self):
       print 'Foo created'

f = Foo() # Error, this isn't how you get the instance of a singleton

f = Foo.instance() # Good. Being explicit is in line with the Python Zen
g = Foo.instance() # Returns already created instance

print f is g # True

And here's the code:

class Singleton:
    """
    A non-thread-safe helper class to ease implementing singletons.
    This should be used as a decorator -- not a metaclass -- to the
    class that should be a singleton.

    The decorated class can define one `__init__` function that
    takes only the `self` argument. Also, the decorated class cannot be
    inherited from. Other than that, there are no restrictions that apply
    to the decorated class.

    To get the singleton instance, use the `instance` method. Trying
    to use `__call__` will result in a `TypeError` being raised.

    """

    def __init__(self, decorated):
        self._decorated = decorated

    def instance(self):
        """
        Returns the singleton instance. Upon its first call, it creates a
        new instance of the decorated class and calls its `__init__` method.
        On all subsequent calls, the already created instance is returned.

        """
        try:
            return self._instance
        except AttributeError:
            self._instance = self._decorated()
            return self._instance

    def __call__(self):
        raise TypeError('Singletons must be accessed through `instance()`.')

    def __instancecheck__(self, inst):
        return isinstance(inst, self._decorated)

Resize height with Highcharts

You must set the height of the container explicitly

#container {
    height:100%;
    width:100%;
    position:absolute; 
}

See other Stackoverflow answer

Highcharts documentation

Cross compile Go on OSX?

You can do this pretty easily using Docker, so no extra libs required. Just run this command:

docker run --rm -it -v "$GOPATH":/go -w /go/src/github.com/iron-io/ironcli golang:1.4.2-cross sh -c '
for GOOS in darwin linux windows; do
  for GOARCH in 386 amd64; do
    echo "Building $GOOS-$GOARCH"
    export GOOS=$GOOS
    export GOARCH=$GOARCH
    go build -o bin/ironcli-$GOOS-$GOARCH
  done
done
'

You can find more details in this post: https://medium.com/iron-io-blog/how-to-cross-compile-go-programs-using-docker-beaa102a316d

How to get a json string from url?

Use the WebClient class in System.Net:

var json = new WebClient().DownloadString("url");

Keep in mind that WebClient is IDisposable, so you would probably add a using statement to this in production code. This would look like:

using (WebClient wc = new WebClient())
{
   var json = wc.DownloadString("url");
}

Set the text in a span

Use .text() instead, and change your selector:

$(".ui-datepicker-prev .ui-icon.ui-icon-circle-triangle-w").text('<<');

-- VIEW DEMO --

How to check for palindrome using Python logic

def isPalin(checkWord):
    Hsize = len(lst)/2
    seed = 1
    palind=True
    while seed<Hsize+1:
        #print seed,lst[seed-1], lst [-(seed)]
        if(lst[seed-1] != lst [-seed]):
            palind = False
            break
        seed = seed+1
    return palind

lst = 'testset'
print lst, isPalin(lst)    
lst = 'testsest'
print lst, isPalin(lst) 

Output

testset True
testsest False

Get latest from Git branch

If you have forked a repository fro Delete your forked copy and fork it again from master.

Taking pictures with camera on Android programmatically

You can use Magical Take Photo library.

1. try with compile in gradle

compile 'com.frosquivel:magicaltakephoto:1.0'

2. You need this permission in your manifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA"/>

3. instance the class like this

// "this" is the current activity param

MagicalTakePhoto magicalTakePhoto =  new MagicalTakePhoto(this,ANY_INTEGER_0_TO_4000_FOR_QUALITY);

4. if you need to take picture use the method

magicalTakePhoto.takePhoto("my_photo_name");

5. if you need to select picture in device, try with the method:

magicalTakePhoto.selectedPicture("my_header_name");

6. You need to override the method onActivityResult of the activity or fragment like this:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
     super.onActivityResult(requestCode, resultCode, data);
     magicalTakePhoto.resultPhoto(requestCode, resultCode, data);

     // example to get photo
     // imageView.setImageBitmap(magicalTakePhoto.getMyPhoto());
}

Note: Only with this Library you can take and select picture in the device, this use a min API 15.

Chrome / Safari not filling 100% height of flex parent

Solution: Remove height: 100% in .item-inner and add display: flex in .item

Demo: https://codepen.io/tronghiep92/pen/NvzVoo

Using GregorianCalendar with SimpleDateFormat

A SimpleDateFormat, as its name indicates, formats Dates. Not a Calendar. So, if you want to format a GregorianCalendar using a SimpleDateFormat, you must convert the Calendar to a Date first:

dateFormat.format(calendar.getTime());

And what you see printed is the toString() representation of the calendar. It's intended usage is debugging. It's not intended to be used to display a date in a GUI. For that, use a (Simple)DateFormat.

Finally, to convert from a String to a Date, you should also use a (Simple)DateFormat (its parse() method), rather than splitting the String as you're doing. This will give you a Date object, and you can create a Calendar from the Date by instanciating it (Calendar.getInstance()) and setting its time (calendar.setTime()).

My advice would be: Googling is not the solution here. Reading the API documentation is what you need to do.

Best way to serialize/unserialize objects in JavaScript?

I had the exact same problem, and written a small tool to do the mixing of data and model. See https://github.com/khayll/jsmix

This is how you would do it:

//model object (or whatever you'd like the implementation to be)
var Person = function() {}
Person.prototype.isOld = function() {
    return this.age > RETIREMENT_AGE;
}

//then you could say:
var result = JSMix(jsonData).withObject(Person.prototype, "persons").build();

//and use
console.log(result.persons[3].isOld());

It can handle complex objects, like nested collections recursively as well.

As for serializing JS functions, I wouldn't do such thing because of security reasons.

SFTP file transfer using Java JSch

The most trivial way to upload a file over SFTP with JSch is:

JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();

ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();

sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");

Similarly for a download:

sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");

You may need to deal with UnknownHostKey exception.

TypeError: $ is not a function WordPress

There is an easy way to fix it. Just install a plugin and active it. For more : https://www.aitlp.com/wordpress-5-3-is-not-a-function-fix/ .

Tested with Wordpress version 5.3.

Store query result in a variable using in PL/pgSQL

Create Learning Table:

CREATE TABLE "public"."learning" (
    "api_id" int4 DEFAULT nextval('share_api_api_id_seq'::regclass) NOT NULL,
    "title" varchar(255) COLLATE "default"
);

Insert Data Learning Table:

INSERT INTO "public"."learning" VALUES ('1', 'Google AI-01');
INSERT INTO "public"."learning" VALUES ('2', 'Google AI-02');
INSERT INTO "public"."learning" VALUES ('3', 'Google AI-01');

Step: 01

CREATE OR REPLACE FUNCTION get_all (pattern VARCHAR) RETURNS TABLE (
        learn_id INT,
        learn_title VARCHAR
) AS $$
BEGIN
    RETURN QUERY SELECT
        api_id,
        title
    FROM
        learning
    WHERE
        title = pattern ;
END ; $$ LANGUAGE 'plpgsql';

Step: 02

SELECT * FROM get_all('Google AI-01');

Step: 03

DROP FUNCTION get_all();

Demo: enter image description here

Why does IE9 switch to compatibility mode on my website?

To force IE to render in IE9 standards mode you should use

<meta http-equiv="X-UA-Compatible" content="IE=edge">

Some conditions may cause IE9 to jump down into the compatibility modes. By default this can occur on intranet sites.

UnicodeDecodeError when reading CSV file in Pandas with Python

You can try this.

import csv
import pandas as pd
df = pd.read_csv(filepath,encoding='unicode_escape')

Git Cherry-pick vs Merge Workflow

Both rebase (and cherry-pick) and merge have their advantages and disadvantages. I argue for merge here, but it's worth understanding both. (Look here for an alternate, well-argued answer enumerating cases where rebase is preferred.)

merge is preferred over cherry-pick and rebase for a couple of reasons.

  1. Robustness. The SHA1 identifier of a commit identifies it not just in and of itself but also in relation to all other commits that precede it. This offers you a guarantee that the state of the repository at a given SHA1 is identical across all clones. There is (in theory) no chance that someone has done what looks like the same change but is actually corrupting or hijacking your repository. You can cherry-pick in individual changes and they are likely the same, but you have no guarantee. (As a minor secondary issue the new cherry-picked commits will take up extra space if someone else cherry-picks in the same commit again, as they will both be present in the history even if your working copies end up being identical.)
  2. Ease of use. People tend to understand the merge workflow fairly easily. rebase tends to be considered more advanced. It's best to understand both, but people who do not want to be experts in version control (which in my experience has included many colleagues who are damn good at what they do, but don't want to spend the extra time) have an easier time just merging.

Even with a merge-heavy workflow rebase and cherry-pick are still useful for particular cases:

  1. One downside to merge is cluttered history. rebase prevents a long series of commits from being scattered about in your history, as they would be if you periodically merged in others' changes. That is in fact its main purpose as I use it. What you want to be very careful of, is never to rebase code that you have shared with other repositories. Once a commit is pushed someone else might have committed on top of it, and rebasing will at best cause the kind of duplication discussed above. At worst you can end up with a very confused repository and subtle errors it will take you a long time to ferret out.
  2. cherry-pick is useful for sampling out a small subset of changes from a topic branch you've basically decided to discard, but realized there are a couple of useful pieces on.

As for preferring merging many changes over one: it's just a lot simpler. It can get very tedious to do merges of individual changesets once you start having a lot of them. The merge resolution in git (and in Mercurial, and in Bazaar) is very very good. You won't run into major problems merging even long branches most of the time. I generally merge everything all at once and only if I get a large number of conflicts do I back up and re-run the merge piecemeal. Even then I do it in large chunks. As a very real example I had a colleague who had 3 months worth of changes to merge, and got some 9000 conflicts in 250000 line code-base. What we did to fix is do the merge one month's worth at a time: conflicts do not build up linearly, and doing it in pieces results in far fewer than 9000 conflicts. It was still a lot of work, but not as much as trying to do it one commit at a time.

How to open a website when a Button is clicked in Android application?

you can use this on your button click activity

Intent webOpen = new Intent(android.content.Intent.ACTION_VIEW);
            WebOpen.setData(Uri.parse("http://www.google.com"));
                startActivity(myWebLink);

and import this on your code

import android.net.Uri;

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

The compiler is confused by the function signature. You can fix it like this:

let task = URLSession.shared.dataTask(with: request as URLRequest) {

But, note that we don't have to cast "request" as URLRequest in this signature if it was declared earlier as URLRequest instead of NSMutableURLRequest:

var request = URLRequest(url:myUrl!)

This is the automatic casting between NSMutableURLRequest and the new URLRequest that is failing and which forced us to do this casting here.

Change the background color of a pop-up dialog

If you just want a light theme and aren't particular about the specific color, then you can pass a theme id to the AlertDialog.Builder constructor.

AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT)...

or

AlertDialog.Builder(this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)...

How to ignore a property in class if null, using json.net

Here's an option that's similar, but provides another choice:

public class DefaultJsonSerializer : JsonSerializerSettings
{
    public DefaultJsonSerializer()
    {
        NullValueHandling = NullValueHandling.Ignore;
    }
}

Then, I use it like this:

JsonConvert.SerializeObject(postObj, new DefaultJsonSerializer());

The difference here is that:

  • Reduces repeated code by instantiating and configuring JsonSerializerSettings each place it's used.
  • Saves time in configuring every property of every object to be serialized.
  • Still gives other developers flexibility in serialization options, rather than having the property explicitly specified on a reusable object.
  • My use-case is that the code is a 3rd party library and I don't want to force serialization options on developers who would want to reuse my classes.
  • Potential drawbacks are that it's another object that other developers would need to know about, or if your application is small and this approach wouldn't matter for a single serialization.

Get all rows from SQLite

Using Android's built in method

If you want every column and every row, then just pass in null for the SQLiteDatabase column and selection parameters.

Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null, null);

More details

The other answers use rawQuery, but you can use Android's built in SQLiteDatabase. The documentation for query says that you can just pass in null to the selection parameter to get all the rows.

selection Passing null will return all rows for the given table.

And while you can also pass in null for the column parameter to get all of the columns (as in the one-liner above), it is better to only return the columns that you need. The documentation says

columns Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.

Example

SQLiteDatabase db = mHelper.getReadableDatabase();
String[] columns = {
        MyDatabaseHelper.COLUMN_1,
        MyDatabaseHelper.COLUMN_2,
        MyDatabaseHelper.COLUMN_3};
String selection = null; // this will select all rows
Cursor cursor = db.query(MyDatabaseHelper.MY_TABLE, columns, selection,
        null, null, null, null, null);

applying css to specific li class

You have specified different colors for the li elements but it is being overridden by the specified color in the a within the li. Remove color: #C1C1C1; style from a element and it should work.

HTML5 placeholder css padding

The placeholder is not affected by line-height and padding is inconsistent on browsers.

I have found another solution though.

VERTICAL-ALIGN. This is probably the only time it works but try that instead and cave many lines of CSS code.

Zoom to fit all markers in Mapbox or Leaflet

To fit to the visible markers only, I've this method.

fitMapBounds() {
    // Get all visible Markers
    const visibleMarkers = [];
    this.map.eachLayer(function (layer) {
        if (layer instanceof L.Marker) {
            visibleMarkers.push(layer);
        }
    });

    // Ensure there's at least one visible Marker
    if (visibleMarkers.length > 0) {

        // Create bounds from first Marker then extend it with the rest
        const markersBounds = L.latLngBounds([visibleMarkers[0].getLatLng()]);
        visibleMarkers.forEach((marker) => {
            markersBounds.extend(marker.getLatLng());
        });

        // Fit the map with the visible markers bounds
        this.map.flyToBounds(markersBounds, {
            padding: L.point(36, 36), animate: true,
        });
    }
}

How do I fetch lines before/after the grep result in bash?

This prints 10 lines of trailing context after matching lines

grep -i "my_regex" -A 10

If you need to print 10 lines of leading context before matching lines,

grep -i "my_regex" -B 10

And if you need to print 10 lines of leading and trailing output context.

grep -i "my_regex" -C 10

Example

user@box:~$ cat out 
line 1
line 2
line 3
line 4
line 5 my_regex
line 6
line 7
line 8
line 9
user@box:~$

Normal grep

user@box:~$ grep my_regex out 
line 5 my_regex
user@box:~$ 

Grep exact matching lines and 2 lines after

user@box:~$ grep -A 2 my_regex out   
line 5 my_regex
line 6
line 7
user@box:~$ 

Grep exact matching lines and 2 lines before

user@box:~$ grep -B 2 my_regex out  
line 3
line 4
line 5 my_regex
user@box:~$ 

Grep exact matching lines and 2 lines before and after

user@box:~$ grep -C 2 my_regex out  
line 3
line 4
line 5 my_regex
line 6
line 7
user@box:~$ 

Reference: manpage grep

-A num
--after-context=num

    Print num lines of trailing context after matching lines.
-B num
--before-context=num

    Print num lines of leading context before matching lines.
-C num
-num
--context=num

    Print num lines of leading and trailing output context.

How do I get the position selected in a RecyclerView?

1. Create class Name RecyclerTouchListener.java

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener 
{

private GestureDetector gestureDetector;
private ClickListener clickListener;

public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
    this.clickListener = clickListener;
    gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
            if (child != null && clickListener != null) {
                clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
            }
        }
    });
}

@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

    View child = rv.findChildViewUnder(e.getX(), e.getY());
    if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
        clickListener.onClick(child, rv.getChildAdapterPosition(child));
    }
    return false;
}

@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}

@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

}

public interface ClickListener {
    void onClick(View view, int position);

    void onLongClick(View view, int position);
}
}

2. Call RecyclerTouchListener

recycleView.addOnItemTouchListener(new RecyclerTouchListener(this, recycleView, 
new RecyclerTouchListener.ClickListener() {
    @Override
    public void onClick(View view, int position) {
        Toast.makeText(MainActivity.this,Integer.toString(position),Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onLongClick(View view, int position) {

    }
}));

How do I grep for all non-ASCII characters?

Finding all non-ascii characters gives the impression that one is either looking for unicode strings or intends to strip said characters individually.

For the former, try one of these (variable file is used for automation):

 file=file.txt ; LC_ALL=C grep -Piao '[\x80-\xFF\x20]{7,}' $file | iconv -f $(uchardet $file) -t utf-8

 file=file.txt ; pcregrep -iao '[\x80-\xFF\x20]{7,}' $file | iconv -f $(uchardet $file) -t utf-8

 file=file.txt ; pcregrep -iao '[^\x00-\x19\x21-\x7F]{7,}' $file | iconv -f $(uchardet $file) -t utf-8

Vanilla grep doesn't work correctly without LC_ALL=C as noted in the previous answers.

ASCII range is x00-x7F, space is x20, since strings have spaces the negative range omits it.

Non-ASCII range is x80-xFF, since strings have spaces the positive range adds it.

String is presumed to be at least 7 consecutive characters within the range. {7,}.

For shell readable output, uchardet $file returns a guess of the file encoding which is passed to iconv for automatic interpolation.

system("pause"); - Why is it wrong?

It's frowned upon because it's a platform-specific hack that has nothing to do with actually learning programming, but instead to get around a feature of the IDE/OS - the console window launched from Visual Studio closes when the program has finished execution, and so the new user doesn't get to see the output of his new program.

Bodging in System("pause") runs the Windows command-line "pause" program and waits for that to terminate before it continues execution of the program - the console window stays open so you can read the output.

A better idea would be to put a breakpoint at the end and debug it, but that again has problems.

Android: TextView: Remove spacing and padding on top and bottom

Simple method worked:

setSingleLine();
setIncludeFontPadding(false);

If it not worked, then try to add this above that code:

setLineSpacing(0f,0f);
// and set padding and margin to 0

If you need multi line, maybe you'll need to calculate exactly the height of padding top and bottom via temp single line TextView (before and after remove padding) , then apply decrease height result with negative padding or some Ghost Layout with translate Y. Lol

Volatile Vs Atomic

There are two important concepts in multithreading environment:

  1. atomicity
  2. visibility

The volatile keyword eradicates visibility problems, but it does not deal with atomicity. volatile will prevent the compiler from reordering instructions which involve a write and a subsequent read of a volatile variable; e.g. k++. Here, k++ is not a single machine instruction, but three:

  1. copy the value to a register;
  2. increment the value;
  3. place it back.

So, even if you declare a variable as volatile, this will not make this operation atomic; this means another thread can see a intermediate result which is a stale or unwanted value for the other thread.

On the other hand, AtomicInteger, AtomicReference are based on the Compare and swap instruction. CAS has three operands: a memory location V on which to operate, the expected old value A, and the new value B. CAS atomically updates V to the new value B, but only if the value in V matches the expected old value A; otherwise, it does nothing. In either case, it returns the value currently in V. The compareAndSet() methods of AtomicInteger and AtomicReference take advantage of this functionality, if it is supported by the underlying processor; if it is not, then the JVM implements it via spin lock.

Is there a way to get LaTeX to place figures in the same page as a reference to that figure?

I solve this problem by always using the [h] option on floats (such as figures) so that they (mostly) go where I place them. Then when I look at the final draft, I adjust the location of the float by moving it in the LaTeX source. Usually that means moving it around the paragraph where it is referenced. Sometimes I need to add a page break at an appropriate spot.

I've found that the default placement of floats is reasonable in LaTeX, but manual adjustments are almost always needed to get things like this just right. (And sometimes it isn't possible for everything to be perfect when there are lots of floats and footnotes.)

The manual for the memoir class has some good information about how LaTeX places floats and some advice for manipulating the algorithm.

Android Error Building Signed APK: keystore.jks not found for signing config 'externalOverride'

This is a problem that can arise from writing down a "filename" instead of a path, while generating the .jks file. Generate a new one, put it on the Desktop (or any other real path) and re-generate APK.

How to change text color and console color in code::blocks?

Functions like textcolor worked in old compilers like turbo C and Dev C. In today's compilers these functions would not work. I am going to give two function SetColor and ChangeConsoleToColors. You copy paste these functions code in your program and do the following steps.The code I am giving will not work in some compilers.

The code of SetColor is -

 void SetColor(int ForgC)
 {
     WORD wColor;

      HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
      CONSOLE_SCREEN_BUFFER_INFO csbi;

                       //We use csbi for the wAttributes word.
     if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
     {
                 //Mask out all but the background attribute, and add in the forgournd     color
          wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
          SetConsoleTextAttribute(hStdOut, wColor);
     }
     return;
 }

To use this function you need to call it from your program. For example I am taking your sample program -

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <dos.h>
#include <dir.h>

int main(void)
{
  SetColor(4);
  printf("\n \n \t This text is written in Red Color \n ");
  getch();
  return 0;
}

void SetColor(int ForgC)
 {
 WORD wColor;

  HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
  CONSOLE_SCREEN_BUFFER_INFO csbi;

                       //We use csbi for the wAttributes word.
 if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
 {
                 //Mask out all but the background attribute, and add in the forgournd color
      wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
      SetConsoleTextAttribute(hStdOut, wColor);
 }
 return;
}

When you run the program you will get the text color in RED. Now I am going to give you the code of each color -

Name         | Value
             |
Black        |   0
Blue         |   1
Green        |   2
Cyan         |   3
Red          |   4
Magenta      |   5
Brown        |   6
Light Gray   |   7
Dark Gray    |   8
Light Blue   |   9
Light Green  |   10
Light Cyan   |   11
Light Red    |   12
Light Magenta|   13
Yellow       |   14
White        |   15

Now I am going to give the code of ChangeConsoleToColors. The code is -

void ClearConsoleToColors(int ForgC, int BackC)
 {
 WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);
               //Get the handle to the current output buffer...
 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
                     //This is used to reset the carat/cursor to the top left.
 COORD coord = {0, 0};
                  //A return value... indicating how many chars were written
                    //   not used but we need to capture this since it will be
                      //   written anyway (passing NULL causes an access violation).
  DWORD count;

                               //This is a structure containing all of the console info
                      // it is used here to find the size of the console.
 CONSOLE_SCREEN_BUFFER_INFO csbi;
                 //Here we will set the current color
 SetConsoleTextAttribute(hStdOut, wColor);
 if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
 {
                          //This fills the buffer with a given character (in this case 32=space).
      FillConsoleOutputCharacter(hStdOut, (TCHAR) 32, csbi.dwSize.X * csbi.dwSize.Y, coord, &count);

      FillConsoleOutputAttribute(hStdOut, csbi.wAttributes, csbi.dwSize.X * csbi.dwSize.Y, coord, &count );
                          //This will set our cursor position for the next print statement.
      SetConsoleCursorPosition(hStdOut, coord);
 }
 return;
}

In this function you pass two numbers. If you want normal colors just put the first number as zero and the second number as the color. My example is -

#include <windows.h>          //header file for windows
#include <stdio.h>

void ClearConsoleToColors(int ForgC, int BackC);

int main()
{
ClearConsoleToColors(0,15);
Sleep(1000);
return 0;
}
void ClearConsoleToColors(int ForgC, int BackC)
{
 WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);
               //Get the handle to the current output buffer...
 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
                     //This is used to reset the carat/cursor to the top left.
 COORD coord = {0, 0};
                  //A return value... indicating how many chars were written
                    //   not used but we need to capture this since it will be
                      //   written anyway (passing NULL causes an access violation).
 DWORD count;

                               //This is a structure containing all of the console info
                      // it is used here to find the size of the console.
 CONSOLE_SCREEN_BUFFER_INFO csbi;
                 //Here we will set the current color
 SetConsoleTextAttribute(hStdOut, wColor);
 if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
 {
                          //This fills the buffer with a given character (in this case 32=space).
      FillConsoleOutputCharacter(hStdOut, (TCHAR) 32, csbi.dwSize.X * csbi.dwSize.Y, coord, &count);

      FillConsoleOutputAttribute(hStdOut, csbi.wAttributes, csbi.dwSize.X * csbi.dwSize.Y, coord, &count );
                          //This will set our cursor position for the next print statement.
      SetConsoleCursorPosition(hStdOut, coord);
 }
 return;
} 

In this case I have put the first number as zero and the second number as 15 so the console color will be white as the code for white is 15. This is working for me in code::blocks. Hope it works for you too.

How to convert NUM to INT in R?

You can use convert from hablar to change a column of the data frame quickly.

library(tidyverse)
library(hablar)

x <- tibble(var = c(1.34, 4.45, 6.98))

x %>% 
  convert(int(var))

gives you:

# A tibble: 3 x 1
    var
  <int>
1     1
2     4
3     6

Call a function from another file?

append a dot(.) in front of a file name if you want to import this file which is in the same directory where you are running your code.

For example, i'm running a file named a.py and i want to import a method named addFun which is written in b.py, and b.py is there in the same directory

from .b import addFun

Is there any way I can define a variable in LaTeX?

add the following to you preamble:

\newcommand{\newCommandName}{text to insert}

Then you can just use \newCommandName{} in the text

For more info on \newcommand, see e.g. wikibooks

Example:

\documentclass{article}
\newcommand\x{30}
\begin{document}
\x
\end{document}

Output:

30

Text to speech(TTS)-Android

MainActivity.class

import java.util.Locale;

import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences.Editor;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {

    String text;
    EditText et;
    TextToSpeech tts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et=(EditText)findViewById(R.id.editText1);
        tts=new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {

            @Override
            public void onInit(int status) {
                // TODO Auto-generated method stub
                if(status == TextToSpeech.SUCCESS){
                    int result=tts.setLanguage(Locale.US);
                    if(result==TextToSpeech.LANG_MISSING_DATA ||
                            result==TextToSpeech.LANG_NOT_SUPPORTED){
                        Log.e("error", "This Language is not supported");
                    }
                    else{
                        ConvertTextToSpeech();
                    }
                }
                else
                    Log.e("error", "Initilization Failed!");
            }
        });


    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub

        if(tts != null){

            tts.stop();
            tts.shutdown();
        }
        super.onPause();
    }

    public void onClick(View v){

        ConvertTextToSpeech();

    }

    private void ConvertTextToSpeech() {
        // TODO Auto-generated method stub
        text = et.getText().toString();
        if(text==null||"".equals(text))
        {
            text = "Content not available";
            tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
        }else
            tts.speak(text+"is saved", TextToSpeech.QUEUE_FLUSH, null);
    }

}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="177dp"
        android:onClick="onClick"
        android:text="Button" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="81dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

</RelativeLayout>

Column order manipulation using col-lg-push and col-lg-pull in Twitter Bootstrap 3

Misconception Common misconception with column ordering is that, I should (or could) do the pushing and pulling on mobile devices, and that the desktop views should render in the natural order of the markup. This is wrong.

Reality Bootstrap is a mobile first framework. This means that the order of the columns in your HTML markup should represent the order in which you want them displayed on mobile devices. This mean that the pushing and pulling is done on the larger desktop views. not on mobile devices view..

Brandon Schmalz - Full Stack Web Developer Have a look at full description here

REST API - file (ie images) processing - best practices

There's no easy solution. Each way has their pros and cons . But the canonical way is using the first option: multipart/form-data. As W3 recommendation guide says

The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

We aren't sending forms,really, but the implicit principle still applies. Using base64 as a binary representation, is incorrect because you're using the incorrect tool for accomplish your goal, in other hand, the second option forces your API clients to do more job in order to consume your API service. You should do the hard work in the server side in order to supply an easy-to-consume API. The first option is not easy to debug, but when you do it, it probably never changes.

Using multipart/form-data you're sticked with the REST/http philosophy. You can view an answer to similar question here.

Another option if mixing the alternatives, you can use multipart/form-data but instead of send every value separate, you can send a value named payload with the json payload inside it. (I tried this approach using ASP.NET WebAPI 2 and works fine).

Oracle "(+)" Operator

The (+) operator indicates an outer join. This means that Oracle will still return records from the other side of the join even when there is no match. For example if a and b are emp and dept and you can have employees unassigned to a department then the following statement will return details of all employees whether or not they've been assigned to a department.

select * from emp, dept where emp.dept_id=dept.dept_id(+)

So in short, removing the (+) may make a significance difference but you might not notice for a while depending on your data!

What is the right way to debug in iPython notebook?

In Python 3.7 you can use breakpoint() function. Just enter

breakpoint()

wherever you would like runtime to stop and from there you can use the same pdb commands (r, c, n, ...) or evaluate your variables.

Check if Variable is Empty - Angular 2

It depends if you know the given variable Type. If you expect it to be an Object than you could check if myVar is an empty Object like this:

 public isEmpty(myVar): boolean {
     return (myVar && (Object.keys(myVar).length === 0));
 }

Otherwise: if (!myVar) {}, should do the job

How can I make an svg scale with its parent container?

To specify the coordinates within the SVG image independently of the scaled size of the image, use the viewBox attribute on the SVG element to define what the bounding box of the image is in the coordinate system of the image, and use the width and height attributes to define what the width or height are with respect to the containing page.

For instance, if you have the following:

<svg>
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

It will render as a 10px by 20px triangle:

10x20 triangle

Now, if you set only the width and height, that will change the size of the SVG element, but not scale the triangle:

<svg width=100 height=50>
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

10x20 triangle

If you set the view box, that causes it to transform the image such that the given box (in the coordinate system of the image) is scaled up to fit within the given width and height (in the coordinate system of the page). For instance, to scale up the triangle to be 100px by 50px:

<svg width=100 height=50 viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

100x50 triangle

If you want to scale it up to the width of the HTML viewport:

<svg width="100%" viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

300x150 triangle

Note that by default, the aspect ratio is preserved. So if you specify that the element should have a width of 100%, but a height of 50px, it will actually only scale up to the height of 50px (unless you have a very narrow window):

<svg width="100%" height="50px" viewBox="0 0 20 10">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

100x50 triangle

If you actually want it to stretch horizontally, disable aspect ratio preservation with preserveAspectRatio=none:

<svg width="100%" height="50px" viewBox="0 0 20 10" preserveAspectRatio="none">
    <polygon fill=red stroke-width=0 
             points="0,10 20,10 10,0" />
</svg>

300x50 triangle

(note that while in my examples I use syntax that works for HTML embedding, to include the examples as an image in StackOverflow I am instead embedding within another SVG, so I need to use valid XML syntax)

Where do I call the BatchNormalization function in Keras?

Just to answer this question in a little more detail, and as Pavel said, Batch Normalization is just another layer, so you can use it as such to create your desired network architecture.

The general use case is to use BN between the linear and non-linear layers in your network, because it normalizes the input to your activation function, so that you're centered in the linear section of the activation function (such as Sigmoid). There's a small discussion of it here

In your case above, this might look like:


# import BatchNormalization
from keras.layers.normalization import BatchNormalization

# instantiate model
model = Sequential()

# we can think of this chunk as the input layer
model.add(Dense(64, input_dim=14, init='uniform'))
model.add(BatchNormalization())
model.add(Activation('tanh'))
model.add(Dropout(0.5))

# we can think of this chunk as the hidden layer    
model.add(Dense(64, init='uniform'))
model.add(BatchNormalization())
model.add(Activation('tanh'))
model.add(Dropout(0.5))

# we can think of this chunk as the output layer
model.add(Dense(2, init='uniform'))
model.add(BatchNormalization())
model.add(Activation('softmax'))

# setting up the optimization of our weights 
sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='binary_crossentropy', optimizer=sgd)

# running the fitting
model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True, validation_split=0.2, verbose = 2)

Hope this clarifies things a bit more.

PHP: How to handle <![CDATA[ with SimpleXMLElement?

This did the trick for me:

echo trim($entry->title);

Differences between Microsoft .NET 4.0 full Framework and Client Profile

You should deploy "Client Profile" instead of "Full Framework" inside a corporation mostly in one case only: you want explicitly deny some .NET features are running on the client computers. The only real case is denying of ASP.NET on the client machines of the corporation, for example, because of security reasons or the existing corporate policy.

Saving of less than 8 MB on client computer can not be a serious reason of "Client Profile" deployment in a corporation. The risk of the necessity of the deployment of the "Full Framework" later in the corporation is higher than costs of 8 MB per client.

send mail to multiple receiver with HTML mailto

"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."

http://www.sightspecific.com/~mosh/www_faq/multrec.html

For a quick fix to your problem, change your ; to a comma , and eliminate the spaces between email addresses

<a href='mailto:[email protected],[email protected]'>Email Us</a>