Programs & Examples On #Ie8 webslice

How do I find which process is leaking memory?

You can run the top command (to run non-interactively, type top -b -n 1). To see applications which are leaking memory, look at the following columns:

  • RPRVT - resident private address space size
  • RSHRD - resident shared address space size
  • RSIZE - resident memory size
  • VPRVT - private address space size
  • VSIZE - total memory size

In PowerShell, how do I test whether or not a specific variable exists in global scope?

So far, it looks like the answer that works is this one.

To break it out further, what worked for me was this:

Get-Variable -Name foo -Scope Global -ea SilentlyContinue | out-null

$? returns either true or false.

Why am I getting error CS0246: The type or namespace name could not be found?

I was using .NET Framework 4.5 but my new library had .NET Framework 4.5.2 and I got the same issue when I tried to build. I solved it by updating my project from 4.5 to 4.5.2 (same as my library).

WPF Datagrid set selected row

I have changed the code of serge_gubenko and it works better

for (int i = 0; i < dataGrid.Items.Count; i++)
{
    string txt = searchTxt.Text;
    dataGrid.ScrollIntoView(dataGrid.Items[i]);
    DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(i);
    TextBlock cellContent = dataGrid.Columns[1].GetCellContent(row) as TextBlock;
    if (cellContent != null && cellContent.Text.ToLower().Equals(txt.ToLower()))
    {
        object item = dataGrid.Items[i];
        dataGrid.SelectedItem = item;
        dataGrid.ScrollIntoView(item);
        row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        break;
    }
}

What is the best alternative IDE to Visual Studio

Zeus.

Here's an example showing code completion, taken from the Zeus homepage.

example.cs open in Zeus, showing code-completion

How do I resize an image using PIL and maintain its aspect ratio?

I resizeed the image in such a way and it's working very well

from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
import os, sys
from PIL import Image


def imageResize(image):
    outputIoStream = BytesIO()
    imageTemproaryResized = imageTemproary.resize( (1920,1080), Image.ANTIALIAS) 
    imageTemproaryResized.save(outputIoStream , format='PNG', quality='10') 
    outputIoStream.seek(0)
    uploadedImage = InMemoryUploadedFile(outputIoStream,'ImageField', "%s.jpg" % image.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None)

    ## For upload local folder
    fs = FileSystemStorage()
    filename = fs.save(uploadedImage.name, uploadedImage)

Username and password in command for git push

According to the Git documentation, the last argument of the git push command can be the repository that you want to push to:

    git push [--all | --mirror | --tags] [-n | --dry-run] [--receive-pack=<git-receive-pack>]
             [--repo=<repository>] [-f | --force] [--prune] [-v | --verbose] [-u | --set-upstream]
             [<repository> [<refspec>…]]

And the repository parameter can be either a URL or a remote name.

So you can specify username and password the same way as you do in your example of clone command.

Calculating width from percent to pixel then minus by pixel in LESS CSS

You can escape the calc arguments in order to prevent them from being evaluated on compilation.

Using your example, you would simply surround the arguments, like this:

calc(~'100% - 10px')

Demo : http://jsfiddle.net/c5aq20b6/


I find that I use this in one of the following three ways:

Basic Escaping

Everything inside the calc arguments is defined as a string, and is totally static until it's evaluated by the client:

LESS Input

div {
    > span {
        width: calc(~'100% - 10px');
    }
}

CSS Output

div > span {
  width: calc(100% - 10px);
}

Interpolation of Variables

You can insert a LESS variable into the string:

LESS Input

div {
    > span {
        @pad: 10px;
        width: calc(~'100% - @{pad}');
    }
}

CSS Output

div > span {
  width: calc(100% - 10px);
}

Mixing Escaped and Compiled Values

You may want to escape a percentage value, but go ahead and evaluate something on compilation:

LESS Input

@btnWidth: 40px;
div {
    > span {
        @pad: 10px;
        width: calc(~'(100% - @{pad})' - (@btnWidth * 2));
    }
}

CSS Output

div > span {
  width: calc((100% - 10px) - 80px);
}

Source: http://lesscss.org/functions/#string-functions-escape.

How to check whether java is installed on the computer

You can do it programmatically by reading the java system properties

@Test
public void javaVersion() {
    System.out.println(System.getProperty("java.version"));
    System.out.println(System.getProperty("java.runtime.version"));
    System.out.println(System.getProperty("java.home"));
    System.out.println(System.getProperty("java.vendor"));
    System.out.println(System.getProperty("java.vendor.url"));
    System.out.println(System.getProperty("java.class.path"));
}

This will output somthing like

1.7.0_17
1.7.0_17-b02
C:\workspaces\Oracle\jdk1.7\jre
Oracle Corporation
http://java.oracle.com/
C:\workspaces\Misc\Miscellaneous\bin; ...

The first line shows the version number. You can parse it an see whether it fits your minimun required java version or not. You can find a description for the naming convention here and more infos here.

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

I had the same error message:

System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

In my case, the error went away after clean and re-build the solution.

jQuery Datepicker localization

You can do like this

 $.datepicker.regional['fr'] = {clearText: 'Effacer', clearStatus: '',
    closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
    prevText: '&lt;Préc', prevStatus: 'Voir le mois précédent',
    nextText: 'Suiv&gt;', nextStatus: 'Voir le mois suivant',
    currentText: 'Courant', currentStatus: 'Voir le mois courant',
    monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
    'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
    monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
    'Jul','Aoû','Sep','Oct','Nov','Déc'],
    monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
    weekHeader: 'Sm', weekStatus: '',
    dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
    dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
    dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
    dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
    dateFormat: 'dd/mm/yy', firstDay: 0, 
    initStatus: 'Choisir la date', isRTL: false};
 $.datepicker.setDefaults($.datepicker.regional['fr']);

Preferred Java way to ping an HTTP URL for availability

You could also use HttpURLConnection, which allows you to set the request method (to HEAD for example). Here's an example that shows how to send a request, read the response, and disconnect.

How does "FOR" work in cmd batch file?

Couldn't resist throwing this out there, old as this thread is... Usually when the need arises to iterate through each of the files in PATH, all you really want to do is find a particular file... If that's the case, this one-liner will spit out the first directory it finds your file in:

(ex: looking for java.exe)

for %%x in (java.exe) do echo %%~dp$PATH:x

jquery change style of a div on click

As what I have understand on your question, this is what you want.

Here is a jsFiddle of the below:

_x000D_
_x000D_
$('.childDiv').click(function() {_x000D_
  $(this).parent().find('.childDiv').css('background-color', '#ffffff');_x000D_
  $(this).css('background-color', '#ff0000');_x000D_
});
_x000D_
.parentDiv {_x000D_
  border: 1px solid black;_x000D_
  padding: 10px;_x000D_
  width: 80px;_x000D_
  margin: 5px;_x000D_
  display: relative;_x000D_
}_x000D_
.childDiv {_x000D_
  border: 1px solid blue;_x000D_
  height: 50px;_x000D_
  margin: 10px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>_x000D_
<div id="divParent1" class="parentDiv">_x000D_
  Group 1_x000D_
  <div id="child1" class="childDiv">_x000D_
    Child 1_x000D_
  </div>_x000D_
  <div id="child2" class="childDiv">_x000D_
    Child 2_x000D_
  </div>_x000D_
</div>_x000D_
<div id="divParent2" class="parentDiv">_x000D_
  Group 2_x000D_
  <div id="child1" class="childDiv">_x000D_
    Child 1_x000D_
  </div>_x000D_
  <div id="child2" class="childDiv">_x000D_
    Child 2_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I echo the whole content of a .html file in PHP?

If you want to make sure the HTML file doesn't contain any PHP code and will not be executed as PHP, do not use include or require. Simply do:

echo file_get_contents("/path/to/file.html");

href="tel:" and mobile numbers

When dialing a number within the country you are in, you still need to dial the national trunk number before the rest of the number. For example, in Australia one would dial:

   0 - trunk prefix
   2 - Area code for New South Wales
6555 - STD code for a specific telephone exchange
1234 - Telephone Exchange specific extension.

For a mobile phone this becomes

   0 -      trunk prefix
   4 -      Area code for a mobile telephone
1234 5678 - Mobile telephone number

Now, when I want to dial via the international trunk, you need to drop the trunk prefix and replace it with the international dialing prefix

   + -      Short hand for the country trunk number
  61 -      Country code for Australia
   4 -      Area code for a mobile telephone
1234 5678 - Mobile telephone number

This is why you often find that the first digit of a telephone number is dropped when dialling internationally, even when using international prefixing to dial within the same country.

So as per the trunk prefix for Germany drop the 0 and add the +49 for Germany's international calling code (for example) giving:

_x000D_
_x000D_
<a href="tel:+496170961709" class="Blondie">_x000D_
    Call me, call me any, anytime_x000D_
      <b>Call me (call me) I'll arrive</b>_x000D_
        When you're ready we can share the wine!_x000D_
</a>
_x000D_
_x000D_
_x000D_

How to do a SOAP Web Service call from Java class?

I found a much simpler alternative way to generating soap message. Given a Person Object:

import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Person {
  private String name;
  private int age;
  private String address; //setter and getters below
}

Below is a simple Soap Message Generator:

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

@Slf4j
public class SoapGenerator {

  protected static final ObjectMapper XML_MAPPER = new XmlMapper()
      .enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
      .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      .registerModule(new JavaTimeModule());

  private static final String SOAP_BODY_OPEN = "<soap:Body>";
  private static final String SOAP_BODY_CLOSE = "</soap:Body>";
  private static final String SOAP_ENVELOPE_OPEN = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
  private static final String SOAP_ENVELOPE_CLOSE = "</soap:Envelope>";

  public static String soapWrap(String xml) {
    return SOAP_ENVELOPE_OPEN + SOAP_BODY_OPEN + xml + SOAP_BODY_CLOSE + SOAP_ENVELOPE_CLOSE;
  }

  public static String soapUnwrap(String xml) {
    return StringUtils.substringBetween(xml, SOAP_BODY_OPEN, SOAP_BODY_CLOSE);
  }
}

You can use by:

 public static void main(String[] args) throws Exception{
        Person p = new Person();
        p.setName("Test");
        p.setAge(12);

        String xml = SoapGenerator.soapWrap(XML_MAPPER.writeValueAsString(p));
        log.info("Generated String");
        log.info(xml);
      }

Failed to decode downloaded font

I was having the same issue with font awesome v4.4 and I fixed it by removing the woff2 format. I was getting a warning in Chrome only.

@font-face {
  font-family: 'FontAwesome';
  src: url('../fonts/fontawesome-webfont.eot?v=4.4.0');
  src: url('../fonts/fontawesome-webfont.eot?#iefix&v=4.4.0') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff?v=4.4.0') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.4.0') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.4.0#fontawesomeregular') format('svg');
  font-weight: normal;
  font-style: normal;
}

Sleep function in ORACLE

You can use DBMS_PIPE.SEND_MESSAGE with a message that is too large for the pipe, for example for a 5 second delay write XXX to a pipe that can only accept one byte using a 5 second timeout as below

dbms_pipe.pack_message('XXX');<br>
dummy:=dbms_pipe.send_message('TEST_PIPE', 5, 1);

But then that requires a grant for DBMS_PIPE so perhaps no better.

SELECT INTO using Oracle

Use:

create table new_table_name 
as
select column_name,[more columns] from Existed_table;

Example:

create table dept
as
select empno, ename from emp;

If the table already exists:

insert into new_tablename select columns_list from Existed_table;

How to print to console when using Qt

If it is good enough to print to stderr, you can use the following streams originally intended for debugging:

#include<QDebug>

//qInfo is qt5.5+ only.
qInfo() << "C++ Style Info Message";
qInfo( "C Style Info Message" );

qDebug() << "C++ Style Debug Message";
qDebug( "C Style Debug Message" );

qWarning() << "C++ Style Warning Message";
qWarning( "C Style Warning Message" );

qCritical() << "C++ Style Critical Error Message";
qCritical( "C Style Critical Error Message" );

// qFatal does not have a C++ style method.
qFatal( "C Style Fatal Error Message" );

Though as pointed out in the comments, bear in mind qDebug messages are removed if QT_NO_DEBUG_OUTPUT is defined

If you need stdout you could try something like this (as Kyle Strand has pointed out):

QTextStream& qStdOut()
{
    static QTextStream ts( stdout );
    return ts;
}

You could then call as follows:

qStdOut() << "std out!";

New line character in VB.Net?

it's :

vbnewline

for example

Msgbox ("Fst line" & vbnewline & "second line")

vertical-align with Bootstrap 3

Update 2020

I know the original question was for Bootstrap 3, but now that Bootstrap 4 has been released, here is some updated guidance on vertical center.

Important! Vertical center is relative to the height of the parent

If the parent of the element your trying to center has no defined height, none of the vertical centering solutions will work!

Bootstrap 4

Now that Bootstrap 4 is flexbox by default there are many different approaches to vertical alignment using: auto-margins, flexbox utils, or the display utils along with vertical align utils. At first "vertical align utils" seems obvious, but these only work with inline and table display elements. Here are some Bootstrap 4 vertical centering options..


1 - Vertical Center Using Auto Margins:

Another way to vertically center is to use my-auto. This will center the element within its container. For example, h-100 makes the row full height, and my-auto will vertically center the col-sm-12 column.

<div class="row h-100">
    <div class="col-sm-12 my-auto">
        <div class="card card-block w-25">Card</div>
    </div>
</div>

Bootstrap 4 - Vertical center using auto-margins Demo

my-auto represents margins on the vertical y-axis and is equivalent to:

margin-top: auto;
margin-bottom: auto;

2 - Vertical Center with Flexbox:

Vertical center grid columns

Since Bootstrap 4 .row is now display:flex you can simply use align-self-center on any column to vertically center it...

       <div class="row">
           <div class="col-6 align-self-center">
                <div class="card card-block">
                 Center
                </div>
           </div>
           <div class="col-6">
                <div class="card card-inverse card-danger">
                    Taller
                </div>
          </div>
    </div>

or, use align-items-center on the entire .row to vertically center align all col-* in the row...

       <div class="row align-items-center">
           <div class="col-6">
                <div class="card card-block">
                 Center
                </div>
           </div>
           <div class="col-6">
                <div class="card card-inverse card-danger">
                    Taller
                </div>
          </div>
    </div>

Bootstrap 4 - Vertical center different height columns Demo


3 - Vertical Center Using Display Utils:

Bootstrap 4 has display utils that can be used for display:table, display:table-cell, display:inline, etc.. These can be used with the vertical alignment utils to align inline, inline-block or table cell elements.

<div class="row h-50">
    <div class="col-sm-12 h-100 d-table">
        <div class="card card-block d-table-cell align-middle">
            I am centered vertically
        </div>
    </div>
</div>

Bootstrap 4 - Vertical center using display utils Demo

Also see: Vertical Align Center in Bootstrap 4


Bootstrap 3

Flexbox method on the container of the item(s) to center:

.display-flex-center {
    display: flex;
    align-items: center;
}

Transform translateY method:

.transform-center-parent {
    position: relative;
    transform-style: preserve-3d;
}

.transform-center {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

Display inline method:

.display-inline-block {
    display: inline;
}
.display-inline-block > div {
    display: inline-block;
    float: none;
    vertical-align: middle;
}

Demo of Bootstrap 3 centering methods

A generic error occurred in GDI+, JPEG Image to MemoryStream

SOLVED - I had this exact problem. The fix, for me, was to up the disk quota for IUSR on the IIS server. In this instance, we have a catalog app with images of items and such. The upload quota for the "Anonymous Web User" was set to 100MB, which is the default for this particular hosting company's IIS servers. I upped it to 400MB and was able to upload images without error.

This might not be your issue, but if it is, it's an easy fix.

Check to see if cURL is installed locally?

In the Terminal, type:

$ curl -V

That's a capital V for the version

How can I remove the top and right axis in matplotlib?

Alternatively, this

def simpleaxis(ax):
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()

seems to achieve the same effect on an axis without losing rotated label support.

(Matplotlib 1.0.1; solution inspired by this).

With form validation: why onsubmit="return functionname()" instead of onsubmit="functionname()"?

An extension to what GenericTypeTea says - Here is a concrete example:

<form onsubmit="return false">

The above form will not submit, whereas...

<form onsubmit="false">

...does nothing, i.e. the form will submit.

Without the return, onsubmit doesn't receive a value and the event is executed just like without any handler at all.

Start index for iterating Python list

Why are people using list slicing (slow because it copies to a new list), importing a library function, or trying to rotate an array for this?

Use a normal for-loop with range(start, stop, step) (where start and step are optional arguments).

For example, looping through an array starting at index 1:

for i in range(1, len(arr)):
    print(arr[i])

Show pop-ups the most elegant way

Angular-ui comes with dialog directive.Use it and set templateurl to whatever page you want to include.That is the most elegant way and i have used it in my project as well. You can pass several other parameters for dialog as per need.

Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit

java -version
java -showversion

Both commands work In Linux 16.04 LTS

Difference between pre-increment and post-increment in a loop?

i++ ; ++i ; both are similar as they are not used in an expression.

class A {

     public static void main (String []args) {

     int j = 0 ;
     int k = 0 ;
     ++j;
     k++;
    System.out.println(k+" "+j);

}}

prints out :  1 1

Get generic type of java.util.List

As others have said, the only correct answer is no, the type has been erased.

If the list has a non-zero number of elements, you could investigate the type of the first element ( using it's getClass method, for instance ). That won't tell you the generic type of the list, but it would be reasonable to assume that the generic type was some superclass of the types in the list.

I wouldn't advocate the approach, but in a bind it might be useful.

Do copyright dates need to be updated?

The copyright notice on a work establishes a claim to copyright. The date on the notice establishes how far back the claim is made. This means if you update the date, you are no longer claiming the copyright for the original date and that means if somebody has copied the work in the meantime and they claim its theirs on the ground that their publishing the copy was before your claim, then it will be difficult to establish who is the originator of the work.

Therefore, if the claim is based on common law copyright (not formally registered), then the date should be the date of first publication. If the claim is a registered copyright, then the date should be the date claimed in the registration. In cases where the work was substantially revised you may establish a new copyright claim to the revised work by adding another copyright notice with a newer date or by adding an additional date to the existing notice as in "© 2000, 2010". Again, the added date establishes how far back the claim is made on the revision.

fork() and wait() with two child processes

Put your wait() function in a loop and wait for all the child processes. The wait function will return -1 and errno will be equal to ECHILD if no more child processes are available.

Fixing Sublime Text 2 line endings?

The comment states

// Determines what character(s) are used to terminate each line in new files.
// Valid values are 'system' (whatever the OS uses), 'windows' (CRLF) and
// 'unix' (LF only).

You are setting

"default_line_ending": "LF",

You should set

"default_line_ending": "unix",

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

I think this has turned into more of a question of "why follow the spec when browser's don't care." Here is my generalized answer:

Standards are not a "present" thing. They are a "future" thing. If we, as developers, follow web standards, then browser vendors are more likely to correctly implement those standards, and we move closer to a completely interoperable web, where CSS hacks, feature detection, and browser detection are not necessary. Where we don't have to figure out why our layouts break in a particular browser, or how to work around that.

Specifically, if HTML5 does not require using &amp; in your specific situation, and you're using an HTML5 doctype (and also expecting your users to be using HTML5-compliant browsers), then there is no reason to do it.

java.io.FileNotFoundException: class path resource cannot be opened because it does not exist

The file location/path has to relative to your classpath locations. If resources directory is in your classpath you just need "app-context.xml" as file location.

Is there a constraint that restricts my generic method to numeric types?

This question is a bit of a FAQ one, so I'm posting this as wiki (since I've posted similar before, but this is an older one); anyway...

What version of .NET are you using? If you are using .NET 3.5, then I have a generic operators implementation in MiscUtil (free etc).

This has methods like T Add<T>(T x, T y), and other variants for arithmetic on different types (like DateTime + TimeSpan).

Additionally, this works for all the inbuilt, lifted and bespoke operators, and caches the delegate for performance.

Some additional background on why this is tricky is here.

You may also want to know that dynamic (4.0) sort-of solves this issue indirectly too - i.e.

dynamic x = ..., y = ...
dynamic result = x + y; // does what you expect

How to use google maps without api key

You can still use free with iframe in google maps share button for example enter image description here

Split a string by another string in C#

There's an overload of String.Split for this:

"THExxQUICKxxBROWNxxFOX".Split(new [] {"xx"}, StringSplitOptions.None);

"continue" in cursor.forEach()

Each iteration of the forEach() will call the function that you have supplied. To stop further processing within any given iteration (and continue with the next item) you just have to return from the function at the appropriate point:

elementsCollection.forEach(function(element){
  if (!element.shouldBeProcessed)
    return; // stop processing this iteration

  // This part will be avoided if not neccessary
  doSomeLengthyOperation();
});

Abort trap 6 error in C

You are writing to memory you do not own:

int board[2][50]; //make an array with 3 columns  (wrong)
                  //(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
    board[2][i] = 'O';
          ^

Change this line:

int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
          ^

To:

int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
          ^

When creating an array, the value used to initialize: [3] indicates array size.
However, when accessing existing array elements, index values are zero based.

For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]

EDIT To address bad output comment and initialization comment

add an additional "\n" for formatting output:

Change:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
 }

       ...

To:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
  printf("\n");//at the end of every row, print a new line
}
...  

Initialize board variable:

int board[3][50] = {0};//initialize all elements to zero

( array initialization discussion... )

What's the difference between the atomic and nonatomic attributes?

There is no such keyword "atomic"

@property(atomic, retain) UITextField *userName;

We can use the above like

@property(retain) UITextField *userName;

See Stack Overflow question I am getting issues if I use @property(atomic,retain)NSString *myString.

Create PostgreSQL ROLE (user) if it doesn't exist

The accepted answer suffers from a race condition if two such scripts are executed concurrently on the same Postgres cluster (DB server), as is common in continuous-integration environments.

It's generally safer to try to create the role and gracefully deal with problems when creating it:

DO $$
BEGIN
  CREATE ROLE my_role WITH NOLOGIN;
  EXCEPTION WHEN DUPLICATE_OBJECT THEN
  RAISE NOTICE 'not creating role my_role -- it already exists';
END
$$;

Adding a library/JAR to an Eclipse Android project

Now for the missing class problem.

I'm an Eclipse Java EE developer and have been in the habit for many years of adding third-party libraries via the "User Library" mechanism in Build Path. Of course, there are at least 3 ways to add a third-party library, the one I use is the most elegant, in my humble opinion.

This will not work, however, for Android, whose Dalvik "JVM" cannot handle an ordinary Java-compiled class, but must have it converted to a special format. This does not happen when you add a library in the way I'm wont to do it.

Instead, follow the (widely available) instructions for importing the third-party library, then adding it using Build Path (which makes it known to Eclipse for compilation purposes). Here is the step-by-step:

  1. Download the library to your host development system.
  2. Create a new folder, libs, in your Eclipse/Android project.
  3. Right-click libs and choose Import -> General -> File System, then Next, Browse in the filesystem to find the library's parent directory (i.e.: where you downloaded it to).
  4. Click OK, then click the directory name (not the checkbox) in the left pane, then check the relevant JAR in the right pane. This puts the library into your project (physically).
  5. Right-click on your project, choose Build Path -> Configure Build Path, then click the Libraries tab, then Add JARs..., navigate to your new JAR in the libs directory and add it. (This, incidentally, is the moment at which your new JAR is converted for use on Android.)

NOTE

Step 5 may not be needed, if the lib is already included in your build path. Just ensure that its existence first before adding it.

What you've done here accomplishes two things:

  1. Includes a Dalvik-converted JAR in your Android project.
  2. Makes Java definitions available to Eclipse in order to find the third-party classes when developing (that is, compiling) your project's source code.

Git: See my last commit

After you do several commits or clone/pull a repository, you might want to see what commits have been made. Just check these simple solutions to see your commit history (from last/recent commit to the first one).

For the last commit, just fire this command: git log -1. For more interesting things see below -

  1. To see the commit ID (SHA-1 checksum), Author name <mail ID>, Date along with time, and commit message -

    git log
    
  2. To see some more stats, such as the names of all the files changed during that commit and number of insertions/deletions. This comes in very handy while reviewing the code -

    git log --stat
    
  3. To see commit histories in some pretty formats :) (This is followed by some prebuild options)-

    • If you have too many commits to review, this command will show them in a neat single line:

      git log --pretty=oneline
      
    • To see short, medium, full, or even more details of your commit, use following, respectively -

      git log --pretty=short
      git log --pretty=medium
      git log --pretty=full
      git log --pretty=fuller
      
  4. You can even use your own output format using the format option -

    git log --pretty=format:"%an, %ae - %s"
    

    where %an - author name, %ae - author email, %s - subject of commit, etc.

This can help you with your commit histories. For more information, click here.

Where do alpha testers download Google Play Android apps?

In my experience the flow is:

  • you publish the app as beta in Google Play and create the Google+ community
  • invite the tester to the community
  • once he has joined, send him the link of the test app in Google Play
  • the tester opens the link in the browser (not google play app)
  • registers as tester
  • in the browser, install the apps to the device (the app will be magically pushed to the device)

UIView frame, bounds and center

I found this image most helpful for understanding frame, bounds, etc.

enter image description here

Also please note that frame.size != bounds.size when the image is rotated.

How do I iterate over a JSON structure?

If this is your dataArray:

var dataArray = [{"id":28,"class":"Sweden"}, {"id":56,"class":"USA"}, {"id":89,"class":"England"}];

then:

$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {  
         var ID = this.id;
         var CLASS = this.class;
});

Failed to resolve: com.android.support:appcompat-v7:26.0.0

If you already use jitpack.io or any repository. You can add google repository like this:

allprojects {
    repositories {
        maven { url "https://jitpack.io" }
        maven { url "https://maven.google.com" }
    }
}

How to run java application by .bat file

  • javac (.exe on Windows) binary path must be added into global PATH env. variable.

    javac MyProgram.java

  • or with java (.exe on Windows)

    java MyProgram.jar

MySQL error: key specification without a key length

In case your data type is TEXT - you will have to change it to VARCHAR
solution 1: Query

ALTER TABLE table_name MODIFY COLUMN col_name datatype;
ALTER TABLE my_table MODIFY COLUMN my_col VARCHAR(255);

solution 2: GUI (MySQL workbench)
step1 - write in the text box enter image description here

step2 - edit data type, apply enter image description here

Javascript - object key->value

I use the following syntax:

objTest = {"error": true, "message": "test message"};

get error:

 var name = "error"
 console.log(objTest[name]);

get message:

 name = "message"
 console.log(objTest[name]);

HTML Canvas Full Screen

A - How To Calculate Full Screen Width & Height

Here is the functions;

canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

Check this out

B - How To Make Full Screen Stable With Resize

Here is the resize method for the resize event;

function resizeCanvas() {
    canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

    WIDTH = canvas.width;
    HEIGHT = canvas.height;

    clearScreen();
}

C - How To Get Rid Of Scroll Bars

Simply;

<style>
    html, body {
        overflow: hidden;
    }
</style>

D - Demo Code

_x000D_
_x000D_
<html>_x000D_
 <head>_x000D_
  <title>Full Screen Canvas Example</title>_x000D_
  <style>_x000D_
   html, body {_x000D_
    overflow: hidden;_x000D_
   }_x000D_
  </style>_x000D_
 </head>_x000D_
 <body onresize="resizeCanvas()">_x000D_
  <canvas id="mainCanvas">_x000D_
  </canvas>_x000D_
  <script>_x000D_
   (function () {_x000D_
    canvas = document.getElementById('mainCanvas');_x000D_
    ctx = canvas.getContext("2d");_x000D_
    _x000D_
    canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;_x000D_
    canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;_x000D_
    WIDTH = canvas.width;_x000D_
    HEIGHT = canvas.height;_x000D_
    _x000D_
    clearScreen();_x000D_
   })();_x000D_
   _x000D_
   function resizeCanvas() {_x000D_
    canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;_x000D_
    canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;_x000D_
    _x000D_
    WIDTH = canvas.width;_x000D_
    HEIGHT = canvas.height;_x000D_
    _x000D_
    clearScreen();_x000D_
   }_x000D_
   _x000D_
   function clearScreen() {_x000D_
    var grd = ctx.createLinearGradient(0,0,0,180);_x000D_
    grd.addColorStop(0,"#6666ff");_x000D_
    grd.addColorStop(1,"#aaaacc");_x000D_
_x000D_
    ctx.fillStyle = grd;_x000D_
    ctx.fillRect(  0, 0, WIDTH, HEIGHT );_x000D_
   }_x000D_
  </script>_x000D_
 </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Download a file by jQuery.Ajax

That's it works so fine in any browser (I'm using asp.net core)

_x000D_
_x000D_
            function onDownload() {_x000D_
_x000D_
  const api = '@Url.Action("myaction", "mycontroller")'; _x000D_
  var form = new FormData(document.getElementById('form1'));_x000D_
_x000D_
  fetch(api, { body: form, method: "POST"})_x000D_
      .then(resp => resp.blob())_x000D_
      .then(blob => {_x000D_
          const url = window.URL.createObjectURL(blob);_x000D_
        $('#linkdownload').attr('download', 'Attachement.zip');_x000D_
          $('#linkdownload').attr("href", url);_x000D_
          $('#linkdownload')_x000D_
              .fadeIn(3000,_x000D_
                  function() { });_x000D_
_x000D_
      })_x000D_
      .catch(() => alert('An error occurred'));_x000D_
_x000D_
_x000D_
_x000D_
}
_x000D_
 _x000D_
 <button type="button" onclick="onDownload()" class="btn btn-primary btn-sm">Click to Process Files</button>_x000D_
 _x000D_
 _x000D_
 _x000D_
 <a role="button" href="#" style="display: none" class="btn btn-sm btn-secondary" id="linkdownload">Click to download Attachments</a>_x000D_
 _x000D_
 _x000D_
 <form asp-controller="mycontroller" asp-action="myaction" id="form1"></form>_x000D_
 _x000D_
 
_x000D_
_x000D_
_x000D_

        function onDownload() {
            const api = '@Url.Action("myaction", "mycontroller")'; 
            //form1 is your id form, and to get data content of form
            var form = new FormData(document.getElementById('form1'));

            fetch(api, { body: form, method: "POST"})
                .then(resp => resp.blob())
                .then(blob => {
                    const url = window.URL.createObjectURL(blob);
                    $('#linkdownload').attr('download', 'Attachments.zip');
                    $('#linkdownload').attr("href", url);
                    $('#linkdownload')
                        .fadeIn(3000,
                            function() {

                            });
                })
                .catch(() => alert('An error occurred'));                 

        }

Image library for Python 3

As of March 30, 2012, I have tried and failed to get the sloonz fork on GitHub to open images. I got it to compile ok, but it didn't actually work. I also tried building gohlke's library, and it compiled also but failed to open any images. Someone mentioned PythonMagick above, but it only compiles on Windows. See PythonMagick on the wxPython wiki.

PIL was last updated in 2009, and while it's website says they are working on a Python 3 port, it's been 3 years, and the mailing list has gone cold.

To solve my Python 3 image manipulation problem, I am using subprocess.call() to execute ImageMagick shell commands. This method works.

See the subprocess module documentation.

How to switch Python versions in Terminal?

pyenv is a 3rd party version manager which is super commonly used (18k stars, 1.6k forks) and exactly what I looked for when I came to this question.

Install pyenv.

Usage

$ pyenv install --list
Available versions:
  2.1.3
  [...]
  3.8.1
  3.9-dev
  activepython-2.7.14
  activepython-3.5.4
  activepython-3.6.0
  anaconda-1.4.0
  [... a lot more; including anaconda, miniconda, activepython, ironpython, pypy, stackless, ....]

$ pyenv install 3.8.1
Downloading Python-3.8.1.tar.xz...
-> https://www.python.org/ftp/python/3.8.1/Python-3.8.1.tar.xz
Installing Python-3.8.1...
Installed Python-3.8.1 to /home/moose/.pyenv/versions/3.8.1

$ pyenv versions
* system (set by /home/moose/.pyenv/version)
  2.7.16
  3.5.7
  3.6.9
  3.7.4
  3.8-dev

$ python --version
Python 2.7.17
$ pip --version
pip 19.3.1 from /home/moose/.local/lib/python3.6/site-packages/pip (python 3.6)

$ mkdir pyenv-experiment && echo "3.8.1" > "pyenv-experiment/.python-version"
$ cd pyenv-experiment

$ python --version
Python 3.8.1
$ pip --version
pip 19.2.3 from /home/moose/.pyenv/versions/3.8.1/lib/python3.8/site-packages/pip (python 3.8)

Test if a command outputs an empty string

As mentioned by tripleee in the question comments , use moreutils ifne (if input not empty).

In this case we want ifne -n which negates the test:

ls -A /tmp/empty | ifne -n command-to-run-if-empty-input

The advantage of this over many of the another answers when the output of the initial command is non-empty. ifne will start writing it to STDOUT straight away, rather than buffering the entire output then writing it later, which is important if the initial output is slowly generated or extremely long and would overflow the maximum length of a shell variable.

There are a few utils in moreutils that arguably should be in coreutils -- they're worth checking out if you spend a lot of time living in a shell.

In particular interest to the OP may be dirempty/exists tool which at the time of writing is still under consideration, and has been for some time (it could probably use a bump).

C# - insert values from file into two arrays

string[] lines = File.ReadAllLines("sample.txt"); List<string> list1 = new List<string>(); List<string> list2 = new List<string>();  foreach (var line in lines) {     string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);     list1.Add(values[0]);     list2.Add(values[1]);  } 

Android ListView with onClick items

listview.setOnItemClickListener(new OnItemClickListener(){

    @Override
    public void onItemClick(AdapterView<?>adapter,View v, int position){
    Intent intent;
    switch(position){
      case 0:
        intent = new Intent(Activity.this,firstActivity.class);
        break;
      case 1:
        intent = new Intent(Activity.this,secondActivity.class);
        break;
     case 2:
        intent = new Intent(Activity.this,thirdActivity.class);
        break;
    //add more if you have more items in listview
   //0 is the first item 1 second and so on...
    }
    startActivity(intent);
  }

});

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

As of Rails 5.0.0.beta4 you can use the new String#upcase_firstmethod or ActiveSupport::Inflector#upcase_first to do it. Check this blog post for more info.

How to store Query Result in variable using mysql

Additionally, if you want to set multiple variables at once by one query, you can use the other syntax for setting variables which goes like this: SELECT @varname:=value.

A practical example:

SELECT @total_count:=COUNT(*), @total_price:=SUM(quantity*price) FROM items ...

Declaring variable workbook / Worksheet vba

Third solution: I would set ws to a sheet of workbook wb as the use of Sheet("name") always refers to the active workbook, which might change as your code develops.

sub kl() 

    Dim wb As Workbook
    Dim ws As Worksheet

    Set wb = ActiveWorkbook
    'be aware as this might produce an error, if Shet "name" does not exist
    Set ws = wb.Sheets("name")
    ' if wb is other than the active workbook
    wb.activate
    ws.Select

End Sub

SQLSTATE[42S22]: Column not found: 1054 Unknown column - Laravel

Try to change where Member class

public function users() {
    return $this->hasOne('User');
} 

return $this->belongsTo('User');

How do I convert a IPython Notebook into a Python file via commandline?

Jupytext is nice to have in your toolchain for such conversions. It allows not only conversion from a notebook to a script, but you can go back again from the script to notebook as well. And even have that notebook produced in executed form.

jupytext --to py notebook.ipynb                 # convert notebook.ipynb to a .py file
jupytext --to notebook notebook.py              # convert notebook.py to an .ipynb file with no outputs
jupytext --to notebook --execute notebook.py    # convert notebook.py to an .ipynb file and run it 

Import Script from a Parent Directory

If you want to run the script directly, you can:

  1. Add the FolderA's path to the environment variable (PYTHONPATH).
  2. Add the path to sys.path in the your script.

Then:

import module_you_wanted

Laravel Controller Subfolder routing

For those using Laravel 5 you need to set the namespace for the controller within the sub-directory (Laravel 5 is still in development and changes are happening daily)

To get a folder structure like:

Http
----Controllers
    ----Admin
            PostsController.php
    PostsController.php

namespace Admin\PostsController.php file like so:

<?php namespace App\Http\Controller\Admin;

use App\Http\Controllers\Controller;

class PostsController extends Controller {

    //business logic here
}

Then your route for this is:

$router->get('/', 'Admin\PostsController@index');

And lastly, don't for get to do either composer or artisan dump

composer dump-autoload

or

php artisan dump

How to convert a negative number to positive?

If "keep a positive one" means you want a positive number to stay positive, but also convert a negative number to positive, use abs():

>>> abs(-1)
1
>>> abs(1)
1

What's the advantage of a Java enum versus a class with public static final fields?

You get compile time checking of valid values when you use an enum. Look at this question.

Django TemplateDoesNotExist?

I had an embarrassing problem...

I got this error because I was rushing and forgot to put the app in INSTALLED_APPS. You would think Django would raise a more descriptive error.

Convert a String to a byte array and then back to the original String

I would suggest using the members of string, but with an explicit encoding:

byte[] bytes = text.getBytes("UTF-8");
String text = new String(bytes, "UTF-8");

By using an explicit encoding (and one which supports all of Unicode) you avoid the problems of just calling text.getBytes() etc:

  • You're explicitly using a specific encoding, so you know which encoding to use later, rather than relying on the platform default.
  • You know it will support all of Unicode (as opposed to, say, ISO-Latin-1).

EDIT: Even though UTF-8 is the default encoding on Android, I'd definitely be explicit about this. For example, this question only says "in Java or Android" - so it's entirely possible that the code will end up being used on other platforms.

Basically given that the normal Java platform can have different default encodings, I think it's best to be absolutely explicit. I've seen way too many people using the default encoding and losing data to take that risk.

EDIT: In my haste I forgot to mention that you don't have to use the encoding's name - you can use a Charset instead. Using Guava I'd really use:

byte[] bytes = text.getBytes(Charsets.UTF_8);
String text = new String(bytes, Charsets.UTF_8);

Random number generator only generating one random number

There are a lot of solutions, here one: if you want only number erase the letters and the method receives a random and the result length.

public String GenerateRandom(Random oRandom, int iLongitudPin)
{
    String sCharacters = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
    int iLength = sCharacters.Length;
    char cCharacter;
    int iLongitudNuevaCadena = iLongitudPin; 
    String sRandomResult = "";
    for (int i = 0; i < iLongitudNuevaCadena; i++)
    {
        cCharacter = sCharacters[oRandom.Next(iLength)];
        sRandomResult += cCharacter.ToString();
    }
    return (sRandomResult);
}

How to get a certain element in a list, given the position?

Not very efficient, but if you must use a list, you can deference the iterator

*myList.begin()+N

update package.json version automatically

You can use the version-select package:

npm i -D version-select
{
    "name": "test",
    "version": "1.0.0",
    "scripts": {
        "version-select": "version-select"
    },
    "devDependencies": {
        "version-select": "^1.0.13"
    }
}

enter image description here

Read more

ngrok command not found

  • Download the zip file.
  • Unzip it.
  • Open The terminal in the current location (inside unzip folder) where you unzip the file.
  • Execute the following command into the terminal :

    sudo cp ngrok /usr/local/bin          
    

    Now your ngrok execuatable file is successfully copied to the /usr/local/bin directory. Now you are able to run the ngrok command in the terminal

Response Buffer Limit Exceeded

Here is what a Microsoft support page says about this: https://support.microsoft.com/en-us/help/944886/error-message-when-you-use-the-response-binarywrite-method-in-iis-6-an.

But it’s easier in the GUI:

  • In Internet Information Services (IIS) Manager, click on ASP.
  • Change Behavior > Limits Properties > Response Buffering Limit from 4 MB to 64 MB.
  • Apply and restart.

How to get $(this) selected option in jQuery?

Best guess:

var cur_value = $('#select-id').children('option:selected').text();

I like children better in this case because you know you're only going one branch down the DOM tree...

indexOf method in an object array?

Using the ES6 findIndex method, without lodash or any other libraries, you can write:

function deepIndexOf(arr, obj) {
  return arr.findIndex(function (cur) {
    return Object.keys(obj).every(function (key) {
      return obj[key] === cur[key];
    });
  });
}

This will compare the immediate properties of the object, but not recurse into the properties.

If your implementation doesn't provide findIndex yet (most don't), you can add a light polyfill that supports this search:

function deepIndexOf(arr, obj) {
  function findIndex = Array.prototype.findIndex || function (pred) {
    for (let i = 0; i < this.length; ++i) {
      if (pred.call(this, this[i], i)) {
        return i;
      }
    }

    return -1;
  }

  return findIndex.call(arr, function (cur) {
    return Object.keys(obj).every(function (key) {
      return obj[key] === cur[key];
    });
  });
}

(from my answer on this dupe)

How do I set an ASP.NET Label text from code behind on page load?

I know this was posted a long while ago, and it has been marked answered, but to me, the selected answer was not answering the question I thought the user was posing. It seemed to me he was looking for the approach one can take in ASP .Net that corresponds to his inline data binding previously performed in php.

Here was his php:

<p>Here is the username: <?php echo GetUserName(); ?></p>

Here is what one would do in ASP .Net:

<p>Here is the username: <%= GetUserName() %></p>

How to draw circle in html page?

  1. _x000D_
    _x000D_
    h1 {_x000D_
    border: dashed 2px blue;_x000D_
      width: 200px;_x000D_
      height: 200px;_x000D_
      border-radius: 100px;_x000D_
      text-align: center;_x000D_
      line-height: 60px;_x000D_
      _x000D_
    }
    _x000D_
    <h1> <br>hello world</h1>
    _x000D_
    _x000D_
    _x000D_

Submit button doesn't work

I faced this problem today, and the issue was I was preventing event default action in document onclick:

document.onclick = function(e) {
    e.preventDefault();
}

Document onclick usually is used for event delegation but it's wrong to prevent default for every event, you must do it only for required elements:

document.onclick = function(e) {
    if (e.target instanceof HTMLAnchorElement) e.preventDefault();
}

Getting the difference between two sets

You can use CollectionUtils.disjunction to get all differences or CollectionUtils.subtract to get the difference in the first collection.

Here is an example of how to do that:

    var collection1 = List.of(1, 2, 3, 4, 5);
    var collection2 = List.of(2, 3, 5, 6);
    System.out.println(StringUtils.join(collection1, " , "));
    System.out.println(StringUtils.join(collection2, " , "));
    System.out.println(StringUtils.join(CollectionUtils.subtract(collection1, collection2), " , "));
    System.out.println(StringUtils.join(CollectionUtils.retainAll(collection1, collection2), " , "));
    System.out.println(StringUtils.join(CollectionUtils.collate(collection1, collection2), " , "));
    System.out.println(StringUtils.join(CollectionUtils.disjunction(collection1, collection2), " , "));
    System.out.println(StringUtils.join(CollectionUtils.intersection(collection1, collection2), " , "));
    System.out.println(StringUtils.join(CollectionUtils.union(collection1, collection2), " , "));

Most popular screen sizes/resolutions on Android phones

A blog article from Localytics, Android Not As Fragmented as Many Think, lists most popular Android sizes and resolutions:

Another concern for Android developers is screen size and resolution. Of all app usage analyzed for this study, 41% of all sessions came from Android devices with 4.3 inch screens, by far the most popular size. 4 inch screens accounted for 22% of sessions, 3.2 inch screens for 11%, and 3.7 inch screens contributed 9%.

Resolutions were even less fragmented, however, with the most widely-seen screen resolution – 800 x 480 pixels – contributing 62% of the study’s sessions. The next most popular screen resolutions were 480 x 320 (14%), 960 x 540 (6%), 480 x 854 (5%) and 320 x 240 (5%).

Please note these statistics are from February 2012, which might be outdated today. Also, please always keep in mind that your app might be used under the inch sizes and resolutions not listed in this article.

EDIT: You should also be aware that there are Android "tablets" with large resolutions. The following quote is from the same article I mentioned:

Screen resolution and size are actually even less fragmented than handsets – 74% of Android tablet usage takes place on 7 inch devices with 1024 x 600 resolution. 22% are 10.1 inch devices with 1280 x 800 resolutions, so by taking into account two screen size/resolution combinations, developers should be able to easily reach nearly all of the Android tablet market.

Is there a php echo/print equivalent in javascript

From w3school's page on JavaScript output,

JavaScript can "display" data in different ways:

Writing into an alert box, using window.alert().

Writing into the HTML output using document.write().

Writing into an HTML element, using innerHTML.

Writing into the browser console, using console.log().

Flutter plugin not installed error;. When running flutter doctor

The best way to install it on Windows 

Doctor summary (to see all details, run flutter doctor -v):
[v] Flutter (Channel stable, 1.20.1, on Microsoft Windows [Version 10.0.18363.959], locale en-US)
[v] Android toolchain - develop for Android devices (Android SDK version 30.0.0)
[v] Android Studio (version 4.0)
[v] VS Code (version 1.47.3)
[!] Connected device
    ! No devices available

1- Open Android Studio File->Settings->Plugins and Make Sure You have Flutter and Dart Installed enter image description here

2- Go to VSCode to Extensions and install Flutter and Dart Extension

enter image description here

Hope It Solved the problem

How does it work - requestLocationUpdates() + LocationRequest/Listener

I use this one:

LocationManager.requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)

For example, using a 1s interval:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);

the time is in milliseconds, the distance is in meters.

This automatically calls:

public void onLocationChanged(Location location) {
    //Code here, location.getAccuracy(), location.getLongitude() etc...
}

I also had these included in the script but didnt actually use them:

public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}

In short:

public class GPSClass implements LocationListener {

    public void onLocationChanged(Location location) {
        // Called when a new location is found by the network location provider.
        Log.i("Message: ","Location changed, " + location.getAccuracy() + " , " + location.getLatitude()+ "," + location.getLongitude());
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}
    public void onProviderEnabled(String provider) {}
    public void onProviderDisabled(String provider) {}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
    }
}

Get key from a HashMap using the value

public class Class1 {
private String extref="MY";

public String getExtref() {
    return extref;
}

public String setExtref(String extref) {
    return this.extref = extref;
}

public static void main(String[] args) {

    Class1 obj=new Class1();
    String value=obj.setExtref("AFF");
    int returnedValue=getMethod(value);     
    System.out.println(returnedValue);
}

/**
 * @param value
 * @return
 */
private static int getMethod(String value) {
      HashMap<Integer, String> hashmap1 = new HashMap<Integer, String>();
        hashmap1.put(1,"MY");
        hashmap1.put(2,"AFF");

        if (hashmap1.containsValue(value))
        {
            for (Map.Entry<Integer,String> e : hashmap1.entrySet()) {
                Integer key = e.getKey();
                Object value2 = e.getValue();
                if ((value2.toString()).equalsIgnoreCase(value))
                {
                    return key;
                }
            }
        }   
        return 0;

}
}

Mixing a PHP variable with a string literal

$bucket = '$node->' . $fieldname . "['und'][0]['value'] = " . '$form_state' . "['values']['" . $fieldname . "']";

print $bucket;

yields:

$node->mindd_2_study_status['und'][0]['value'] = $form_state['values']
['mindd_2_study_status']

What causes java.lang.IncompatibleClassChangeError?

An additional cause of this issue, is if you have Instant Run enabled for Android Studio.

The fix

If you find you start getting this error, turn off Instant Run.

  1. Android Studio main settings
  2. Build, Execution, Deployment
  3. Instant Run
  4. Untick "Enable instant run..."

Why

Instant Run modifies a large number of things during development, to make it quicker to provide updates to your running App. Hence instant run. When it works, it is really useful. However, when an issue such as this strikes, the best thing to do is to turn off Instant Run until the next version of Android Studio releases.

How to compile and run C/C++ in a Unix console/Mac terminal?

For running c++ files run below command, Assuming file name is "main.cpp"

1.Compile to make object file from c++ file.

g++ -c main.cpp -o main.o

2.Since #include <conio.h> does not support in MacOS so we should use its alternative which supports in Mac that is #include <curses.h>. Now object file needs to be converted to executable file. To use curses.h we have to use library -lcurses.

g++ -o main main.o -lcurses

3.Now run the executable.

./main

Unable to load DLL 'SQLite.Interop.dll'

I don't know why this has not been included yet, but I had to do the research and find this out for myself, so hopefully someone will find this answer and be saved the trouble. This was for a WPF app. It worked fine on my Dev box, but did not work on the computer where I was copying it and got the Unable to load DLL 'SQLite.Interop.dll' error. I ported over all of its associated directories and files, directly from my "Debug" folder to this other computer when I got the same error as the OP when I ran it. My "bin" folder that contained my DLLs had been copied to "Debug\bin" and all were included, along with my application files when I did my copying to the other computer using this path, so it was not missing any files.

Things I saw said in other answers that did not apply:

  • I did not use the NuGet package or need to create x86 or x64 folders that it seems that NuGet package creates. My DLLs (System.Data.SQLite and SQLite.Interop.dll, along with System.Data.SQLite.config) are in the "bin" folder in my project and were copied in manually (create "bin" folder in Solution Explorer in VS, paste DLLs into this folder in Windows Explorer, use Add > Existing Item to bring files into VS folder/project). Then I reference them as Referenced Assemblies in my project using that location ("References" > "Add Reference", and browse to one, rinse, repeat for the rest). This ensures my project knows exactly where they are.
  • I did not need to reference any SQLite DLL file in my app.config or even touch my MyProject.csproj file.
  • I did not even need to specify a particular processor! My project's build is for "Any CPU", even though I have only mixed or 64-bit DLLs and will only be running on Windows 7+, which are 64-bit OSes. (no x86-only/32-bit solely DLLs)
  • I was already specifying them as "Content" and "copy if newer" for these DLLs when I experienced the OP's error.

What I found was this, from https://system.data.sqlite.org/index.html/doc/trunk/www/faq.wiki#q20 :

(11) Why do I get a DllNotFoundException (for "sqlite3.dll" or "SQLite.Interop.dll") when trying to run my application?

Either the named dynamic link library (DLL) cannot be located or it cannot be loaded due to missing dependencies. Make sure the named dynamic link library is located in the application directory or a directory along the system PATH and try again. Also, be sure the necessary Visual C++ runtime redistributable has been installed unless you are using a dynamic link library that was built statically linked to it.

Emphasis mine on that bolded part inside the paragraph. The target computer was fresh and had no programs loaded except .NET 4.0. Once I installed C++, it was able to complete the commands to SQLite. This should have been one of the first FAQs and part of the pre-requisities, but it was buried at #11. My development computer already had it loaded because it came with Visual Studio, so that's why it worked, there.

Download:
Visual C++ Redistributable for Visual Studio 2015:
https://www.microsoft.com/en-us/download/details.aspx?id=48145

Update 3 (cumulative update):
https://www.microsoft.com/en-us/download/details.aspx?id=53587

How can I implement rate limiting with Apache? (requests per second)

The best

  • mod_evasive (Focused more on reducing DoS exposure)
  • mod_cband (Best featured for 'normal' bandwidth control)

and the rest

Converting a string to a date in DB2

I know its old post but still I want to contribute
Above will not work if you have data format like this
'YYYMMDD'

For example:

Dt
20151104

So I tried following in order to get the desired result.

select cast(Left('20151104', 4)||'-'||substring('20151104',5,2)||'-'||substring('20151104', 7,2) as date) from SYSIBM.SYSDUMMY1;

Additionally, If you want to run the query from MS SQL linked server to DB2(To display only 100 rows).

    SELECT top 100 * from OPENQUERY([Linked_Server_Name],
    'select cast(Left(''20151104'', 4)||''-''||substring(''20151104'',5,2)||''-''||substring(''20151104'', 7,2) as date) AS Dt 
    FROM SYSIBM.SYSDUMMY1')

Result after above query:

Dt
2015-11-04

Hope this helps for others.

Good Free Alternative To MS Access

VistaDB is the only alternative if you going to run your website at shared hosting (almost all of them won't let you run your websites under Full Trust mode) and also if you need simple x-copy deployment enabled website.

Send Email to multiple Recipients with MailMessage?

Easy!

Just split the incoming address list on the ";" character, and add them to the mail message:

foreach (var address in addresses.Split(new [] {";"}, StringSplitOptions.RemoveEmptyEntries))
{
    mailMessage.To.Add(address);    
}

In this example, addresses contains "[email protected];[email protected]".

How to find index of list item in Swift?

In Swift 4, if you are traversing through your DataModel array, make sure your data model conforms to Equatable Protocol , implement the lhs=rhs method , and only then you can use ".index(of" . For example

class Photo : Equatable{
    var imageURL: URL?
    init(imageURL: URL){
        self.imageURL = imageURL
    }

    static func == (lhs: Photo, rhs: Photo) -> Bool{
        return lhs.imageURL == rhs.imageURL
    }
}

And then,

let index = self.photos.index(of: aPhoto)

How to do paging in AngularJS?

I just made a JSFiddle that show pagination + search + order by on each column using btford code: http://jsfiddle.net/SAWsA/11/

How to output to the console in C++/Windows

There is a good solution

if (AllocConsole() == 0)
{
    // Handle error here. Use ::GetLastError() to get the error.
}

// Redirect CRT standard input, output and error handles to the console window.
FILE * pNewStdout = nullptr;
FILE * pNewStderr = nullptr;
FILE * pNewStdin = nullptr;

::freopen_s(&pNewStdout, "CONOUT$", "w", stdout);
::freopen_s(&pNewStderr, "CONOUT$", "w", stderr);
::freopen_s(&pNewStdin, "CONIN$", "r", stdin);

// Clear the error state for all of the C++ standard streams. Attempting to accessing the streams before they refer
// to a valid target causes the stream to enter an error state. Clearing the error state will fix this problem,
// which seems to occur in newer version of Visual Studio even when the console has not been read from or written
// to yet.
std::cout.clear();
std::cerr.clear();
std::cin.clear();

std::wcout.clear();
std::wcerr.clear();
std::wcin.clear();

How do I change Bootstrap 3 column order on mobile layout?

The answers here work for just 2 cells, but as soon as those columns have more in them it can lead to a bit more complexity. I think I've found a generalized solution for any number of cells in multiple columns.

#Goals Get a vertical sequence of tags on mobile to arrange themselves in whatever order the design calls for on tablet/desktop. In this concrete example, one tag must enter flow earlier than it normally would, and another later than it normally would.

##Mobile

[1 headline]
[2 image]
[3 qty]
[4 caption]
[5 desc]

##Tablet+

[2 image  ][1 headline]
[         ][3 qty     ]
[         ][5 desc    ]
[4 caption][          ]
[         ][          ]

So headline needs to shuffle right on tablet+, and technically, so does desc - it sits above the caption tag that precedes it on mobile. You'll see in a moment 4 caption is in trouble too.

Let's assume every cell could vary in height, and needs to be flush top-to-bottom with its next cell (ruling out weak tricks like a table).

As with all Bootstrap Grid problems step 1 is to realize the HTML has to be in mobile-order, 1 2 3 4 5, on the page. Then, determine how to get tablet/desktop to reorder itself in this way - ideally without Javascript.

The solution to get 1 headline and 3 qty to sit to the right not the left is to simply set them both pull-right. This applies CSS float: right, meaning they find the first open space they'll fit to the right. You can think of the browser's CSS processor working in the following order: 1 fits in to the right top corner. 2 is next and is regular (float: left), so it goes to top-left corner. Then 3, which is float: right so it leaps over underneath 1.

But this solution wasn't enough for 4 caption; because the right 2 cells are so short 2 image on the left tends to be longer than the both of them combined. Bootstrap Grid is a glorified float hack, meaning 4 caption is float: left. With 2 image occupying so much room on the left, 4 caption attempts to fit in the next available space - often the right column, not the left where we wanted it.

The solution here (and more generally for any issue like this) was to add a hack tag, hidden on mobile, that exists on tablet+ to push caption out, that then gets covered up by a negative margin - like this:

[2 image  ][1 headline]
[         ][3 qty     ]
[         ][4 hack    ]
[5 caption][6 desc ^^^]
[         ][          ]

http://jsfiddle.net/b9chris/52VtD/16633/

HTML:

<div id=headline class="col-xs-12 col-sm-6 pull-right">Product Headline</div>
<div id=image class="col-xs-12 col-sm-6">Product Image</div>
<div id=qty class="col-xs-12 col-sm-6 pull-right">Qty, Add to cart</div>
<div id=hack class="hidden-xs col-sm-6">Hack</div>
<div id=caption class="col-xs-12 col-sm-6">Product image caption</div>
<div id=desc class="col-xs-12 col-sm-6 pull-right">Product description</div>

CSS:

#hack { height: 50px; }

@media (min-width: @screen-sm) {
    #desc { margin-top: -50px; }
}

So, the generalized solution here is to add hack tags that can disappear on mobile. On tablet+ the hack tags allow displayed tags to appear earlier or later in the flow, then get pulled up or down to cover up those hack tags.

Note: I've used fixed heights for the sake of the simple example in the linked jsfiddle, but the actual site content I was working on varies in height in all 5 tags. It renders properly with relatively large variance in tag heights, especially image and desc.

Note 2: Depending on your layout, you may have a consistent enough column order on tablet+ (or larger resolutions), that you can avoid use of hack tags, using margin-bottom instead, like so:

Note 3: This uses Bootstrap 3. Bootstrap 4 uses a different grid set, and won't work with these examples.

http://jsfiddle.net/b9chris/52VtD/16632/

Tensorflow: how to save/restore a model?

For TensorFlow version < 0.11.0RC1:

The checkpoints that are saved contain values for the Variables in your model, not the model/graph itself, which means that the graph should be the same when you restore the checkpoint.

Here's an example for a linear regression where there's a training loop that saves variable checkpoints and an evaluation section that will restore variables saved in a prior run and compute predictions. Of course, you can also restore variables and continue training if you'd like.

x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)

w = tf.Variable(tf.zeros([1, 1], dtype=tf.float32))
b = tf.Variable(tf.ones([1, 1], dtype=tf.float32))
y_hat = tf.add(b, tf.matmul(x, w))

...more setup for optimization and what not...

saver = tf.train.Saver()  # defaults to saving all variables - in this case w and b

with tf.Session() as sess:
    sess.run(tf.initialize_all_variables())
    if FLAGS.train:
        for i in xrange(FLAGS.training_steps):
            ...training loop...
            if (i + 1) % FLAGS.checkpoint_steps == 0:
                saver.save(sess, FLAGS.checkpoint_dir + 'model.ckpt',
                           global_step=i+1)
    else:
        # Here's where you're restoring the variables w and b.
        # Note that the graph is exactly as it was when the variables were
        # saved in a prior training run.
        ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)
        if ckpt and ckpt.model_checkpoint_path:
            saver.restore(sess, ckpt.model_checkpoint_path)
        else:
            ...no checkpoint found...

        # Now you can run the model to get predictions
        batch_x = ...load some data...
        predictions = sess.run(y_hat, feed_dict={x: batch_x})

Here are the docs for Variables, which cover saving and restoring. And here are the docs for the Saver.

How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe?

To simplify Kirubaharan's answer a bit:

df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])
df = df.set_index('Datetime')

And to get rid of unwanted columns (as OP did but did not specify per se in the question):

df = df.drop(['date','time'], axis=1)

SQL Server - copy stored procedures from one db to another

This code copies all stored procedures in the Master database to the target database, you can copy just the procedures you like by filtering the query on procedure name.

@sql is defined as nvarchar(max), @Name is the target database

DECLARE c CURSOR FOR 
   SELECT Definition
   FROM [ResiDazeMaster].[sys].[procedures] p
   INNER JOIN [ResiDazeMaster].sys.sql_modules m ON p.object_id = m.object_id

OPEN c

FETCH NEXT FROM c INTO @sql

WHILE @@FETCH_STATUS = 0 
BEGIN
   SET @sql = REPLACE(@sql,'''','''''')
   SET @sql = 'USE [' + @Name + ']; EXEC(''' + @sql + ''')'

   EXEC(@sql)

   FETCH NEXT FROM c INTO @sql
END             

CLOSE c
DEALLOCATE c

HTML CSS Invisible Button

HTML

<input type="button">

CSS

input[type=button]{
 background:transparent;
 border:0;
}

Git Symlinks in Windows

so as things have changed with GIT since alot of these answers were posted here is the correct instructions to get symlinks working correctly in windows as of

AUGUST 2018


1. Make sure git is installed with symlink support

During the install of git on windows

2. Tell Bash to create hardlinks instead of symlinks

EDIT -- (git folder)/etc/bash.bashrc

ADD TO BOTTOM - MSYS=winsymlinks:nativestrict

3. Set git config to use symlinks

git config core.symlinks true

or

git clone -c core.symlinks=true <URL>

NOTE: I have tried adding this to the global git config and at the moment it is not working for me so I recommend adding this to each repo...

4. pull the repo

NOTE: Unless you have enabled developer mode in the latest version of Windows 10, you need to run bash as administrator to create symlinks

5. Reset all Symlinks (optional) If you have an existing repo, or are using submodules you may find that the symlinks are not being created correctly so to refresh all the symlinks in the repo you can run these commands.

find -type l -delete
git reset --hard

NOTE: this will reset any changes since last commit so make sure you have committed first

Finding square root without using sqrt function?

Why not try to use the Babylonian method for finding a square root.

Here is my code for it:

double sqrt(double number)
{
    double error = 0.00001; //define the precision of your result
    double s = number;

    while ((s - number / s) > error) //loop until precision satisfied 
    {
        s = (s + number / s) / 2;
    }
    return s;
}

Good luck!

What is a Question Mark "?" and Colon ":" Operator Used for?

Maybe It can be perfect example for Android, For example:

void setWaitScreen(boolean set) {
    findViewById(R.id.screen_main).setVisibility(
            set ? View.GONE : View.VISIBLE);
    findViewById(R.id.screen_wait).setVisibility(
            set ? View.VISIBLE : View.GONE);
}

Can one class extend two classes?

What you're asking about is multiple inheritance, and it's very problematic for a number of reasons. Multiple inheritance was specifically avoided in Java; the choice was made to support multiple interface implementation, instead, which is the appropriate workaround.

Stop absolutely positioned div from overlapping text

Thank you for all your answers, Whilst all were correct, none actually solved my problem. The solution for me was to create a second invisible div at the end of the content of unknown length, this invisible div is the same size as my absolutely positioned div, this ensures that there is always a space at the end of my content for the absolutely positioned div.

This answer was previously provided here: Prevent absolutely-positioned elements from overlapping with text However I didn't see (until now) how to apply it to a bottom right positioned div.

New structure is as follows:

_x000D_
_x000D_
<div id="outer" style="position: relative; width:450px; background-color:yellow;">
        <p>Content of unknown length</p>
        <div>Content of unknown height </div>
        <div id="spacer" style="width: 200px; height: 25px; margin-right:0px;"></div>
        <div style="position: absolute; right: 0; bottom: 0px; width: 200px; height: 20px; background-color:red;">bottom right</div>
    </div>
_x000D_
_x000D_
_x000D_

This seems to solve the issue.

Is there an easy way to reload css without reloading the page?

In a simple manner you can use rel="preload" instead of rel="stylesheet" .

<link rel="preload" href="path/to/mystylesheet.css" as="style" onload="this.rel='stylesheet'">

Create new user in MySQL and give it full access to one database

$ mysql -u root -p -e "grant all privileges on dbTest.* to
`{user}`@`{host}` identified by '{long-password}'; flush privileges;"

ignore -p option, if mysql user has no password or just press "[Enter]" button to by-pass. strings surrounded with curly braces need to replaced with actual values.

Make 2 functions run at the same time

Do this:

from threading import Thread

def func1():
    print('Working')

def func2():
    print("Working")

if __name__ == '__main__':
    Thread(target = func1).start()
    Thread(target = func2).start()

How to write and read a file with a HashMap?

You can write an object to a file using writeObject in ObjectOutputStream

ObjectOutputStream

ASP.NET: Session.SessionID changes between requests

In my case this was happening a lot in my development and test environments. After trying all of the above solutions without any success I found that I was able to fix this problem by deleting all session cookies. The web developer extension makes this very easy to do. I mostly use Firefox for testing and development, but this also happened while testing in Chrome. The fix also worked in Chrome.

I haven't had to do this yet in the production environment and have not received any reports of people not being able to log in. This also only seemed to happen after making the session cookies to be secure. It never happened in the past when they were not secure.

Double precision - decimal places

In most contexts where double values are used, calculations will have a certain amount of uncertainty. The difference between 1.33333333333333300 and 1.33333333333333399 may be less than the amount of uncertainty that exists in the calculations. Displaying the value of "2/3 + 2/3" as "1.33333333333333" is apt to be more meaningful than displaying it as "1.33333333333333319", since the latter display implies a level of precision that doesn't really exist.

In the debugger, however, it is important to uniquely indicate the value held by a variable, including essentially-meaningless bits of precision. It would be very confusing if a debugger displayed two variables as holding the value "1.333333333333333" when one of them actually held 1.33333333333333319 and the other held 1.33333333333333294 (meaning that, while they looked the same, they weren't equal). The extra precision shown by the debugger isn't apt to represent a numerically-correct calculation result, but indicates how the code will interpret the values held by the variables.

Execute a PHP script from another PHP script

Possible and easiest one-line solution is to use:

file_get_contents("YOUR_REQUESTED_FILE");

Or equivavelt for example CURL.

Can I change the scroll speed using css or jQuery?

I just made a pure Javascript function based on that code. Javascript only version demo: http://jsbin.com/copidifiji

That is the independent code from jQuery

if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false); 
window.onmousewheel = document.onmousewheel = wheel;}

function wheel(event) {
    var delta = 0;
    if (event.wheelDelta) delta = (event.wheelDelta)/120 ;
    else if (event.detail) delta = -(event.detail)/3;

    handle(delta);
    if (event.preventDefault) event.preventDefault();
    event.returnValue = false;
}

function handle(sentido) {
    var inicial = document.body.scrollTop;
    var time = 1000;
    var distance = 200;
  animate({
    delay: 0,
    duration: time,
    delta: function(p) {return p;},
    step: function(delta) {
window.scrollTo(0, inicial-distance*delta*sentido);   
    }});}

function animate(opts) {
  var start = new Date();
  var id = setInterval(function() {
    var timePassed = new Date() - start;
    var progress = (timePassed / opts.duration);
    if (progress > 1) {progress = 1;}
    var delta = opts.delta(progress);
    opts.step(delta);
    if (progress == 1) {clearInterval(id);}}, opts.delay || 10);
}

Naming threads and thread-pools of ExecutorService

This is my customized factory providing a customized names for thread dump analyzers. Usually I just give tf=null to reuse JVM default thread factory. This website has more advanced thread factory.

public class SimpleThreadFactory implements ThreadFactory {
    private ThreadFactory tf;
    private String nameSuffix;

    public SimpleThreadFactory (ThreadFactory tf, String nameSuffix) {
        this.tf = tf!=null ? tf : Executors.defaultThreadFactory();
        this.nameSuffix = nameSuffix; 
    }

    @Override public Thread newThread(Runnable task) {
        // default "pool-1-thread-1" to "pool-1-thread-1-myapp-MagicTask"
        Thread thread=tf.newThread(task);
        thread.setName(thread.getName()+"-"+nameSuffix);
        return thread;
    }
}

- - - - - 

ExecutorService es = Executors.newFixedThreadPool(4, new SimpleThreadFactory(null, "myapp-MagicTask") );

For your convenience this is a thread dump loop for debug purpose.

    ThreadMXBean mxBean=ManagementFactory.getThreadMXBean();
    long[] tids = mxBean.getAllThreadIds();
    System.out.println("------------");
    System.out.println("ThreadCount="+tids.length);
    for(long tid : tids) {
        ThreadInfo mxInfo=mxBean.getThreadInfo(tid);
        if (mxInfo==null) {
            System.out.printf("%d %s\n", tid, "Thread not found");
        } else {
            System.out.printf("%d %s, state=%s, suspended=%d, lockowner=%d %s\n"
                    , mxInfo.getThreadId(), mxInfo.getThreadName()
                    , mxInfo.getThreadState().toString()
                    , mxInfo.isSuspended()?1:0
                    , mxInfo.getLockOwnerId(), mxInfo.getLockOwnerName()
            );
        }
    }

Find full path of the Python interpreter?

Just noting a different way of questionable usefulness, using os.environ:

import os
python_executable_path = os.environ['_']

e.g.

$ python -c "import os; print(os.environ['_'])"
/usr/bin/python

Converting an integer to binary in C

You can convert decimal to bin, hexa to decimal, hexa to bin, vice-versa etc by following this example. CONVERTING DECIMAL TO BIN

int convert_to_bin(int number){
    int binary = 0, counter = 0;
    while(number > 0){
        int remainder = number % 2;
        number /= 2;
        binary += pow(10, counter) * remainder;
        counter++;
    }   
}

Then you can print binary equivalent like this:

printf("08%d", convert_to_bin(13)); //shows leading zeros

Creating a timer in python

I want to create a kind of stopwatch that when minutes reach 20 minutes, brings up a dialog box.

All you need is to sleep the specified time. time.sleep() takes seconds to sleep, so 20 * 60 is 20 minutes.

import time
run = raw_input("Start? > ")
time.sleep(20 * 60)
your_code_to_bring_up_dialog_box()

How to change font in ipython notebook

I would also suggest that you explore the options offered by the jupyter themer. For more modest interface changes you may be satisfied with running the syntax:

jupyter-themer [-c COLOR, --color COLOR]
                      [-l LAYOUT, --layout LAYOUT]
                      [-t TYPOGRAPHY, --typography TYPOGRAPHY]

where the options offered by themer would provide you with a less onerous way of making some changes in to the look of Jupyter Notebook. Naturally, you may still to prefer edit the .css files if the changes you want to apply are elaborate.

Should you always favor xrange() over range()?

I would just like to say that it REALLY isn't that difficult to get an xrange object with slice and indexing functionality. I have written some code that works pretty dang well and is just as fast as xrange for when it counts (iterations).

from __future__ import division

def read_xrange(xrange_object):
    # returns the xrange object's start, stop, and step
    start = xrange_object[0]
    if len(xrange_object) > 1:
       step = xrange_object[1] - xrange_object[0]
    else:
        step = 1
    stop = xrange_object[-1] + step
    return start, stop, step

class Xrange(object):
    ''' creates an xrange-like object that supports slicing and indexing.
    ex: a = Xrange(20)
    a.index(10)
    will work

    Also a[:5]
    will return another Xrange object with the specified attributes

    Also allows for the conversion from an existing xrange object
    '''
    def __init__(self, *inputs):
        # allow inputs of xrange objects
        if len(inputs) == 1:
            test, = inputs
            if type(test) == xrange:
                self.xrange = test
                self.start, self.stop, self.step = read_xrange(test)
                return

        # or create one from start, stop, step
        self.start, self.step = 0, None
        if len(inputs) == 1:
            self.stop, = inputs
        elif len(inputs) == 2:
            self.start, self.stop = inputs
        elif len(inputs) == 3:
            self.start, self.stop, self.step = inputs
        else:
            raise ValueError(inputs)

        self.xrange = xrange(self.start, self.stop, self.step)

    def __iter__(self):
        return iter(self.xrange)

    def __getitem__(self, item):
        if type(item) is int:
            if item < 0:
                item += len(self)

            return self.xrange[item]

        if type(item) is slice:
            # get the indexes, and then convert to the number
            start, stop, step = item.start, item.stop, item.step
            start = start if start != None else 0 # convert start = None to start = 0
            if start < 0:
                start += start
            start = self[start]
            if start < 0: raise IndexError(item)
            step = (self.step if self.step != None else 1) * (step if step != None else 1)
            stop = stop if stop is not None else self.xrange[-1]
            if stop < 0:
                stop += stop

            stop = self[stop]
            stop = stop

            if stop > self.stop:
                raise IndexError
            if start < self.start:
                raise IndexError
            return Xrange(start, stop, step)

    def index(self, value):
        error = ValueError('object.index({0}): {0} not in object'.format(value))
        index = (value - self.start)/self.step
        if index % 1 != 0:
            raise error
        index = int(index)


        try:
            self.xrange[index]
        except (IndexError, TypeError):
            raise error
        return index

    def __len__(self):
        return len(self.xrange)

Honestly, I think the whole issue is kind of silly and xrange should do all of this anyway...

Append String in Swift

In the accepted answer PREMKUMAR there are a couple of errors in his Complete code in Swift answer. First print should read (appendString) and Second print should read (appendString1). Also, updated println deprecated in Swift 2.0

His

let string1 = "This is"
let string2 = "Swift Language"
var appendString = "\(string1) \(string2)"
var appendString1 = string1+string2
println("APPEND STRING1:\(appendString1)")
println("APPEND STRING2:\(appendString2)")

Corrected

let string1 = "This is"
let string2 = "Swift Language"
var appendString = "\(string1) \(string2)"
var appendString1 = string1+string2
print("APPEND STRING:\(appendString)")
print("APPEND STRING1:\(appendString1)")

How to add Class in <li> using wp_nav_menu() in Wordpress?

I added a class to easily implement menu arguments. So you can customize and include in your function like this:

include_once get_template_directory() . DIRECTORY_SEPARATOR . "your-directory" . DIRECTORY_SEPARATOR . "Menu.php";

<?php $menu = (new Menu('your-theme-location'))
            ->setMenuClass('your-menu')
            ->setMenuID('your-menu-id')
            ->setListClass('your-menu-class')
            ->setLinkClass('your-menu-link anchor') ?>
    
            // Print your menu
            <?php $menu->showMenu() ?>
<?php

class Menu
{
    private $args = [
        'theme_location' => '',
        'container' => '',
        'menu_id' => '',
        'menu_class' => '',
        'add_li_class' => '',
        'link_class' => ''
    ];

    public function __construct($themeLocation)
    {
        add_filter('nav_menu_css_class', [$this,'add_additional_class_on_li'], 1, 3);
        add_filter( 'nav_menu_link_attributes', [$this,'add_menu_link_class'], 1, 3 );

        $this->args['theme_location'] = $themeLocation;
    }

    public function wrapWithTag($tagName){
        $this->args['container'] = $tagName;
        return $this;
    }

    public function setMenuID($id)
    {
        $this->args['menu_id'] = $id;
        return $this;
    }

    public function setMenuClass($class)
    {
        $this->args['menu_class'] = $class;
        return $this;
    }

    public function setListClass($class)
    {
        $this->args['add_li_class'] = $class;
        return $this;
    }

    public function setLinkClass($class)
    {
        $this->args['link_class'] = $class;
        return $this;
    }

    public function showMenu()
    {
        return wp_nav_menu($this->args);
    }

    function add_additional_class_on_li($classes, $item, $args) {
        if(isset($args->add_li_class)) {
            $classes[] = $args->add_li_class;
        }
        return $classes;
    }

    function add_menu_link_class( $atts, $item, $args ) {
        if (property_exists($args, 'link_class')) {
            $atts['class'] = $args->link_class;
        }
        return $atts;
    }
}

How to download a file using a Java REST service and a data stream

"How can I directly (without saving the file on 2nd server) download the file from 1st server to client's machine?"

Just use the Client API and get the InputStream from the response

Client client = ClientBuilder.newClient();
String url = "...";
final InputStream responseStream = client.target(url).request().get(InputStream.class);

There are two flavors to get the InputStream. You can also use

Response response = client.target(url).request().get();
InputStream is = (InputStream)response.getEntity();

Which one is the more efficient? I'm not sure, but the returned InputStreams are different classes, so you may want to look into that if you care to.

From 2nd server I can get a ByteArrayOutputStream to get the file from 1st server, can I pass this stream further to the client using the REST service?

So most of the answers you'll see in the link provided by @GradyGCooper seem to favor the use of StreamingOutput. An example implementation might be something like

final InputStream responseStream = client.target(url).request().get(InputStream.class);
System.out.println(responseStream.getClass());
StreamingOutput output = new StreamingOutput() {
    @Override
    public void write(OutputStream out) throws IOException, WebApplicationException {  
        int length;
        byte[] buffer = new byte[1024];
        while((length = responseStream.read(buffer)) != -1) {
            out.write(buffer, 0, length);
        }
        out.flush();
        responseStream.close();
    }   
};
return Response.ok(output).header(
        "Content-Disposition", "attachment, filename=\"...\"").build();

But if we look at the source code for StreamingOutputProvider, you'll see in the writeTo, that it simply writes the data from one stream to another. So with our implementation above, we have to write twice.

How can we get only one write? Simple return the InputStream as the Response

final InputStream responseStream = client.target(url).request().get(InputStream.class);
return Response.ok(responseStream).header(
        "Content-Disposition", "attachment, filename=\"...\"").build();

If we look at the source code for InputStreamProvider, it simply delegates to ReadWriter.writeTo(in, out), which simply does what we did above in the StreamingOutput implementation

 public static void writeTo(InputStream in, OutputStream out) throws IOException {
    int read;
    final byte[] data = new byte[BUFFER_SIZE];
    while ((read = in.read(data)) != -1) {
        out.write(data, 0, read);
    }
}

Asides:

  • Client objects are expensive resources. You may want to reuse the same Client for request. You can extract a WebTarget from the client for each request.

    WebTarget target = client.target(url);
    InputStream is = target.request().get(InputStream.class);
    

    I think the WebTarget can even be shared. I can't find anything in the Jersey 2.x documentation (only because it is a larger document, and I'm too lazy to scan through it right now :-), but in the Jersey 1.x documentation, it says the Client and WebResource (which is equivalent to WebTarget in 2.x) can be shared between threads. So I'm guessing Jersey 2.x would be the same. but you may want to confirm for yourself.

  • You don't have to make use of the Client API. A download can be easily achieved with the java.net package APIs. But since you're already using Jersey, it doesn't hurt to use its APIs

  • The above is assuming Jersey 2.x. For Jersey 1.x, a simple Google search should get you a bunch of hits for working with the API (or the documentation I linked to above)


UPDATE

I'm such a dufus. While the OP and I are contemplating ways to turn a ByteArrayOutputStream to an InputStream, I missed the simplest solution, which is simply to write a MessageBodyWriter for the ByteArrayOutputStream

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;

@Provider
public class OutputStreamWriter implements MessageBodyWriter<ByteArrayOutputStream> {

    @Override
    public boolean isWriteable(Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType) {
        return ByteArrayOutputStream.class == type;
    }

    @Override
    public long getSize(ByteArrayOutputStream t, Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType) {
        return -1;
    }

    @Override
    public void writeTo(ByteArrayOutputStream t, Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType,
            MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
            throws IOException, WebApplicationException {
        t.writeTo(entityStream);
    }
}

Then we can simply return the ByteArrayOutputStream in the response

return Response.ok(baos).build();

D'OH!

UPDATE 2

Here are the tests I used (

Resource class

@Path("test")
public class TestResource {

    final String path = "some_150_mb_file";

    @GET
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response doTest() throws Exception {
        InputStream is = new FileInputStream(path);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len;
        byte[] buffer = new byte[4096];
        while ((len = is.read(buffer, 0, buffer.length)) != -1) {
            baos.write(buffer, 0, len);
        }
        System.out.println("Server size: " + baos.size());
        return Response.ok(baos).build();
    }
}

Client test

public class Main {
    public static void main(String[] args) throws Exception {
        Client client = ClientBuilder.newClient();
        String url = "http://localhost:8080/api/test";
        Response response = client.target(url).request().get();
        String location = "some_location";
        FileOutputStream out = new FileOutputStream(location);
        InputStream is = (InputStream)response.getEntity();
        int len = 0;
        byte[] buffer = new byte[4096];
        while((len = is.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        out.flush();
        out.close();
        is.close();
    }
}

UPDATE 3

So the final solution for this particular use case was for the OP to simply pass the OutputStream from the StreamingOutput's write method. Seems the third-party API, required a OutputStream as an argument.

StreamingOutput output = new StreamingOutput() {
    @Override
    public void write(OutputStream out) {
        thirdPartyApi.downloadFile(.., .., .., out);
    }
}
return Response.ok(output).build();

Not quite sure, but seems the reading/writing within the resource method, using ByteArrayOutputStream`, realized something into memory.

The point of the downloadFile method accepting an OutputStream is so that it can write the result directly to the OutputStream provided. For instance a FileOutputStream, if you wrote it to file, while the download is coming in, it would get directly streamed to the file.

It's not meant for us to keep a reference to the OutputStream, as you were trying to do with the baos, which is where the memory realization comes in.

So with the way that works, we are writing directly to the response stream provided for us. The method write doesn't actually get called until the writeTo method (in the MessageBodyWriter), where the OutputStream is passed to it.

You can get a better picture looking at the MessageBodyWriter I wrote. Basically in the writeTo method, replace the ByteArrayOutputStream with StreamingOutput, then inside the method, call streamingOutput.write(entityStream). You can see the link I provided in the earlier part of the answer, where I link to the StreamingOutputProvider. This is exactly what happens

Download a file from HTTPS using download.file()

Had exactly the same problem as UseR (original question), I'm also using windows 7. I tried all proposed solutions and they didn't work.

I resolved the problem doing as follows:

  1. Using RStudio instead of R console.

  2. Actualising the version of R (from 3.1.0 to 3.1.1) so that the library RCurl runs OK on it. (I'm using now R3.1.1 32bit although my system is 64bit).

  3. I typed the URL address as https (secure connection) and with / instead of backslashes \\.

  4. Setting method = "auto".

It works for me now. You should see the message:

Content type 'text/csv; charset=utf-8' length 9294 bytes
opened URL
downloaded 9294 by

How do I show/hide a UIBarButtonItem?

One way to do it is use the initWithCustomView:(UIView *) property of when allocating the UIBarButtonItem. Subclass for UIView will have hide/unhide property.

For example:

1. Have a UIButton which you want to hide/unhide.

2. Make the UIButtonas the custom view. Like :

UIButton*myButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];//your button

UIBarButtonItem*yourBarButton=[[UIBarButtonItem alloc] initWithCustomView:myButton];

3. You can hide/unhide the myButton you've created. [myButton setHidden:YES];

jQuery check if Cookie exists, if not create it

I was having alot of trouble with this because I was using:

if($.cookie('token') === null || $.cookie('token') === "")
{
      //no cookie
}
else
{
     //have cookie
}

The above was ALWAYS returning false, no matter what I did in terms of setting the cookie or not. From my tests it seems that the object is therefore undefined before it's set so adding the following to my code fixed it.

if($.cookie('token') === null || $.cookie('token') === "" 
    || $.(cookie('token') === "null" || $.cookie('token') === undefined)
{
      //no cookie
}
else
{
     //have cookie
}

How to send email to multiple address using System.Net.Mail

MailAddress fromAddress = new MailAddress  (fromMail,fromName);
MailAddress toAddress = new MailAddress(toMail,toName);
MailMessage message = new MailMessage(fromAddress,toAddress);
message.Subject = subject;
message.Body = body;
SmtpClient smtp = new SmtpClient()
{
    Host = host, Port = port,
    enabHost = "smtp.gmail.com",
    Port = 25,
    EnableSsl = true,
    UseDefaultCredentials = true,
    Credentials = new  NetworkCredentials (fromMail, password)
};
smtp.send(message);

How to find the minimum value of a column in R?

If you prefer using column names, you could do something like this as an alternative:

min(data$column_name)

Logging framework incompatibility

You are mixing the 1.5.6 version of the jcl bridge with the 1.6.0 version of the slf4j-api; this won't work because of a few changes in 1.6.0. Use the same versions for both, i.e. 1.6.1 (the latest). I use the jcl-over-slf4j bridge all the time and it works fine.

Get value from hidden field using jQuery

var hiddenFieldID = "input[id$=" + hiddenField + "]";
var requiredVal= $(hiddenFieldID).val();

How to free memory in Java?

* "For example, say you'd declared a List at the beginning of a method which grew in size to be very large, but was only required until half-way through the method. You could at this point set the List reference to null to allow the garbage collector to potentially reclaim this object before the method completes (and the reference falls out of scope anyway)." *

This is correct, but this solution may not be generalizable. While setting a List object reference to null -will- make memory available for garbage collection, this is only true for a List object of primitive types. If the List object instead contains reference types, setting the List object = null will not dereference -any- of the reference types contained -in- the list. In this case, setting the List object = null will orphan the contained reference types whose objects will not be available for garbage collection unless the garbage collection algorithm is smart enough to determine that the objects have been orphaned.

How to get row count in an Excel file using POI library?

Sheet.getPhysicalNumberOfRows() does not involve some empty rows. If you want to loop for all rows, do not use this to know the loop size.

Select elements by attribute in CSS

It's also possible to select attributes regardless of their content, in modern browsers

with:

[data-my-attribute] {
   /* Styles */
}

[anything] {
   /* Styles */
}

For example: http://codepen.io/jasonm23/pen/fADnu

Works on a very significant percentage of browsers.

Note this can also be used in a JQuery selector, or using document.querySelector

How to parse a CSV in a Bash script?

First prototype using plain old grep and cut:

grep "${VALUE}" inputfile.csv | cut -d, -f"${INDEX}"

If that's fast enough and gives the proper output, you're done.

How to fix committing to the wrong Git branch?

4 years late on the topic, but this might be helpful to someone.

If you forgot to create a new branch before committing and committed all on master, no matter how many commits you did, the following approach is easier:

git stash                       # skip if all changes are committed
git branch my_feature
git reset --hard origin/master
git checkout my_feature
git stash pop                   # skip if all changes were committed

Now you have your master branch equals to origin/master and all new commits are on my_feature. Note that my_feature is a local branch, not a remote one.

Create a .csv file with values from a Python list

Use python's csv module for reading and writing comma or tab-delimited files. The csv module is preferred because it gives you good control over quoting.

For example, here is the worked example for you:

import csv
data = ["value %d" % i for i in range(1,4)]

out = csv.writer(open("myfile.csv","w"), delimiter=',',quoting=csv.QUOTE_ALL)
out.writerow(data)

Produces:

"value 1","value 2","value 3"

How to force two figures to stay on the same page in LaTeX?

Try using the float package and then the [H] option for your figure.

\usepackage{float}

...

\begin{figure}[H]
\centering
\includegraphics{fig1}
\caption{Write some caption here}\label{fig1}
\end{figure}

as already suggested by this insightful answer!

https://tex.stackexchange.com/questions/8625/force-figure-placement-in-text

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

  1. Search for sqllocaldb or localDB in your windows start menu and right click on open file location
  2. Open command prompt in the file location you found from the search
  3. On your command prompt type sqllocaldb start

  4. Use <add name="defaultconnection" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=tododb;Integrated Security=True" providerName="System.Data.SqlClient" />

Java time-based map/cache with expiring keys

Guava cache is easy to implementation.We can expires key on time base using guava cache. I have read fully post and below gives key of my study.

cache = CacheBuilder.newBuilder().refreshAfterWrite(2,TimeUnit.SECONDS).
              build(new CacheLoader<String, String>(){
                @Override
                public String load(String arg0) throws Exception {
                    // TODO Auto-generated method stub
                    return addcache(arg0);
                }

              }

Reference : guava cache example

Change hover color on a button with Bootstrap customization

I had to add !important to get it to work. I also made my own class button-primary-override.

.button-primary-override:hover, 
.button-primary-override:active,
.button-primary-override:focus,
.button-primary-override:visited{
    background-color: #42A5F5 !important;
    border-color: #42A5F5 !important;
    background-image: none !important;
    border: 0 !important;
}

How to end C++ code

return 0; put that wherever you want within int main() and the program will immediately close.

How to read numbers separated by space using scanf

It should be as simple as using a list of receiving variables:

scanf("%i %i %i", &var1, &var2, &var3);

How to format a numeric column as phone number in SQL

Updated @sqiller's function for my purposes

CREATE FUNCTION [toolbox].[FormatPhoneNumber] (
    @PhoneNumber VARCHAR(50),
    @DefaultIfUnknown VARCHAR(50)
)
RETURNS VARCHAR(50)
AS
BEGIN
    -- remove any extension
    IF CHARINDEX('x', @PhoneNumber, 1) > 0
        SET @PhoneNumber = SUBSTRING(@PhoneNumber, 1, CHARINDEX('x', @PhoneNumber, 1) - 1)

    -- cleanse phone number string
    WHILE PATINDEX('%[^0-9]%',@PhoneNumber) > 0
        SET @PhoneNumber = REPLACE(@PhoneNumber,
                SUBSTRING(@PhoneNumber,PATINDEX('%[^0-9]%',@PhoneNumber),1),'')

    -- Remove US international code if exists, i.e. 12345678900
    IF SUBSTRING(@PhoneNumber,1,1) = '1' AND LEN(@PhoneNumber) = 11
        SET @PhoneNumber = SUBSTRING(@PhoneNumber, 2, 10)

    -- any phone numbers without 10 characters are set to default
    IF LEN(@PhoneNumber) <> 10
        RETURN @DefaultIfUnknown

    -- build US standard phone number
    SET @PhoneNumber = '(' + SUBSTRING(@PhoneNumber,1,3) + ') ' +
                SUBSTRING(@PhoneNumber,4,3) + '-' + SUBSTRING(@PhoneNumber,7,4)

    RETURN @PhoneNumber
END

How to delete last item in list?

If you have a list of lists (tracked_output_sheet in my case), where you want to delete last element from each list, you can use the following code:

interim = []
for x in tracked_output_sheet:interim.append(x[:-1])
tracked_output_sheet= interim

How to add action listener that listens to multiple buttons

The problem is that button1 is a local variable. You could do it by just change the way you add the actionListener.

button.addActionListener(new ActionListener() {  
            public void actionPerformed(ActionEvent e)
            {
                //button is pressed
                System.out.println("You clicked the button");
            }});

Or you make button1 a global variable.

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

For anybody who is getting an error like : '2*' string cannot be converted to Length.

<Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2*" /><!--This will make any control in this column of grid take 2/5 of total width-->
        <ColumnDefinition Width="3*" /><!--This will make any control in this column of grid take 3/5 of total width-->
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition MinHeight="30" />
    </Grid.RowDefinitions>

    <TextBlock Grid.Column="0" Grid.Row="0">Your text block a:</TextBlock>
    <TextBlock Grid.Column="1" Grid.Row="0">Your text block b:</TextBlock>
</Grid>

Cancel a UIView animation?

None of the above solved it for me, but this helped: The UIView animation sets the property immediately, then animates it. It stops the animation when the presentation layer matches the model (the set property).

I solved my issue, which was "I want to animate from where you look like you appear" ('you' meaning the view). If you want THAT, then:

  1. Add QuartzCore.
  2. CALayer * pLayer = theView.layer.presentationLayer;

set the position to the presentation layer

I use a few options including UIViewAnimationOptionOverrideInheritedDuration

But because Apple's documentation is vague, I don't know if it really overrides the other animations when used, or just resets timers.

[UIView animateWithDuration:blah... 
                    options: UIViewAnimationOptionBeginFromCurrentState ... 
                    animations: ^ {
                                   theView.center = CGPointMake( pLayer.position.x + YOUR_ANIMATION_OFFSET, pLayer.position.y + ANOTHER_ANIMATION_OFFSET);
                   //this only works for translating, but you get the idea if you wanna flip and scale it. 
                   } completion: ^(BOOL complete) {}];

And that should be a decent solution for now.

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

That true,Mustafa....its working..its point to two layout

  1. setContentView(R.layout.your_layout)
  2. v23(your_layout).

You should take Button both activity layout...
solve this problem successfully

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

try using this one

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest -Uri https://apod.nasa.gov/apod/

Jackson with JSON: Unrecognized field, not marked as ignorable

What worked for me, was to make the property public. It solved the problem for me.

AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?

I had similar issue. I was not able to use value="something" to display and edit. I had to use the below command inside my <input>along withe ng model being declared.

[(ngModel)]=userDataToPass.pinCode

Where I have the list of data in the object userDataToPass and the item that I need to display and edit is pinCode.

For the same , I referred to this YouTube video

XSL if: test with multiple test conditions

Thanks to @IanRoberts, I had to use the normalize-space function on my nodes to check if they were empty.

<xsl:if test="((node/ABC!='') and (normalize-space(node/DEF)='') and (normalize-space(node/GHI)=''))">
  This worked perfectly fine.
</xsl:if>

AngularJS format JSON string output

I guess you want to use to edit the json text. Then you can use ivarni's way:

{{data | json}}
and add an adition attribute to make
 editable

<pre contenteditable="true">{{data | json}}</pre>

Hope this can help you.

What is the difference between function and procedure in PL/SQL?

The following are the major differences between procedure and function,

  1. Procedure is named PL/SQL block which performs one or more tasks. where function is named PL/SQL block which performs a specific action.
  2. Procedure may or may not return value where as function should return one value.
  3. we can call functions in select statement where as procedure we cant.

Bootstrap 3 .col-xs-offset-* doesn't work?

// it works in bootstrap 4, there was some changes in documentation.We dont need prefix col-, just offset-lg-3 e.g.

<div class="row">
   <div class="offset-lg-3 col-lg-6"> Some content...
   </div>
</div>

// here doc: http://v4-alpha.getbootstrap.com/layout/grid/#example-offsetting-columns

Editable 'Select' element

Nothing is impossible. Here's a solution that simply sets the value of a text input whenever the value of the <select> changes (rendering has been tested on Firefox and Google Chrome):

_x000D_
_x000D_
.select-editable {position:relative; background-color:white; border:solid grey 1px;  width:120px; height:18px;}_x000D_
.select-editable select {position:absolute; top:0px; left:0px; font-size:14px; border:none; width:120px; margin:0;}_x000D_
.select-editable input {position:absolute; top:0px; left:0px; width:100px; padding:1px; font-size:12px; border:none;}_x000D_
.select-editable select:focus, .select-editable input:focus {outline:none;}
_x000D_
<div class="select-editable">_x000D_
  <select onchange="this.nextElementSibling.value=this.value">_x000D_
    <option value=""></option>_x000D_
    <option value="115x175 mm">115x175 mm</option>_x000D_
    <option value="120x160 mm">120x160 mm</option>_x000D_
    <option value="120x287 mm">120x287 mm</option>_x000D_
  </select>_x000D_
  <input type="text" name="format" value=""/>_x000D_
</div>
_x000D_
_x000D_
_x000D_ jsfiddle: https://jsfiddle.net/nwH8A/

The next example adds the user input to the empty option slot of the <select> (thanks to @TomerPeled). It also has a little bit more flexible/variable CSS:

_x000D_
_x000D_
.select-editable {position:relative; width:120px;}_x000D_
.select-editable > * {position:absolute; top:0; left:0; box-sizing:border-box; outline:none;}_x000D_
.select-editable select {width:100%;}_x000D_
.select-editable input {width:calc(100% - 20px); margin:1px; border:none; text-overflow:ellipsis;}
_x000D_
<div class="select-editable">_x000D_
  <select onchange="this.nextElementSibling.value=this.value">_x000D_
    <option value=""></option>_x000D_
    <option value="115x175 mm">115x175 mm</option>_x000D_
    <option value="120x160 mm">120x160 mm</option>_x000D_
    <option value="120x287 mm">120x287 mm</option>_x000D_
  </select>_x000D_
  <input type="text" oninput="this.previousElementSibling.options[0].value=this.value; this.previousElementSibling.options[0].innerHTML=this.value" onchange="this.previousElementSibling.selectedIndex=0" value="" />_x000D_
</div>
_x000D_
_x000D_
_x000D_ jsfiddle: https://jsfiddle.net/pu7cndLv/1/


DataList

In HTML5 you can also do this with the <input> list attribute and <datalist> element:

_x000D_
_x000D_
<input list="browsers" name="browser">_x000D_
<datalist id="browsers">_x000D_
  <option value="Internet Explorer">_x000D_
  <option value="Firefox">_x000D_
  <option value="Chrome">_x000D_
  <option value="Opera">_x000D_
  <option value="Safari">_x000D_
</datalist>_x000D_
(click once to focus and edit, click again to see option dropdown)
_x000D_
_x000D_
_x000D_ jsfiddle: https://jsfiddle.net/hrkxebtw/

But this acts more like an auto-complete list; once you start typing, only the options that contain the typed string are left as suggestions. Depending on what you want to use it for, this may or may not be practical.

Datatables on-the-fly resizing

The code below is the combination of Chintan Panchal's answer along with Antoine Leclair's comment (placing the code in the windows resize event). (I didn't need the debounce mentioned by Antoine Leclair, however that could be a best practice.)

  $(window).resize( function() {
      $("#example").DataTable().columns.adjust().draw();
  });

This was the approach that worked in my case.

How to keep one variable constant with other one changing with row in excel

For future visitors - use this for range: ($A$1:$A$10)

Example
=COUNTIF($G$6:$G$9;J6)>0

How do I get the name of the current executable in C#?

When uncertain or in doubt, run in circles, scream and shout.

class Ourself
{
    public static string OurFileName() {
        System.Reflection.Assembly _objParentAssembly;

        if (System.Reflection.Assembly.GetEntryAssembly() == null)
            _objParentAssembly = System.Reflection.Assembly.GetCallingAssembly();
        else
            _objParentAssembly = System.Reflection.Assembly.GetEntryAssembly();

        if (_objParentAssembly.CodeBase.StartsWith("http://"))
            throw new System.IO.IOException("Deployed from URL");

        if (System.IO.File.Exists(_objParentAssembly.Location))
            return _objParentAssembly.Location;
        if (System.IO.File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + System.AppDomain.CurrentDomain.FriendlyName))
            return System.AppDomain.CurrentDomain.BaseDirectory + System.AppDomain.CurrentDomain.FriendlyName;
        if (System.IO.File.Exists(System.Reflection.Assembly.GetExecutingAssembly().Location))
            return System.Reflection.Assembly.GetExecutingAssembly().Location;

        throw new System.IO.IOException("Assembly not found");
    }
}

I can't claim to have tested each option, but it doesn't do anything stupid like returning the vhost during debugging sessions.

How to localise a string inside the iOS info.plist file?

Tips

  1. Remember that the iOS Simulator exploits by default your system language. Please change the language (and region) in the iOS Simulator Setting too in order to test your translations.

  2. The localisation string (see Apple docs here) should be

    NSLocationWhenInUseUsageDescription = "Description of this";
    

    and not (with quote "...")

    "NSLocationWhenInUseUsageDescription" = "Description of this";
    

Excel doesn't update value unless I hit Enter

Executive summary / TL;DR:
Try doing a find & replace of "=" with "=". Yes, replace the equals sign with itself. For my scenario, it forced everything to update.

Background:
I frequently make formulas across multiple columns then concatenate them together. After doing such, I'll copy & paste them as values to extract my created formula. After this process, they're typically stuck displaying a formula, and not displaying a value, unless I enter the cell and press Enter. Pressing F2 & Enter repeatedly is not fun.

APK signing error : Failed to read key from keystore

Most likely that your key alias does not exist for your keystore file.

This answer should fix your signing issue ;)

JSON.Net Self referencing loop detected

You must set Preserving Object References:

var jsonSerializerSettings = new JsonSerializerSettings
{
    PreserveReferencesHandling = PreserveReferencesHandling.Objects
};

Then call your query var q = (from a in db.Events where a.Active select a).ToList(); like

string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(q, jsonSerializerSettings);

See: https://www.newtonsoft.com/json/help/html/PreserveObjectReferences.htm

How to deal with http status codes other than 200 in Angular 2

Include required imports and you can make ur decision in handleError method Error status will give the error code

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import {Observable, throwError} from "rxjs/index";
import { catchError, retry } from 'rxjs/operators';
import {ApiResponse} from "../model/api.response";
import { TaxType } from '../model/taxtype.model'; 

private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
  // A client-side or network error occurred. Handle it accordingly.
  console.error('An error occurred:', error.error.message);
} else {
  // The backend returned an unsuccessful response code.
  // The response body may contain clues as to what went wrong,
  console.error(
    `Backend returned code ${error.status}, ` +
    `body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
  'Something bad happened; please try again later.');
  };

  getTaxTypes() : Observable<ApiResponse> {
return this.http.get<ApiResponse>(this.baseUrl).pipe(
  catchError(this.handleError)
);
  }

How do I parse a HTML page with Node.js

Htmlparser2 by FB55 seems to be a good alternative.

CSS rotation cross browser with jquery.animate()

Without plugin cross browser with setInterval:

                        function rotatePic() {
                            jQuery({deg: 0}).animate(
                               {deg: 360},  
                               {duration: 3000, easing : 'linear', 
                                 step: function(now, fx){
                                   jQuery("#id").css({
                                      '-moz-transform':'rotate('+now+'deg)',
                                      '-webkit-transform':'rotate('+now+'deg)',
                                      '-o-transform':'rotate('+now+'deg)',
                                      '-ms-transform':'rotate('+now+'deg)',
                                      'transform':'rotate('+now+'deg)'
                                  });
                              }
                            });
                        }

                        var sec = 3;
                        rotatePic();
                        var timerInterval = setInterval(function() {
                            rotatePic();
                            sec+=3;
                            if (sec > 30) {
                                clearInterval(timerInterval);
                            }
                        }, 3000);

Getting IPV4 address from a sockaddr structure

You can use getnameinfo for Windows and for Linux.

Assuming you have a good (i.e. it's members have appropriate values) sockaddr* called pSockaddr:

char clienthost[NI_MAXHOST];  //The clienthost will hold the IP address.
char clientservice[NI_MAXSERV];
int theErrorCode = getnameinfo(pSockaddr, sizeof(*pSockaddr), clienthost, sizeof(clienthost), clientservice, sizeof(clientservice), NI_NUMERICHOST|NI_NUMERICSERV);

if( theErrorCode != 0 )
{
    //There was an error.
    cout << gai_strerror(e1) << endl;
}else{
    //Print the info.
    cout << "The ip address is = " << clienthost << endl;
    cout << "The clientservice = " << clientservice << endl;
}

What is the difference between Google App Engine and Google Compute Engine?

App Engine is a Platform-as-a-Service. It means that you simply deploy your code, and the platform does everything else for you. For example, if your app becomes very successful, App Engine will automatically create more instances to handle the increased volume.

Read more about App Engine

Compute Engine is an Infrastructure-as-a-Service. You have to create and configure your own virtual machine instances. It gives you more flexibility and generally costs much less than App Engine. The drawback is that you have to manage your app and virtual machines yourself.

Read more about Compute Engine

You can mix both App Engine and Compute Engine, if necessary. They both work well with the other parts of the Google Cloud Platform.

EDIT (May 2016):

One more important distinction: projects running on App Engine can scale down to zero instances if no requests are coming in. This is extremely useful at the development stage as you can go for weeks without going over the generous free quota of instance-hours. Flexible runtime (i.e. "managed VMs") require at least one instance to run constantly.

EDIT (April 2017):

Cloud Functions (currently in beta) is the next level up from App Engine in terms of abstraction - no instances! It allows developers to deploy bite-size pieces of code that execute in response to different events, which may include HTTP requests, changes in Cloud Storage, etc.

The biggest difference with App Engine is that functions are priced per 100 milliseconds, while App Engine's instances shut down only after 15 minutes of inactivity. Another advantage is that Cloud Functions execute immediately, while a call to App Engine may require a new instance - and cold-starting a new instance may take a few seconds or longer (depending on runtime and your code).

This makes Cloud Functions ideal for (a) rare calls - no need to keep an instance live just in case something happens, (b) rapidly changing loads where instances are often spinning and shutting down, and possibly more use cases.

Read more about Cloud Functions

How to iterate over the files of a certain directory, in Java?

If you have the directory name in myDirectoryPath,

import java.io.File;
...
  File dir = new File(myDirectoryPath);
  File[] directoryListing = dir.listFiles();
  if (directoryListing != null) {
    for (File child : directoryListing) {
      // Do something with child
    }
  } else {
    // Handle the case where dir is not really a directory.
    // Checking dir.isDirectory() above would not be sufficient
    // to avoid race conditions with another process that deletes
    // directories.
  }

How do I clear inner HTML

Take a look at this. a clean and simple solution using jQuery.

http://jsfiddle.net/ma2Yd/

    <h1 onmouseover="go('The dog is in its shed')" onmouseout="clear()">lalala</h1>
    <div id="goy"></div>


    <script type="text/javascript">

    $(function() {
       $("h1").on('mouseover', function() {
          $("#goy").text('The dog is in its shed');
       }).on('mouseout', function() {
          $("#goy").text("");
       });
   });

Notepad++ Setting for Disabling Auto-open Previous Files

Go to: Settings > Preferences > Backup > and Uncheck Remember current session for next launch

In older versions (6.5-), this option is located on Settings > Preferences > MISC.

javascript: optional first argument in function

my_function = function(hash) { /* use hash.options and hash.content */ };

and then call:

my_function ({ options: options });
my_function ({ options: options, content: content });

Java: Why is the Date constructor deprecated, and what do I use instead?

I came across this question as a duplicate of a newer question which asked what the non-deprecated way to get a Date at a specific year, month, and day was.

The answers here so far say to use the Calendar class, and that was true until Java 8 came out. But as of Java 8, the standard way to do this is:

LocalDate localDate = LocalDate.of(1985, 1, 1);

And then if you really really need a java.util.Date, you can use the suggestions in this question.

For more info, check out the API or the tutorials for Java 8.

How can I check whether a variable is defined in Node.js?

if ( typeof query !== 'undefined' && query )
{
  //do stuff if query is defined and not null
}
else
{

}

How do I validate a date in this format (yyyy-mm-dd) using jquery?

try this Here is working Demo:

$(function() {
    $('#btnSubmit').bind('click', function(){
        var txtVal =  $('#txtDate').val();
        if(isDate(txtVal))
            alert('Valid Date');
        else
            alert('Invalid Date');
    });

function isDate(txtDate)
{
    var currVal = txtDate;
    if(currVal == '')
        return false;

    var rxDatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; //Declare Regex
    var dtArray = currVal.match(rxDatePattern); // is format OK?

    if (dtArray == null) 
        return false;

    //Checks for mm/dd/yyyy format.
    dtMonth = dtArray[3];
    dtDay= dtArray[5];
    dtYear = dtArray[1];        

    if (dtMonth < 1 || dtMonth > 12) 
        return false;
    else if (dtDay < 1 || dtDay> 31) 
        return false;
    else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31) 
        return false;
    else if (dtMonth == 2) 
    {
        var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
        if (dtDay> 29 || (dtDay ==29 && !isleap)) 
                return false;
    }
    return true;
}

});

changed regex is:

var rxDatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; //Declare Regex

Why are the Level.FINE logging messages not showing?

why is my java logging not working

provides a jar file that will help you work out why your logging in not working as expected. It gives you a complete dump of what loggers and handlers have been installed and what levels are set and at which level in the logging hierarchy.

How do I select a sibling element using jQuery?

Since $(this) refers to .countdown you can use $(this).next() or $(this).next('button') more specifically.

how to convert a string to an array in php

The explode() function breaks a string into an array.

<?php
    $str = "Hello world. It's a beautiful day.";
    print_r (explode(" ",$str));
?>

Output: Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. )

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

See the following snippet, is this what you want?

_x000D_
_x000D_
body {
    background: silver;
    padding: 0 10px;
}

#content:after {
    height: 10px;
    display: block;
    width: 100px;
    background: #808080;
    border-right: 1px white;
    content: '';
}

#footer:before {
    display: block;
    content: '';
    background: silver;
    height: 10px;
    margin-top: -20px;
    margin-left: 101px;
}

#content {
    background: white;
}


#footer {
    padding-top: 10px;
    background: #404040;
}

p {
    padding: 100px;
    text-align: center;
}

#footer p {
    color: white;
}
_x000D_
<body>
    <div id="content"><p>#content</p></div>
    <div id="footer"><p>#footer</p></div>
</body>
_x000D_
_x000D_
_x000D_

JSFiddle

find files by extension, *.html under a folder in nodejs

What, hang on?! ... Okay ya, maybe this makes more sense to someones else too.

[nodejs 7 mind you]

fs = import('fs');
let dirCont = fs.readdirSync( dir );
let files = dirCont.filter( function( elm ) {return elm.match(/.*\.(htm?html)/ig);});

Do whatever with regex make it an argument you set in the function with a default etc.

GET and POST methods with the same Action name in the same Controller

Today I was checking some resources about the same question and I got an example very interesting.

It is possible to call the same method by GET and POST protocol, but you need to overload the parameters like that:

@using (Ajax.BeginForm("Index", "MyController", ajaxOptions, new { @id = "form-consulta" }))
{
//code
}

The action:

[ActionName("Index")]
public async Task<ActionResult> IndexAsync(MyModel model)
{
//code
}

By default a method without explicit protocol is GET, but in that case there is a declared parameter which allows the method works like a POST.

When GET is executed the parameter does not matter, but when POST is executed the parameter is required on your request.

Oracle Date TO_CHAR('Month DD, YYYY') has extra spaces in it

select to_char(sysdate, 'DD-fmMONTH-YYYY') "Date" from Dual;

The above query result will be as given below.

Date

01-APRIL-2019

www-data permissions?

As stated in an article by Slicehost:

User setup

So let's start by adding the main user to the Apache user group:

sudo usermod -a -G www-data demo

That adds the user 'demo' to the 'www-data' group. Do ensure you use both the -a and the -G options with the usermod command shown above.

You will need to log out and log back in again to enable the group change.

Check the groups now:

groups
...
# demo www-data

So now I am a member of two groups: My own (demo) and the Apache group (www-data).

Folder setup

Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).

Let's set that up:

sudo chgrp -R www-data /home/demo/public_html

As we are talking about permissions I'll add a quick note regarding the sudo command: It's a good habit to use absolute paths (/home/demo/public_html) as shown above rather than relative paths (~/public_html). It ensures sudo is being used in the correct location.

If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.

Setgid

Good so far, but remember the command we just gave only affects existing folders. What about anything new?

We can set the ownership so anything new is also in the 'www-data' group.

The first command will change the permissions for the public_html directory to include the "setgid" bit:

sudo chmod 2750 /home/demo/public_html

That will ensure that any new files are given the group 'www-data'. If you have subdirectories, you'll want to run that command for each subdirectory (this type of permission doesn't work with '-R'). Fortunately new subdirectories will be created with the 'setgid' bit set automatically.

If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:

sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads

The permissions only need to be set once as new files will automatically be assigned the correct ownership.

Why are C# 4 optional parameters defined on interface not enforced on implementing class?

Optional parameters are kind of like a macro substitution from what I understand. They are not really optional from the method's point of view. An artifact of that is the behavior you see where you get different results if you cast to an interface.

How to convert string to Title Case in Python?

Potential library: https://pypi.org/project/stringcase/

Example:

import stringcase
stringcase.camelcase('foo_bar_baz') # => "fooBarBaz"

Though it's questionable whether it will leave spaces in. (Examples show it removing space, but there is a bug tracker issue noting that it leaves them in.)

HTML table with horizontal scrolling (first column fixed)

Use jQuery DataTables plug-in, it supports fixed header and columns. This example adds fixed column support to the html table "example":

http://datatables.net/extensions/fixedcolumns/

For two fixed columns:

http://www.datatables.net/release-datatables/extensions/FixedColumns/examples/two_columns.html

How to use a servlet filter in Java to change an incoming servlet request url?

A simple JSF Url Prettyfier filter based in the steps of BalusC's answer. The filter forwards all the requests starting with the /ui path (supposing you've got all your xhtml files stored there) to the same path, but adding the xhtml suffix.

public class UrlPrettyfierFilter implements Filter {

    private static final String JSF_VIEW_ROOT_PATH = "/ui";

    private static final String JSF_VIEW_SUFFIX = ".xhtml";

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = ((HttpServletRequest) request);
        String requestURI = httpServletRequest.getRequestURI();
        //Only process the paths starting with /ui, so as other requests get unprocessed. 
        //You can register the filter itself for /ui/* only, too
        if (requestURI.startsWith(JSF_VIEW_ROOT_PATH) 
                && !requestURI.contains(JSF_VIEW_SUFFIX)) {
            request.getRequestDispatcher(requestURI.concat(JSF_VIEW_SUFFIX))
                .forward(request,response);
        } else {
            chain.doFilter(httpServletRequest, response);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}

Prevent content from expanding grid items

The existing answers solve most cases. However, I ran into a case where I needed the content of the grid-cell to be overflow: visible. I solved it by absolutely positioning within a wrapper (not ideal, but the best I know), like this:


.month-grid {
  display: grid;
  grid-template: repeat(6, 1fr) / repeat(7, 1fr);
  background: #fff;
  grid-gap: 2px;  
}

.day-item-wrapper {
  position: relative;
}

.day-item {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 10px;

  background: rgba(0,0,0,0.1);
}

https://codepen.io/bjnsn/pen/vYYVPZv

Loading custom configuration files

The config file is just an XML file, you can open it by:

private static XmlDocument loadConfigDocument()
{
    XmlDocument doc = null;
    try
    {
        doc = new XmlDocument();
        doc.Load(getConfigFilePath());
        return doc;
    }
    catch (System.IO.FileNotFoundException e)
    {
        throw new Exception("No configuration file found.", e);
    }
    catch (Exception ex)
    {
        return null;
    }
}

and later retrieving values by:

    // retrieve appSettings node

    XmlNode node =  doc.SelectSingleNode("//appSettings");

How to have the formatter wrap code with IntelliJ?

In the latest Intellij ver 2020, we have an option called soft-wrap these files. Settings > Editor > General > soft-wrap these files. Check this option and add the type of files u need wrap.

soft wrap intellij option

Git add and commit in one command

you can use git commit -am "[comment]" // best solution or git add . && git commit -m "[comment]"

Simplest/cleanest way to implement a singleton in JavaScript

This should work:

function Klass() {
   var instance = this;
   Klass = function () { return instance; }
}

Catch checked change event of a checkbox

This code does what your need:

<input type="checkbox" id="check" >check it</input>

$("#check").change( function(){
   if( $(this).is(':checked') ) {
        alert("checked");
    }else{
        alert("unchecked");
   }
});

Also, you can check it on jsfiddle

How do you write multiline strings in Go?

Go and multiline strings

Using back ticks you can have multiline strings:

package main

import "fmt"

func main() {

    message := `This is a 
Multi-line Text String
Because it uses the raw-string back ticks 
instead of quotes.
`

    fmt.Printf("%s", message)
}

Instead of using either the double quote (“) or single quote symbols (‘), instead use back-ticks to define the start and end of the string. You can then wrap it across lines.

If you indent the string though, remember that the white space will count.

Please check the playground and do experiments with it.

Swap DIV position with CSS only

Someone linked me this: What is the best way to move an element that's on the top to the bottom in Responsive design.

The solution in that worked perfectly. Though it doesn’t support old IE, that doesn’t matter for me, since I’m using responsive design for mobile. And it works for most mobile browsers.

Basically, I had this:

@media (max-width: 30em) {
  .container {
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -webkit-box-orient: vertical;
    -moz-box-orient: vertical;
    -webkit-flex-direction: column;
    -ms-flex-direction: column;
    flex-direction: column;
    /* optional */
    -webkit-box-align: start;
    -moz-box-align: start;
    -ms-flex-align: start;
    -webkit-align-items: flex-start;
    align-items: flex-start;
  }

  .container .first_div {
    -webkit-box-ordinal-group: 2;
    -moz-box-ordinal-group: 2;
    -ms-flex-order: 2;
    -webkit-order: 2;
    order: 2;
  }

  .container .second_div {
    -webkit-box-ordinal-group: 1;
    -moz-box-ordinal-group: 1;
    -ms-flex-order: 1;
    -webkit-order: 1;
    order: 1;
  }
}

This worked better than floats for me, because I needed them stacked on top of each other and I had about five different divs that I had to swap around the position of.

How do I manually configure a DataSource in Java?

The javadoc for DataSource you refer to is of the wrong package. You should look at javax.sql.DataSource. As you can see this is an interface. The host and port name configuration depends on the implementation, i.e. the JDBC driver you are using.

I have not checked the Derby javadocs but I suppose the code should compile like this:

ClientDataSource ds = org.apache.derby.jdbc.ClientDataSource()
ds.setHost etc....

How to comment multiple lines in Visual Studio Code?

visual studio 2017 we do a: Comment Selection

Ctrl+K, Ctrl+C

press Ctrl+K to get shortcut. press Ctrl+C to confirm http://visualstudioshortcuts.com/2017/