Programs & Examples On #Roundcube

Roundcube is a web-based IMAP email client written in the PHP programming language. It is released under GNU General Public License.

ERROR 1698 (28000): Access denied for user 'root'@'localhost'

Let me solve it for ya.

  • Get into the sql.
  • Enter the following thing.
SET GLOBAL validate_password.length = 4;
SET GLOBAL validate_password.mixed_case_count = 0;
SET GLOBAL validate_password.number_count = 0;
SET GLOBAL validate_password.policy = LOW;
SET GLOBAL validate_password.special_char_count = 0;
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'test';

Only for testing purposes.

Delete cookie by name?

//if passed exMins=0 it will delete as soon as it creates it.

function setCookie(cname, cvalue, exMins) {
    var d = new Date();
    d.setTime(d.getTime() + (exMins*60*1000));
    var expires = "expires="+d.toUTCString();  
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

setCookie('cookieNameToDelete','',0) // this will delete the cookie.

Run a php app using tomcat?

There this PHP/Java bridge. This is basically running PHP via FastCGI. I have not used it myself.

javascript convert int to float

toFixed() method formats a number using fixed-point notation. Read MDN Web Docs for full reference.

var fval = 4;

console.log(fval.toFixed(2)); // prints 4.00

How to limit file upload type file size in PHP?

Hope This useful...

form:

<form action="check.php" method="post" enctype="multipart/form-data">
<label>Upload An Image</label>
<input type="file" name="file_upload" />
<input type="submit" name="upload"/>
</form>

check.php:

<?php 
    if(isset($_POST['upload'])){
        $maxsize=2097152;
        $format=array('image/jpeg');
    if($_FILES['file_upload']['size']>=$maxsize){
        $error_1='File Size too large';
        echo '<script>alert("'.$error_1.'")</script>';
    }
    elseif($_FILES['file_upload']['size']==0){
        $error_2='Invalid File';
        echo '<script>alert("'.$error_2.'")</script>';
    }
    elseif(!in_array($_FILES['file_upload']['type'],$format)){
        $error_3='Format Not Supported.Only .jpeg files are accepted';
        echo '<script>alert("'.$error_3.'")</script>';
        }

        else{
            $target_dir = "uploads/";
            $target_file = $target_dir . basename($_FILES["file_upload"]["name"]);
            if(move_uploaded_file($_FILES["file_upload"]["tmp_name"], $target_file)){ 
            echo "The file ". basename($_FILES["file_upload"]["name"]). " has been uploaded.";
            }
            else{
                echo "sorry";
                }
            }
    }
?>

Pass arguments to Constructor in VBA

When you export a class module and open the file in Notepad, you'll notice, near the top, a bunch of hidden attributes (the VBE doesn't display them, and doesn't expose functionality to tweak most of them either). One of them is VB_PredeclaredId:

Attribute VB_PredeclaredId = False

Set it to True, save, and re-import the module into your VBA project.

Classes with a PredeclaredId have a "global instance" that you get for free - exactly like UserForm modules (export a user form, you'll see its predeclaredId attribute is set to true).

A lot of people just happily use the predeclared instance to store state. That's wrong - it's like storing instance state in a static class!

Instead, you leverage that default instance to implement your factory method:

[Employee class]

'@PredeclaredId
Option Explicit

Private Type TEmployee
    Name As String
    Age As Integer
End Type

Private this As TEmployee

Public Function Create(ByVal emplName As String, ByVal emplAge As Integer) As Employee
    With New Employee
        .Name = emplName
        .Age = emplAge
        Set Create = .Self 'returns the newly created instance
    End With
End Function

Public Property Get Self() As Employee
    Set Self = Me
End Property

Public Property Get Name() As String
    Name = this.Name
End Property

Public Property Let Name(ByVal value As String)
    this.Name = value
End Property

Public Property Get Age() As String
    Age = this.Age
End Property

Public Property Let Age(ByVal value As String)
    this.Age = value
End Property

With that, you can do this:

Dim empl As Employee
Set empl = Employee.Create("Johnny", 69)

Employee.Create is working off the default instance, i.e. it's considered a member of the type, and invoked from the default instance only.

Problem is, this is also perfectly legal:

Dim emplFactory As New Employee
Dim empl As Employee
Set empl = emplFactory.Create("Johnny", 69)

And that sucks, because now you have a confusing API. You could use '@Description annotations / VB_Description attributes to document usage, but without Rubberduck there's nothing in the editor that shows you that information at the call sites.

Besides, the Property Let members are accessible, so your Employee instance is mutable:

empl.Name = "Jane" ' Johnny no more!

The trick is to make your class implement an interface that only exposes what needs to be exposed:

[IEmployee class]

Option Explicit

Public Property Get Name() As String : End Property
Public Property Get Age() As Integer : End Property

And now you make Employee implement IEmployee - the final class might look like this:

[Employee class]

'@PredeclaredId
Option Explicit
Implements IEmployee

Private Type TEmployee
    Name As String
    Age As Integer
End Type

Private this As TEmployee

Public Function Create(ByVal emplName As String, ByVal emplAge As Integer) As IEmployee
    With New Employee
        .Name = emplName
        .Age = emplAge
        Set Create = .Self 'returns the newly created instance
    End With
End Function

Public Property Get Self() As IEmployee
    Set Self = Me
End Property

Public Property Get Name() As String
    Name = this.Name
End Property

Public Property Let Name(ByVal value As String)
    this.Name = value
End Property

Public Property Get Age() As String
    Age = this.Age
End Property

Public Property Let Age(ByVal value As String)
    this.Age = value
End Property

Private Property Get IEmployee_Name() As String
    IEmployee_Name = Name
End Property

Private Property Get IEmployee_Age() As Integer
    IEmployee_Age = Age
End Property

Notice the Create method now returns the interface, and the interface doesn't expose the Property Let members? Now calling code can look like this:

Dim empl As IEmployee
Set empl = Employee.Create("Immutable", 42)

And since the client code is written against the interface, the only members empl exposes are the members defined by the IEmployee interface, which means it doesn't see the Create method, nor the Self getter, nor any of the Property Let mutators: so instead of working with the "concrete" Employee class, the rest of the code can work with the "abstract" IEmployee interface, and enjoy an immutable, polymorphic object.

Is there a way to 'uniq' by column?

Here is a very nifty way.

First format the content such that the column to be compared for uniqueness is a fixed width. One way of doing this is to use awk printf with a field/column width specifier ("%15s").

Now the -f and -w options of uniq can be used to skip preceding fields/columns and to specify the comparison width (column(s) width).

Here are three examples.

In the first example...

1) Temporarily make the column of interest a fixed width greater than or equal to the field's max width.

2) Use -f uniq option to skip the prior columns, and use the -w uniq option to limit the width to the tmp_fixed_width.

3) Remove trailing spaces from the column to "restore" it's width (assuming there were no trailing spaces beforehand).

printf "%s" "$str" \
| awk '{ tmp_fixed_width=15; uniq_col=8; w=tmp_fixed_width-length($uniq_col); for (i=0;i<w;i++) { $uniq_col=$uniq_col" "}; printf "%s\n", $0 }' \
| uniq -f 7 -w 15 \
| awk '{ uniq_col=8; gsub(/ */, "", $uniq_col); printf "%s\n", $0 }'

In the second example...

Create a new uniq column 1. Then remove it after the uniq filter has been applied.

printf "%s" "$str" \
| awk '{ uniq_col_1=4; printf "%15s %s\n", uniq_col_1, $0 }' \
| uniq -f 0 -w 15 \
| awk '{ $1=""; gsub(/^ */, "", $0); printf "%s\n", $0 }'

The third example is the same as the second, but for multiple columns.

printf "%s" "$str" \
| awk '{ uniq_col_1=4; uniq_col_2=8; printf "%5s %15s %s\n", uniq_col_1, uniq_col_2, $0 }' \
| uniq -f 0 -w 5 \
| uniq -f 1 -w 15 \
| awk '{ $1=$2=""; gsub(/^ */, "", $0); printf "%s\n", $0 }'

Make flex items take content width, not width of parent container

Use align-items: flex-start on the container, or align-self: flex-start on the flex items.

No need for display: inline-flex.


An initial setting of a flex container is align-items: stretch. This means that flex items will expand to cover the full length of the container along the cross axis.

The align-self property does the same thing as align-items, except that align-self applies to flex items while align-items applies to the flex container.

By default, align-self inherits the value of align-items.

Since your container is flex-direction: column, the cross axis is horizontal, and align-items: stretch is expanding the child element's width as much as it can.

You can override the default with align-items: flex-start on the container (which is inherited by all flex items) or align-self: flex-start on the item (which is confined to the single item).


Learn more about flex alignment along the cross axis here:

Learn more about flex alignment along the main axis here:

How to get complete current url for Cakephp

I use $this->here for the path, to get the whole URL you'll have to do as Juhana said and use the $_SERVER variables. There's no need to use a Cake function for this.

What is a difference between unsigned int and signed int in C?

ISO C states what the differences are.

The int data type is signed and has a minimum range of at least -32767 through 32767 inclusive. The actual values are given in limits.h as INT_MIN and INT_MAX respectively.

An unsigned int has a minimal range of 0 through 65535 inclusive with the actual maximum value being UINT_MAX from that same header file.

Beyond that, the standard does not mandate twos complement notation for encoding the values, that's just one of the possibilities. The three allowed types would have encodings of the following for 5 and -5 (using 16-bit data types):

        two's complement  |  ones' complement   |   sign/magnitude
    +---------------------+---------------------+---------------------+
 5  | 0000 0000 0000 0101 | 0000 0000 0000 0101 | 0000 0000 0000 0101 |
-5  | 1111 1111 1111 1011 | 1111 1111 1111 1010 | 1000 0000 0000 0101 |
    +---------------------+---------------------+---------------------+
  • In two's complement, you get a negative of a number by inverting all bits then adding 1.
  • In ones' complement, you get a negative of a number by inverting all bits.
  • In sign/magnitude, the top bit is the sign so you just invert that to get the negative.

Note that positive values have the same encoding for all representations, only the negative values are different.

Note further that, for unsigned values, you do not need to use one of the bits for a sign. That means you get more range on the positive side (at the cost of no negative encodings, of course).

And no, 5 and -5 cannot have the same encoding regardless of which representation you use. Otherwise, there'd be no way to tell the difference.


As an aside, there are currently moves underway, in both C and C++ standards, to nominate two's complement as the only encoding for negative integers.

jQuery .find() on data from .ajax() call is returning "[object Object]" instead of div

I just spent 3 hours to solve a similar problem. This is what worked for me.

The element that I was attempting to retrieve from my $.get response was a first child element of the body tag. For some reason when I wrapped a div around this element, it became retrievable through $(response).find('#nameofelement').

No idea why but yeah, retrievable element cannot be first child of body... that might be helpful to someone :)

How to delete a record in Django models?

There are a couple of ways:

To delete it directly:

SomeModel.objects.filter(id=id).delete()

To delete it from an instance:

instance = SomeModel.objects.get(id=id)
instance.delete()

CSS: How to align vertically a "label" and "input" inside a "div"?

_x000D_
_x000D_
div {_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
    height: 50px;_x000D_
    border: 1px solid red;_x000D_
}
_x000D_
<div>_x000D_
    <label for='name'>Name:</label>_x000D_
    <input type='text' id='name' />_x000D_
</div>
_x000D_
_x000D_
_x000D_

The advantages of this method is that you can change the height of the div, change the height of the text field and change the font size and everything will always stay in the middle.

http://jsfiddle.net/53ALd/6/

placeholder for select tag

     <select>
         <option value="" disabled selected hidden> placeholder</option>
         <option value="op1">op1</option>
         <option value="op2">op2</option>
         <option value="op3">op3</option>
         <option value="op4">op4</option>
     </select>

Links in <select> dropdown options

You can use the onChange property. Something like:

<select onChange="window.location.href=this.value">
    <option value="www.google.com">A</option>
    <option value="www.aol.com">B</option>
</select>

How do I create batch file to rename large number of files in a folder?

You don't need a batch file, just do this from powershell :

powershell -C "gci | % {rni $_.Name ($_.Name -replace 'Vacation2010', 'December')}"

C# Checking if button was clicked

These helped me a lot: I wanted to save values from my gridview, and it was reloading my gridview /overriding my new values, as i have IsPostBack inside my PageLoad.

if (HttpContext.Current.Request["MYCLICKEDBUTTONID"] == null)
{
   //Do not reload the gridview.

}
else
{
   reload my gridview.
}

SOURCE: http://bytes.com/topic/asp-net/answers/312809-please-help-how-identify-button-clicked

Spring JUnit: How to Mock autowired component in autowired component

You could use Mockito. I am not sure with PostConstruct specifically, but this generally works:

// Create a mock of Resource to change its behaviour for testing
@Mock
private Resource resource;

// Testing instance, mocked `resource` should be injected here 
@InjectMocks
@Resource
private TestedClass testedClass;

@Before
public void setUp() throws Exception {
    // Initialize mocks created above
    MockitoAnnotations.initMocks(this);
    // Change behaviour of `resource`
    when(resource.getSomething()).thenReturn("Foo");   
}

Parsing JSON from URL

GSON has a builder that takes a Reader object: fromJson(Reader json, Class classOfT).

This means you can create a Reader from a URL and then pass it to Gson to consume the stream and do the deserialisation.

Only three lines of relevant code.

import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;

import com.google.gson.Gson;

public class GsonFetchNetworkJson {

    public static void main(String[] ignored) throws Exception {

        URL url = new URL("https://httpbin.org/get?color=red&shape=oval");
        InputStreamReader reader = new InputStreamReader(url.openStream());
        MyDto dto = new Gson().fromJson(reader, MyDto.class);

        // using the deserialized object
        System.out.println(dto.headers);
        System.out.println(dto.args);
        System.out.println(dto.origin);
        System.out.println(dto.url);
    }

    private class MyDto {
        Map<String, String> headers;
        Map<String, String> args;
        String origin;
        String url;
    }
}

If you happen to get a 403 error code with an endpoint which otherwise works fine (e.g. with curl or other clients) then a possible cause could be that the endpoint expects a User-Agent header and by default Java URLConnection is not setting it. An easy fix is to add at the top of the file e.g. System.setProperty("http.agent", "Netscape 1.0");.

Using Mockito to stub and execute methods for testing

SHORT ANSWER

How to do in your case:

int argument = 5; // example with int but could be another type
Mockito.when(mockMyAgent.otherMethod(Mockito.anyInt()).thenReturn(requiredReturnArg(argument));

LONG ANSWER

Actually what you want to do is possible, at least in Java 8. Maybe you didn't get this answer by other people because I am using Java 8 that allows that and this question is before release of Java 8 (that allows to pass functions, not only values to other functions).

Let's simulate a call to a DataBase query. This query returns all the rows of HotelTable that have FreeRoms = X and StarNumber = Y. What I expect during testing, is that this query will give back a List of different hotel: every returned hotel has the same value X and Y, while the other values and I will decide them according to my needs. The following example is simple but of course you can make it more complex.

So I create a function that will give back different results but all of them have FreeRoms = X and StarNumber = Y.

static List<Hotel> simulateQueryOnHotels(int availableRoomNumber, int starNumber) {
    ArrayList<Hotel> HotelArrayList = new ArrayList<>();
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Rome, 1, 1));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Krakow, 7, 15));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Madrid, 1, 1));
    HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Athens, 4, 1));

    return HotelArrayList;
}

Maybe Spy is better (please try), but I did this on a mocked class. Here how I do (notice the anyInt() values):

//somewhere at the beginning of your file with tests...
@Mock
private DatabaseManager mockedDatabaseManager;

//in the same file, somewhere in a test...
int availableRoomNumber = 3;
int starNumber = 4;
// in this way, the mocked queryOnHotels will return a different result according to the passed parameters
when(mockedDatabaseManager.queryOnHotels(anyInt(), anyInt())).thenReturn(simulateQueryOnHotels(availableRoomNumber, starNumber));

Xpath: select div that contains class AND whose specific child element contains text

You could use the xpath :

//div[@class="measure-tab" and .//span[contains(., "someText")]]

Input :

<root>
<div class="measure-tab">
  <td> someText</td>
</div>
<div class="measure-tab">
  <div>
    <div2>
       <span>someText2</span>
   </div2>
  </div>
</div>
</root>

Output :

    Element='<div class="measure-tab">
  <div>
    <div2>
      <span>someText2</span>
    </div2>
  </div>
</div>'

Spring Boot Rest Controller how to return different HTTP status codes?

There are several options you can use. Quite good way is to use exceptions and class for handling called @ControllerAdvice:

@ControllerAdvice
class GlobalControllerExceptionHandler {
    @ResponseStatus(HttpStatus.CONFLICT)  // 409
    @ExceptionHandler(DataIntegrityViolationException.class)
    public void handleConflict() {
        // Nothing to do
    }
}

Also you can pass HttpServletResponse to controller method and just set response code:

public RestModel create(@RequestBody String data, HttpServletResponse response) {
    // response committed...
    response.setStatus(HttpServletResponse.SC_ACCEPTED);
}

Please refer to the this great blog post for details: Exception Handling in Spring MVC


NOTE

In Spring MVC using @ResponseBody annotation is redundant - it's already included in @RestController annotation.

Unable to copy a file from obj\Debug to bin\Debug

No matter what the cause of this problem is, the only working solution for me is the following:

Go to Your-Project-Properties -> Application tab(first tab) -> Change the Assembly name.

This way your app creates a new assembly file each time you change the assembly name.

Finally, after you finish to develop, you can delete all those extra assembly files and just keep the last one (main one). Non of the other solutions worked for me, except this one.

"Unable to locate tools.jar" when running ant

I was also having the same problem So I just removed the JDK path from the end and put it in start even before all System or Windows 32 paths.

Before it was like this:

C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Users\Rajkaran\AppData\Local\Smartbar\Application\;C:\Users\Rajkaran\AppData\Local\Smartbar\Application\;C:\Program Files\doxygen\bin;%JAVA_HOME%\bin;%ANT_HOME%\bin

So I made it like this:

%JAVA_HOME%\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Users\Rajkaran\AppData\Local\Smartbar\Application\;C:\Users\Rajkaran\AppData\Local\Smartbar\Application\;C:\Program Files\doxygen\bin;%ANT_HOME%\bin

gradient descent using python and numpy

I know this question already have been answer but I have made some update to the GD function :

  ### COST FUNCTION

def cost(theta,X,y):
     ### Evaluate half MSE (Mean square error)
     m = len(y)
     error = np.dot(X,theta) - y
     J = np.sum(error ** 2)/(2*m)
     return J

 cost(theta,X,y)



def GD(X,y,theta,alpha):

    cost_histo = [0]
    theta_histo = [0]

    # an arbitrary gradient, to pass the initial while() check
    delta = [np.repeat(1,len(X))]
    # Initial theta
    old_cost = cost(theta,X,y)

    while (np.max(np.abs(delta)) > 1e-6):
        error = np.dot(X,theta) - y
        delta = np.dot(np.transpose(X),error)/len(y)
        trial_theta = theta - alpha * delta
        trial_cost = cost(trial_theta,X,y)
        while (trial_cost >= old_cost):
            trial_theta = (theta +trial_theta)/2
            trial_cost = cost(trial_theta,X,y)
            cost_histo = cost_histo + trial_cost
            theta_histo = theta_histo +  trial_theta
        old_cost = trial_cost
        theta = trial_theta
    Intercept = theta[0] 
    Slope = theta[1]  
    return [Intercept,Slope]

res = GD(X,y,theta,alpha)

This function reduce the alpha over the iteration making the function too converge faster see Estimating linear regression with Gradient Descent (Steepest Descent) for an example in R. I apply the same logic but in Python.

How to check if an integer is within a range of numbers in PHP?

You could whip up a little helper function to do this:

/**
 * Determines if $number is between $min and $max
 *
 * @param  integer  $number     The number to test
 * @param  integer  $min        The minimum value in the range
 * @param  integer  $max        The maximum value in the range
 * @param  boolean  $inclusive  Whether the range should be inclusive or not
 * @return boolean              Whether the number was in the range
 */
function in_range($number, $min, $max, $inclusive = FALSE)
{
    if (is_int($number) && is_int($min) && is_int($max))
    {
        return $inclusive
            ? ($number >= $min && $number <= $max)
            : ($number > $min && $number < $max) ;
    }

    return FALSE;
}

And you would use it like so:

var_dump(in_range(5, 0, 10));        // TRUE
var_dump(in_range(1, 0, 1));         // FALSE
var_dump(in_range(1, 0, 1, TRUE));   // TRUE
var_dump(in_range(11, 0, 10, TRUE)); // FALSE

// etc...

Oracle Sql get only month and year in date datatype

"FEB-2010" is not a Date, so it would not make a lot of sense to store it in a date column.

You can always extract the string part you need , in your case "MON-YYYY" using the TO_CHAR logic you showed above.

If this is for a DIMENSION table in a Data warehouse environment and you want to include these as separate columns in the Dimension table (as Data attributes), you will need to store the month and Year in two different columns, with appropriate Datatypes...

Example..

Month varchar2(3) --Month code in Alpha..
Year  NUMBER      -- Year in number

or

Month number(2)    --Month Number in Year.
Year  NUMBER      -- Year in number

How to send HTML email using linux command line

The problem is that when redirecting a file into 'mail' like that, it's used for the message body only. Any headers you embed in the file will go into the body instead.

Try:

mail --append="Content-type: text/html" -s "Built notification" [email protected] < /var/www/report.csv

--append lets you add arbitrary headers to the mail, which is where you should specify the content-type and content-disposition. There's no need to embed the To and Subject headers in your file, or specify them with --append, since you're implicitly setting them on the command line already (-s is the subject, and [email protected] automatically becomes the To).

MySQL combine two columns and add into a new column

Are you sure you want to do this? In essence, you're duplicating the data that is in the three original columns. From that point on, you'll need to make sure that the data in the combined field matches the data in the first three columns. This is more overhead for your application, and other processes that update the system will need to understand the relationship.

If you need the data, why not select in when you need it? The SQL for selecting what would be in that field would be:

SELECT CONCAT(zipcode, ' - ', city, ', ', state) FROM Table;

This way, if the data in the fields changes, you don't have to update your combined field.

How to restrict the selectable date ranges in Bootstrap Datepicker?

With selectable date ranges you might want to use something like this. My solution prevents selecting #from_date bigger than #to_date and changes #to_date startDate every time when user selects new date in #from_date box:

http://bootply.com/74352

JS file:

var startDate = new Date('01/01/2012');
var FromEndDate = new Date();
var ToEndDate = new Date();

ToEndDate.setDate(ToEndDate.getDate()+365);

$('.from_date').datepicker({

    weekStart: 1,
    startDate: '01/01/2012',
    endDate: FromEndDate, 
    autoclose: true
})
    .on('changeDate', function(selected){
        startDate = new Date(selected.date.valueOf());
        startDate.setDate(startDate.getDate(new Date(selected.date.valueOf())));
        $('.to_date').datepicker('setStartDate', startDate);
    }); 
$('.to_date')
    .datepicker({

        weekStart: 1,
        startDate: startDate,
        endDate: ToEndDate,
        autoclose: true
    })
    .on('changeDate', function(selected){
        FromEndDate = new Date(selected.date.valueOf());
        FromEndDate.setDate(FromEndDate.getDate(new Date(selected.date.valueOf())));
        $('.from_date').datepicker('setEndDate', FromEndDate);
    });

HTML:

<input class="from_date" placeholder="Select start date" contenteditable="false" type="text">
<input class="to_date" placeholder="Select end date" contenteditable="false" type="text" 

And do not forget to include bootstrap datepicker.js and .css files aswell.

How to Install pip for python 3.7 on Ubuntu 18?

pip3 not pip. You can create an alias like you did with python3 if you like.

How to extract svg as file from web page

When the SVG is integrated as <svg ...></svg> markup directly into the HTML page.

  1. Right click on the SVG to inspect it in developer tools
  2. Find the root of the <svg> element and right click to "Copy element"
  3. Go to https://jakearchibald.github.io/svgomg/ and "Paste markup"
  4. Download your optimized SVG file and enjoy

What is the difference between Sessions and Cookies in PHP?

The main difference between a session and a cookie is that session data is stored on the server, whereas cookies store data in the visitor’s browser.

Sessions are more secure than cookies as it is stored in server. Cookie can be turned off from browser.

Data stored in cookie can be stored for months or years, depending on the life span of the cookie. But the data in the session is lost when the web browser is closed.

Create controller for partial view in ASP.NET MVC

It does not need its own controller. You can use

@Html.Partial("../ControllerName/_Testimonials.cshtml")

This allows you to render the partial from any page. Just make sure the relative path is correct.

How to: Add/Remove Class on mouseOver/mouseOut - JQuery .hover?

Your selector is missing a . and though you say you want to change the border-color - you're adding and removing a class that sets the background-color

Convert.ToDateTime: how to set format

DateTime doesn't have a format. the format only applies when you're turning a DateTime into a string, which happens implicitly you show the value on a form, web page, etc.

Look at where you're displaying the DateTime and set the format there (or amend your question if you need additional guidance).

Allowed memory size of X bytes exhausted

ini_set('memory_limit', '128M'); 

or

php.ini  =>  memory_limit = 128M

or

php_value memory_limit 128M

ASP.Net MVC 4 Form with 2 submit buttons/actions

We can have this in 2 ways,

Either have 2 form submissions within the same View and having 2 Action methods at the controller but you will need to have the required fields to be submitted with the form to be placed within

ex is given here with code Multiple forms in view asp.net mvc with multiple submit buttons

Or

Have 2 or multiple submit buttons say btnSubmit1 and btnSubmit2 and check on the Action method which button was clicked using the code

if (Request.Form["btnSubmit1"] != null)
{
 //
}
if (Request.Form["btnSubmit2"] != null)
{
 //
}

How to avoid soft keyboard pushing up my layout?

I had the same problem, but setting windowSoftInputMode did not help, and I did not want to change the upper view to have isScrollContainer="false" because I wanted it to scroll.

My solution was to define the top location of the navigation tools instead of the bottom. I'm using Titanium, so I'm not sure exactly how this would translate to android. Defining the top location of the navigation tools view prevented the soft keyboard from pushing it up, and instead covered the nav controls like I wanted.

How to implement reCaptcha for ASP.NET MVC?

An async version for MVC 5 (i.e. avoiding ActionFilterAttribute, which is not async until MVC 6) and reCAPTCHA 2

ExampleController.cs

public class HomeController : Controller
{
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> ContactSubmit(
        [Bind(Include = "FromName, FromEmail, FromPhone, Message, ContactId")]
        ContactViewModel model)
    {
        if (!await RecaptchaServices.Validate(Request))
        {
            ModelState.AddModelError(string.Empty, "You have not confirmed that you are not a robot");
        }
        if (ModelState.IsValid)
        {
           ...

ExampleView.cshtml

@model MyMvcApp.Models.ContactViewModel

@*This is assuming the master layout places the styles section within the head tags*@
@section Styles {
    @Styles.Render("~/Content/ContactPage.css")
    <script src='https://www.google.com/recaptcha/api.js'></script>
}

@using (Html.BeginForm("ContactSubmit", "Home",FormMethod.Post, new { id = "contact-form" }))
{
    @Html.AntiForgeryToken()
    ...
    <div class="form-group">
      @Html.LabelFor(m => m.Message) 
      @Html.TextAreaFor(m => m.Message, new { @class = "form-control", @cols = "40", @rows = "3" })
      @Html.ValidationMessageFor(m => m.Message)
    </div>

    <div class="row">
      <div class="g-recaptcha" data-sitekey='@System.Configuration.ConfigurationManager.AppSettings["RecaptchaClientKey"]'></div>
    </div>

    <div class="row">
      <input type="submit" id="submit-button" class="btn btn-default" value="Send Your Message" />
    </div>
}

RecaptchaServices.cs

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web;
using System.Configuration;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Runtime.Serialization;

namespace MyMvcApp.Services
{
    public class RecaptchaServices
    {
        //ActionFilterAttribute has no async for MVC 5 therefore not using as an actionfilter attribute - needs revisiting in MVC 6
        internal static async Task<bool> Validate(HttpRequestBase request)
        {
            string recaptchaResponse = request.Form["g-recaptcha-response"];
            if (string.IsNullOrEmpty(recaptchaResponse))
            {
                return false;
            }
            using (var client = new HttpClient { BaseAddress = new Uri("https://www.google.com") })
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("secret", ConfigurationManager.AppSettings["RecaptchaSecret"]),
                    new KeyValuePair<string, string>("response", recaptchaResponse),
                    new KeyValuePair<string, string>("remoteip", request.UserHostAddress)
                });
                var result = await client.PostAsync("/recaptcha/api/siteverify", content);
                result.EnsureSuccessStatusCode();
                string jsonString = await result.Content.ReadAsStringAsync();
                var response = JsonConvert.DeserializeObject<RecaptchaResponse>(jsonString);
                return response.Success;
            }
        }

        [DataContract]
        internal class RecaptchaResponse
        {
            [DataMember(Name = "success")]
            public bool Success { get; set; }
            [DataMember(Name = "challenge_ts")]
            public DateTime ChallengeTimeStamp { get; set; }
            [DataMember(Name = "hostname")]
            public string Hostname { get; set; }
            [DataMember(Name = "error-codes")]
            public IEnumerable<string> ErrorCodes { get; set; }
        }

    }
}

web.config

<configuration>
  <appSettings>
    <!--recaptcha-->
    <add key="RecaptchaSecret" value="***secret key from https://developers.google.com/recaptcha***" />
    <add key="RecaptchaClientKey" value="***client key from https://developers.google.com/recaptcha***" />
  </appSettings>
</configuration>

How to find an available port?

If you don't mind the port used, specify a port of 0 to the ServerSocket constructor and it will listen on any free port.

ServerSocket s = new ServerSocket(0);
System.out.println("listening on port: " + s.getLocalPort());

If you want to use a specific set of ports, then the easiest way is probably to iterate through them until one works. Something like this:

public ServerSocket create(int[] ports) throws IOException {
    for (int port : ports) {
        try {
            return new ServerSocket(port);
        } catch (IOException ex) {
            continue; // try next port
        }
    }

    // if the program gets here, no port in the range was found
    throw new IOException("no free port found");
}

Could be used like so:

try {
    ServerSocket s = create(new int[] { 3843, 4584, 4843 });
    System.out.println("listening on port: " + s.getLocalPort());
} catch (IOException ex) {
    System.err.println("no available ports");
}

Is HTML considered a programming language?

YES, a declarative programming language.

You really want to list the most important things you know that are relative to the job you're applying for on your resume. If you list ASP.NET but don't list HTML, even though it's somewhat obvious, there are a lot of managers and/or HR types that will assume you don't know HTML since it's not listed. I've had it happen to me before.

Update - Some say no it isn't a programming language, and you may not agree with me on this, but regardless on a resume it IS a programming language. You get HR types looking at your resume before the hiring manager even sees it. If the manager says you need to know HTML, and it's not listed in the 'programming languages' section then the HR person may disregard you resume thinking you don't know it because it's not listed.

Update 6-8-2012: Any instruction that tells the computer to do something is a programming language. So even after all these years, I still stand by my answer. HTML is a programming language. Something that isn't a programming language would be XML.

How do I set the default schema for a user in MySQL

If your user has a local folder e.g. Linux, in your users home folder you could create a .my.cnf file and provide the credentials to access the server there. for example:-

[client]
host=localhost
user=yourusername
password=yourpassword or exclude to force entry
database=mygotodb

Mysql would then open this file for each user account read the credentials and open the selected database.

Not sure on Windows, I upgraded from Windows because I needed the whole house not just the windows (aka Linux) a while back.

Draw in Canvas by finger, Android

Regarding the beautiful code of Raghunandan above.

Many have asked how to "clear" the drawing. Here's how to do that:

public void clearDrawing()
    {
    Utils.Log("RaghunandanDraw, how to clear....");

    setDrawingCacheEnabled(false);
    // don't forget that one and the match below,
    // or you just keep getting a duplicate when you save.

    onSizeChanged(width, height, width, height);
    invalidate();

    setDrawingCacheEnabled(true);
    }

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
    {
    super.onSizeChanged(w, h, oldw, oldh);

    width = w;      // don't forget these
    height = h;

    mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    mCanvas = new Canvas(mBitmap);
    }

Many have asked how to "save" the drawing. Here's how to do that:

public DrawingView(Context c)
  {
  circlePaint.setStrokeJoin(Paint.Join.MITER);
  circlePaint.setStrokeWidth(4f); 
  etc...

  // in the class where you set up the view, add this:
  setDrawingCacheEnabled( true );
  }

public void saveDrawing()
  {
  Bitmap whatTheUserDrewBitmap = getDrawingCache();
  // don't forget to clear it (see above) or you just get duplicates

  // almost always you will want to reduce res from the very high screen res
  whatTheUserDrewBitmap =
         ThumbnailUtils.extractThumbnail(whatTheUserDrewBitmap, 256, 256);
  // NOTE that's an incredibly useful trick for cropping/resizing squares
  // while handling all memory problems etc
  // http://stackoverflow.com/a/17733530/294884

  // you can now save the bitmap to a file, or display it in an ImageView:
  ImageView testArea = ...
  testArea.setImageBitmap( whatTheUserDrewBitmap );

  // these days you often need a "byte array". for example,
  // to save to parse.com or other cloud services
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  whatTheUserDrewBitmap.compress(Bitmap.CompressFormat.PNG, 0, baos);
  byte[] yourByteArray;
  yourByteArray = baos.toByteArray();
  }

Hope it helps someone as this has helped me.

How to loop through elements of forms with JavaScript?

$(function() {
    $('form button').click(function() {
        var allowSubmit = true;
        $.each($('form input:text'), function(index, formField) {
            if($(formField).val().trim().length == 0) {
                alert('field is empty!');
                allowSubmit = false;
            }
        });
        return allowSubmit;
    });
});

DEMO

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

Recursive convert object to array

function is_object(mixed_var) {
    if (mixed_var instanceof Array) {
        return false;
    } else {
        return (mixed_var !== null) && (typeof( mixed_var ) == 'object');
    }
}


function objectToArray(obj) {
    var array = [], tempObject;
    for (var key in obj) {

        tempObject = obj[key];

        if (is_object(obj[key])) {
            tempObject = objectToArray(obj[key]);
        }
        array[key] = tempObject;
    }
    return array;
}

How to change legend size with matplotlib.pyplot

There are multiple settings for adjusting the legend size. The two I find most useful are:

  • labelspacing: which sets the spacing between label entries in multiples of the font size. For instance with a 10 point font, legend(..., labelspacing=0.2) will reduce the spacing between entries to 2 points. The default on my install is about 0.5.
  • prop: which allows full control of the font size, etc. You can set an 8 point font using legend(..., prop={'size':8}). The default on my install is about 14 points.

In addition, the legend documentation lists a number of other padding and spacing parameters including: borderpad, handlelength, handletextpad, borderaxespad, and columnspacing. These all follow the same form as labelspacing and area also in multiples of fontsize.

These values can also be set as the defaults for all figures using the matplotlibrc file.

MySQL Insert with While Loop

You cannot use WHILE like that; see: mysql DECLARE WHILE outside stored procedure how?

You have to put your code in a stored procedure. Example:

CREATE PROCEDURE myproc()
BEGIN
    DECLARE i int DEFAULT 237692001;
    WHILE i <= 237692004 DO
        INSERT INTO mytable (code, active, total) VALUES (i, 1, 1);
        SET i = i + 1;
    END WHILE;
END

Fiddle: http://sqlfiddle.com/#!2/a4f92/1

Alternatively, generate a list of INSERT statements using any programming language you like; for a one-time creation, it should be fine. As an example, here's a Bash one-liner:

for i in {2376921001..2376921099}; do echo "INSERT INTO mytable (code, active, total) VALUES ($i, 1, 1);"; done

By the way, you made a typo in your numbers; 2376921001 has 10 digits, 237692200 only 9.

How to include an HTML page into another HTML page without frame/iframe?

If you mean client side then you will have to use JavaScript or frames.
Simple way to start, try jQuery

$("#links").load("/Main_Page #jq-p-Getting-Started li");

More at jQuery Docs

If you want to use IFrames then start with Wikipedia on IFrames

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
        <title>Example</title>
  </head>
  <body>
        The material below comes from the website http://example.com/
        <iframe src="http://example.com/" height="200">
            Alternative text for browsers that do not understand IFrames.
        </iframe>
   </body>
</html>

How do I keep a label centered in WinForms?

Set Label's AutoSize property to False, TextAlign property to MiddleCenter and Dock property to Fill.

The intel x86 emulator accelerator (HAXM installer) revision 6.0.5 is showing not compatible with windows

Try the following

  1. download HAXM from Intel https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager.

  2. Unzip the file and Run intelhaxm-android.exe.

  3. Run silent_install.bat.

In my computer Win10 x64 - VS2015 it worked

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

Error "The input device is not a TTY"

My Jenkins pipeline step shown below failed with the same error.

       steps {
            echo 'Building ...' 
            sh 'sh ./Tools/build.sh'
        }

In my "build.sh" script file "docker run" command output this error when it was executed by Jenkins job. However it was working OK when the script ran in the shell terminal.The error happened because of -t option passed to docker run command that as I know tries to allocate terminal and fails if there is no terminal to allocate.

In my case I have changed the script to pass -t option only if a terminal could be detected. Here is the code after changes :

DOCKER_RUN_OPTIONS="-i --rm"

# Only allocate tty if we detect one
if [ -t 0 ] && [ -t 1 ]; then
    DOCKER_RUN_OPTIONS="$DOCKER_RUN_OPTIONS -t"
fi

docker run $DOCKER_RUN_OPTIONS --name my-container-name  my-image-tag

java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication Maven

If you are running spring cloud application, make sure your boot version matches cloud version. You can check the version compatibility matrix at the bottom of this page : https://spring.io/projects/spring-cloud.

Can I call methods in constructor in Java?

Singleton pattern

public class MyClass() {

    private static MyClass instance = null;
    /**
    * Get instance of my class, Singleton
    **/
    public static MyClass getInstance() {
        if(instance == null) {
            instance = new MyClass();
        }
        return instance;
    }
    /**
    * Private constructor
    */
    private MyClass() {
        //This will only be called once, by calling getInstanse() method. 
    }
}

Space between two divs

DIVs inherently lack any useful meaning, other than to divide, of course.

Best course of action would be to add a meaningful class name to them, and style their individual margins in CSS.

<h1>Important Title</h1>
<div class="testimonials">...</div>
<div class="footer">...</div>

h1 {margin-bottom: 0.1em;}
div.testimonials {margin-bottom: 0.2em;}
div.footer {margin-bottom: 0;}

What size do you use for varchar(MAX) in your parameter declaration?

If you do something like this:

    cmd.Parameters.Add("@blah",SqlDbType.VarChar).Value = "some large text";

size will be taken from "some large text".Length

This can be problematic when it's an output parameter, you get back no more characters then you put as input.

Remove columns from DataTable in C#

Aside from limiting the columns selected to reduce bandwidth and memory:

DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);

How to get current time in milliseconds in PHP?

PHP 5.2.2 <

$d = new DateTime();
echo $d->format("Y-m-d H:i:s.u"); // u : Microseconds

PHP 7.0.0 < 7.1

$d = new DateTime();
echo $d->format("Y-m-d H:i:s.v"); // v : Milliseconds 

How do I print to the debug output window in a Win32 app?

I was looking for a way to do this myself and figured out a simple solution.

I'm assuming that you started a default Win32 Project (Windows application) in Visual Studio, which provides a "WinMain" function. By default, Visual Studio sets the entry point to "SUBSYSTEM:WINDOWS". You need to first change this by going to:

Project -> Properties -> Linker -> System -> Subsystem

And select "Console (/SUBSYSTEM:CONSOLE)" from the drop-down list.

Now, the program will not run, since a "main" function is needed instead of the "WinMain" function.

So now you can add a "main" function like you normally would in C++. After this, to start the GUI program, you can call the "WinMain" function from inside the "main" function.

The starting part of your program should now look something like this:

#include <iostream>

using namespace std;

// Main function for the console
int main(){

    // Calling the wWinMain function to start the GUI program
    // Parameters:
    // GetModuleHandle(NULL) - To get a handle to the current instance
    // NULL - Previous instance is not needed
    // NULL - Command line parameters are not needed
    // 1 - To show the window normally
    wWinMain(GetModuleHandle(NULL), NULL,NULL, 1); 

    system("pause");
    return 0;
}

// Function for entry into GUI program
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPWSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
    // This will display "Hello World" in the console as soon as the GUI begins.
    cout << "Hello World" << endl;
.
.
.

Result of my implementation

Now you can use functions to output to the console in any part of your GUI program for debugging or other purposes.

How to read GET data from a URL using JavaScript?

You can do like this

function parseURLParams(url) {
        var queryStart = url.indexOf("?") + 1,
            queryEnd   = url.indexOf("#") + 1 || url.length + 1,
            query = url.slice(queryStart, queryEnd - 1),
            pairs = query.replace(/\+/g, " ").split("&"),
            parms = {}, i, n, v, nv;

        if (query === url || query === "") return;

        for (i = 0; i < pairs.length; i++) {
            nv = pairs[i].split("=", 2);
            n = decodeURIComponent(nv[0]);
            v = decodeURIComponent(nv[1]);

            if (!parms.hasOwnProperty(n)) parms[n] = [];
            parms[n].push(nv.length === 2 ? v : null);
        }
        return parms;
    }

    //enter code here


    var urlString = "http://www.examle.com/bar?a=a+a&b%20b=b&c=1&c=2&d#hash";

    urlParams = parseURLParams(urlString);
    console.log(urlParams)

Sorting a Python list by two fields

list1 = sorted(csv1, key=lambda x: (x[1], x[2]) )

How to create an integer array in Python?

two ways:

x = [0] * 10
x = [0 for i in xrange(10)]

Edit: replaced range by xrange to avoid creating another list.

Also: as many others have noted including Pi and Ben James, this creates a list, not a Python array. While a list is in many cases sufficient and easy enough, for performance critical uses (e.g. when duplicated in thousands of objects) you could look into python arrays. Look up the array module, as explained in the other answers in this thread.

Do AJAX requests retain PHP Session info?

put your session() auth in all server side pages accepting an ajax request:

if(require_once("auth.php")) {

//run json code

}

// do nothing otherwise

that's about the only way I've ever done it.

Is there a better jQuery solution to this.form.submit();?

I have found that using jQuery the best solution is

$(this.form).submit()

Using this statement jquery plugins (e.g. jquery form plugin) works correctly and jquery DOM traversing overhead is minimized.

vim line numbers - how to have them on by default?

To change the default setting to display line numbers in vi/vim:

vi ~/.vimrc

then add the following line to the file:

set number

Either we can source ~/.vimrc or save and quit by :wq, now future vi/vim sessions will have numbering :)

Using sendmail from bash script for multiple recipients

Try doing this :

recipients="[email protected],[email protected],[email protected]"

And another approach, using shell here-doc :

/usr/sbin/sendmail "$recipients" <<EOF
subject:$subject
from:$from

Example Message
EOF

Be sure to separate the headers from the body with a blank line as per RFC 822.

How do I set up access control in SVN?

The best way is to set up Apache and to set the access through it. Check the svn book for help. If you don't want to use Apache, you can also do minimalistic access control using svnserve.

Efficient way to add spaces between characters in a string

s = "BINGO"
print(" ".join(s))

Should do it.

Get rid of "The value for annotation attribute must be a constant expression" message

The value for an annotation must be a compile time constant, so there is no simple way of doing what you are trying to do.

See also here: How to supply value to an annotation from a Constant java

It is possible to use some compile time tools (ant, maven?) to config it if the value is known before you try to run the program.

How to set gradle home while importing existing project in Android studio

This is my solution on AndroidStudio/Idea for Mac

$ env | grep GRADLE
GRADLE_HOME=/usr/local/Cellar/gradle/2.6
GRADLE_USER_HOME=/Users/leon/.gradle

Throwing exceptions from constructors

#include <iostream>

class bar
{
public:
  bar()
  {
    std::cout << "bar() called" << std::endl;
  }

  ~bar()
  {
    std::cout << "~bar() called" << std::endl;

  }
};
class foo
{
public:
  foo()
    : b(new bar())
  {
    std::cout << "foo() called" << std::endl;
    throw "throw something";
  }

  ~foo()
  {
    delete b;
    std::cout << "~foo() called" << std::endl;
  }

private:
  bar *b;
};


int main(void)
{
  try {
    std::cout << "heap: new foo" << std::endl;
    foo *f = new foo();
  } catch (const char *e) {
    std::cout << "heap exception: " << e << std::endl;
  }

  try {
    std::cout << "stack: foo" << std::endl;
    foo f;
  } catch (const char *e) {
    std::cout << "stack exception: " << e << std::endl;
  }

  return 0;
}

the output:

heap: new foo
bar() called
foo() called
heap exception: throw something
stack: foo
bar() called
foo() called
stack exception: throw something

the destructors are not called, so if a exception need to be thrown in a constructor, a lot of stuff(e.g. clean up?) to do.

YouTube Video Embedded via iframe Ignoring z-index?

I have the same problem on YouTube iframe embeds only in internet explorer though.

Z-index was being ignored totally, or the flash video was just appearing at highest index possible.

This was what I used, slight adapting the above jquery script.

My embed code, straight from YouTube...

<iframe width="560" height="315" src="http://www.youtube.com/embed/QldZiR9eQ_0?rel=0" frameborder="0" allowfullscreen></iframe>


The jQuery slighty adapted from the above answer...

$('iframe').each( function() {
    var url = $(this).attr("src")
    $(this).attr({
        "src" : url.replace('?rel=0', '')+"?wmode=transparent",
        "wmode" : "Opaque"
    })
});


Basically if you don't select Show suggested videos when the video finishes in your embed settings, you have a ?rel=0 at the end of your "src" url. So I've added the replace bit in case ?rel=0 exists. Otherwise ?wmode=transparent won't work.


ComboBox: Adding Text and Value to an Item (no Binding Source)

If anyone is still interested in this, here is a simple and flexible class for a combobox item with a text and a value of any type (very similar to Adam Markowitz's example):

public class ComboBoxItem<T>
{
    public string Name;
    public T value = default(T);

    public ComboBoxItem(string Name, T value)
    {
        this.Name = Name;
        this.value = value;
    }

    public override string ToString()
    {
        return Name;
    }
}

Using the <T> is better than declaring the value as an object, because with object you'd then have to keep track of the type you used for each item, and cast it in your code to use it properly.

I've been using it on my projects for quite a while now. It is really handy.

How to return a result (startActivityForResult) from a TabHost Activity?

Oh, god! After spending several hours and downloading the Android sources, I have finally come to a solution.

If you look at the Activity class, you will see, that finish() method only sends back the result if there is a mParent property set to null. Otherwise the result is lost.

public void finish() {
    if (mParent == null) {
        int resultCode;
        Intent resultData;
        synchronized (this) {
            resultCode = mResultCode;
            resultData = mResultData;
        }
        if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
        try {
            if (ActivityManagerNative.getDefault()
                .finishActivity(mToken, resultCode, resultData)) {
                mFinished = true;
            }
        } catch (RemoteException e) {
            // Empty
        }
    } else {
        mParent.finishFromChild(this);
    }
}

So my solution is to set result to the parent activity if present, like that:

Intent data = new Intent();
 [...]
if (getParent() == null) {
    setResult(Activity.RESULT_OK, data);
} else {
    getParent().setResult(Activity.RESULT_OK, data);
}
finish();

I hope that will be helpful if someone looks for this problem workaround again.

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

I've tried all examples, posted here, but they do not work without extra CSS. Try this:

<a href="http://www.google.com"><button type="button" class="btn btn-success">Google</button></a>

Works perfectly without any extra CSS.

Android Studio says "cannot resolve symbol" but project compiles

I also had this issue with my Android app depending on some of my own Android libraries (using Android Studio 3.0 and 3.1.1).

Whenever I updated a lib and go back to the app, triggering a Gradle Sync, Android Studio was not able to detect the code changes I made to the lib. Compilation worked fine, but Android Studio showed red error lines on some code using the lib.

After investigating, I found that it's because gradle keeps pointing to an old compiled version of my libs. If you go to yourProject/.idea/libraries/ you'll see a list of xml files that contains the link to the compiled version of your libs. These files starts with Gradle__artifacts_*.xml (where * is the name of your libs).

So in order for Android Studio to take the latest version of your libs, you need to delete these Gradle__artifacts_*.xml files, and Android Studio will regenerate them, pointing to the latest compiled version of your libs.

If you don't want to do that manually every time you click on "Gradle sync" (who would want to do that...), you can add this small gradle task in the build.gradle file of your app.

task deleteArtifacts {
    doFirst {
        File librariesFolderPath = file(getProjectDir().absolutePath + "/../.idea/libraries/")
        File[] files = librariesFolderPath.listFiles({ File file -> file.name.startsWith("Gradle__artifacts_") } as FileFilter)

        for (int i = 0; i < files.length; i++) {
            files[i].delete()
        }
    }
}

And in order for your app to always execute this task before doing a gradle sync, you just need to go to the Gradle window, then find the "deleteArtifacts" task under yourApp/Tasks/other/, right click on it and select "Execute Before Sync" (see below).

Gradle window to configure task execution

Now, every time you do a Gradle sync, Android Studio will be forced to use the latest version of your libs.

What is the syntax to insert one list into another list in python?

If we just do x.append(y), y gets referenced into x such that any changes made to y will affect appended x as well. So if we need to insert only elements, we should do following:

x = [1,2,3] y = [4,5,6] x.append(y[:])

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Came across this issue when using Bootstrap 3. My solution was to add the carousel-fade class to the carousel main DIV and slot the following CSS in, somewhere after the Bootstrap CSS is included:

.carousel-fade .item {
  opacity: 0;
  -webkit-transition: opacity 2s ease-in-out;
  -moz-transition: opacity 2s ease-in-out;
  -ms-transition: opacity 2s ease-in-out;
  -o-transition: opacity 2s ease-in-out;
  transition: opacity 2s ease-in-out;
  left: 0 !important;
}

.carousel-fade .active {
  opacity: 1 !important;
}

.carousel-fade .left {
  opacity: 0 !important;
  -webkit-transition: opacity 0.5s ease-in-out !important;
  -moz-transition: opacity 0.5s ease-in-out !important;
  -ms-transition: opacity 0.5s ease-in-out !important;
  -o-transition: opacity 0.5s ease-in-out !important;
  transition: opacity 0.5s ease-in-out !important;
}

.carousel-fade .carousel-control {
  opacity: 1 !important;
}

The style transitions that Bootstrap applies mean that you have to have the mid-stride transitions (active left, next left) quickly, otherwise the item just ends up disappearing (hence the 1/2 second transition time).

I haven't experimented with adjusting the .item and .left transition times, but they will probably need adjusting proportionally to keep the effect looking nice.

Flutter Countdown Timer

doesnt directly answer your question. But helpful for those who want to start something after some time.

Future.delayed(Duration(seconds: 1), () {
            print('yo hey');
          });

How to make phpstorm display line numbers by default?

File -> Settings -> Editor -> General -> Appearance check "Show Line Numbers"

This is the current location as of phpStorm 8.0.2 on Ubuntu 14.04

Javascript Get Values from Multiple Select Option Box

Here i am posting the answer just for reference which may become useful.

<!DOCTYPE html>
<html>
<head>
<script>
function show()
{
     var InvForm = document.forms.form;
     var SelBranchVal = "";
     var x = 0;
     for (x=0;x<InvForm.kb.length;x++)
         {
            if(InvForm.kb[x].selected)
            {
             //alert(InvForm.kb[x].value);
             SelBranchVal = InvForm.kb[x].value + "," + SelBranchVal ;
            }
         }
         alert(SelBranchVal);
}
</script>
</head>
<body>
<form name="form">
<select name="kb" id="kb" onclick="show();" multiple>
<option value="India">India</option>
<option selected="selected" value="US">US</option>
<option value="UK">UK</option>
<option value="Japan">Japan</option>
</select>
<!--input type="submit" name="cmdShow" value="Customize Fields"
 onclick="show();" id="cmdShow" /-->
</form>
</body>
</html>

Insert new column into table in sqlite?

You have two options. First, you could simply add a new column with the following:

ALTER TABLE {tableName} ADD COLUMN COLNew {type};

Second, and more complicatedly, but would actually put the column where you want it, would be to rename the table:

ALTER TABLE {tableName} RENAME TO TempOldTable;

Then create the new table with the missing column:

CREATE TABLE {tableName} (name TEXT, COLNew {type} DEFAULT {defaultValue}, qty INTEGER, rate REAL);

And populate it with the old data:

INSERT INTO {tableName} (name, qty, rate) SELECT name, qty, rate FROM TempOldTable;

Then delete the old table:

DROP TABLE TempOldTable;

I'd much prefer the second option, as it will allow you to completely rename everything if need be.

Why is "using namespace std;" considered bad practice?

A namespace is a named scope. Namespaces are used to group related declarations and to keep separate items separate. For example, two separately developed libraries may use the same name to refer to different items, but a user can still use both:

namespace Mylib{
    template<class T> class Stack{ /* ... */ };
    // ...
}

namespace Yourlib{
    class Stack{ /* ... */ };
    // ...
}

void f(int max) {
    Mylib::Stack<int> s1(max); // Use my stack
    Yourlib::Stack    s2(max); // Use your stack
    // ...
}

Repeating a namespace name can be a distraction for both readers and writers. Consequently, it is possible to state that names from a particular namespace are available without explicit qualification. For example:

void f(int max) {
    using namespace Mylib; // Make names from Mylib accessible
    Stack<int> s1(max); // Use my stack
    Yourlib::Stack s2(max); // Use your stack
    // ...
}

Namespaces provide a powerful tool for the management of different libraries and of different versions of code. In particular, they offer the programmer alternatives of how explicit to make a reference to a nonlocal name.

Source: An Overview of the C++ Programming Language by Bjarne Stroustrup

Multi value Dictionary

I don't think you can do that directly. You could create a class containing both your object and double and put an instance of it in the dictionary though.

class Pair
{
    object obj;
    double dbl;
}

Dictionary<int, Pair> = new Dictionary<int, Pair>();

Terminal Multiplexer for Microsoft Windows - Installers for GNU Screen or tmux

Look. This is way old, but on the off chance that someone from Google finds this, absolutely the best solution to this - (and it is AWESOME) - is to use ConEmu (or a package that includes and is built on top of ConEmu called cmder) and then either use plink or putty itself to connect to a specific machine, or, even better, set up a development environment as a local VM using Vagrant.

This is the only way I can ever see myself developing from a Windows box again.

I am confident enough to say that every other answer - while not necessarily bad answers - offer garbage solutions compared to this.

Update: As Of 1/8/2020 not all other solutions are garbage - Windows Terminal is getting there and WSL exists.

Google Forms file upload complete example

As of October 2016, Google has added a file upload question type in native Google Forms, no Google Apps Script needed. See documentation.

Where is Ubuntu storing installed programs?

to find the program you want you can run this command at terminal:

find / usr-name "your_program"

How to unit test abstract classes: extend with stubs?

Write a Mock object and use them just for testing. They usually are very very very minimal (inherit from the abstract class) and not more.Then, in your Unit Test you can call the abstract method you want to test.

You should test abstract class that contain some logic like all other classes you have.

How to open generated pdf using jspdf in new window

STEP 1
Turn off addblock

STEP 2
Add

window.open(doc.output('bloburl'), '_blank');

Or try

doc.output('dataurlnewwindow')

How to remove element from ArrayList by checking its value?

Just use myList.remove(myObject).

It uses the equals method of the class. See http://docs.oracle.com/javase/6/docs/api/java/util/List.html#remove(java.lang.Object)

BTW, if you have more complex things to do, you should check out the guava library that has dozen of utility to do that with predicates and so on.

Open links in new window using AngularJS

It works for me. Inject $window service in to your controller.

$window.open("somepath/", "_blank")

Best XML parser for Java

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

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

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

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

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

jQuery DataTable overflow and text-wrapping issues

I'm way late here, but after reading @Greg Pettit's answer and a couple of blogs or other SO questions I unfortunately can't remember I decided to just make a couple of dataTables plugins to deal with this.

I put them on bitbucket in a Mercurial repo. I follwed the fnSetFilteringDelay plugin and just changed the comments and code inside, as I've never made a plugin for anything before. I made 2, and feel free to use them, contribute to them, or provide suggestions.

  • dataTables.TruncateCells - truncates each cell in a column down to a set number of characters, replacing the last 3 with an ellipses, and puts the full pre-truncated text in the cell's title attributed.

  • dataTables.BreakCellText - attempts to insert a break character every X, user defined, characters in each cell in the column. There are quirks regarding cells that contain both spaces and hyphens, you can get some weird looking results (like a couple of characters straggling after the last inserted
    character). Maybe someone can make that more robust, or you can just fiddle with the breakPos for the column to make it look alright with your data.

How to Position a table HTML?

You would want to use CSS to achieve that.

say you have a table with the attribute id="my_table"

You would want to write the following in your css file

#my_table{
    margin-top:10px //moves your table 10pixels down
    margin-left:10px //moves your table 10pixels right
}

if you do not have a CSS file then you may just add margin-top:10px, margin-left:10px to the style attribute in your table element like so

<table style="margin-top:10px; margin-left:10px;">
    ....
</table>

There are a lot of resources on the net describing CSS and HTML in detail

Why do this() and super() have to be the first statement in a constructor?

Actually, super() is the first statement of a constructor because to make sure its superclass is fully-formed before the subclass being constructed. Even if you don't have super() in your first statement, the compiler will add it for you!

Unable to merge dex

Check if you have debugCompile and releaseCompile in build.gradle. Change it to debugImplementation and releaseImplementation. This was how I have solved it, gradle should pass through this successfully marked instructions as deprecated, but suddenly it stucked exactly on this two.

What does a bitwise shift (left or right) do and what is it used for?

Here is an example:

#include"stdio.h"
#include"conio.h"

void main()
{
    int rm, vivek;
    clrscr();
    printf("Enter any numbers\t(E.g., 1, 2, 5");
    scanf("%d", &rm); // rm = 5(0101) << 2 (two step add zero's), so the value is 10100
    printf("This left shift value%d=%d", rm, rm<<4);
    printf("This right shift value%d=%d", rm, rm>>2);
    getch();
}

editing PATH variable on mac

use

~/.bash_profile

or

~/.MacOSX/environment.plist

(see Runtime Configuration Guidelines)

How to make the script wait/sleep in a simple way in unity

You were correct to use WaitForSeconds. But I suspect that you tried using it without coroutines. That's how it should work:

public void SomeMethod()
{
    StartCoroutine(SomeCoroutine());
}

private IEnumerator SomeCoroutine()
{
    TextUI.text = "Welcome to Number Wizard!";
    yield return new WaitForSeconds (3);
    TextUI.text = ("The highest number you can pick is " + max);
    yield return new WaitForSeconds (3);
    TextUI.text = ("The lowest number you can pick is " + min);
}

How to read a file into a variable in shell?

Two important pitfalls

which were ignored by other answers so far:

  1. Trailing newline removal from command expansion
  2. NUL character removal

Trailing newline removal from command expansion

This is a problem for the:

value="$(cat config.txt)"

type solutions, but not for read based solutions.

Command expansion removes trailing newlines:

S="$(printf "a\n")"
printf "$S" | od -tx1

Outputs:

0000000 61
0000001

This breaks the naive method of reading from files:

FILE="$(mktemp)"
printf "a\n\n" > "$FILE"
S="$(<"$FILE")"
printf "$S" | od -tx1
rm "$FILE"

POSIX workaround: append an extra char to the command expansion and remove it later:

S="$(cat $FILE; printf a)"
S="${S%a}"
printf "$S" | od -tx1

Outputs:

0000000 61 0a 0a
0000003

Almost POSIX workaround: ASCII encode. See below.

NUL character removal

There is no sane Bash way to store NUL characters in variables.

This affects both expansion and read solutions, and I don't know any good workaround for it.

Example:

printf "a\0b" | od -tx1
S="$(printf "a\0b")"
printf "$S" | od -tx1

Outputs:

0000000 61 00 62
0000003

0000000 61 62
0000002

Ha, our NUL is gone!

Workarounds:

  • ASCII encode. See below.

  • use bash extension $"" literals:

    S=$"a\0b"
    printf "$S" | od -tx1
    

    Only works for literals, so not useful for reading from files.

Workaround for the pitfalls

Store an uuencode base64 encoded version of the file in the variable, and decode before every usage:

FILE="$(mktemp)"
printf "a\0\n" > "$FILE"
S="$(uuencode -m "$FILE" /dev/stdout)"
uudecode -o /dev/stdout <(printf "$S") | od -tx1
rm "$FILE"

Output:

0000000 61 00 0a
0000003

uuencode and udecode are POSIX 7 but not in Ubuntu 12.04 by default (sharutils package)... I don't see a POSIX 7 alternative for the bash process <() substitution extension except writing to another file...

Of course, this is slow and inconvenient, so I guess the real answer is: don't use Bash if the input file may contain NUL characters.

Datetime equal or greater than today in MySQL

SELECT * FROM users WHERE created >= CURDATE();

But I think you mean created < today

Iterate over model instance field names and values in template

Just an edit of @wonder

def to_dict(obj, exclude=[]):
    tree = {}
    for field in obj._meta.fields + obj._meta.many_to_many:
        if field.name in exclude or \
           '%s.%s' % (type(obj).__name__, field.name) in exclude:
            continue
        try :
            value = getattr(obj, field.name)
        except obj.DoesNotExist as e:
            value = None
        except ObjectDoesNotExist as e:
            value = None
            continue
        if type(field) in [ForeignKey, OneToOneField]:
            tree[field.name] = to_dict(value, exclude=exclude)
        elif isinstance(field, ManyToManyField):
            vs = []
            for v in value.all():
                vs.append(to_dict(v, exclude=exclude))
            tree[field.name] = vs
        else:
            tree[field.name] = obj.serializable_value(field.name)
    return tree

Let Django handle all the other fields other than the related fields. I feel that is more stable

Tests not running in Test Explorer

If you are using NUnit rather than MSTest then you will need the NUnit Test Adapter Extension for Visual Studio 2012/2013.

Setting up Vim for Python

Re: the dead "Turning Vim Into A Modern Python IDE" link, back in 2013 I saved a copy, that I converted to a HTML page as well as a PDF copy:

http://persagen.com/files/misc/Turning_vim_into_a_modern_Python_IDE.html

http://persagen.com/files/misc/Turning_vim_into_a_modern_Python_IDE.pdf

Edit (Sep 08, 2017) updated URLs.

Counting unique values in a column in pandas dataframe like in Qlik?

Count distinct values, use nunique:

df['hID'].nunique()
5

Count only non-null values, use count:

df['hID'].count()
8

Count total values including null values, use the size attribute:

df['hID'].size
8

Edit to add condition

Use boolean indexing:

df.loc[df['mID']=='A','hID'].agg(['nunique','count','size'])

OR using query:

df.query('mID == "A"')['hID'].agg(['nunique','count','size'])

Output:

nunique    5
count      5
size       5
Name: hID, dtype: int64

Regex for Comma delimited list

i used this for a list of items that had to be alphanumeric without underscores at the front of each item.

^(([0-9a-zA-Z][0-9a-zA-Z_]*)([,][0-9a-zA-Z][0-9a-zA-Z_]*)*)$

anaconda - graphviz - can't import after installation

Check if tensorflow is activated in your terminal

first deactivate it using

conda deactivate

then use the command

conda install python-graphviz

and then install

conda install graphviz

this is solution for UBUNTU USERS :) CHEERS :)

Can vue-router open a link in a new tab?

This works for me:

In HTML template: <a target="_blank" :href="url" @click.stop>your_name</a>

In mounted(): this.url = `${window.location.origin}/your_page_name`;

Fit background image to div

try any of the following,

background-size: contain;
background-size: cover;
background-size: 100%;

.container{
    background-size: 100%;
}

Matplotlib figure facecolor (background color)

It's because savefig overrides the facecolor for the background of the figure.

(This is deliberate, actually... The assumption is that you'd probably want to control the background color of the saved figure with the facecolor kwarg to savefig. It's a confusing and inconsistent default, though!)

The easiest workaround is just to do fig.savefig('whatever.png', facecolor=fig.get_facecolor(), edgecolor='none') (I'm specifying the edgecolor here because the default edgecolor for the actual figure is white, which will give you a white border around the saved figure)

Hope that helps!

How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?

Try this:

1) Plug your iOS device into your Mac using a lightning cable. You may need to select to Trust This Computer on your device.

2) Open Xcode and go to Window > Devices and Simulators.

3) Select your device and then select the Connect via network checkbox to pair your device.

4) Run your project after removing your lighting cable.

Javascript - validation, numbers only

var elem = document.getElementsByClassName("number-validation"); //use the CLASS in your input field.
for (i = 0; i < elem.length; i++) {
   elem[i].addEventListener('keypress', function(event){
      var keys = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0];
      var validIndex = keys.indexOf(event.charCode);
      if(validIndex == -1){
         event.preventDefault();
      }
  });
}

ListBox vs. ListView - how to choose for data binding

A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.

If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).

Creating a div element in jQuery

div = $("<div>").html("Loading......");
$("body").prepend(div);    

is there any IE8 only css hack?

There are various ways to get a class onto the HTML element, identifying which IE version you're contending with: Modernizr, the HTML 5 Boilerplate, etc - or just roll your own. Then you can use that class (eg .lt-ie9) in a normal CSS selector, no hack needed. If you only want to affect IE8 and not previous versions, put the old value back using a .lt-ie8 selector.

numpy matrix vector multiplication

Simplest solution

Use numpy.dot or a.dot(b). See the documentation here.

>>> a = np.array([[ 5, 1 ,3], 
                  [ 1, 1 ,1], 
                  [ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])

This occurs because numpy arrays are not matrices, and the standard operations *, +, -, / work element-wise on arrays. Instead, you could try using numpy.matrix, and * will be treated like matrix multiplication.


Other Solutions

Also know there are other options:

  • As noted below, if using python3.5+ the @ operator works as you'd expect:

    >>> print(a @ b)
    array([16, 6, 8])
    
  • If you want overkill, you can use numpy.einsum. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.

    >>> np.einsum('ji,i->j', a, b)
    array([16, 6, 8])
    
  • As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul, which works like numpy.dot with two major exceptions: no scalar multiplication but it works with stacks of matrices.

    >>> np.matmul(a, b)
    array([16, 6, 8])
    
  • numpy.inner functions the same way as numpy.dot for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).

    >>> np.inner(a, b)
    array([16, 6, 8])
    
    # Beware using for matrix-matrix multiplication though!
    >>> b = a.T
    >>> np.dot(a, b)
    array([[35,  9, 10],
           [ 9,  3,  4],
           [10,  4,  6]])
    >>> np.inner(a, b) 
    array([[29, 12, 19],
           [ 7,  4,  5],
           [ 8,  5,  6]])
    

Rarer options for edge cases

  • If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot with the optional argument axes=1:

    >>> np.tensordot(a, b, axes=1)
    array([16,  6,  8])
    
  • Don't use numpy.vdot if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m vs n).

Uncaught SyntaxError: Unexpected token < On Chrome

header("Location: route_to_main_page");

I've encountered this problem while having a custom 404 error handling file. Instead of throwing some html content it was suppose to redirect to the main page url. It worked well.

Then I used this as a skeleton for a next project, therefore not changing the "route_to_main_page" actually on the new project (different URL) became a "route_to_external_url" so any 404 errors within your code (missing css stylesheets, js libraries) would return the "Uncaught SyntaxError: Unexpected token <".

Change the color of cells in one column when they don't match cells in another column

In my case I had to compare column E and I.

I used conditional formatting with new rule. Formula was "=IF($E1<>$I1,1,0)" for highlights in orange and "=IF($E1=$I1,1,0)" to highlight in green.

Next problem is how many columns you want to highlight. If you open Conditional Formatting Rules Manager you can edit for each rule domain of applicability: Check "Applies to"

In my case I used "=$E:$E,$I:$I" for both rules so I highlight only two columns for differences - column I and column E.

Hide all elements with class using plain Javascript

I use a modified version of this:

function getElementsByClass(nameOfClass) {    
  var temp, all, elements;

  all = document.getElementsByTagName("*");
  elements = [];

  for(var a=0;a<all.length;a++) {
    temp = all[a].className.split(" ");
    for(var b=0;b<temp.length;b++) {
      if(temp[b]==nameOfClass) { 
        elements.push(ALL[a]); 
        break; 
      }
    }
  }
  return elements;
};

And JQuery will do this really easily too.

How to Remove Line Break in String

I know this post is very old but I could not find anything that would do this. So I finally put this together from all the forums.

This will remove All line breaks from the left and right, and removes any blank lines. Then Trim it all to look good. Alter as you see fit. I also made one that removes All Line Breaks, if interested. TY

    Sub RemoveBlankLines()
    Application.ScreenUpdating = False
    Dim rngCel As Range
    Dim strOldVal As String
    Dim strNewVal As String

    For Each rngCel In Selection
        If rngCel.HasFormula = False Then
            strOldVal = rngCel.Value
            strNewVal = strOldVal
            Debug.Print rngCel.Address

            Do
            If Left(strNewVal, 1) = vbLf Then strNewVal = Right(strNewVal, Len(strNewVal) - 1)
            If strNewVal = strOldVal Then Exit Do
                strOldVal = strNewVal
            Loop

            Do
            If Right(strNewVal, 1) = vbLf Then strNewVal = Left(strNewVal, Len(strNewVal) - 1)
            If strNewVal = strOldVal Then Exit Do
                strOldVal = strNewVal
            Loop

            Do
            strNewVal = Replace(strNewVal, vbLf & vbLf, "^")
            strNewVal = Replace(strNewVal, Replace(String(Len(strNewVal) - _
                        Len(Replace(strNewVal, "^", "")), "^"), "^", "^"), "^")
            strNewVal = Replace(strNewVal, "^", vbLf)

            If strNewVal = strOldVal Then Exit Do
                strOldVal = strNewVal
            Loop

            If rngCel.Value <> strNewVal Then
                rngCel = strNewVal
            End If

        rngCel.Value = Application.Trim(rngCel.Value)
        End If
    Next rngCel
    Application.ScreenUpdating = True
End Sub

How to trigger event in JavaScript?

The accepted answer didn’t work for me, none of the createEvent ones did.

What worked for me in the end was:

targetElement.dispatchEvent(
    new MouseEvent('click', {
        bubbles: true,
        cancelable: true,
        view: window,
}));

Here’s a snippet:

_x000D_
_x000D_
const clickBtn = document.querySelector('.clickme');_x000D_
const viaBtn = document.querySelector('.viame');_x000D_
_x000D_
viaBtn.addEventListener('click', function(event) {_x000D_
    clickBtn.dispatchEvent(_x000D_
        new MouseEvent('click', {_x000D_
            bubbles: true,_x000D_
            cancelable: true,_x000D_
            view: window,_x000D_
    }));_x000D_
});_x000D_
_x000D_
clickBtn.addEventListener('click', function(event) {_x000D_
    console.warn(`I was accessed via the other button! A ${event.type} occurred!`);_x000D_
});
_x000D_
<button class="clickme">Click me</button>_x000D_
_x000D_
<button class="viame">Via me</button>
_x000D_
_x000D_
_x000D_

From reading: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent

Printing leading 0's in C

printf("%05d", zipCode);

The 0 indicates what you are padding with and the 5 shows the width of the integer number.

Example 1: If you use "%02d" (useful for dates) this would only pad zeros for numbers in the ones column. E.g., 06 instead of 6.

Example 2: "%03d" would pad 2 zeros for one number in the ones column and pad 1 zero for a number in the tens column. E.g., number 7 padded to 007 and number 17 padded to 017.

regular expression to validate datetime format (MM/DD/YYYY)

you can look into this link and I hope this may be of great help as its was for me.

If you are using the regex given in the above link in Java code then use the following regex

"^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\\d\\d$"

As I noticed in your example you are using js function then this use regex

"^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$"

This will match a date in mm/dd/yyyy format from between 1900-01-01 and 2099-12-31, with a choice of four separators. and not to forget the

return regex.test(testdate);

Angular: Cannot find a differ supporting object '[object Object]'

If this is an Observable being return in the HTML simply add the async pipe

    observable | async

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

COPY copies a file/directory from your host to your image.

ADD copies a file/directory from your host to your image, but can also fetch remote URLs, extract TAR files, etc...

Use COPY for simply copying files and/or directories into the build context.

Use ADD for downloading remote resources, extracting TAR files, etc..

Ignoring SSL certificate in Apache HttpClient 4.3

Here's a working distillation of the above techniques, equivalent to "curl --insecure":

HttpClient getInsecureHttpClient() throws GeneralSecurityException {
    TrustStrategy trustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) {
            return true;
        }
    };

    HostnameVerifier hostnameVerifier = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    return HttpClients.custom()
            .setSSLSocketFactory(new SSLConnectionSocketFactory(
                    new SSLContextBuilder().loadTrustMaterial(trustStrategy).build(),
                    hostnameVerifier))
            .build();
}

How do I declare class-level properties in Objective-C?

properties have a specific meaning in Objective-C, but I think you mean something that's equivalent to a static variable? E.g. only one instance for all types of Foo?

To declare class functions in Objective-C you use the + prefix instead of - so your implementation would look something like:

// Foo.h
@interface Foo {
}

+ (NSDictionary *)dictionary;

// Foo.m
+ (NSDictionary *)dictionary {
  static NSDictionary *fooDict = nil;
  if (fooDict == nil) {
    // create dict
  }
  return fooDict;
}

jQuery - passing value from one input to another

Get input1 data to send them to input2 immediately

<div>
<label>Input1</label>
 <input type="text" id="input1" value="">
</div>

</br>
<label>Input2</label>
<input type="text" id="input2" value="">

<script type="text/javascript">
        $(document).ready(function () {
            $("#input1").keyup(function () {
                var value = $(this).val();
                $("#input2").val(value);
            });
        });
</script>

Android scale animation on view

try this code to create Scale animation without using xml

ScaleAnimation animation = new ScaleAnimation(fromXscale, toXscale, fromYscale, toYscale, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

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

textcolor function is no longer supported in the latest compilers.

This the simplest way to change text color in Code Blocks. You can use system function.

To change Text Color :

#include<stdio.h> 
#include<stdlib.h> //as system function is in the standard library

int main()        
        {
          system("color 1"); //here 1 represents the text color
          printf("This is dummy program for text color");
          return 0;
        }

If you want to change both the text color & console color you just need to add another color code in system function

To change Text Color & Console Color :

system("color 41"); //here 4 represents the console color and 1 represents the text color

N.B: Don't use spaces between color code like these

system("color 4 1");

Though if you do it Code Block will show all the color codes. You can use this tricks to know all supported color codes.

How to escape apostrophe (') in MySql?

Standard SQL uses doubled-up quotes; MySQL has to accept that to be reasonably compliant.

'He said, "Don''t!"'

How to use gitignore command in git

So based on what you said, these files are libraries/documentation you don't want to delete but also don't want to push to github. Let say you have your project in folder your_project and a doc directory: your_project/doc.

  1. Remove it from the project directory (without actually deleting it): git rm --cached doc/*
  2. If you don't already have a .gitignore, you can make one right inside of your project folder: project/.gitignore.
  3. Put doc/* in the .gitignore
  4. Stage the file to commit: git add project/.gitignore
  5. Commit: git commit -m "message".
  6. Push your change to github.

How do you share constants in NodeJS modules?

I recommend doing it with webpack (assumes you're using webpack).

Defining constants is as simple as setting the webpack config file:

var webpack = require('webpack');
module.exports = {
    plugins: [
        new webpack.DefinePlugin({
            'APP_ENV': '"dev"',
            'process.env': {
                'NODE_ENV': '"development"'
            }
        })
    ],    
};

This way you define them outside your source, and they will be available in all your files.

Trying Gradle build - "Task 'build' not found in root project"

run

gradle clean 

then try

gradle build 

it worked for me

Delete item from state array in react

I also had a same requirement to delete an element from array which is in state.

const array= [...this.state.selectedOption]
const found= array.findIndex(x=>x.index===k)
if(found !== -1){
   this.setState({
   selectedOption:array.filter(x => x.index !== k)
    })
 }

First I copied the elements into an array. Then checked whether the element exist in the array or not. Then only I have deleted the element from the state using the filter option.

Setting default value for TypeScript object passed as argument

Without destructuring, you can create a defaults params and pass it in

interface Name {
   firstName: string;
   lastName: string;
}

export const defaultName extends Omit<Name, 'firstName'> {
    lastName: 'Smith'
}

sayName({ ...defaultName, firstName: 'Bob' })

how to draw smooth curve through N points using javascript HTML5 canvas?

A bit late, but for the record.

You can achieve smooth lines by using cardinal splines (aka canonical spline) to draw smooth curves that goes through the points.

I made this function for canvas - it's split into three function to increase versatility. The main wrapper function looks like this:

function drawCurve(ctx, ptsa, tension, isClosed, numOfSegments, showPoints) {

    showPoints  = showPoints ? showPoints : false;

    ctx.beginPath();

    drawLines(ctx, getCurvePoints(ptsa, tension, isClosed, numOfSegments));

    if (showPoints) {
        ctx.stroke();
        ctx.beginPath();
        for(var i=0;i<ptsa.length-1;i+=2) 
                ctx.rect(ptsa[i] - 2, ptsa[i+1] - 2, 4, 4);
    }
}

To draw a curve have an array with x, y points in the order: x1,y1, x2,y2, ...xn,yn.

Use it like this:

var myPoints = [10,10, 40,30, 100,10]; //minimum two points
var tension = 1;

drawCurve(ctx, myPoints); //default tension=0.5
drawCurve(ctx, myPoints, tension);

The function above calls two sub-functions, one to calculate the smoothed points. This returns an array with new points - this is the core function which calculates the smoothed points:

function getCurvePoints(pts, tension, isClosed, numOfSegments) {

    // use input value if provided, or use a default value   
    tension = (typeof tension != 'undefined') ? tension : 0.5;
    isClosed = isClosed ? isClosed : false;
    numOfSegments = numOfSegments ? numOfSegments : 16;

    var _pts = [], res = [],    // clone array
        x, y,           // our x,y coords
        t1x, t2x, t1y, t2y, // tension vectors
        c1, c2, c3, c4,     // cardinal points
        st, t, i;       // steps based on num. of segments

    // clone array so we don't change the original
    //
    _pts = pts.slice(0);

    // The algorithm require a previous and next point to the actual point array.
    // Check if we will draw closed or open curve.
    // If closed, copy end points to beginning and first points to end
    // If open, duplicate first points to befinning, end points to end
    if (isClosed) {
        _pts.unshift(pts[pts.length - 1]);
        _pts.unshift(pts[pts.length - 2]);
        _pts.unshift(pts[pts.length - 1]);
        _pts.unshift(pts[pts.length - 2]);
        _pts.push(pts[0]);
        _pts.push(pts[1]);
    }
    else {
        _pts.unshift(pts[1]);   //copy 1. point and insert at beginning
        _pts.unshift(pts[0]);
        _pts.push(pts[pts.length - 2]); //copy last point and append
        _pts.push(pts[pts.length - 1]);
    }

    // ok, lets start..

    // 1. loop goes through point array
    // 2. loop goes through each segment between the 2 pts + 1e point before and after
    for (i=2; i < (_pts.length - 4); i+=2) {
        for (t=0; t <= numOfSegments; t++) {

            // calc tension vectors
            t1x = (_pts[i+2] - _pts[i-2]) * tension;
            t2x = (_pts[i+4] - _pts[i]) * tension;

            t1y = (_pts[i+3] - _pts[i-1]) * tension;
            t2y = (_pts[i+5] - _pts[i+1]) * tension;

            // calc step
            st = t / numOfSegments;

            // calc cardinals
            c1 =   2 * Math.pow(st, 3)  - 3 * Math.pow(st, 2) + 1; 
            c2 = -(2 * Math.pow(st, 3)) + 3 * Math.pow(st, 2); 
            c3 =       Math.pow(st, 3)  - 2 * Math.pow(st, 2) + st; 
            c4 =       Math.pow(st, 3)  -     Math.pow(st, 2);

            // calc x and y cords with common control vectors
            x = c1 * _pts[i]    + c2 * _pts[i+2] + c3 * t1x + c4 * t2x;
            y = c1 * _pts[i+1]  + c2 * _pts[i+3] + c3 * t1y + c4 * t2y;

            //store points in array
            res.push(x);
            res.push(y);

        }
    }

    return res;
}

And to actually draw the points as a smoothed curve (or any other segmented lines as long as you have an x,y array):

function drawLines(ctx, pts) {
    ctx.moveTo(pts[0], pts[1]);
    for(i=2;i<pts.length-1;i+=2) ctx.lineTo(pts[i], pts[i+1]);
}

_x000D_
_x000D_
var ctx = document.getElementById("c").getContext("2d");_x000D_
_x000D_
_x000D_
function drawCurve(ctx, ptsa, tension, isClosed, numOfSegments, showPoints) {_x000D_
_x000D_
  ctx.beginPath();_x000D_
_x000D_
  drawLines(ctx, getCurvePoints(ptsa, tension, isClosed, numOfSegments));_x000D_
  _x000D_
  if (showPoints) {_x000D_
    ctx.beginPath();_x000D_
    for(var i=0;i<ptsa.length-1;i+=2) _x000D_
      ctx.rect(ptsa[i] - 2, ptsa[i+1] - 2, 4, 4);_x000D_
  }_x000D_
_x000D_
  ctx.stroke();_x000D_
}_x000D_
_x000D_
_x000D_
var myPoints = [10,10, 40,30, 100,10, 200, 100, 200, 50, 250, 120]; //minimum two points_x000D_
var tension = 1;_x000D_
_x000D_
drawCurve(ctx, myPoints); //default tension=0.5_x000D_
drawCurve(ctx, myPoints, tension);_x000D_
_x000D_
_x000D_
function getCurvePoints(pts, tension, isClosed, numOfSegments) {_x000D_
_x000D_
  // use input value if provided, or use a default value  _x000D_
  tension = (typeof tension != 'undefined') ? tension : 0.5;_x000D_
  isClosed = isClosed ? isClosed : false;_x000D_
  numOfSegments = numOfSegments ? numOfSegments : 16;_x000D_
_x000D_
  var _pts = [], res = [], // clone array_x000D_
      x, y,   // our x,y coords_x000D_
      t1x, t2x, t1y, t2y, // tension vectors_x000D_
      c1, c2, c3, c4,  // cardinal points_x000D_
      st, t, i;  // steps based on num. of segments_x000D_
_x000D_
  // clone array so we don't change the original_x000D_
  //_x000D_
  _pts = pts.slice(0);_x000D_
_x000D_
  // The algorithm require a previous and next point to the actual point array._x000D_
  // Check if we will draw closed or open curve._x000D_
  // If closed, copy end points to beginning and first points to end_x000D_
  // If open, duplicate first points to befinning, end points to end_x000D_
  if (isClosed) {_x000D_
    _pts.unshift(pts[pts.length - 1]);_x000D_
    _pts.unshift(pts[pts.length - 2]);_x000D_
    _pts.unshift(pts[pts.length - 1]);_x000D_
    _pts.unshift(pts[pts.length - 2]);_x000D_
    _pts.push(pts[0]);_x000D_
    _pts.push(pts[1]);_x000D_
  }_x000D_
  else {_x000D_
    _pts.unshift(pts[1]); //copy 1. point and insert at beginning_x000D_
    _pts.unshift(pts[0]);_x000D_
    _pts.push(pts[pts.length - 2]); //copy last point and append_x000D_
    _pts.push(pts[pts.length - 1]);_x000D_
  }_x000D_
_x000D_
  // ok, lets start.._x000D_
_x000D_
  // 1. loop goes through point array_x000D_
  // 2. loop goes through each segment between the 2 pts + 1e point before and after_x000D_
  for (i=2; i < (_pts.length - 4); i+=2) {_x000D_
    for (t=0; t <= numOfSegments; t++) {_x000D_
_x000D_
      // calc tension vectors_x000D_
      t1x = (_pts[i+2] - _pts[i-2]) * tension;_x000D_
      t2x = (_pts[i+4] - _pts[i]) * tension;_x000D_
_x000D_
      t1y = (_pts[i+3] - _pts[i-1]) * tension;_x000D_
      t2y = (_pts[i+5] - _pts[i+1]) * tension;_x000D_
_x000D_
      // calc step_x000D_
      st = t / numOfSegments;_x000D_
_x000D_
      // calc cardinals_x000D_
      c1 =   2 * Math.pow(st, 3)  - 3 * Math.pow(st, 2) + 1; _x000D_
      c2 = -(2 * Math.pow(st, 3)) + 3 * Math.pow(st, 2); _x000D_
      c3 =     Math.pow(st, 3) - 2 * Math.pow(st, 2) + st; _x000D_
      c4 =     Math.pow(st, 3) -    Math.pow(st, 2);_x000D_
_x000D_
      // calc x and y cords with common control vectors_x000D_
      x = c1 * _pts[i] + c2 * _pts[i+2] + c3 * t1x + c4 * t2x;_x000D_
      y = c1 * _pts[i+1] + c2 * _pts[i+3] + c3 * t1y + c4 * t2y;_x000D_
_x000D_
      //store points in array_x000D_
      res.push(x);_x000D_
      res.push(y);_x000D_
_x000D_
    }_x000D_
  }_x000D_
_x000D_
  return res;_x000D_
}_x000D_
_x000D_
function drawLines(ctx, pts) {_x000D_
  ctx.moveTo(pts[0], pts[1]);_x000D_
  for(i=2;i<pts.length-1;i+=2) ctx.lineTo(pts[i], pts[i+1]);_x000D_
}
_x000D_
canvas { border: 1px solid red; }
_x000D_
<canvas id="c"><canvas>
_x000D_
_x000D_
_x000D_

This results in this:

Example pix

You can easily extend the canvas so you can call it like this instead:

ctx.drawCurve(myPoints);

Add the following to the javascript:

if (CanvasRenderingContext2D != 'undefined') {
    CanvasRenderingContext2D.prototype.drawCurve = 
        function(pts, tension, isClosed, numOfSegments, showPoints) {
       drawCurve(this, pts, tension, isClosed, numOfSegments, showPoints)}
}

You can find a more optimized version of this on NPM (npm i cardinal-spline-js) or on GitLab.

Start/Stop and Restart Jenkins service on Windows

To Start Jenkins through Command Line

  1. Run CMD with admin

  2. You can run following commands

    "net start servicename" to start

    "net restart servicename" to restart

    "net stop servicename" to stop service

for more reference https://www.windows-commandline.com/start-stop-service-command-line/

Delete newline in Vim

If you are on the first line, pressing (upper case) J will join that line and the next line together, removing the newline. You can also combine this with a count, so pressing 3J will combine all 3 lines together.

How to call codeigniter controller function from view

I had this same issue , but after a couple of research I fond it out it's quite simple to do,

Locate this URL in your Codeigniter project: application/helpers/util_helper.php

add this below code

//you can define any kind of function but I have queried database in my case

//check if the function exist
 if (!function_exists('yourfunctionname')) {
    function yourfunctionname($param (if neccesary)) {
        
        //get the instance
        $ci = & get_instance();
    
        // write your query with the instance class

        $data =  $ci->db->select('*');
        $data =  $ci->db->from('table');  
        $data =  $ci->db->where('something', 'something');

        //you can return anythting

        $data =  $ci->db->get()->num_rows(); 

        if ($data > 0) {
            return $data;
        }  else {
            return 0;
        }  
    }
}

Make hibernate ignore class variables that are not mapped

JPA will use all properties of the class, unless you specifically mark them with @Transient:

@Transient
private String agencyName;

The @Column annotation is purely optional, and is there to let you override the auto-generated column name. Furthermore, the length attribute of @Column is only used when auto-generating table definitions, it has no effect on the runtime.

Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

Just create a variable as $base_url

$base_url = load_class('Config')->config['base_url'];

<?php echo $base_url ?>

and call it in your code..

Disable Scrolling on Body

This post was helpful, but just wanted to share a slight alternative that may help others:

Setting max-height instead of height also does the trick. In my case, I'm disabling scrolling based on a class toggle. Setting .someContainer {height: 100%; overflow: hidden;} when the container's height is smaller than that of the viewport would stretch the container, which wouldn't be what you'd want. Setting max-height accounts for this, but if the container's height is greater than the viewport's when the content changes, still disables scrolling.

Add and remove multiple classes in jQuery

easiest way to append class name using javascript. It can be useful when .siblings() are misbehaving.

document.getElementById('myId').className += ' active';

JavaFX Location is not set error message

The answer below by CsPeitch and others is on the right track. Just make sure that the fxml file is being copied over to your class output target, or the runtime will not see it. Check the generated class file directory and see if the fxml is there

SQL exclude a column using SELECT * [except columnA] FROM tableA?

That what I use often for this case:

declare @colnames varchar(max)=''

select @colnames=@colnames+','+name from syscolumns where object_id(tablename)=id and name not in (column3,column4)

SET @colnames=RIGHT(@colnames,LEN(@colnames)-1)

@colnames looks like column1,column2,column5

getFilesDir() vs Environment.getDataDirectory()

Environment returns user data directory. And getFilesDir returns application data directory.

The Response content must be a string or object implementing __toString(), "boolean" given after move to psql

I got this issue when I used an ajax call to retrieve data from the database. When the controller returned the array it converted it to a boolean. The problem was that I had "invalid characters" like ú (u with accent).

jquery live hover

.live() has been deprecated as of jQuery 1.7

Use .on() instead and specify a descendant selector

http://api.jquery.com/on/

$("table").on({
  mouseenter: function(){
    $(this).addClass("inside");
  },
  mouseleave: function(){
    $(this).removeClass("inside");
  }
}, "tr");  // descendant selector

HTML colspan in CSS

There's no simple, elegant CSS analog for colspan.

Searches on this very issue will return a variety of solutions that include a bevy of alternatives, including absolute positioning, sizing, along with a similar variety of browser- and circumstance-specific caveats. Read, and make the best informed decision you can based on what you find.

How do I position a div at the bottom center of the screen

If you aren't comfortable with using negative margins, check this out.

div {
  position: fixed;
  left: 50%;
  bottom: 20px;
  transform: translate(-50%, -50%);
  margin: 0 auto;
}
<div>
  Your Text
</div>

Especially useful when you don't know the width of the div.


align="center" has no effect.

Since you have position:absolute, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.

#manipulate {
    position:absolute;
    width:300px;
    height:300px;
    background:#063;
    bottom:0px;
    right:25%;
    left:50%;
    margin-left:-150px;
}

Selenium webdriver click google search

Simple Xpath for locating Google search box is: Xpath=//span[text()='Google Search']

Netbeans installation doesn't find JDK

Set JAVA_HOME in environment variable.

set JAVA_HOME to only JDK1.6.0_23 or whatever jdk folder you have. dont include bin folder in path.

How to make a Div appear on top of everything else on the screen?

Try setting position to absolute, ie.

#yourDiv{
    position: absolute;
    z-index: 10;
};

AngularJS $http, CORS and http authentication

No you don't have to put credentials, You have to put headers on client side eg:

 $http({
        url: 'url of service',
        method: "POST",
        data: {test :  name },
        withCredentials: true,
        headers: {
                    'Content-Type': 'application/json; charset=utf-8'
        }
    });

And and on server side you have to put headers to this is example for nodejs:

/**
 * On all requests add headers
 */
app.all('*', function(req, res,next) {


    /**
     * Response settings
     * @type {Object}
     */
    var responseSettings = {
        "AccessControlAllowOrigin": req.headers.origin,
        "AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name",
        "AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
        "AccessControlAllowCredentials": true
    };

    /**
     * Headers
     */
    res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
    res.header("Access-Control-Allow-Origin",  responseSettings.AccessControlAllowOrigin);
    res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
    res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);

    if ('OPTIONS' == req.method) {
        res.send(200);
    }
    else {
        next();
    }


});

catching stdout in realtime from subprocess

Change the stdout from the rsync process to be unbuffered.

p = subprocess.Popen(cmd,
                     shell=True,
                     bufsize=0,  # 0=unbuffered, 1=line-buffered, else buffer-size
                     stdin=subprocess.PIPE,
                     stderr=subprocess.PIPE,
                     stdout=subprocess.PIPE)

Java - using System.getProperty("user.dir") to get the home directory

Program to get the current working directory=user.dir

public class CurrentDirectoryExample {

    public static void main(String args[]) {

        String current = System.getProperty("user.dir");
        System.out.println("Current working directory in Java : " + current);
    }
}

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

I found this question serval years ago.

recently I tried to "rewrite" the submit method. below is my code

window.onload= function (){
for(var i= 0;i<document.forms.length;i++){
    (function (p){
        var form= document.forms[i];
        var originFn= form.submit;
        form.submit=function (){
            //do something you like
            alert("submitting "+form.id+" using submit method !");
            originFn();
        }
        form.onsubmit= function (){
            alert("submitting "+form.id+" with onsubmit event !");
        }
    })(i);


}

}

<form method="get" action="" id="form1">
<input type="submit" value="??form1" />
<input type="button" name="" id="" value="button????1" onclick="document.forms[0].submit();" /></form>

It did in IE,but failed in other browsers for the same reason as "cletus"

Storing images in SQL Server?

While performance issues are valid the real reasons in practice that you should avoid storing images in a database are for database management reasons. Your database will grow very rapidly and databases cost much more than simple file storage. Database backups and restores are much more expensive and time-consuming than file backup restores. In a pinch, you can restore a smaller database much more quickly than one bloated with images. Compare 1 TB of file storage on Azure to a 1 TB database and you'll see the vast difference in cost.

Plugin with id 'com.google.gms.google-services' not found

apply plugin: 'com.google.gms.google-services'

add above line at the bottom of your app gradle.build.

How can I remove a substring from a given String?

You can use Substring also for replacing with existing string:

var str = "abc awwwa";
var Index = str.indexOf('awwwa');
str = str.substring(0, Index);

How can I get the content of CKEditor using JQuery?

Easy way to get the text inside of the editor or the length of it :)

 var editorText = CKEDITOR.instances['<%= your_editor.ClientID %>'].getData();
 alert(editorText);

 var editorTextLength = CKEDITOR.instances['<%= your_editor.ClientID %>'].getData().length;
 alert(editorTextLength);

What is the best regular expression to check if a string is a valid URL?

Use this one its working for me

function validUrl(Url) {
    var myRegExp  =/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/i;

    if (!RegExp.test(Url.value)) {
        $("#urlErrorLbl").removeClass('highlightNew');
        return false;
    } 

    $("#urlErrorLbl").addClass('highlightNew'); 
    return true; 
}

Caching a jquery ajax response in javascript/browser

cache:true only works with GET and HEAD request.

You could roll your own solution as you said with something along these lines :

var localCache = {
    data: {},
    remove: function (url) {
        delete localCache.data[url];
    },
    exist: function (url) {
        return localCache.data.hasOwnProperty(url) && localCache.data[url] !== null;
    },
    get: function (url) {
        console.log('Getting in cache for url' + url);
        return localCache.data[url];
    },
    set: function (url, cachedData, callback) {
        localCache.remove(url);
        localCache.data[url] = cachedData;
        if ($.isFunction(callback)) callback(cachedData);
    }
};

$(function () {
    var url = '/echo/jsonp/';
    $('#ajaxButton').click(function (e) {
        $.ajax({
            url: url,
            data: {
                test: 'value'
            },
            cache: true,
            beforeSend: function () {
                if (localCache.exist(url)) {
                    doSomething(localCache.get(url));
                    return false;
                }
                return true;
            },
            complete: function (jqXHR, textStatus) {
                localCache.set(url, jqXHR, doSomething);
            }
        });
    });
});

function doSomething(data) {
    console.log(data);
}

Working fiddle here

EDIT: as this post becomes popular, here is an even better answer for those who want to manage timeout cache and you also don't have to bother with all the mess in the $.ajax() as I use $.ajaxPrefilter(). Now just setting {cache: true} is enough to handle the cache correctly :

var localCache = {
    /**
     * timeout for cache in millis
     * @type {number}
     */
    timeout: 30000,
    /** 
     * @type {{_: number, data: {}}}
     **/
    data: {},
    remove: function (url) {
        delete localCache.data[url];
    },
    exist: function (url) {
        return !!localCache.data[url] && ((new Date().getTime() - localCache.data[url]._) < localCache.timeout);
    },
    get: function (url) {
        console.log('Getting in cache for url' + url);
        return localCache.data[url].data;
    },
    set: function (url, cachedData, callback) {
        localCache.remove(url);
        localCache.data[url] = {
            _: new Date().getTime(),
            data: cachedData
        };
        if ($.isFunction(callback)) callback(cachedData);
    }
};

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
    if (options.cache) {
        var complete = originalOptions.complete || $.noop,
            url = originalOptions.url;
        //remove jQuery cache as we have our own localCache
        options.cache = false;
        options.beforeSend = function () {
            if (localCache.exist(url)) {
                complete(localCache.get(url));
                return false;
            }
            return true;
        };
        options.complete = function (data, textStatus) {
            localCache.set(url, data, complete);
        };
    }
});

$(function () {
    var url = '/echo/jsonp/';
    $('#ajaxButton').click(function (e) {
        $.ajax({
            url: url,
            data: {
                test: 'value'
            },
            cache: true,
            complete: doSomething
        });
    });
});

function doSomething(data) {
    console.log(data);
}

And the fiddle here CAREFUL, not working with $.Deferred

Here is a working but flawed implementation working with deferred:

var localCache = {
    /**
     * timeout for cache in millis
     * @type {number}
     */
    timeout: 30000,
    /** 
     * @type {{_: number, data: {}}}
     **/
    data: {},
    remove: function (url) {
        delete localCache.data[url];
    },
    exist: function (url) {
        return !!localCache.data[url] && ((new Date().getTime() - localCache.data[url]._) < localCache.timeout);
    },
    get: function (url) {
        console.log('Getting in cache for url' + url);
        return localCache.data[url].data;
    },
    set: function (url, cachedData, callback) {
        localCache.remove(url);
        localCache.data[url] = {
            _: new Date().getTime(),
            data: cachedData
        };
        if ($.isFunction(callback)) callback(cachedData);
    }
};

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
    if (options.cache) {
        //Here is our identifier for the cache. Maybe have a better, safer ID (it depends on the object string representation here) ?
        // on $.ajax call we could also set an ID in originalOptions
        var id = originalOptions.url+ JSON.stringify(originalOptions.data);
        options.cache = false;
        options.beforeSend = function () {
            if (!localCache.exist(id)) {
                jqXHR.promise().done(function (data, textStatus) {
                    localCache.set(id, data);
                });
            }
            return true;
        };

    }
});

$.ajaxTransport("+*", function (options, originalOptions, jqXHR, headers, completeCallback) {

    //same here, careful because options.url has already been through jQuery processing
    var id = originalOptions.url+ JSON.stringify(originalOptions.data);

    options.cache = false;

    if (localCache.exist(id)) {
        return {
            send: function (headers, completeCallback) {
                completeCallback(200, "OK", localCache.get(id));
            },
            abort: function () {
                /* abort code, nothing needed here I guess... */
            }
        };
    }
});

$(function () {
    var url = '/echo/jsonp/';
    $('#ajaxButton').click(function (e) {
        $.ajax({
            url: url,
            data: {
                test: 'value'
            },
            cache: true
        }).done(function (data, status, jq) {
            console.debug({
                data: data,
                status: status,
                jqXHR: jq
            });
        });
    });
});

Fiddle HERE Some issues, our cache ID is dependent of the json2 lib JSON object representation.

Use Console view (F12) or FireBug to view some logs generated by the cache.

Android, getting resource ID from string?

In your res/layout/my_image_layout.xml

<LinearLayout ...>
    <ImageView
        android:id="@+id/row_0_col_7"
      ...>
    </ImageView>
</LinearLayout>

To grab that ImageView by its @+id value, inside your java code do this:

String row = "0";
String column= "7";
String tileID = "row_" + (row) + "_col_" + (column);
ImageView image = (ImageView) activity.findViewById(activity.getResources()
                .getIdentifier(tileID, "id", activity.getPackageName()));

/*Bottom code changes that ImageView to a different image. "blank" (R.mipmap.blank) is the name of an image I have in my drawable folder. */
image.setImageResource(R.mipmap.blank);  

Does swift have a trim method on String?

**Swift 5**

extension String {

    func trimAllSpace() -> String {
         return components(separatedBy: .whitespacesAndNewlines).joined()
    }
    
    func trimSpace() -> String {
        return self.trimmingCharacters(in: .whitespacesAndNewlines)
    }
}

**Use:**
let result = " abc ".trimAllSpace()
// result == "abc"
let ex = " abc cd  ".trimSpace()
// ex == "abc cd"

JavaScript chop/slice/trim off last character in string

For a number like your example, I would recommend doing this over substring:

_x000D_
_x000D_
console.log(parseFloat('12345.00').toFixed(1));
_x000D_
_x000D_
_x000D_

Do note that this will actually round the number, though, which I would imagine is desired but maybe not:

_x000D_
_x000D_
console.log(parseFloat('12345.46').toFixed(1));
_x000D_
_x000D_
_x000D_

failed to lazily initialize a collection of role

It's possible that you're not fetching the Joined Set. Be sure to include the set in your HQL:

public List<Node> getAll() {
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery("FROM Node as n LEFT JOIN FETCH n.nodeValues LEFT JOIN FETCH n.nodeStats");
    return  query.list();
}

Where your class has 2 sets like:

public class Node implements Serializable {

@OneToMany(fetch=FetchType.LAZY)
private Set<NodeValue> nodeValues;

@OneToMany(fetch=FetchType.LAZY)
private Set<NodeStat> nodeStats;

}

format statement in a string resource file

You should add formatted="false" to your string resource


Here is an example

In your strings.xml :

<string name="all" formatted="false">Amount: %.2f%n  for %d days</string>

In your code:

yourTextView.setText(String.format(getString(R.string.all), 3.12, 2));

JavaScript is in array

I'd use a different data structure, since array seem to be not the best solution.

Instead of array, use an object as a hash-table, like so:

(posted also in jsbin)

var arr = ["x", "y", "z"];
var map = {};
for (var k=0; k < arr.length; ++k) {
  map[arr[k]] = true;
}

function is_in_map(key) {
  try {
    return map[key] === true;
  } catch (e) {
    return false;
  }
}


function print_check(key) {
  console.log(key + " exists? - " + (is_in_map(key) ? "yes" : "no"));
}

print_check("x");
print_check("a");

Console output:

x exists? - yes
a exists? - no

That's a straight-forward solution. If you're more into an object oriented approach, then search Google for "js hashtable".

How do I correct "Commit Failed. File xxx is out of date. xxx path not found."

Had similar problem with the SVN 1.6.5 on Mac 10.6.5, upgraded to SVN 1.6.9 and the commit succeeded.

Convert Python ElementTree to string

Element objects have no .getroot() method. Drop that call, and the .tostring() call works:

xmlstr = ElementTree.tostring(et, encoding='utf8', method='xml')

You only need to use .getroot() if you have an ElementTree instance.

Other notes:

  • This produces a bytestring, which in Python 3 is the bytes type.
    If you must have a str object, you have two options:

    1. Decode the resulting bytes value, from UTF-8: xmlstr.decode("utf8")

    2. Use encoding='unicode'; this avoids an encode / decode cycle:

      xmlstr = ElementTree.tostring(et, encoding='unicode', method='xml')
      
  • If you wanted the UTF-8 encoded bytestring value or are using Python 2, take into account that ElementTree doesn't properly detect utf8 as the standard XML encoding, so it'll add a <?xml version='1.0' encoding='utf8'?> declaration. Use utf-8 or UTF-8 (with a dash) if you want to prevent this. When using encoding="unicode" no declaration header is added.

What is sr-only in Bootstrap 3?

The .sr-only class hides an element to all devices except screen readers:

Skip to main content Combine .sr-only with .sr-only-focusable to show the element again when it is focused

.sr-only {
border: 0 !important;
clip: rect(1px, 1px, 1px, 1px) !important; /* 1 */
-webkit-clip-path: inset(50%) !important;
    clip-path: inset(50%) !important;  /* 2 */
height: 1px !important;
margin: -1px !important;
overflow: hidden !important;
padding: 0 !important;
position: absolute !important;
width: 1px !important;
white-space: nowrap !important;            /* 3 */

}

Output of git branch in tree like fashion

Tested on Ubuntu:

sudo apt install git-extras
git-show-tree

This produces an effect similar to the 2 most upvoted answers here.

Source: http://manpages.ubuntu.com/manpages/bionic/man1/git-show-tree.1.html


Also, if you have arcanist installed (correction: Uber's fork of arcanist installed--see the bottom of this answer here for installation instructions), arc flow shows a beautiful dependency tree of upstream dependencies (ie: which were set previously via arc flow new_branch or manually via git branch --set-upstream-to=upstream_branch).

Bonus git tricks:

Related:

  1. What's the difference between `arc graft` and `arc patch`?

How can I create a simple message box in Python?

On Mac, the python standard library has a module called EasyDialogs. There is also a (ctypes based) windows version at http://www.averdevelopment.com/python/EasyDialogs.html

If it matters to you: it uses native dialogs and doesn't depend on Tkinter like the already mentioned easygui, but it might not have as much features.

What is the use of BindingResult interface in spring MVC?

Basically BindingResult is an interface which dictates how the object that stores the result of validation should store and retrieve the result of the validation(errors, attempt to bind to disallowed fields etc)

From Spring MVC Form Validation with Annotations Tutorial:

[BindingResult] is Spring’s object that holds the result of the validation and binding and contains errors that may have occurred. The BindingResult must come right after the model object that is validated or else Spring will fail to validate the object and throw an exception.

When Spring sees @Valid, it tries to find the validator for the object being validated. Spring automatically picks up validation annotations if you have “annotation-driven” enabled. Spring then invokes the validator and puts any errors in the BindingResult and adds the BindingResult to the view model.

How to detect if a string contains at least a number?

DECLARE @str AS VARCHAR(50)
SET @str = 'PONIES!!...pon1es!!...p0n1es!!'

IF PATINDEX('%[0-9]%', @str) > 0
   PRINT 'YES, The string has numbers'
ELSE
   PRINT 'NO, The string does not have numbers' 

Parse date string and change format

@codeling and @user1767754 : The following two lines will work. I saw no one posted the complete solution for the example problem that was asked. Hopefully this is enough explanation.

import datetime

x = datetime.datetime.strptime("Mon Feb 15 2010", "%a %b %d %Y").strftime("%d/%m/%Y")
print(x)

Output:

15/02/2010

Passing variables in remote ssh command

If you use

ssh [email protected] "~/tools/run_pvt.pl $BUILD_NUMBER"

instead of

ssh [email protected] '~/tools/run_pvt.pl $BUILD_NUMBER'

your shell will interpolate the $BUILD_NUMBER before sending the command string to the remote host.

What is the difference between syntax and semantics in programming languages?

Wikipedia has the answer. Read syntax (programming languages) & semantics (computer science) wikipages.

Or think about the work of any compiler or interpreter. The first step is lexical analysis where tokens are generated by dividing string into lexemes then parsing, which build some abstract syntax tree (which is a representation of syntax). The next steps involves transforming or evaluating these AST (semantics).

Also, observe that if you defined a variant of C where every keyword was transformed into its French equivalent (so if becoming si, do becoming faire, else becoming sinon etc etc...) you would definitely change the syntax of your language, but you won't change much the semantics: programming in that French-C won't be easier!

Ring Buffer in Java

I had the same problem some time ago and was disappointed because I couldn't find any solution that suites my needs so I wrote my own class. Honestly, I did found some code back then, but even that wasn't what I was searching for so I adapted it and now I'm sharing it, just like the author of that piece of code did.

EDIT: This is the original (although slightly different) code: CircularArrayList for java

I don't have the link of the source because it was time ago, but here's the code:

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.RandomAccess;

public class CircularArrayList<E> extends AbstractList<E> implements RandomAccess {

private final int n; // buffer length
private final List<E> buf; // a List implementing RandomAccess
private int leader = 0;
private int size = 0;


public CircularArrayList(int capacity) {
    n = capacity + 1;
    buf = new ArrayList<E>(Collections.nCopies(n, (E) null));
}

public int capacity() {
    return n - 1;
}

private int wrapIndex(int i) {
    int m = i % n;
    if (m < 0) { // modulus can be negative
        m += n;
    }
    return m;
}

@Override
public int size() {
    return this.size;
}

@Override
public E get(int i) {
    if (i < 0 || i >= n-1) throw new IndexOutOfBoundsException();

    if(i > size()) throw new NullPointerException("Index is greater than size.");

    return buf.get(wrapIndex(leader + i));
}

@Override
public E set(int i, E e) {
    if (i < 0 || i >= n-1) {
        throw new IndexOutOfBoundsException();
    }
    if(i == size()) // assume leader's position as invalid (should use insert(e))
        throw new IndexOutOfBoundsException("The size of the list is " + size() + " while the index was " + i
                +". Please use insert(e) method to fill the list.");
    return buf.set(wrapIndex(leader - size + i), e);
}

public void insert(E e)
{
    int s = size();     
    buf.set(wrapIndex(leader), e);
    leader = wrapIndex(++leader);
    buf.set(leader, null);
    if(s == n-1)
        return; // we have replaced the eldest element.
    this.size++;

}

@Override
public void clear()
{
    int cnt = wrapIndex(leader-size());
    for(; cnt != leader; cnt = wrapIndex(++cnt))
        this.buf.set(cnt, null);
    this.size = 0;      
}

public E removeOldest() {
    int i = wrapIndex(leader+1);

    for(;;i = wrapIndex(++i)) {
        if(buf.get(i) != null) break;
        if(i == leader)
            throw new IllegalStateException("Cannot remove element."
                    + " CircularArrayList is empty.");
    }

    this.size--;
    return buf.set(i, null);
}

@Override
public String toString()
{
    int i = wrapIndex(leader - size());
    StringBuilder str = new StringBuilder(size());

    for(; i != leader; i = wrapIndex(++i)){
        str.append(buf.get(i));
    }
    return str.toString();
}

public E getOldest(){
    int i = wrapIndex(leader+1);

    for(;;i = wrapIndex(++i)) {
        if(buf.get(i) != null) break;
        if(i == leader)
            throw new IllegalStateException("Cannot remove element."
                    + " CircularArrayList is empty.");
    }

    return buf.get(i);
}

public E getNewest(){
    int i = wrapIndex(leader-1);
    if(buf.get(i) == null)
        throw new IndexOutOfBoundsException("Error while retrieving the newest element. The Circular Array list is empty.");
    return buf.get(i);
}
}

How do I check if I'm running on Windows in Python?

import platform
is_windows = any(platform.win32_ver())

or

import sys
is_windows = hasattr(sys, 'getwindowsversion')

How to check the Angular version?

  1. ng v
  2. ng --v

you shall see something like the following:

Angular CLI: 7.3.8
Node: 10.15.1
OS: win32 x64
Angular: 5.2.10
... animations, common, compiler, core, forms, http
... platform-browser, platform-browser-dynamic, router

Angular version is in line 4 above

printf a variable in C

Your printf needs a format string:

printf("%d\n", x);

This reference page gives details on how to use printf and related functions.

Python Graph Library

There are two excellent choices:

NetworkX

and

igraph

I like NetworkX, but I read good things about igraph as well. I routinely use NetworkX with graphs with 1 million nodes with no problem (it's about double the overhead of a dict of size V + E)

If you want a feature comparison, see this from the Networkx-discuss list

Feature comparison thread

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

As @Sean said, fcntl() is largely standardized, and therefore available across platforms. The ioctl() function predates fcntl() in Unix, but is not standardized at all. That the ioctl() worked for you across all the platforms of relevance to you is fortunate, but not guaranteed. In particular, the names used for the second argument are arcane and not reliable across platforms. Indeed, they are often unique to the particular device driver that the file descriptor references. (The ioctl() calls used for a bit-mapped graphics device running on an ICL Perq running PNX (Perq Unix) of twenty years ago never translated to anything else anywhere else, for example.)

How to convert from Hex to ASCII in JavaScript?

For completeness sake the reverse function:

function a2hex(str) {
  var arr = [];
  for (var i = 0, l = str.length; i < l; i ++) {
    var hex = Number(str.charCodeAt(i)).toString(16);
    arr.push(hex);
  }
  return arr.join('');
}
a2hex('2460'); //returns 32343630

Strip out HTML and Special Characters

You can do it in one single line :) specially useful for GET or POST requests

$clear = preg_replace('/[^A-Za-z0-9\-]/', '', urldecode($_GET['id']));

What is the easiest way to get the current day of the week in Android?

Calendar.getInstance().get(Calendar.DAY_OF_WEEK)

or

new GregorianCalendar().get(Calendar.DAY_OF_WEEK);

Just the same as in Java, nothing particular to Android.

Selecting Multiple Values from a Dropdown List in Google Spreadsheet

To Add to AlexG's answer, a better and enhanced version of multi-select is found in this following link (which I tried and worked as expected):

https://gist.github.com/coinsandsteeldev/4c67dfa5411e8add913273fc5a30f5e7

For general guidance on setting up a script in Google Sheets, see this quickstart guide.

To use this script:

  1. In your Google Sheet, set up data validation for a cell (or cells), using data from a range. In cell validation, do not select 'Reject input'.
  2. Go to Tools > Script editor...
  3. In the script editor, go to File > New > Script file
  4. Name the file multi-select.gs and paste in the contents of multi-select.gs. File > Save.
  5. In the script editor, go to File > New > Html file Name the file dialog.html and paste in the contents of dialog.html. File > Save.
  6. Back in your spreadsheet, you should now have a new menu called 'Scripts'. Refresh the page if necessary.
  7. Select the cell you want to fill with multiple items from your validation range.
  8. Go to Scripts > Multi-select for this cell... and the sidebar should open, showing a checklist of valid items.
  9. Tick the items you want and click the 'Set' button to fill your cell with those selected items, comma separated.

You can leave the script sidebar open. When you select any cell that has validation, click 'Refresh validation' in the script sidebar to bring up that cell's checklist.

The above mentioned steps are taken from this link

Android studio Error "Unsupported Modules Detected: Compilation is not supported for following modules"

Check in build.gradle in app you have good compile link .I have mistake with this line compile 'com.android.support:support-annotations:x.x.x' delete and work.

jquery select option click handler

its working for me

<select name="" id="select">
    <option value="1"></option>
    <option value="2"></option>
    <option value="3"></option>
</select>

<script>
    $("#select > option").on("click", function () {
       alert(1)
    })
</script>

Cross-reference (named anchor) in markdown

Markdown Anchor supports the hashmark, so a link to an anchor in the page would simply be [Pookie](#pookie)

Generating the anchor is not actually supported in Gruber Markdown, but is in other implementations, such as Markdown Extra.

In Markdown Extra, the anchor ID is appended to a header or subhead with {#pookie}.

Github Flavored Markdown in Git repository pages (but not in Gists) automatically generates anchors with several markup tags on all headers (h1, h2, h3, etc.), including:

  • id="user-content-HEADERTEXT"
  • class="anchor"
  • href="#HEADERTEXT"
  • aria-hidden="true" (this is for an svg link icon that displays on mouseover)

Excluding the aria/svg icon, when one writes:

  • # Header Title

Github generates:

  • <h1><a id="user-content-header-title" class="anchor" href="#header-title">Header Title</a></h1>

Therefore, one need do nothing to create the header links, and can always link to them with:

  • Link to the [Header Title](#header-title)

What is the difference between int, Int16, Int32 and Int64?

Int=Int32 --> Original long type

Int16 --> Original int

Int64 --> New data type become available after 64 bit systems

"int" is only available for backward compatibility. We should be really using new int types to make our programs more precise.

---------------

One more thing I noticed along the way is there is no class named Int similar to Int16, Int32 and Int64. All the helpful functions like TryParse for integer come from Int32.TryParse.