Programs & Examples On #Metalc

Bootstrap Datepicker - Months and Years Only

To view the months of the current year, and only the months, use this format - it only takes the months of that year. It can also be restricted so that a certain number of months is displayed.

<input class="form-control" id="txtDateMMyyyy"  autocomplete="off" required readonly/>

<script>
('#txtDateMMyyyy').datetimepicker({
    format: "mm/yyyy",
    startView: "year",
    minView: "year"
}).datetimepicker("setDate", new Date());
</script>

inner join in linq to entities

var res = from s in Splitting 
          join c in Customer on s.CustomerId equals c.Id
         where c.Id == customrId
            && c.CompanyId == companyId
        select s;

Using Extension methods:

var res = Splitting.Join(Customer,
                 s => s.CustomerId,
                 c => c.Id,
                 (s, c) => new { s, c })
           .Where(sc => sc.c.Id == userId && sc.c.CompanyId == companId)
           .Select(sc => sc.s);

How to check if a .txt file is in ASCII or UTF-8 format in Windows environment?

Open it in a hex editor and make sure that the first three bytes are a UTF8 BOM (EF BB BF)

Convert string to BigDecimal in java

May I add something. If you are using currency you should use Scale(2), and you should probably figure out a round method.

Xamarin.Forms ListView: Set the highlight color of a tapped item

Here is the purely cross platform and neat way:

1) Define a trigger action

namespace CustomTriggers {
   public class DeselectListViewItemAction:TriggerAction<ListView> {
       protected override void Invoke(ListView sender) {
                sender.SelectedItem = null;
       }
   }
}

2) Apply the above class instance as an EventTrigger action in XAML as below

 <ListView x:Name="YourListView" ItemsSource="{Binding ViewModelItems}">
    <ListView.Triggers>
        <EventTrigger Event="ItemSelected">
            <customTriggers:DeselectListViewItemAction></customTriggers:DeselectListViewItemAction>
        </EventTrigger>
    </ListView.Triggers>
</ListView>

Don't forget to add xmlns:customTriggers="clr-namespace:CustomTriggers;assembly=ProjectAssembly"

Note: Because none of your items are in selected mode, selection styling will not get applied on either of the platforms.

ImportError: No module named enum

Or run a pip install --upgrade pip enum34

How can I compare strings in C using a `switch` statement?

I have published a header file to perform the switch on the strings in C. It contains a set of macro that hide the call to the strcmp() (or similar) in order to mimic a switch-like behaviour. I have tested it only with GCC in Linux, but I'm quite sure that it can be adapted to support other environment.

EDIT: added the code here, as requested

This is the header file you should include:

#ifndef __SWITCHS_H__
#define __SWITCHS_H__

#include <string.h>
#include <regex.h>
#include <stdbool.h>

/** Begin a switch for the string x */
#define switchs(x) \
    { char *__sw = (x); bool __done = false; bool __cont = false; \
        regex_t __regex; regcomp(&__regex, ".*", 0); do {

/** Check if the string matches the cases argument (case sensitive) */
#define cases(x)    } if ( __cont || !strcmp ( __sw, x ) ) \
                        { __done = true; __cont = true;

/** Check if the string matches the icases argument (case insensitive) */
#define icases(x)    } if ( __cont || !strcasecmp ( __sw, x ) ) { \
                        __done = true; __cont = true;

/** Check if the string matches the specified regular expression using regcomp(3) */
#define cases_re(x,flags) } regfree ( &__regex ); if ( __cont || ( \
                              0 == regcomp ( &__regex, x, flags ) && \
                              0 == regexec ( &__regex, __sw, 0, NULL, 0 ) ) ) { \
                                __done = true; __cont = true;

/** Default behaviour */
#define defaults    } if ( !__done || __cont ) {

/** Close the switchs */
#define switchs_end } while ( 0 ); regfree(&__regex); }

#endif // __SWITCHS_H__

And this is how you use it:

switchs(argv[1]) {
    cases("foo")
    cases("bar")
        printf("foo or bar (case sensitive)\n");
        break;

    icases("pi")
        printf("pi or Pi or pI or PI (case insensitive)\n");
        break;

    cases_re("^D.*",0)
        printf("Something that start with D (case sensitive)\n");
        break;

    cases_re("^E.*",REG_ICASE)
        printf("Something that start with E (case insensitive)\n");
        break;

    cases("1")
        printf("1\n");
        // break omitted on purpose

    cases("2")
        printf("2 (or 1)\n");
        break;

    defaults
        printf("No match\n");
        break;
} switchs_end;

Compare object instances for equality by their attributes

As a summary :

  1. It's advised to implement __eq__ rather than __cmp__, except if you run python <= 2.0 (__eq__ has been added in 2.1)
  2. Don't forget to also implement __ne__ (should be something like return not self.__eq__(other) or return not self == other except very special case)
  3. Don`t forget that the operator must be implemented in each custom class you want to compare (see example below).
  4. If you want to compare with object that can be None, you must implement it. The interpreter cannot guess it ... (see example below)

    class B(object):
      def __init__(self):
        self.name = "toto"
      def __eq__(self, other):
        if other is None:
          return False
        return self.name == other.name
    
    class A(object):
      def __init__(self):
        self.toto = "titi"
        self.b_inst = B()
      def __eq__(self, other):
        if other is None:
          return False
        return (self.toto, self.b_inst) == (other.toto, other.b_inst)
    

How large is a DWORD with 32- and 64-bit code?

No ... on all Windows platforms DWORD is 32 bits. LONGLONG or LONG64 is used for 64 bit types.

ReferenceError: Invalid left-hand side in assignment

The same happened for me with eslint module. EsLinter throw Parsing error: Invalid left-hand side in assignment expression for await in second if statement.

if (condition_one) {
  let result = await myFunction()
}

if (condition_two) {
  let result = await myFunction() // eslint parsing error
}

As strange as it sounds what fixed this error was to add ; semicolon at the end of line where await occurred.

if (condition_one) {
  let result = await myFunction();
}

if (condition_two) {
  let result = await myFunction();
}

What is the default value for enum variable?

It is whatever member of the enumeration represents the value 0. Specifically, from the documentation:

The default value of an enum E is the value produced by the expression (E)0.

As an example, take the following enum:

enum E
{
    Foo, Bar, Baz, Quux
}

Without overriding the default values, printing default(E) returns Foo since it's the first-occurring element.

However, it is not always the case that 0 of an enum is represented by the first member. For example, if you do this:

enum F
{
    // Give each element a custom value
    Foo = 1, Bar = 2, Baz = 3, Quux = 0
}

Printing default(F) will give you Quux, not Foo.

If none of the elements in an enum G correspond to 0:

enum G
{
    Foo = 1, Bar = 2, Baz = 3, Quux = 4
}

default(G) returns literally 0, although its type remains as G (as quoted by the docs above, a cast to the given enum type).

Bootstrap modal - close modal when "call to action" button is clicked

Use data-dismiss="modal". In the version of Bootstrap I am using v3.3.5, when data-dismiss="modal" is added to the desired button like shown below it calls my external Javascript (JQuery) function beautifully and magically closes the modal. Its soo Sweet, I was worried I would have to call some modal hide in another function and chain that to the real working function

 <a href="#" id="btnReleaseAll" class="btn btn-primary btn-default btn-small margin-right pull-right" data-dismiss="modal">Yes</a>

In some external script file, and in my doc ready there is of course a function for the click of that identifier ID

 $("#divExamListHeader").on('click', '#btnReleaseAll', function () {
               // Do DatabaseMagic Here for a call a MVC ActionResult

How can I avoid getting this MySQL error Incorrect column specifier for column COLUMN NAME?

To use AUTO_INCREMENT you need to deifne column as INT or floating-point types, not CHAR.

AUTO_INCREMENT use only unsigned value, so it's good to use UNSIGNED as well;

CREATE TABLE discussion_topics (

     topic_id INT NOT NULL unsigned AUTO_INCREMENT,
     project_id char(36) NOT NULL,
     topic_subject VARCHAR(255) NOT NULL,
     topic_content TEXT default NULL,
     date_created DATETIME NOT NULL,
     date_last_post DATETIME NOT NULL,
     created_by_user_id char(36) NOT NULL,
     last_post_user_id char(36) NOT NULL,
     posts_count char(36) default NULL,
     PRIMARY KEY (topic_id) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

Order by in Inner Join

You have to sort it if you want the data to come back a certain way. When you say you are expecting "Mohit" to be the first row, I am assuming you say that because "Mohit" is the first row in the [One] table. However, when SQL Server joins tables, it doesn't necessarily join in the order you think.

If you want the first row from [One] to be returned, then try sorting by [One].[ID]. Alternatively, you can order by any other column.

Forward slash in Java Regex

The problem is actually that you need to double-escape backslashes in the replacement string. You see, "\\/" (as I'm sure you know) means the replacement string is \/, and (as you probably don't know) the replacement string \/ actually just inserts /, because Java is weird, and gives \ a special meaning in the replacement string. (It's supposedly so that \$ will be a literal dollar sign, but I think the real reason is that they wanted to mess with people. Other languages don't do it this way.) So you have to write either:

"Hello/You/There".replaceAll("/", "\\\\/");

or:

"Hello/You/There".replaceAll("/", Matcher.quoteReplacement("\\/"));

(Using java.util.regex.Matcher.quoteReplacement(String).)

Vertical Menu in Bootstrap

Responsive utility classes

Easiest way I can think of is to have a vertical left menu AND the collapsing Top Nav in your design and attach/use bootstraps responsive css.

Then just add classes of hidden phone, tablet etc (to suit) to your left nav and hidden desktop etc to the top nav

see: http://twitter.github.com/bootstrap/scaffolding.html#responsive

play around with that and hopefully it should be able to do what you want

How to run multiple Python versions on Windows

  1. install python

    • C:\Python27
    • C:\Python36
  2. environment variable

    • PYTHON2_HOME: C:\Python27
    • PYTHON3_HOME: C:\Python36
    • Path: %PYTHON2_HOME%;%PYTHON2_HOME%\Scripts;%PYTHON3_HOME%;%PYTHON3_HOME%\Scripts;
  3. file rename

    • C:\Python27\python.exe ? C:\Python27\python2.exe
    • C:\Python36\python.exe ? C:\Python36\python3.exe
  4. pip

    • python2 -m pip install package
    • python3 -m pip install package

How/When does Execute Shell mark a build as failure in Jenkins?

First things first, hover the mouse over the grey area below. Not part of the answer, but absolutely has to be said:

If you have a shell script that does "checkout, build, deploy" all by itself, then why are you using Jenkins? You are foregoing all the features of Jenkins that make it what it is. You might as well have a cron or an SVN post-commit hook call the script directly. Jenkins performing the SVN checkout itself is crucial. It allows the builds to be triggered only when there are changes (or on timer, or manual, if you prefer). It keeps track of changes between builds. It shows those changes, so you can see which build was for which set of changes. It emails committers when their changes caused successful or failed build (again, as configured as you prefer). It will email committers when their fixes fixed the failing build. And more and more. Jenkins archiving the artifacts also makes them available, per build, straight off Jenkins. While not as crucial as the SVN checkout, this is once again an integral part of what makes it Jenkins. Same with deploying. Unless you have a single environment, deployment usually happens to multiple environments. Jenkins can keep track of which environment a specific build (with specific set of SVN changes) is deployed it, through the use of Promotions. You are foregoing all of this. It sounds like you are told "you have to use Jenkins" but you don't really want to, and you are doing it just to get your bosses off your back, just to put a checkmark "yes, I've used Jenkins"

The short answer is: the exit code of last command of the Jenkin's Execute Shell build step is what determines the success/failure of the Build Step. 0 - success, anything else - failure. Note, this is determining the success/failure of the build step, not the whole job run. The success/failure of the whole job run can further be affected by multiple build steps, and post-build actions and plugins.

You've mentioned Build step 'Execute shell' marked build as failure, so we will focus just on a single build step. If your Execute shell build step only has a single line that calls your shell script, then the exit code of your shell script will determine the success/failure of the build step. If you have more lines, after your shell script execution, then carefully review them, as they are the ones that could be causing failure.

Finally, have a read here Jenkins Build Script exits after Google Test execution. It is not directly related to your question, but note that part about Jenkins launching the Execute Shell build step, as a shell script with /bin/sh -xe

The -e means that the shell script will exit with failure, even if just 1 command fails, even if you do error checking for that command (because the script exits before it gets to your error checking). This is contrary to normal execution of shell scripts, which usually print the error message for the failed command (or redirect it to null and handle it by other means), and continue.

To circumvent this, add set +e to the top of your shell script.

Since you say your script does all it is supposed to do, chances are the failing command is somewhere at the end of the script. Maybe a final echo? Or copy of artifacts somewhere? Without seeing the full console output, we are just guessing.

Please post the job run's console output, and preferably the shell script itself too, and then we could tell you exactly which line is failing.

Python BeautifulSoup extract text between element

The BeautifulSoup documentation provides an example about removing objects from a document using the extract method. In the following example the aim is to remove all comments from the document:

Removing Elements

Once you have a reference to an element, you can rip it out of the tree with the extract method. This code removes all the comments from a document:

from BeautifulSoup import BeautifulSoup, Comment
soup = BeautifulSoup("""1<!--The loneliest number-->
                    <a>2<!--Can be as bad as one--><b>3""")
comments = soup.findAll(text=lambda text:isinstance(text, Comment))
[comment.extract() for comment in comments]
print soup
# 1
# <a>2<b>3</b></a>

Crystal Reports 13 And Asp.Net 3.5

I had this same problem and resolved it by making sure all references to the previous version of crystal from the Web Config file, the server, and the publishing workstation were removed. Other than the full trust basically everything that user707217 did, I did and it worked for my upgraded Web application

extract part of a string using bash/cut/split

Using a single Awk:

... | awk -F '[/:]' '{print $5}'

That is, using as field separator either / or :, the username is always in field 5.

To store it in a variable:

username=$(... | awk -F '[/:]' '{print $5}')

A more flexible implementation with sed that doesn't require username to be field 5:

... | sed -e s/:.*// -e s?.*/??

That is, delete everything from : and beyond, and then delete everything up until the last /. sed is probably faster too than awk, so this alternative is definitely better.

How to create a simple http proxy in node.js?

Here's a proxy server using request that handles redirects. Use it by hitting your proxy URL http://domain.com:3000/?url=[your_url]

var http = require('http');
var url = require('url');
var request = require('request');

http.createServer(onRequest).listen(3000);

function onRequest(req, res) {

    var queryData = url.parse(req.url, true).query;
    if (queryData.url) {
        request({
            url: queryData.url
        }).on('error', function(e) {
            res.end(e);
        }).pipe(res);
    }
    else {
        res.end("no url found");
    }
}

Show/hide image with JavaScript

You can do this with jquery just visit http://jquery.com/ to get the link then do something like this

<a id="show_image">Show Image</a>
<img id="my_images" style="display:none" src="http://myimages.com/img.png">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $('#show_image').on("click", function(){
         $('#my_images').show('slow');
      });
   });
</script>

or if you would like the link to turn the image on and off do this

<a id="show_image">Show Image</a>
<img id="my_images" style="display:none;" src="http://myimages.com/img.png">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $('#show_image').on("click", function(){
         $('#my_images').toggle();
      });
   });
</script>

How can I comment a single line in XML?

No, there is no way to comment a line in XML and have the comment end automatically on a linebreak.

XML has only one definition for a comment:

'<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'

XML forbids -- in comments to maintain compatibility with SGML.

How to sort an array of objects in Java?

public class Student implements Comparable<Student> {

    private int sid;
    private String sname;

    public Student(int sid, String sname) {
        super();
        this.sid = sid;
        this.sname = sname;
    }

    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    @Override
    public String toString() {
        return "Student [sid=" + sid + ", sname=" + sname + "]";
    }

    public int compareTo(Student o) {
        if (this.getSname().compareTo(o.getSname()) > 1) {
            return toString().compareTo(o.getSname());
        } else if (this.getSname().compareTo(o.getSname()) < 1) {
            return toString().compareTo(o.getSname());
        }
        return 0;
    }

}

What are the alternatives now that the Google web search API has been deprecated?

Here is an option at the bottom of the Custom Search Control Panel: "Sites to search", you can choose "Search the entire web but emphasize included sites"

Custom Search Control Panel - Sites to search

Codeigniter $this->db->get(), how do I return values for a specific row?

you can use row() instead of result().

$this->db->where('id', '3');
$q = $this->db->get('my_users_table')->row();

How to search a specific value in all tables (PostgreSQL)?

If you're using IntelliJ add your DB to Database view then right click on databases and select full text search, it will list all tables and all fields for your specific text.

passing JSON data to a Spring MVC controller

You can stringify the JSON Object with JSON.stringify(jsonObject) and receive it on controller as String.

In the Controller, you can use the javax.json to convert and manipulate this.

Download and add the .jar to the project libs and import the JsonObject.

To create an json object, you can use

JsonObjectBuilder job = Json.createObjectBuilder();
job.add("header1", foo1);
job.add("header2", foo2);
JsonObject json = job.build();

To read it from String, you can use

JsonReader jr = Json.createReader(new StringReader(jsonString));
JsonObject json = jsonReader.readObject();
jsonReader.close();

HTML/CSS--Creating a banner/header

You have a type-o:

its: height: 200x;

and it should be: height: 200px; also check the image url; it should be in the same directory it seems.

Also, dont use 'px' at null (aka '0') values. 0px, 0em, 0% is still 0. :)

top: 0px;

is the same with:

top: 0;

Good Luck!

How to change an application icon programmatically in Android?

To get the solution by Markus working I needed the first Intent so be:

Intent myLauncherIntent = new Intent(Intent.ACTION_MAIN);
            myLauncherIntent.setClassName(this,  this.getClass().getName());
            myLauncherIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

reading from stdin in c++

You have not defined the variable input_line.

Add this:

string input_line;

And add this include.

#include <string>

Here is the full example. I also removed the semi-colon after the while loop, and you should have getline inside the while to properly detect the end of the stream.

#include <iostream>
#include <string>

int main() {
    for (std::string line; std::getline(std::cin, line);) {
        std::cout << line << std::endl;
    }
    return 0;
}

Overlay normal curve to histogram in R

This is an implementation of aforementioned StanLe's anwer, also fixing the case where his answer would produce no curve when using densities.

This replaces the existing but hidden hist.default() function, to only add the normalcurve parameter (which defaults to TRUE).

The first three lines are to support roxygen2 for package building.

#' @noRd
#' @exportMethod hist.default
#' @export
hist.default <- function(x,
                         breaks = "Sturges",
                         freq = NULL,
                         include.lowest = TRUE,
                         normalcurve = TRUE,
                         right = TRUE,
                         density = NULL,
                         angle = 45,
                         col = NULL,
                         border = NULL,
                         main = paste("Histogram of", xname),
                         ylim = NULL,
                         xlab = xname,
                         ylab = NULL,
                         axes = TRUE,
                         plot = TRUE,
                         labels = FALSE,
                         warn.unused = TRUE,
                         ...)  {

  # https://stackoverflow.com/a/20078645/4575331
  xname <- paste(deparse(substitute(x), 500), collapse = "\n")

  suppressWarnings(
    h <- graphics::hist.default(
      x = x,
      breaks = breaks,
      freq = freq,
      include.lowest = include.lowest,
      right = right,
      density = density,
      angle = angle,
      col = col,
      border = border,
      main = main,
      ylim = ylim,
      xlab = xlab,
      ylab = ylab,
      axes = axes,
      plot = plot,
      labels = labels,
      warn.unused = warn.unused,
      ...
    )
  )

  if (normalcurve == TRUE & plot == TRUE) {
    x <- x[!is.na(x)]
    xfit <- seq(min(x), max(x), length = 40)
    yfit <- dnorm(xfit, mean = mean(x), sd = sd(x))
    if (isTRUE(freq) | (is.null(freq) & is.null(density))) {
      yfit <- yfit * diff(h$mids[1:2]) * length(x)
    }
    lines(xfit, yfit, col = "black", lwd = 2)
  }

  if (plot == TRUE) {
    invisible(h)
  } else {
    h
  }
}

Quick example:

hist(g)

enter image description here

For dates it's bit different. For reference:

#' @noRd
#' @exportMethod hist.Date
#' @export
hist.Date <- function(x,
                      breaks = "months",
                      format = "%b",
                      normalcurve = TRUE,
                      xlab = xname,
                      plot = TRUE,
                      freq = NULL,
                      density = NULL,
                      start.on.monday = TRUE,
                      right = TRUE,
                      ...)  {

  # https://stackoverflow.com/a/20078645/4575331
  xname <- paste(deparse(substitute(x), 500), collapse = "\n")

  suppressWarnings(
    h <- graphics:::hist.Date(
      x = x,
      breaks = breaks,
      format = format,
      freq = freq,
      density = density,
      start.on.monday = start.on.monday,
      right = right,
      xlab = xlab,
      plot = plot,
      ...
    )
  )

  if (normalcurve == TRUE & plot == TRUE) {
    x <- x[!is.na(x)]
    xfit <- seq(min(x), max(x), length = 40)
    yfit <- dnorm(xfit, mean = mean(x), sd = sd(x))
    if (isTRUE(freq) | (is.null(freq) & is.null(density))) {
      yfit <- as.double(yfit) * diff(h$mids[1:2]) * length(x)
    }
    lines(xfit, yfit, col = "black", lwd = 2)
  }

  if (plot == TRUE) {
    invisible(h)
  } else {
    h
  }
}

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

Methods for Aligning Flex Items along the Main Axis

As stated in the question:

To align flex items along the main axis there is one property: justify-content

To align flex items along the cross axis there are three properties: align-content, align-items and align-self.

The question then asks:

Why are there no justify-items and justify-self properties?

One answer may be: Because they're not necessary.

The flexbox specification provides two methods for aligning flex items along the main axis:

  1. The justify-content keyword property, and
  2. auto margins

justify-content

The justify-content property aligns flex items along the main axis of the flex container.

It is applied to the flex container but only affects flex items.

There are five alignment options:

  • flex-start ~ Flex items are packed toward the start of the line.

    enter image description here

  • flex-end ~ Flex items are packed toward the end of the line.

    enter image description here

  • center ~ Flex items are packed toward the center of the line.

    enter image description here

  • space-between ~ Flex items are evenly spaced, with the first item aligned to one edge of the container and the last item aligned to the opposite edge. The edges used by the first and last items depends on flex-direction and writing mode (ltr or rtl).

    enter image description here

  • space-around ~ Same as space-between except with half-size spaces on both ends.

    enter image description here


Auto Margins

With auto margins, flex items can be centered, spaced away or packed into sub-groups.

Unlike justify-content, which is applied to the flex container, auto margins go on flex items.

They work by consuming all free space in the specified direction.


Align group of flex items to the right, but first item to the left

Scenario from the question:

  • making a group of flex items align-right (justify-content: flex-end) but have the first item align left (justify-self: flex-start)

    Consider a header section with a group of nav items and a logo. With justify-self the logo could be aligned left while the nav items stay far right, and the whole thing adjusts smoothly ("flexes") to different screen sizes.

enter image description here

enter image description here


Other useful scenarios:

enter image description here

enter image description here

enter image description here


Place a flex item in the corner

Scenario from the question:

  • placing a flex item in a corner .box { align-self: flex-end; justify-self: flex-end; }

enter image description here


Center a flex item vertically and horizontally

enter image description here

margin: auto is an alternative to justify-content: center and align-items: center.

Instead of this code on the flex container:

.container {
    justify-content: center;
    align-items: center;
}

You can use this on the flex item:

.box56 {
    margin: auto;
}

This alternative is useful when centering a flex item that overflows the container.


Center a flex item, and center a second flex item between the first and the edge

A flex container aligns flex items by distributing free space.

Hence, in order to create equal balance, so that a middle item can be centered in the container with a single item alongside, a counterbalance must be introduced.

In the examples below, invisible third flex items (boxes 61 & 68) are introduced to balance out the "real" items (box 63 & 66).

enter image description here

enter image description here

Of course, this method is nothing great in terms of semantics.

Alternatively, you can use a pseudo-element instead of an actual DOM element. Or you can use absolute positioning. All three methods are covered here: Center and bottom-align flex items

NOTE: The examples above will only work – in terms of true centering – when the outermost items are equal height/width. When flex items are different lengths, see next example.


Center a flex item when adjacent items vary in size

Scenario from the question:

  • in a row of three flex items, affix the middle item to the center of the container (justify-content: center) and align the adjacent items to the container edges (justify-self: flex-start and justify-self: flex-end).

    Note that values space-around and space-between on justify-content property will not keep the middle item centered in relation to the container if the adjacent items have different widths (see demo).

As noted, unless all flex items are of equal width or height (depending on flex-direction), the middle item cannot be truly centered. This problem makes a strong case for a justify-self property (designed to handle the task, of course).

_x000D_
_x000D_
#container {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  background-color: lightyellow;_x000D_
}_x000D_
.box {_x000D_
  height: 50px;_x000D_
  width: 75px;_x000D_
  background-color: springgreen;_x000D_
}_x000D_
.box1 {_x000D_
  width: 100px;_x000D_
}_x000D_
.box3 {_x000D_
  width: 200px;_x000D_
}_x000D_
#center {_x000D_
  text-align: center;_x000D_
  margin-bottom: 5px;_x000D_
}_x000D_
#center > span {_x000D_
  background-color: aqua;_x000D_
  padding: 2px;_x000D_
}
_x000D_
<div id="center">_x000D_
  <span>TRUE CENTER</span>_x000D_
</div>_x000D_
_x000D_
<div id="container">_x000D_
  <div class="box box1"></div>_x000D_
  <div class="box box2"></div>_x000D_
  <div class="box box3"></div>_x000D_
</div>_x000D_
_x000D_
<p>The middle box will be truly centered only if adjacent boxes are equal width.</p>
_x000D_
_x000D_
_x000D_

Here are two methods for solving this problem:

Solution #1: Absolute Positioning

The flexbox spec allows for absolute positioning of flex items. This allows for the middle item to be perfectly centered regardless of the size of its siblings.

Just keep in mind that, like all absolutely positioned elements, the items are removed from the document flow. This means they don't take up space in the container and can overlap their siblings.

In the examples below, the middle item is centered with absolute positioning and the outer items remain in-flow. But the same layout can be achieved in reverse fashion: Center the middle item with justify-content: center and absolutely position the outer items.

enter image description here

Solution #2: Nested Flex Containers (no absolute positioning)

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
}_x000D_
.box {_x000D_
  flex: 1;_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
}_x000D_
.box71 > span { margin-right: auto; }_x000D_
.box73 > span { margin-left: auto;  }_x000D_
_x000D_
/* non-essential */_x000D_
.box {_x000D_
  align-items: center;_x000D_
  border: 1px solid #ccc;_x000D_
  background-color: lightgreen;_x000D_
  height: 40px;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box box71"><span>71 short</span></div>_x000D_
  <div class="box box72"><span>72 centered</span></div>_x000D_
  <div class="box box73"><span>73 loooooooooooooooong</span></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here's how it works:

  • The top-level div (.container) is a flex container.
  • Each child div (.box) is now a flex item.
  • Each .box item is given flex: 1 in order to distribute container space equally.
  • Now the items are consuming all space in the row and are equal width.
  • Make each item a (nested) flex container and add justify-content: center.
  • Now each span element is a centered flex item.
  • Use flex auto margins to shift the outer spans left and right.

You could also forgo justify-content and use auto margins exclusively.

But justify-content can work here because auto margins always have priority. From the spec:

8.1. Aligning with auto margins

Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.


justify-content: space-same (concept)

Going back to justify-content for a minute, here's an idea for one more option.

  • space-same ~ A hybrid of space-between and space-around. Flex items are evenly spaced (like space-between), except instead of half-size spaces on both ends (like space-around), there are full-size spaces on both ends.

This layout can be achieved with ::before and ::after pseudo-elements on the flex container.

enter image description here

(credit: @oriol for the code, and @crl for the label)

UPDATE: Browsers have begun implementing space-evenly, which accomplishes the above. See this post for details: Equal space between flex items


PLAYGROUND (includes code for all examples above)

Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+)

There are two ways to do it.

  1. In the method that opens the dialog, pass in the following configuration option disableClose as the second parameter in MatDialog#open() and set it to true:

    export class AppComponent {
      constructor(private dialog: MatDialog){}
      openDialog() {
        this.dialog.open(DialogComponent, { disableClose: true });
      }
    }
    
  2. Alternatively, do it in the dialog component itself.

    export class DialogComponent {
      constructor(private dialogRef: MatDialogRef<DialogComponent>){
        dialogRef.disableClose = true;
      }
    }
    

Here's what you're looking for:

<code>disableClose</code> property in material.angular.io

And here's a Stackblitz demo


Other use cases

Here's some other use cases and code snippets of how to implement them.

Allow esc to close the dialog but disallow clicking on the backdrop to close the dialog

As what @MarcBrazeau said in the comment below my answer, you can allow the esc key to close the modal but still disallow clicking outside the modal. Use this code on your dialog component:

import { Component, OnInit, HostListener } from '@angular/core';
import { MatDialogRef } from '@angular/material';
@Component({
  selector: 'app-third-dialog',
  templateUrl: './third-dialog.component.html'
})
export class ThirdDialogComponent {
  constructor(private dialogRef: MatDialogRef<ThirdDialogComponent>) {      
}
  @HostListener('window:keyup.esc') onKeyUp() {
    this.dialogRef.close();
  }

}

Prevent esc from closing the dialog but allow clicking on the backdrop to close

P.S. This is an answer which originated from this answer, where the demo was based on this answer.

To prevent the esc key from closing the dialog but allow clicking on the backdrop to close, I've adapted Marc's answer, as well as using MatDialogRef#backdropClick to listen for click events to the backdrop.

Initially, the dialog will have the configuration option disableClose set as true. This ensures that the esc keypress, as well as clicking on the backdrop will not cause the dialog to close.

Afterwards, subscribe to the MatDialogRef#backdropClick method (which emits when the backdrop gets clicked and returns as a MouseEvent).

Anyways, enough technical talk. Here's the code:

openDialog() {
  let dialogRef = this.dialog.open(DialogComponent, { disableClose: true });
  /*
     Subscribe to events emitted when the backdrop is clicked
     NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
     See https://stackoverflow.com/a/41086381 for more info
  */
  dialogRef.backdropClick().subscribe(() => {
    // Close the dialog
    dialogRef.close();
  })

  // ...
}

Alternatively, this can be done in the dialog component:

export class DialogComponent {
  constructor(private dialogRef: MatDialogRef<DialogComponent>) {
    dialogRef.disableClose = true;
    /*
      Subscribe to events emitted when the backdrop is clicked
      NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
      See https://stackoverflow.com/a/41086381 for more info
    */
    dialogRef.backdropClick().subscribe(() => {
      // Close the dialog
      dialogRef.close();
    })
  }
}

How can you profile a Python script?

A nice profiling module is the line_profiler (called using the script kernprof.py). It can be downloaded here.

My understanding is that cProfile only gives information about total time spent in each function. So individual lines of code are not timed. This is an issue in scientific computing since often one single line can take a lot of time. Also, as I remember, cProfile didn't catch the time I was spending in say numpy.dot.

PHP sessions that have already been started

Only if you want to destroy previous session :

<?php
    if(!isset($_SESSION)) 
    { 
        session_start(); 
    }
    else
    {
        session_destroy();
        session_start(); 
    }
?>

or you can use

unset($_SESSION['variable_session _data'])

to destroy a particular session variable.

Redirecting a request using servlets and the "setHeader" method not working

Another way of doing this if you want to redirect to any url source after the specified point of time

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.*;

public class MyServlet extends HttpServlet


{

public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException

{

response.setContentType("text/html");

PrintWriter pw=response.getWriter();

pw.println("<b><centre>Redirecting to Google<br>");


response.setHeader("refresh,"5;https://www.google.com/"); // redirects to url  after 5 seconds


pw.close();
}

}

How to export html table to excel or pdf in php

<script src="jquery.min.js"></script>
<table border="1" id="ReportTable" class="myClass">
    <tr bgcolor="#CCC">
      <td width="100">xxxxx</td>
      <td width="700">xxxxxx</td>
      <td width="170">xxxxxx</td>
      <td width="30">xxxxxx</td>
    </tr>
    <tr bgcolor="#FFFFFF">
      <td><?php                 
            $date = date_create($row_Recordset3['fecha']);
            echo date_format($date, 'd-m-Y');
            ?></td>
      <td><?php echo $row_Recordset3['descripcion']; ?></td>
      <td><?php echo $row_Recordset3['producto']; ?></td>
      <td><img src="borrar.png" width="14" height="14" class="clickable" onClick="eliminarSeguimiento(<?php echo $row_Recordset3['idSeguimiento']; ?>)" title="borrar"></td>
    </tr>
  </table>

  <input type="hidden" id="datatodisplay" name="datatodisplay">  
    <input type="submit" value="Export to Excel"> 

exporttable.php

<?php
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename=export.xls');
// Fix for crappy IE bug in download.
header("Pragma: ");
header("Cache-Control: ");
echo $_REQUEST['datatodisplay'];
?>

How to return a boolean method in java?

You can also do this, for readability's sake

boolean passwordVerified=(pword.equals(pwdRetypePwd.getText());

if(!passwordVerified ){
    txtaError.setEditable(true);
    txtaError.setText("*Password didn't match!");
    txtaError.setForeground(Color.red);
    txtaError.setEditable(false);
}else{
    addNewUser();
}
return passwordVerified;

What is the GAC in .NET?

Global Assembly Cache

Each computer where the common language runtime is installed has a machine-wide code cache called the global assembly cache. The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer.

You should share assemblies by installing them into the global assembly cache only when you need to. As a general guideline, keep assembly dependencies private, and locate assemblies in the application directory unless sharing an assembly is explicitly required. In addition, it is not necessary to install assemblies into the global assembly cache to make them accessible to COM interop or unmanaged code.

The things MSDN contains may surprise you... you can usually read it like an article. The straightforward and most important bits at the top, the intricate details deeper down. It certainly explains it better than I could.

Note that Visual Studio displays all the DLLs in the GAC in the .NET tab of the References window. (Right-click on a project in Solution Explorer and select Add Reference.) This should give you a more tangeable idea.

Scroll Automatically to the Bottom of the Page

You can use this function wherever you need to call it:

function scroll_to(div){
   if (div.scrollTop < div.scrollHeight - div.clientHeight)
        div.scrollTop += 10; // move down

}

jquery.com: ScrollTo

PHP add elements to multidimensional array with array_push

As in the multi-dimensional array an entry is another array, specify the index of that value to array_push:

array_push($md_array['recipe_type'], $newdata);

You seem to not be depending on "@angular/core". This is an error

**You should be in the newly created YOUR_APP folder before you hit the ng serve command **

Lets start from fresh,

1) install npm

2) create a new angular app ( ng new <YOUR_APP_NAME> )

3) go to app folder (cd YOUR_APP_NAME)

4) ng serve

I hope it will resolve the issue.

Ubuntu says "bash: ./program Permission denied"

Sounds like you don't have the execute flag set on the file permissions, try:

chmod u+x program_name

Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

I had this, but, it was because I had added a NuGet package that had updated the binding redirects. Once I removed the package, the redirects were still there. I removed all of them, and then ran update-package -reinstall. This added the correct redirects.

How to change default text file encoding in Eclipse?

Window -> Preferences -> General -> Workspace : Text file encoding

Checkout another branch when there are uncommitted changes on the current branch

You have two choices: stash your changes:

git stash

then later to get them back:

git stash apply

or put your changes on a branch so you can get the remote branch and then merge your changes onto it. That's one of the greatest things about git: you can make a branch, commit to it, then fetch other changes on to the branch you were on.

You say it doesn't make any sense, but you are only doing it so you can merge them at will after doing the pull. Obviously your other choice is to commit on your copy of the branch and then do the pull. The presumption is you either don't want to do that (in which case I am puzzled that you don't want a branch) or you are afraid of conflicts.

Why is printing "B" dramatically slower than printing "#"?

Pure speculation is that you're using a terminal that attempts to do word-wrapping rather than character-wrapping, and treats B as a word character but # as a non-word character. So when it reaches the end of a line and searches for a place to break the line, it sees a # almost immediately and happily breaks there; whereas with the B, it has to keep searching for longer, and may have more text to wrap (which may be expensive on some terminals, e.g., outputting backspaces, then outputting spaces to overwrite the letters being wrapped).

But that's pure speculation.

How to bind to a PasswordBox in MVVM

Its very simple . Create another property for password and Bind this with TextBox

But all input operations perform with actual password property

private string _Password;

    public string PasswordChar
    {
        get
        {
            string szChar = "";

            foreach(char szCahr in _Password)
            {
                szChar = szChar + "*";
            }

            return szChar;
        }

        set
        {
            _PasswordChar = value; NotifyPropertyChanged();
        }
    }

public string Password { get { return _Password; }

        set
        {
            _Password = value; NotifyPropertyChanged();
            PasswordChar = _Password;
        }
    }

How can I submit a POST form using the <a href="..."> tag?

There really seems no way for fooling the <a href= .. into a POST method. However, given that you have access to CSS of a page, this can be substituted by using a form instead.

Unfortunately, the obvious way of just styling the button in CSS as an anchor tag, is not cross-browser compatible, since different browsers treat <button value= ... differently.

Incorrect:

<form action='actbusy.php' method='post'>
  <button type='submit' name='parameter' value='One'>Two</button>
</form>

The above example will be showing 'Two' and transmit 'parameter:One' in FireFox, while it will show 'One' and transmit also 'parameter:One' in IE8.

The way around is to use hidden input field(s) for delivering data and the button just for submitting it.

<form action='actbusy.php' method='post'>
   <input class=hidden name='parameter' value='blaah'>
   <button type='submit' name='delete' value='Delete'>Delete</button>
</form>

Note, that this method has a side effect that besides 'parameter:blaah' it will also deliver 'delete:Delete' as surplus parameters in POST.

You want to keep for a button the value attribute and button label between tags both the same ('Delete' on this case), since (as stated above) some browsers will display one and some display another as a button label.

How to iterate using ngFor loop Map containing key as string and values as map iteration

If you are using Angular 6.1 or later, the most convenient way is to use KeyValuePipe

   @Component({
      selector: 'keyvalue-pipe',
      template: `<span>
        <p>Object</p>
        <div *ngFor="let item of object | keyvalue">
          {{item.key}}:{{item.value}}
        </div>
        <p>Map</p>
        <div *ngFor="let item of map | keyvalue">
          {{item.key}}:{{item.value}}
        </div>
      </span>`
    })
    export class KeyValuePipeComponent {
      object: Record<number, string> = {2: 'foo', 1: 'bar'};
      map = new Map([[2, 'foo'], [1, 'bar']]);
    }

How to convert timestamp to datetime in MySQL?

To answer Janus Troelsen comment

Use UNIX_TIMESTAMP instead of TIMESTAMP

SELECT from_unixtime( UNIX_TIMESTAMP(  "2011-12-01 22:01:23.048" ) )

The TIMESTAMP function returns a Date or a DateTime and not a timestamp, while UNIX_TIMESTAMP returns a unix timestamp

How to set a fixed width column with CSS flexbox

In case anyone wants to have a responsive flexbox with percentages (%) it is much easier for media queries.

flex-basis: 25%;

This will be a lot smoother when testing.

// VARIABLES
$screen-xs:                                         480px;
$screen-sm:                                         768px;
$screen-md:                                         992px;
$screen-lg:                                         1200px;
$screen-xl:                                         1400px;
$screen-xxl:                                        1600px;

// QUERIES
@media screen (max-width: $screen-lg) {
    flex-basis: 25%;
}

@media screen (max-width: $screen-md) {
    flex-basis: 33.33%;
}

Disable scrolling on `<input type=number>`

I have an alternative suggestion. The problem I see with most of the common recommendation of firing a blur event is that it has unexpected side-effects. It's not always a good thing to remove a focus state unexpectedly.

Why not this instead?

<input type="number" onwheel="return false;" />

It's very simple and straight-forward, easy to implement, and no side-effects that I can think of.

Escaping single quote in PHP when inserting into MySQL

For anyone finding this solution in 2015 and moving forward...

The mysql_real_escape_string() function is deprecated as of PHP 5.5.0.

See: php.net

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

mysqli_real_escape_string()

PDO::quote()

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

in this case, I use space for APP_NAME key in .env file.

and have below error :

The environment file is invalid!
Failed to parse dotenv file due to unexpected whitespace. Failed at [my name].
Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

Don't use space in APP_NAME key !!

View array in Visual Studio debugger?

Are you trying to view an array with memory allocated dynamically? If not, you can view an array for C++ and C# by putting it in the watch window in the debugger, with its contents visible when you expand the array on the little (+) in the watch window by a left mouse-click.

If it's a pointer to a dynamically allocated array, to view N contents of the pointer, type "pointer, N" in the watch window of the debugger. Note, N must be an integer or the debugger will give you an error saying it can't access the contents. Then, left click on the little (+) icon that appears to view the contents.

How to find out the location of currently used MySQL configuration file in linux

The information you want can be found by running

mysql --help

or

mysqld --help --verbose

I tried this command on my machine:

mysql --help | grep "Default options" -A 1

And it printed out:

Default options are read from the following files in the given order:
/etc/my.cnf /usr/local/etc/my.cnf ~/.my.cnf

See if that works for you.

Shell script to copy files from one location to another location and rename add the current date to every file

path_src=./folder1
path_dst=./folder2
date=$(date +"%m%d%y")
for file_src in $path_src/*; do
  file_dst="$path_dst/$(basename $file_src | \
    sed "s/^\(.*\)\.\(.*\)/\1$date.\2/")"
  echo mv "$file_src" "$file_dst"
done

Disable eslint rules for folder

To ignore some folder from eslint rules we could create the file .eslintignore in root directory and add there the path to the folder we want omit (the same way as for .gitignore).

Here is the example from the ESLint docs on Ignoring Files and Directories:

# path/to/project/root/.eslintignore
# /node_modules/* and /bower_components/* in the project root are ignored by default

# Ignore built files except build/index.js
build/*
!build/index.js

Best way to store chat messages in a database?

There's nothing wrong with saving the whole history in the database, they are prepared for that kind of tasks.

Actually you can find here in Stack Overflow a link to an example schema for a chat: example

If you are still worried for the size, you could apply some optimizations to group messages, like adding a buffer to your application that you only push after some time (like 1 minute or so); that way you would avoid having only 1 line messages

Why would $_FILES be empty when uploading files to PHP?

I had similar problem and the issue was in wrong value in htaccess as shamittomar mentioned.

Change php_value post_max_size 10MB to php_value post_max_size 10M

How to connect to LocalDb

Your Connection string should be like`

Data Source=(localdb)\ProjectsV13;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False

How to set a default value in react-select

  1. Create a state property for the default option text in the constructor
    • Don't worry about the default option value
  2. Add an option tag to the render function. Only show using state and ternary expression
  3. Create a function to handle when an option was selected
  4. Change the state of the default option value in this event handler function to null

    Class MySelect extends React.Component
    {
        constructor()
        {
            super()
            this.handleChange = this.handleChange.bind(this);
            this.state = {
                selectDefault: "Select An Option"
            }
        }
        handleChange(event)
        {
            const selectedValue = event.target.value;
            //do something with selectedValue
            this.setState({
                selectDefault: null
            });
        }
        render()
        {
            return (
            <select name="selectInput" id="selectInput" onChange={this.handleChange} value= 
                {this.selectedValue}>
             {this.state.selectDefault ? <option>{this.state.selectDefault}</option> : ''}
                {'map list or static list of options here'}
            </select>
            )
        }
    }
    

Javascript Uncaught TypeError: Cannot read property '0' of undefined

There is no error when I use your code,

but I am calling the hasLetter method like this:

hasLetter("a",words);

Tricks to manage the available memory in an R session

The llfunction in gData package can show the memory usage of each object as well.

gdata::ll(unit='MB')

The Definitive C Book Guide and List

Beginner

Introductory, no previous programming experience

  • C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]

    * Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.

  • Programming: Principles and Practice Using C++ (Bjarne Stroustrup, 2nd Edition - May 25, 2014) (updated for C++11/C++14) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners.

Introductory, with previous programming experience

  • A Tour of C++ (Bjarne Stroustrup) (2nd edition for C++17) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.

  • Accelerated C++ (Andrew Koenig and Barbara Moo, 1st Edition - August 24, 2000) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction to the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach to teaching the language.) Despite this, the C++ it teaches is purely C++98. [Review]

Best practices

  • Effective C++ (Scott Meyers, 3rd Edition - May 22, 2005) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]

  • Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.

  • Effective STL (Scott Meyers) This aims to do the same to the part of the standard library coming from the STL what Effective C++ did to the language as a whole: It presents rules of thumb along with their rationale. [Review]


Intermediate

  • More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.

  • Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]

  • More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object-oriented programming in C++ and correct use of the STL. [Review]

  • Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using non-member functions and the single responsibility principle. [Review]

  • C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]

  • C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition covering C++11, C++14 and C++17 has been already published. [Review]

  • C++ 17 - The Complete Guide (Nicolai M. Josuttis) This book describes all the new features introduced in the C++17 Standard covering everything from the simple ones like 'Inline Variables', 'constexpr if' all the way up to 'Polymorphic Memory Resources' and 'New and Delete with overaligned Data'. [Review]

  • C++ in Action (Bartosz Milewski). This book explains C++ and its features by building an application from ground up. [Review]

  • Functional Programming in C++ (Ivan Cukic). This book introduces functional programming techniques to modern C++ (C++11 and later). A very nice read for those who want to apply functional programming paradigms to C++.

  • Professional C++ (Marc Gregoire, 5th Edition - Feb 2021) Provides a comprehensive and detailed tour of the C++ language implementation replete with professional tips and concise but informative in-text examples, emphasizing C++20 features. Uses C++20 features, such as modules and std::format throughout all examples.


Advanced

  • Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multi-methods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]

  • C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)

  • C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications. A second edition covering C++14 and C++17 has been already published. [Review]

  • Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by type traits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.


Reference Style - All Levels

  • The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much like it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review] Note: All releases of the C++ standard are tracked in the question "Where do I find the current C or C++ standard documents?".

  • C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]

  • The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]

C++11/14/17/… References:

  • The C++11/14/17 Standard (INCITS/ISO/IEC 14882:2011/2014/2017) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. The C++17 standard is released in electronic form for 198 Swiss Francs.

  • The C++17 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++20.

  • Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.

  • The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.

  • The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.

  • cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.


Classics / Older

Note: Some information contained within these books may not be up-to-date or no longer considered best practice.

  • The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.

  • Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]

  • Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.

  • Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly, a good read, if it only was up to date. It was written long before C++ 98 and misses on many features (e.g. namespaces) important for large-scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is released in 2019.

  • Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.

  • The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however, this book goes through the entire C++ standard of the time explaining the rationale, the possible implementations, and features of the language. This is not a book to learn programming principles and patterns on C++, but to understand every aspect of the C++ language.

  • Thinking in C++ (Bruce Eckel, 2nd Edition, 2000). Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they're marred by a number of trivial errors (e.g. maintaining that temporaries are automatically const), with no official errata list. A partial 3rd party errata list is available at http://www.computersciencelab.com/Eckel.htm, but it is apparently not maintained.

  • Scientific and Engineering C++: An Introduction to Advanced Techniques and Examples (John Barton and Lee Nackman) It is a comprehensive and very detailed book that tried to explain and make use of all the features available in C++, in the context of numerical methods. It introduced at the time several new techniques, such as the Curiously Recurring Template Pattern (CRTP, also called Barton-Nackman trick). It pioneered several techniques such as dimensional analysis and automatic differentiation. It came with a lot of compilable and useful code, ranging from an expression parser to a Lapack wrapper. The code is still available online. Unfortunately, the books have become somewhat outdated in the style and C++ features, however, it was an incredible tour-de-force at the time (1994, pre-STL). The chapters on dynamics inheritance are a bit complicated to understand and not very useful. An updated version of this classic book that includes move semantics and the lessons learned from the STL would be very nice.

Xampp-mysql - "Table doesn't exist in engine" #1932

  1. stop mysql
  2. copy xampp\mysql\data\ib* from old server to new server
  3. start mysql

How to load assemblies in PowerShell?

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") worked for me.

window.print() not working in IE

For Firefox use

iframewin.print()

for IE use

iframedocument.execCommand('print', false, null);

see also Unable to print an iframe on IE using JavaScript, prints parent page instead

How to View Oracle Stored Procedure using SQLPlus?

check your casing, the name is typically stored in upper case

SELECT * FROM all_source WHERE name = 'DAILY_UPDATE' ORDER BY TYPE, LINE;

redirect COPY of stdout to log file from within bash script itself

The accepted answer does not preserve STDERR as a separate file descriptor. That means

./script.sh >/dev/null

will not output bar to the terminal, only to the logfile, and

./script.sh 2>/dev/null

will output both foo and bar to the terminal. Clearly that's not the behaviour a normal user is likely to expect. This can be fixed by using two separate tee processes both appending to the same log file:

#!/bin/bash

# See (and upvote) the comment by JamesThomasMoon1979 
# explaining the use of the -i option to tee.
exec >  >(tee -ia foo.log)
exec 2> >(tee -ia foo.log >&2)

echo "foo"
echo "bar" >&2

(Note that the above does not initially truncate the log file - if you want that behaviour you should add

>foo.log

to the top of the script.)

The POSIX.1-2008 specification of tee(1) requires that output is unbuffered, i.e. not even line-buffered, so in this case it is possible that STDOUT and STDERR could end up on the same line of foo.log; however that could also happen on the terminal, so the log file will be a faithful reflection of what could be seen on the terminal, if not an exact mirror of it. If you want the STDOUT lines cleanly separated from the STDERR lines, consider using two log files, possibly with date stamp prefixes on each line to allow chronological reassembly later on.

json and empty array

null is a legal value (and reserved word) in JSON, but some environments do not have a "NULL" object (as opposed to a NULL value) and hence cannot accurately represent the JSON null. So they will sometimes represent it as an empty array.

Whether null is a legal value in that particular element of that particular API is entirely up to the API designer.

Wait until boolean value changes it state

I prefer to use mutex mechanism in such cases, but if you really want to use boolean, then you should declare it as volatile (to provide the change visibility across threads) and just run the body-less cycle with that boolean as a condition :

//.....some class

volatile boolean someBoolean; 

Thread someThread = new Thread() {

    @Override 
    public void run() {
        //some actions
        while (!someBoolean); //wait for condition 
        //some actions 
    }

};

Query comparing dates in SQL

Date format is yyyy-mm-dd. So the above query is looking for records older than 12Apr2013

Suggest you do a quick check by setting the date string to '2013-04-30', if no sql error, date format is confirmed to yyyy-mm-dd.

What exactly is OAuth (Open Authorization)?

OAuth is all about delegating Authorization (choosing someone who can do Authorization for you). Note that Authentication and Authorization are different things. OAuth is Authorization (Access control), and if you want to implement Authentication (ID verification) also, OpenID protocol can be used on top of OAuth.

All big companies like Facebook, Google, Github,... use this kind of authentication/authorization nowadays. For example, I just signed in on this website using my Google account, this means Stackoverflow doesn't know my password, it receives the allowance from Google where my password (hashed obviously) is saved. This gives a lot of benefits, one of them is; In the near future you won't have to make several accounts on every website. One website (which you trust most) can be used to login to all other websites. So you'll only have to remember one password.

Get an element by index in jQuery

You could skip the jquery and just use CSS style tagging:

 <ul>
 <li>India</li>
 <li>Indonesia</li>
 <li style="background-color:#343434;">China</li>
 <li>United States</li>
 <li>United Kingdom</li>
 </ul>

how does unix handle full path name with space and arguments?

Since spaces are used to separate command line arguments, they have to be escaped from the shell. This can be done with either a backslash () or quotes:

"/path/with/spaces in it/to/a/file"
somecommand -spaced\ option
somecommand "-spaced option"
somecommand '-spaced option'

This is assuming you're running from a shell. If you're writing code, you can usually pass the arguments directly, avoiding the problem:

Example in perl. Instead of doing:

print("code sample");system("somecommand -spaced option");

you can do

print("code sample");system("somecommand", "-spaced option");

Since when you pass the system() call a list, it doesn't break arguments on spaces like it does with a single argument call.

Converting a character code to char (VB.NET)

You could use the Chr(int) function

How to add a list item to an existing unordered list?

Just to add to this thread - if you are moving an existing item you will need to use clone and then true/false on whether you clone/deep-clone the events as well (https://api.jquery.com/clone/).

Example: $("#content ul").append($('.existing_li').clone(true));

Jquery Open in new Tab (_blank)

window.location always refers to the location of the current window. Changing it will affect only the current window.

One thing that can be done is forcing a click on the link after setting its target attribute to _blank:

Check this: http://www.techfoobar.com/2012/jquery-programmatically-clicking-a-link-and-forcing-the-default-action

Disclaimer: Its my blog.

How to set the margin or padding as percentage of height of parent container?

An answer to a slightly different question: You can use vh units to pad elements to the center of the viewport:

.centerme {
    margin-top: 50vh;
    background: red;
}

<div class="centerme">middle</div>

Equivalent of Super Keyword in C#

C# equivalent of your code is

  class Imagedata : PDFStreamEngine
  {
     // C# uses "base" keyword whenever Java uses "super" 
     // so instead of super(...) in Java we should call its C# equivalent (base):
     public Imagedata()
       : base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true)) 
     { }

     // Java methods are virtual by default, when C# methods aren't.
     // So we should be sure that processOperator method in base class 
     // (that is PDFStreamEngine)
     // declared as "virtual"
     protected override void processOperator(PDFOperator operations, List arguments)
     {
        base.processOperator(operations, arguments);
     }
  }

"unrecognized selector sent to instance" error in Objective-C

On my case I solved the problem after 2 hours :

The sender (a tabBar item) wasn't having any Referencing Outlet. So it was pointing nowhere.

Juste create a referencing outlet corresponding to your function.

Hope this could help you guys.

Pie chart with jQuery

A few others that have not been mentioned:

For mini pies, lines and bars, Peity is brilliant, simple, tiny, fast, uses really elegant markup.

I'm not sure of it's relationship with Flot (given its name), but Flotr2 is pretty good, certainly does better pies than Flot.

Bluff produces nice-looking line graphs, but I had a bit of trouble with its pies.

Not what I was after, but another commercial product (much like Highcharts) is TeeChart.

How to enter a multi-line command

To expand on cristobalito's answer:

I assume you're talking about on the command-line - if it's in a script, then a new-line >acts as a command delimiter.

On the command line, use a semi-colon ';'

For example:

Sign a PowerShell script on the command-line. No line breaks.

powershell -Command "&{$cert=Get-ChildItem –Path cert:\CurrentUser\my -codeSigningCert ; Set-AuthenticodeSignature -filepath Z:\test.ps1 -Cert $cert}

JavaScript: Passing parameters to a callback function

I was looking for the same thing and end up with the solution and here it's a simple example if anybody wants to go through this.

var FA = function(data){
   console.log("IN A:"+data)
   FC(data,"LastName");
};
var FC = function(data,d2){
   console.log("IN C:"+data,d2)
};
var FB = function(data){
   console.log("IN B:"+data);
    FA(data)
};
FB('FirstName')

Also posted on the other question here

how to change directory using Windows command line

cd /driveName driveName:\pathNamw

How to get scrollbar position with Javascript?

You can use element.scrollTop and element.scrollLeft to get the vertical and horizontal offset, respectively, that has been scrolled. element can be document.body if you care about the whole page. You can compare it to element.offsetHeight and element.offsetWidth (again, element may be the body) if you need percentages.

Wrapping text inside input type="text" element HTML/CSS

You can not use input for it, you need to use textarea instead. Use textarea with the wrap="soft"code and optional the rest of the attributes like this:

<textarea name="text" rows="14" cols="10" wrap="soft"> </textarea>

Atributes: To limit the amount of text in it for example to "40" characters you can add the attribute maxlength="40" like this: <textarea name="text" rows="14" cols="10" wrap="soft" maxlength="40"></textarea> To hide the scroll the style for it. if you only use overflow:scroll; or overflow:hidden; or overflow:auto; it will only take affect for one scroll bar. If you want different attributes for each scroll bar then use the attributes like this overflow:scroll; overflow-x:auto; overflow-y:hidden; in the style area: To make the textarea not resizable you can use the style with resize:none; like this:

<textarea name="text" rows="14" cols="10" wrap="soft" maxlength="40" style="overflow:hidden; resize:none;></textarea>

That way you can have or example a textarea with 14 rows and 10 cols with word wrap and max character length of "40" characters that works exactly like a input text box does but with rows instead and without using input text.

NOTE: textarea works with rows unlike like input <input type="text" name="tbox" size="10"></input> that is made to not work with rows at all.

How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

For the record, the spring.jpa.hibernate.ddl-auto property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto.

The values create, create-drop, validate, and update basically influence how the schema tool management will manipulate the database schema at startup.

For example, the update operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.

The update operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.

Typically in test case scenarios, you'll likely use create-drop so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.

In development, it's often common to see developers use update to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.

In production, it's often highly recommended you use none or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.

Inputting a default image in case the src attribute of an html <img> is not valid?

This works well for me. Maybe you wanna use JQuery to hook the event.

 <img src="foo.jpg" onerror="if (this.src != 'error.jpg') this.src = 'error.jpg';">

Updated with jacquargs error guard

Updated: CSS only solution I recently saw Vitaly Friedman demo a great CSS solution I wasn't aware of. The idea is to apply the content property to the broken image. Normally :after or :before do not apply to images, but when they're broken, they're applied.

<img src="nothere.jpg">
<style>
img:before {
    content: ' ';
    display: block;
    position: absolute;
    height: 50px;
    width: 50px;
    background-image: url(ishere.jpg);
</style>

Demo: https://jsfiddle.net/uz2gmh2k/2/

As the fiddle shows, the broken image itself is not removed, but this will probably solve the problem for most cases without any JS nor gobs of CSS. If you need to apply different images in different locations, simply differentiate with a class: .my-special-case img:before { ...

How to make a phone call using intent in Android?

For call from dialer (No permission needed):

   fun callFromDailer(mContext: Context, number: String) {
        try {
            val callIntent = Intent(Intent.ACTION_DIAL)
            callIntent.data = Uri.parse("tel:$number")
            mContext.startActivity(callIntent)
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(mContext, "No SIM Found", Toast.LENGTH_LONG).show()
        }
    }

For direct call from app(Permission needed):

  fun callDirect(mContext: Context, number: String) {
        try {
            val callIntent = Intent(Intent.ACTION_CALL)
            callIntent.data = Uri.parse("tel:$number")
            mContext.startActivity(callIntent)
        } catch (e: SecurityException) {
            Toast.makeText(mContext, "Need call permission", Toast.LENGTH_LONG).show()
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(mContext, "No SIM Found", Toast.LENGTH_LONG).show()
        }
    }

Permission:

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

How to Batch Rename Files in a macOS Terminal?

To rename files, you can use the rename utility:

brew install rename

For example, to change a search string in all filenames in current directory:

rename -nvs searchword replaceword *

Remove the 'n' parameter to apply the changes.

More info: man rename

How to add content to html body using JS?

You can use

document.getElementById("parentID").appendChild(/*..your content created using DOM methods..*/)

or

document.getElementById("parentID").innerHTML+= "new content"

Read properties file outside JAR file

I did it by other way.

Properties prop = new Properties();
    try {

        File jarPath=new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
        String propertiesPath=jarPath.getParentFile().getAbsolutePath();
        System.out.println(" propertiesPath-"+propertiesPath);
        prop.load(new FileInputStream(propertiesPath+"/importer.properties"));
    } catch (IOException e1) {
        e1.printStackTrace();
    }
  1. Get Jar file path.
  2. Get Parent folder of that file.
  3. Use that path in InputStreamPath with your properties file name.

Adb Devices can't find my phone

I did the following to get my Mac to see the devices again:

  • Run android update adb
  • Run adb kill-server
  • Run adb start-server

At this point, calling adb devices started returning devices again. Now run or debug your project to test it on your device.

Twitter Bootstrap Multilevel Dropdown Menu

[Twitter Bootstrap v3]

To create a n-level dropdown menu (touch device friendly) in Twitter Bootstrap v3,

CSS:

.dropdown-menu>li /* To prevent selection of text */
{   position:relative;
    -webkit-user-select: none; /* Chrome/Safari */        
    -moz-user-select: none; /* Firefox */
    -ms-user-select: none; /* IE10+ */
    /* Rules below not implemented in browsers yet */
    -o-user-select: none;
    user-select: none;
    cursor:pointer;
}
.dropdown-menu .sub-menu 
{
    left: 100%;
    position: absolute;
    top: 0;
    display:none;
    margin-top: -1px;
    border-top-left-radius:0;
    border-bottom-left-radius:0;
    border-left-color:#fff;
    box-shadow:none;
}
.right-caret:after,.left-caret:after
 {  content:"";
    border-bottom: 5px solid transparent;
    border-top: 5px solid transparent;
    display: inline-block;
    height: 0;
    vertical-align: middle;
    width: 0;
    margin-left:5px;
}
.right-caret:after
{   border-left: 5px solid #ffaf46;
}
.left-caret:after
{   border-right: 5px solid #ffaf46;
}

JQuery:

$(function(){
    $(".dropdown-menu > li > a.trigger").on("click",function(e){
        var current=$(this).next();
        var grandparent=$(this).parent().parent();
        if($(this).hasClass('left-caret')||$(this).hasClass('right-caret'))
            $(this).toggleClass('right-caret left-caret');
        grandparent.find('.left-caret').not(this).toggleClass('right-caret left-caret');
        grandparent.find(".sub-menu:visible").not(current).hide();
        current.toggle();
        e.stopPropagation();
    });
    $(".dropdown-menu > li > a:not(.trigger)").on("click",function(){
        var root=$(this).closest('.dropdown');
        root.find('.left-caret').toggleClass('right-caret left-caret');
        root.find('.sub-menu:visible').hide();
    });
});

HTML:

<div class="dropdown" style="position:relative">
    <a href="#" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Click Here <span class="caret"></span></a>
    <ul class="dropdown-menu">
        <li>
            <a class="trigger right-caret">Level 1</a>
            <ul class="dropdown-menu sub-menu">
                <li><a href="#">Level 2</a></li>
                <li>
                    <a class="trigger right-caret">Level 2</a>
                    <ul class="dropdown-menu sub-menu">
                        <li><a href="#">Level 3</a></li>
                        <li><a href="#">Level 3</a></li>
                        <li>
                            <a class="trigger right-caret">Level 3</a>
                            <ul class="dropdown-menu sub-menu">
                                <li><a href="#">Level 4</a></li>
                                <li><a href="#">Level 4</a></li>
                                <li><a href="#">Level 4</a></li>
                            </ul>
                        </li>
                    </ul>
                </li>
                <li><a href="#">Level 2</a></li>
            </ul>
        </li>
        <li><a href="#">Level 1</a></li>
        <li><a href="#">Level 1</a></li>
    </ul>
</div>

OOP vs Functional Programming vs Procedural

I think the available libraries, tools, examples, and communities completely trumps the paradigm these days. For example, ML (or whatever) might be the ultimate all-purpose programming language but if you can't get any good libraries for what you are doing you're screwed.

For example, if you're making a video game, there are more good code examples and SDKs in C++, so you're probably better off with that. For a small web application, there are some great Python, PHP, and Ruby frameworks that'll get you off and running very quickly. Java is a great choice for larger projects because of the compile-time checking and enterprise libraries and platforms.

It used to be the case that the standard libraries for different languages were pretty small and easily replicated - C, C++, Assembler, ML, LISP, etc.. came with the basics, but tended to chicken out when it came to standardizing on things like network communications, encryption, graphics, data file formats (including XML), even basic data structures like balanced trees and hashtables were left out!

Modern languages like Python, PHP, Ruby, and Java now come with a far more decent standard library and have many good third party libraries you can easily use, thanks in great part to their adoption of namespaces to keep libraries from colliding with one another, and garbage collection to standardize the memory management schemes of the libraries.

What is the difference between __str__ and __repr__?

Every object inherits __repr__ from the base class that all objects created.

class Person:
     pass

p=Person()

if you call repr(p) you will get this as default:

 <__main__.Person object at 0x7fb2604f03a0>

But if you call str(p) you will get the same output. it is because when __str__ does not exist, Python calls __repr__

Let's implement our own __str__

class Person:
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def __repr__(self):
        print("__repr__ called")
        return f"Person(name='{self.name}',age={self.age})"

p=Person("ali",20)

print(p) and str(p)will return

 __repr__ called
     Person(name='ali',age=20)

let's add __str__()

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
    def __repr__(self):
        print('__repr__ called')
        return f"Person(name='{self.name}, age=self.age')"
    
    def __str__(self):
        print('__str__ called')
        return self.name

p=Person("ali",20)

if we call print(p) and str(p), it will call __str__() so it will return

__str__ called
ali

repr(p) will return

repr called "Person(name='ali, age=self.age')"

Let's omit __repr__ and just implement __str__.

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

def __str__(self):
    print('__str__ called')
    return self.name

p=Person('ali',20)

print(p) will look for the __str__ and will return:

__str__ called
ali

NOTE= if we had __repr__ and __str__ defined, f'name is {p}' would call __str__

Getting scroll bar width using JavaScript

Here's an easy way using jQuery.

var scrollbarWidth = jQuery('div.withScrollBar').get(0).scrollWidth - jQuery('div.withScrollBar').width();

Basically we subtract the scrollable width from the overall width and that should provide the scrollbar's width. Of course, you'd want to cache the jQuery('div.withScrollBar') selection so you're not doing that part twice.

How to fix 'Notice: Undefined index:' in PHP form action

Use empty() to check if it is available. Try with -

will generate the error if host is not present here

if(!empty($_GET["host"]))
if($_GET["host"]!="")

PHPExcel - set cell type before writing a value in it

try this

$currencyFormat = '_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)';
$textFormat='@';//'General','0.00','@'
$excel->getActiveSheet()->getStyle('B1')->getNumberFormat()->setFormatCode($currencyFormat);
$excel->getActiveSheet()->getStyle('C1')->getNumberFormat()->setFormatCode($textFormat);`

Error: expected type-specifier before 'ClassName'

First of all, let's try to make your code a little simpler:

// No need to create a circle unless it is clearly necessary to
// demonstrate the problem

// Your Rect2f defines a default constructor, so let's use it for simplicity.
shared_ptr<Shape> rect(new Rect2f());

Okay, so now we see that the parentheses are clearly balanced. What else could it be? Let's check the following code snippet's error:

int main() {
    delete new T();
}

This may seem like weird usage, and it is, but I really hate memory leaks. However, the output does seem useful:

In function 'int main()':
Line 2: error: expected type-specifier before 'T'

Aha! Now we're just left with the error about the parentheses. I can't find what causes that; however, I think you are forgetting to include the file that defines Rect2f.

Google Geocoding API - REQUEST_DENIED

I got this problem as well using the drupal 7 Location module. Autofilling all empty locations resulted in this error. Executing one of the requests to the location api manually resulted in this error in the returned JSON:

"Browser API keys cannot have referer restrictions when used with this API."

Resolving the problem then was easy: create a new key without any restrictions and use it only for Geocoding.

Note for those new to google api keys: by restrictions they mean limiting requests using an api key to specific domains / subdomains. (eg. only request from http://yourdomain.com are allowed).

How to determine if a decimal/double is an integer?

    public static bool isInteger(decimal n)
    {
        return n - (Int64)n == 0;
    }

Initialize class fields in constructor or at declaration?

In Java, an initializer with the declaration means the field is always initialized the same way, regardless of which constructor is used (if you have more than one) or the parameters of your constructors (if they have arguments), although a constructor might subsequently change the value (if it is not final). So using an initializer with a declaration suggests to a reader that the initialized value is the value that the field has in all cases, regardless of which constructor is used and regardless of the parameters passed to any constructor. Therefore use an initializer with the declaration only if, and always if, the value for all constructed objects is the same.

Convert list of ints to one number?

pseudo-code:

int magic(list nums)
{
  int tot = 0

  while (!nums.isEmpty())
  {
    int digit = nums.takeFirst()
    tot *= 10
    tot += digit
  }

  return tot
}

Condition within JOIN or WHERE

Most RDBMS products will optimize both queries identically. In "SQL Performance Tuning" by Peter Gulutzan and Trudy Pelzer, they tested multiple brands of RDBMS and found no performance difference.

I prefer to keep join conditions separate from query restriction conditions.

If you're using OUTER JOIN sometimes it's necessary to put conditions in the join clause.

Javascript: Fetch DELETE and PUT requests

Just Simple Answer. FETCH DELETE

function deleteData(item, url) {
  return fetch(url + '/' + item, {
    method: 'delete'
  })
  .then(response => response.json());
}

JSON.parse unexpected token s

What you are passing to JSON.parse method must be a valid JSON after removing the wrapping quotes for string.

so something is not a valid JSON but "something" is.

A valid JSON is -

JSON = null
    /* boolean literal */
    or true or false
    /* A JavaScript Number Leading zeroes are prohibited; a decimal point must be followed by at least one digit.*/
    or JSONNumber
    /* Only a limited sets of characters may be escaped; certain control characters are prohibited; the Unicode line separator (U+2028) and paragraph separator (U+2029) characters are permitted; strings must be double-quoted.*/
    or JSONString

    /* Property names must be double-quoted strings; trailing commas are forbidden. */
    or JSONObject
    or JSONArray

Examples -

JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null 
JSON.parse("'foo'"); // error since string should be wrapped by double quotes

You may want to look JSON.

react-router getting this.props.location in child components

If the above solution didn't work for you, you can use import { withRouter } from 'react-router-dom';


Using this you can export your child class as -

class MyApp extends Component{
    // your code
}

export default withRouter(MyApp);

And your class with Router -

// your code
<Router>
      ...
      <Route path="/myapp" component={MyApp} />
      // or if you are sending additional fields
      <Route path="/myapp" component={() =><MyApp process={...} />} />
<Router>

Maintain/Save/Restore scroll position when returning to a ListView

I found something interesting about this.

I tried setSelection and scrolltoXY but it did not work at all, the list remained in the same position, after some trial and error I got the following code that does work

final ListView list = (ListView) findViewById(R.id.list);
list.post(new Runnable() {            
    @Override
    public void run() {
        list.setSelection(0);
    }
});

If instead of posting the Runnable you try runOnUiThread it does not work either (at least on some devices)

This is a very strange workaround for something that should be straight forward.

How should a model be structured in MVC?

More oftenly most of the applications will have data,display and processing part and we just put all those in the letters M,V and C.

Model(M)-->Has the attributes that holds state of application and it dont know any thing about V and C.

View(V)-->Has displaying format for the application and and only knows about how-to-digest model on it and does not bother about C.

Controller(C)---->Has processing part of application and acts as wiring between M and V and it depends on both M,V unlike M and V.

Altogether there is separation of concern between each. In future any change or enhancements can be added very easily.

Creating threads - Task.Factory.StartNew vs new Thread()

The task gives you all the goodness of the task API:

  • Adding continuations (Task.ContinueWith)
  • Waiting for multiple tasks to complete (either all or any)
  • Capturing errors in the task and interrogating them later
  • Capturing cancellation (and allowing you to specify cancellation to start with)
  • Potentially having a return value
  • Using await in C# 5
  • Better control over scheduling (if it's going to be long-running, say so when you create the task so the task scheduler can take that into account)

Note that in both cases you can make your code slightly simpler with method group conversions:

DataInThread = new Thread(ThreadProcedure);
// Or...
Task t = Task.Factory.StartNew(ThreadProcedure);

How can I implement the Iterable interface?

First off:

public class ProfileCollection implements Iterable<Profile> {

Second:

return m_Profiles.get(m_ActiveProfile);

How to add spacing between columns?

This will allow a space between the two columns and obviously if you want to change the default width you can go for mixins to modify the default bootstrap width. Or, you can give the width using the inline CSS style.

<div class="col-md-5 pull-left"></div>
<div class="col-md-5 pull-right"></div>

error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

I had this problem despite:

  • having a main(); and
  • configuring all other projects in my solution to be static libraries.

My eventual fix was the following:

  • my main() was in a namespace, so was effectively called something::main() ...removing this namespace fixed the problem.

How to add jQuery in JS file

just copy the code from the two files into your file at the top.

or use something like this http://code.google.com/p/minify/ to combine your files dynamically.

Josh

Javascript change Div style

Using jQuery:

$(document).ready(function(){
    $('div').click(function(){
        $(this).toggleClass('clicked');
    });
});?

Live example

Android: Access child views from a ListView

A quick search of the docs for the ListView class has turned up getChildCount() and getChildAt() methods inherited from ViewGroup. Can you iterate through them using these? I'm not sure but it's worth a try.

Found it here

How to use Bootstrap modal using the anchor tag for Register?

Just replace it:

<li><a href="" data-toggle="modal" data-target="#modalRegister">Register</a></li>

Instead of:

<li><a href="#" data-toggle="modal" data-target="modalRegister">Register</a></li>

Check if cookies are enabled

Cookies are Client-side and cannot be tested properly using PHP. That's the baseline and every solution is a wrap-around for this problem.

Meaning if you are looking a solution for your cookie problem, you are on the wrong way. Don'y use PHP, use a client language like Javascript.

Can you use cookies using PHP? Yes, but you have to reload to make the settings to PHP 'visible'.

For instance: Is a test possible to see if the browser can set Cookies with plain PHP'. The only correct answer is 'NO'.

Can you read an already set Cookie: 'YES' use the predefined $_COOKIE (A copy of the settings before you started PHP-App).

How to have multiple conditions for one if statement in python

Darian Moody has a nice solution to this challenge in his blog post:

a = 1
b = 2
c = True

rules = [a == 1,
         b == 2,
         c == True]

if all(rules):
    print("Success!")

The all() method returns True when all elements in the given iterable are true. If not, it returns False.

You can read a little more about it in the python docs here and more information and examples here.

(I also answered the similar question with this info here - How to have multiple conditions for one if statement in python)

Date constructor returns NaN in IE, but works in Firefox and Chrome

I always store my date in UTC time.

This is my own function made from the different functions I found in this page.

It takes a STRING as a mysql DATETIME format (example : 2013-06-15 15:21:41). The checking with the regex is optional. You can delete this part to improve performance.

This function return a timestamp.

The DATETIME is considered as a UTC date. Be carefull : If you expect a local datetime, this function is not for you.

    function datetimeToTimestamp(datetime)
    {
        var regDatetime = /^[0-9]{4}-(?:[0]?[0-9]{1}|10|11|12)-(?:[012]?[0-9]{1}|30|31)(?: (?:[01]?[0-9]{1}|20|21|22|23)(?::[0-5]?[0-9]{1})?(?::[0-5]?[0-9]{1})?)?$/;
        if(regDatetime.test(datetime) === false)
            throw("Wrong format for the param. `Y-m-d H:i:s` expected.");

        var a=datetime.split(" ");
        var d=a[0].split("-");
        var t=a[1].split(":");

        var date = new Date();
        date.setUTCFullYear(d[0],(d[1]-1),d[2]);
        date.setUTCHours(t[0],t[1],t[2], 0);

        return date.getTime();
    }

Best way to import Observable from rxjs

Rxjs v 6.*

It got simplified with newer version of rxjs .

1) Operators

import {map} from 'rxjs/operators';

2) Others

import {Observable,of, from } from 'rxjs';

Instead of chaining we need to pipe . For example

Old syntax :

source.map().switchMap().subscribe()

New Syntax:

source.pipe(map(), switchMap()).subscribe()

Note: Some operators have a name change due to name collisions with JavaScript reserved words! These include:

do -> tap,

catch -> catchError

switch -> switchAll

finally -> finalize


Rxjs v 5.*

I am writing this answer partly to help myself as I keep checking docs everytime I need to import an operator . Let me know if something can be done better way.

1) import { Rx } from 'rxjs/Rx';

This imports the entire library. Then you don't need to worry about loading each operator . But you need to append Rx. I hope tree-shaking will optimize and pick only needed funcionts( need to verify ) As mentioned in comments , tree-shaking can not help. So this is not optimized way.

public cache = new Rx.BehaviorSubject('');

Or you can import individual operators .

This will Optimize your app to use only those files :

2) import { _______ } from 'rxjs/_________';

This syntax usually used for main Object like Rx itself or Observable etc.,

Keywords which can be imported with this syntax

 Observable, Observer, BehaviorSubject, Subject, ReplaySubject

3) import 'rxjs/add/observable/__________';

Update for Angular 5

With Angular 5, which uses rxjs 5.5.2+

import { empty } from 'rxjs/observable/empty';
import { concat} from 'rxjs/observable/concat';

These are usually accompanied with Observable directly. For example

Observable.from()
Observable.of()

Other such keywords which can be imported using this syntax:

concat, defer, empty, forkJoin, from, fromPromise, if, interval, merge, of, 
range, throw, timer, using, zip

4) import 'rxjs/add/operator/_________';

Update for Angular 5

With Angular 5, which uses rxjs 5.5.2+

import { filter } from 'rxjs/operators/filter';
import { map } from 'rxjs/operators/map';

These usually come in the stream after the Observable is created. Like flatMap in this code snippet:

Observable.of([1,2,3,4])
          .flatMap(arr => Observable.from(arr));

Other such keywords using this syntax:

audit, buffer, catch, combineAll, combineLatest, concat, count, debounce, delay, 
distinct, do, every, expand, filter, finally, find , first, groupBy,
ignoreElements, isEmpty, last, let, map, max, merge, mergeMap, min, pluck, 
publish, race, reduce, repeat, scan, skip, startWith, switch, switchMap, take, 
takeUntil, throttle, timeout, toArray, toPromise, withLatestFrom, zip

FlatMap: flatMap is alias to mergeMap so we need to import mergeMap to use flatMap.


Note for /add imports :

We only need to import once in whole project. So its advised to do it at a single place. If they are included in multiple files, and one of them is deleted, the build will fail for wrong reasons.

show all tables in DB2 using the LIST command

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

Connect to the database:

db2 connect to DATABASENAME user USER using PASSWORD

Run this query:

db2 LIST TABLES

This is the equivalent of SHOW TABLES in MySQL.

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

How do I include a JavaScript file in another JavaScript file?

Here is a synchronous version without jQuery:

function myRequire( url ) {
    var ajax = new XMLHttpRequest();
    ajax.open( 'GET', url, false ); // <-- the 'false' makes it synchronous
    ajax.onreadystatechange = function () {
        var script = ajax.response || ajax.responseText;
        if (ajax.readyState === 4) {
            switch( ajax.status) {
                case 200:
                    eval.apply( window, [script] );
                    console.log("script loaded: ", url);
                    break;
                default:
                    console.log("ERROR: script not loaded: ", url);
            }
        }
    };
    ajax.send(null);
}

Note that to get this working cross-domain, the server will need to set allow-origin header in its response.

How do I correct the character encoding of a file?

When you see character sequences like ç and é, it's usually an indication that a UTF-8 file has been opened by a program that reads it in as ANSI (or similar). Unicode characters such as these:

U+00C2 Latin capital letter A with circumflex
U+00C3 Latin capital letter A with tilde
U+0082 Break permitted here
U+0083 No break here

tend to show up in ANSI text because of the variable-byte strategy that UTF-8 uses. This strategy is explained very well here.

The advantage for you is that the appearance of these odd characters makes it relatively easy to find, and thus replace, instances of incorrect conversion.

I believe that, since ANSI always uses 1 byte per character, you can handle this situation with a simple search-and-replace operation. Or more conveniently, with a program that includes a table mapping between the offending sequences and the desired characters, like these:

“ -> “ # should be an opening double curly quote
â€? -> ” # should be a closing double curly quote

Any given text, assuming it's in English, will have a relatively small number of different types of substitutions.

Hope that helps.

How to do a join in linq to sql with method syntax?

var result = from sc in enumerableOfSomeClass
             join soc in enumerableOfSomeOtherClass
             on sc.Property1 equals soc.Property2
             select new { SomeClass = sc, SomeOtherClass = soc };

Would be equivalent to:

var result = enumerableOfSomeClass
    .Join(enumerableOfSomeOtherClass,
          sc => sc.Property1,
          soc => soc.Property2,
          (sc, soc) => new
                       {
                           SomeClass = sc,
                           SomeOtherClass = soc
                       });

As you can see, when it comes to joins, query syntax is usually much more readable than lambda syntax.

Java: JSON -> Protobuf & back conversion

We are currently using protobuf-java-format to convert our Protobuf messages (anything subclass of Message) into a JSON format to send over our web API.

Simply do:

  JsonFormat.printToString(protoMessage)

Finding the handle to a WPF window

If you want window handles for ALL of your application's Windows for some reason, you can use the Application.Windows property to get at all the Windows and then use WindowInteropHandler to get at their handles as you have already demonstrated.

Tree implementation in Java (root, parents and children)

In the accepted answer

public Node(T data, Node<T> parent) {
    this.data = data;
    this.parent = parent;
}

should be

public Node(T data, Node<T> parent) {
    this.data = data;
    this.setParent(parent);
}

otherwise the parent does not have the child in its children list

When should I use GET or POST method? What's the difference between them?

You should use POST if there is a lot of data, or sort-of sensitive information (really sensitive stuff needs a secure connection as well).

Use GET if you want people to be able to bookmark your page, because all the data is included with the bookmark.

Just be careful of people hitting REFRESH with the GET method, because the data will be sent again every time without warning the user (POST sometimes warns the user about resending data).

How do I kill this tomcat process in Terminal?

kill -9 $(ps -ef | grep 8084 | awk 'NR==2{print $2}')

NR is for the number of records in the input file. awk can find or replaces text

Post multipart request with Android SDK

Update April 29th 2014:

My answer is kind of old by now and I guess you rather want to use some kind of high level library such as Retrofit.


Based on this blog I came up with the following solution: http://blog.tacticalnuclearstrike.com/2010/01/using-multipartentity-in-android-applications/

You will have to download additional libraries to get MultipartEntity running!

1) Download httpcomponents-client-4.1.zip from http://james.apache.org/download.cgi#Apache_Mime4J and add apache-mime4j-0.6.1.jar to your project.

2) Download httpcomponents-client-4.1-bin.zip from http://hc.apache.org/downloads.cgi and add httpclient-4.1.jar, httpcore-4.1.jar and httpmime-4.1.jar to your project.

3) Use the example code below.

private DefaultHttpClient mHttpClient;


public ServerCommunication() {
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    mHttpClient = new DefaultHttpClient(params);
}


public void uploadUserPhoto(File image) {

    try {

        HttpPost httppost = new HttpPost("some url");

        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
        multipartEntity.addPart("Title", new StringBody("Title"));
        multipartEntity.addPart("Nick", new StringBody("Nick"));
        multipartEntity.addPart("Email", new StringBody("Email"));
        multipartEntity.addPart("Description", new StringBody(Settings.SHARE.TEXT));
        multipartEntity.addPart("Image", new FileBody(image));
        httppost.setEntity(multipartEntity);

        mHttpClient.execute(httppost, new PhotoUploadResponseHandler());

    } catch (Exception e) {
        Log.e(ServerCommunication.class.getName(), e.getLocalizedMessage(), e);
    }
}

private class PhotoUploadResponseHandler implements ResponseHandler<Object> {

    @Override
    public Object handleResponse(HttpResponse response)
            throws ClientProtocolException, IOException {

        HttpEntity r_entity = response.getEntity();
        String responseString = EntityUtils.toString(r_entity);
        Log.d("UPLOAD", responseString);

        return null;
    }

}

How can I get the count of milliseconds since midnight for the current?

tl;dr

You ask for the fraction of a second of the current time as a number of milliseconds (not count from epoch).

Instant.now()                               // Get current moment in UTC, then…
       .get( ChronoField.MILLI_OF_SECOND )  // interrogate a `TemporalField`.

2017-04-25T03:01:14.113Z ? 113

  1. Get the fractional second in nanoseconds (billions).
  2. Divide by a thousand to truncate to milliseconds (thousands).

See this code run live at IdeOne.com.

Using java.time

The modern way is with the java.time classes.

Capture the current moment in UTC.

Instant.now()

Use the Instant.get method to interrogate for the value of a TemporalField. In our case, the TemporalField we want is ChronoField.MILLI_OF_SECOND.

int millis = Instant.now().get( ChronoField.MILLI_OF_SECOND ) ;  // Get current moment in UTC, then interrogate a `TemporalField`.

Or do the math yourself.

More likely you are asking this for a specific time zone. The fraction of a second is likely to be the same as with Instant but there are so many anomalies with time zones, I hesitate to make that assumption.

ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) ) ;

Interrogate for the fractional second. The Question asked for milliseconds, but java.time classes use a finer resolution of nanoseconds. That means the number of nanoseconds will range from from 0 to 999,999,999.

long nanosFractionOfSecond = zdt.getNano();

If you truly want milliseconds, truncate the finer data by dividing by one million. For example, a half second is 500,000,000 nanoseconds and also is 500 milliseconds.

long millis = ( nanosFractionOfSecond / 1_000_000L ) ;  // Truncate nanoseconds to milliseconds, by a factor of one million.

About java.time

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

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

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

Where to obtain the java.time classes?

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

Array to String PHP?

This one saves KEYS & VALUES

function array2string($data){
    $log_a = "";
    foreach ($data as $key => $value) {
        if(is_array($value))    $log_a .= "[".$key."] => (". array2string($value). ") \n";
        else                    $log_a .= "[".$key."] => ".$value."\n";
    }
    return $log_a;
}

Hope it helps someone.

Call child component method from parent class - Angular

user6779899's answer is neat and more generic However, based on the request by Imad El Hitti, a light weight solution is proposed here. This can be used when a child component is tightly connected to one parent only.

Parent.component.ts

export class Notifier {
    valueChanged: (data: number) => void = (d: number) => { };
}

export class Parent {
    notifyObj = new Notifier();
    tellChild(newValue: number) {
        this.notifyObj.valueChanged(newValue); // inform child
    }
}

Parent.component.html

<my-child-comp [notify]="notifyObj"></my-child-comp>

Child.component.ts

export class ChildComp implements OnInit{
    @Input() notify = new Notifier(); // create object to satisfy typescript
    ngOnInit(){
      this.notify.valueChanged = (d: number) => {
            console.log(`Parent has notified changes to ${d}`);
            // do something with the new value 
        };
    }
 }

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

Tensorflow has a fix in tf-nightly version.

!pip install tf-nightly

The current version is '2.0.0-dev20190511'.

Google Chrome Full Black Screen

You didn't mention anything about the environment you're running. This problem occurs on VirtualBox when running on Windows 10. One thing you can try is disabling 3D Acceleration on your VM, this is a known issue.

https://www.virtualbox.org/ticket/14985

What are the differences between if, else, and else if?

if (numOptions == 1)
    return "if";
else if (numOptions > 2)
    return "else if";
else 
    return "else";

Best way to increase heap size in catalina.bat file

If you look in your installation's bin directory you will see catalina.sh or .bat scripts. If you look in these you will see that they run a setenv.sh or setenv.bat script respectively, if it exists, to set environment variables. The relevant environment variables are described in the comments at the top of catalina.sh/bat. To use them create, for example, a file $CATALINA_HOME/bin/setenv.sh with contents

export JAVA_OPTS="-server -Xmx512m"

For Windows you will need, in setenv.bat, something like

set JAVA_OPTS=-server -Xmx768m

Original answer here

After you run startup.bat, you can easily confirm the correct settings have been applied provided you have turned @echo on somewhere in your catatlina.bat file (a good place could be immediately after echo Using CLASSPATH: "%CLASSPATH%"):

enter image description here

Android device does not show up in adb list

I had similar problem with my "Xiaomi Redmi Note 4" and tried almost 10 solutions I found over internet, but none of them helped my case. I've posted this answer to help someones like myself.

Installing "Intel USB Driver for Android Devices" totally solved my problem. It's described completely here.

Delete all local git branches

To delete all local branches in linux except the one you are on

// hard delete

git branch -D $(git branch)

Changing the child element's CSS when the parent is hovered

Not sure if there's terrible reasons to do this or not, but it seems to work with me on the latest version of Chrome/Firefox without any visible performance problems with quite a lot of elements on the page.

*:not(:hover)>.parent-hover-show{
    display:none;
}

But this way, all you need is to apply parent-hover-show to an element and the rest is taken care of, and you can keep whatever default display type you want without it always being "block" or making multiple classes for each type.

Add a month to a Date

The simplest way is to convert Date to POSIXlt format. Then perform the arithmetic operation as follows:

date_1m_fwd     <- as.POSIXlt("2010-01-01")
date_1m_fwd$mon <- date_1m_fwd$mon +1

Moreover, incase you want to deal with Date columns in data.table, unfortunately, POSIXlt format is not supported.

Still you can perform the add month using basic R codes as follows:

library(data.table)  
dt <- as.data.table(seq(as.Date("2010-01-01"), length.out=5, by="month"))  
dt[,shifted_month:=tail(seq(V1[1], length.out=length(V1)+3, by="month"),length(V1))]

Hope it helps.

Function ereg_replace() is deprecated - How to clear this bug?

Here is more information regarding replacing ereg_replace with preg_replace

What is the strict aliasing rule?

According to the C89 rationale, the authors of the Standard did not want to require that compilers given code like:

int x;
int test(double *p)
{
  x=5;
  *p = 1.0;
  return x;
}

should be required to reload the value of x between the assignment and return statement so as to allow for the possibility that p might point to x, and the assignment to *p might consequently alter the value of x. The notion that a compiler should be entitled to presume that there won't be aliasing in situations like the above was non-controversial.

Unfortunately, the authors of the C89 wrote their rule in a way that, if read literally, would make even the following function invoke Undefined Behavior:

void test(void)
{
  struct S {int x;} s;
  s.x = 1;
}

because it uses an lvalue of type int to access an object of type struct S, and int is not among the types that may be used accessing a struct S. Because it would be absurd to treat all use of non-character-type members of structs and unions as Undefined Behavior, almost everyone recognizes that there are at least some circumstances where an lvalue of one type may be used to access an object of another type. Unfortunately, the C Standards Committee has failed to define what those circumstances are.

Much of the problem is a result of Defect Report #028, which asked about the behavior of a program like:

int test(int *ip, double *dp)
{
  *ip = 1;
  *dp = 1.23;
  return *ip;
}
int test2(void)
{
  union U { int i; double d; } u;
  return test(&u.i, &u.d);
}

Defect Report #28 states that the program invokes Undefined Behavior because the action of writing a union member of type "double" and reading one of type "int" invokes Implementation-Defined behavior. Such reasoning is nonsensical, but forms the basis for the Effective Type rules which needlessly complicate the language while doing nothing to address the original problem.

The best way to resolve the original problem would probably be to treat the footnote about the purpose of the rule as though it were normative, and made the rule unenforceable except in cases which actually involve conflicting accesses using aliases. Given something like:

 void inc_int(int *p) { *p = 3; }
 int test(void)
 {
   int *p;
   struct S { int x; } s;
   s.x = 1;
   p = &s.x;
   inc_int(p);
   return s.x;
 }

There's no conflict within inc_int because all accesses to the storage accessed through *p are done with an lvalue of type int, and there's no conflict in test because p is visibly derived from a struct S, and by the next time s is used, all accesses to that storage that will ever be made through p will have already happened.

If the code were changed slightly...

 void inc_int(int *p) { *p = 3; }
 int test(void)
 {
   int *p;
   struct S { int x; } s;
   p = &s.x;
   s.x = 1;  //  !!*!!
   *p += 1;
   return s.x;
 }

Here, there is an aliasing conflict between p and the access to s.x on the marked line because at that point in execution another reference exists that will be used to access the same storage.

Had Defect Report 028 said the original example invoked UB because of the overlap between the creation and use of the two pointers, that would have made things a lot more clear without having to add "Effective Types" or other such complexity.

When should I use semicolons in SQL Server?

In SQL2008 BOL they say that in next releases semicolons will be required. Therefore, always use it.

Reference:

Format numbers in thousands (K) in Excel

I've found the following combination that works fine for positive and negative numbers (43787200020 is transformed to 43.787.200,02 K)

[>=1000] #.##0,#0. "K";#.##0,#0. "K"

HTTP POST using JSON in Java

Java 8 with apache httpClient 4

CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("www.site.com");


String json = "details={\"name\":\"myname\",\"age\":\"20\"} ";

        try {
            StringEntity entity = new StringEntity(json);
            httpPost.setEntity(entity);

            // set your POST request headers to accept json contents
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            try {
                // your closeablehttp response
                CloseableHttpResponse response = client.execute(httpPost);

                // print your status code from the response
                System.out.println(response.getStatusLine().getStatusCode());

                // take the response body as a json formatted string 
                String responseJSON = EntityUtils.toString(response.getEntity());

                // convert/parse the json formatted string to a json object
                JSONObject jobj = new JSONObject(responseJSON);

                //print your response body that formatted into json
                System.out.println(jobj);

            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {

                e.printStackTrace();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

Using XAMPP, how do I swap out PHP 5.3 for PHP 5.2?

Years later, but for what it's worth - This is simple to do.

  • Just RENAME the C:\xampp directory

  • Install the desired new version of XAMPP

  • Simply run the control panel script "xampp-control.exe" directly from within the xampp folder. (Ignore warnings about "must run from C:\xampp - those have nothing to do with multiple installations.)

To switch between these versions of XAMPP, just rename the xampp directories as necessary, and re-run.

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

The answers so far are great! But I see a need for a solution with the following constraints:

  1. Plain, concise LINQ;
  2. O(n) complexity;
  3. Do not evaluate the property more than once per element.

Here it is:

public static T MaxBy<T, R>(this IEnumerable<T> en, Func<T, R> evaluate) where R : IComparable<R> {
    return en.Select(t => new Tuple<T, R>(t, evaluate(t)))
        .Aggregate((max, next) => next.Item2.CompareTo(max.Item2) > 0 ? next : max).Item1;
}

public static T MinBy<T, R>(this IEnumerable<T> en, Func<T, R> evaluate) where R : IComparable<R> {
    return en.Select(t => new Tuple<T, R>(t, evaluate(t)))
        .Aggregate((max, next) => next.Item2.CompareTo(max.Item2) < 0 ? next : max).Item1;
}

Usage:

IEnumerable<Tuple<string, int>> list = new[] {
    new Tuple<string, int>("other", 2),
    new Tuple<string, int>("max", 4),
    new Tuple<string, int>("min", 1),
    new Tuple<string, int>("other", 3),
};
Tuple<string, int> min = list.MinBy(x => x.Item2); // "min", 1
Tuple<string, int> max = list.MaxBy(x => x.Item2); // "max", 4

Make an Android button change background on click through XML

In the latest version of the SDK, you would use the setBackgroundResource method.

public void onClick(View v) {
   if(v == ButtonName) {
     ButtonName.setBackgroundResource(R.drawable.ImageResource);
   }
}

Send POST data on redirect with JavaScript/jQuery?

per @Kevin-Reid's answer, here's an alternative to the "I ended up doing the following" example that avoids needing to name and then lookup the form object again by constructing the form specifically (using jQuery)..

var url = 'http://example.com/vote/' + Username;
var form = $('<form action="' + url + '" method="post">' +
  '<input type="text" name="api_url" value="' + Return_URL + '" />' +
  '</form>');
$('body').append(form);
form.submit();

How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

I'm using Database First and when this error happened to me my solution was to force ProviderManifestToken="2005" in edmx file (making the models compatible with SQL Server 2005). Don't know if something similar is possible for Code First.

How to set timeout for a line of c# code

You can use the IAsyncResult and Action class/interface to achieve this.

public void TimeoutExample()
{
    IAsyncResult result;
    Action action = () =>
    {
        // Your code here
    };

    result = action.BeginInvoke(null, null);

    if (result.AsyncWaitHandle.WaitOne(10000))
         Console.WriteLine("Method successful.");
    else
         Console.WriteLine("Method timed out.");
}

What are the "standard unambiguous date" formats for string-to-date conversion in R?

This works perfectly for me, not matter how the date was coded previously.

library(lubridate)
data$created_date1 <- mdy_hm(data$created_at)
data$created_date1 <- as.Date(data$created_date1)

How do I call a function inside of another function?

function function_one() {
  function_two(); 
}

function function_two() {
//enter code here
}

Using arrays or std::vectors in C++, what's the performance gap?

STL is a heavily optimized library. In fact, it's even suggested to use STL in games where high performance might be needed. Arrays are too error prone to be used in day to day tasks. Today's compilers are also very smart and can really produce excellent code with STL. If you know what you are doing, STL can usually provide the necessary performance. For example by initializing vectors to required size (if you know from start), you can basically achieve the array performance. However, there might be cases where you still need arrays. When interfacing with low level code (i.e. assembly) or old libraries that require arrays, you might not be able to use vectors.

Mongoose query where value is not null

Hello guys I am stucked with this. I've a Document Profile who has a reference to User,and I've tried to list the profiles where user ref is not null (because I already filtered by rol during the population), but after googleing a few hours I cannot figure out how to get this. I have this query:

const profiles = await Profile.find({ user: {$exists: true,  $ne: null }})
                            .select("-gallery")
                            .sort( {_id: -1} )
                            .skip( skip )
                            .limit(10)
                            .select(exclude)
                            .populate({
                                path: 'user',
                                match: { role: {$eq: customer}},
                                select: '-password -verified -_id -__v'
                              })

                            .exec();

And I get this result, how can I remove from the results the user:null colletions? . I meant, I dont want to get the profile when user is null (the role does not match).
{
    "code": 200,
    "profiles": [
        {
            "description": null,
            "province": "West Midlands",
            "country": "UK",
            "postal_code": "83000",
            "user": null
        },
        {
            "description": null,

            "province": "Madrid",
            "country": "Spain",
            "postal_code": "43000",
            "user": {
                "role": "customer",
                "name": "pedrita",
                "email": "[email protected]",
                "created_at": "2020-06-05T11:05:36.450Z"
            }
        }
    ],
    "page": 1
}

Thanks in advance.

How can I find the link URL by link text with XPath?

Should be something similar to:

//a[text()='text_i_want_to_find']/@href

Pure JavaScript: a function like jQuery's isNumeric()

function IsNumeric(val) {
    return Number(parseFloat(val)) === val;
}

Can a unit test project load the target application's app.config file?

Whether you're using Team System Test or NUnit, the best practice is to create a separate Class Library for your tests. Simply adding an App.config to your Test project will automatically get copied to your bin folder when you compile.

If your code is reliant on specific configuration tests, the very first test I would write validates that the configuration file is available (so that I know I'm not insane) :

<configuration>
   <appSettings>
       <add key="TestValue" value="true" />
   </appSettings>
</configuration>

And the test:

[TestFixture]
public class GeneralFixture
{
     [Test]
     public void VerifyAppDomainHasConfigurationSettings()
     {
          string value = ConfigurationManager.AppSettings["TestValue"];
          Assert.IsFalse(String.IsNullOrEmpty(value), "No App.Config found.");
     }
}

Ideally, you should be writing code such that your configuration objects are passed into your classes. This not only separates you from the configuration file issue, but it also allows you to write tests for different configuration scenarios.

public class MyObject
{
     public void Configure(MyConfigurationObject config)
     {
          _enabled = config.Enabled;
     }

     public string Foo()
     {
         if (_enabled)
         {
             return "foo!";
         }
         return String.Empty;
     }

     private bool _enabled;
}

[TestFixture]
public class MyObjectTestFixture
{
     [Test]
     public void CanInitializeWithProperConfig()
     {
         MyConfigurationObject config = new MyConfigurationObject();
         config.Enabled = true;

         MyObject myObj = new MyObject();
         myObj.Configure(config);

         Assert.AreEqual("foo!", myObj.Foo());
     }
}

What does the "@" symbol do in SQL?

You may be used to MySQL's syntax: Microsoft SQL @ is the same as the MySQL's ?

Configure WAMP server to send email

Sendmail wasn't working for me so I used msmtp 1.6.2 w32 and most just followed the instructions at DeveloperSide. Here is a quick rundown of the setup for posterity:

Enabled IMAP access under your Gmail account (the one msmtp is sending emails from)

Enable access for less secure apps. Log into your google account and go here

Edit php.ini, find and change each setting below to reflect the following:

; These are commented out by prefixing a semicolon
;SMTP = localhost
;smtp_port = 25

; Set these paths to where you put your msmtp files.
; I used backslashes in php.ini and it works fine.
; The example in the devside guide uses forwardslashes. 
sendmail_path = "C:\wamp64\msmtp\msmtp.exe -d -C C:\wamp64\msmtp\msmtprc.ini -t --read-envelope-from"

mail.log = "C:\wamp64\msmtp\maillog.txt"

Create and edit the file msmtprc.ini in the same directory as your msmtp.exe file as follows, replacing it with your own email and password:

# Default values for all accounts
defaults
tls_certcheck off
# I used forward slashes here and it works.
logfile C:/wamp64/msmtp/msmtplog.txt

account Gmail
host smtp.gmail.com
port 587
auth on
tls on
from [email protected]
user [email protected]
password ReplaceWithYourPassword
account default : gmail

php function mail() isn't working

I think you are not configured properly,

if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(use the above send mail path only and it will work)

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.

Update

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

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

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

Getting user input

Use the raw_input() function to get input from users (2.x):

print "Enter a file name:",
filename = raw_input()

or just:

filename = raw_input('Enter a file name: ')

or if in Python 3.x:

filename = input('Enter a file name: ')

How can I "reset" an Arduino board?

Based on my experience with the communication already in use or blocked, I would say that the program you are interfacing with still has the communication open.

I also found that if you disconnect the USB cable it will rest the communication. It is not the greatest solution, but it solves the problem.

Android Fragment onAttach() deprecated

If you use the the framework fragments and the SDK version of the device is lower than 23, OnAttach(Context context) wouldn't be called.

I use support fragments instead, so deprecation is fixed and onAttach(Context context) always gets called.

Table with table-layout: fixed; and how to make one column wider

What you could do is something like this (pseudocode):

<container table>
  <tr>
    <td>
      <"300px" table>
    <td>
      <fixed layout table>

Basically, split up the table into two tables and have it contained by another table.

Check if a key exists inside a json object

function to check undefined and null objects

function elementCheck(objarray, callback) {
        var list_undefined = "";
        async.forEachOf(objarray, function (item, key, next_key) {
            console.log("item----->", item);
            console.log("key----->", key);
            if (item == undefined || item == '') {
                list_undefined = list_undefined + "" + key + "!!  ";
                next_key(null);
            } else {
                next_key(null);
            }
        }, function (next_key) {
            callback(list_undefined);
        })
    }

here is an easy way to check whether object sent is contain undefined or null

var objarray={
"passenger_id":"59b64a2ad328b62e41f9050d",
"started_ride":"1",
"bus_id":"59b8f920e6f7b87b855393ca",
"route_id":"59b1333c36a6c342e132f5d5",
"start_location":"",
"stop_location":""
}
elementCheck(objarray,function(list){
console.log("list");
)

Convert String (UTF-16) to UTF-8 in C#

A string in C# is always UTF-16, there is no way to "convert" it. The encoding is irrelevant as long as you manipulate the string in memory, it only matters if you write the string to a stream (file, memory stream, network stream...).

If you want to write the string to a XML file, just specify the encoding when you create the XmlWriter

Math functions in AngularJS bindings

I think the best way to do it is by creating a filter, like this:

myModule.filter('ceil', function() {
    return function(input) {
        return Math.ceil(input);
    };
});

then the markup looks like this:

<p>The percentage is {{ (100*count/total) | ceil }}%</p>

Updated fiddle: http://jsfiddle.net/BB4T4/

Iterating on a file doesn't work the second time

Of course. That is normal and sane behaviour. Instead of closing and re-opening, you could rewind the file.

How to decode a QR-code image in (preferably pure) Python?

For Windows using ZBar

Pre-requisites:

To decode:

from PIL import Image
from pyzbar import pyzbar

img = Image.open('My-Image.jpg')
output = pyzbar.decode(img)
print(output)

Alternatively, you can also try using ZBarLight by setting it up as mentioned here:
https://pypi.org/project/zbarlight/

Get current application physical path within Application_Start

You can also use

HttpRuntime.AppDomainAppVirtualPath

How do I strip all spaces out of a string in PHP?

Do you just mean spaces or all whitespace?

For just spaces, use str_replace:

$string = str_replace(' ', '', $string);

For all whitespace (including tabs and line ends), use preg_replace:

$string = preg_replace('/\s+/', '', $string);

(From here).

How to enable named/bind/DNS full logging?

Run command rndc querylog on or add querylog yes; to options{}; section in named.conf to activate that channel.

Also make sure you’re checking correct directory if your bind is chrooted.

Is it possible to have a multi-line comments in R?

Put the following into your ~/.Rprofile file:

exclude <-  function(blah) {
    "excluded block"
}

Now, you can exclude blocks like follows:

stuffiwant

exclude({
    stuffidontwant
    morestuffidontwant
})

HashMap to return default value for non-found keys?

You can simply create a new class that inherits HashMap and add getDefault method. Here is a sample code:

public class DefaultHashMap<K,V> extends HashMap<K,V> {
    public V getDefault(K key, V defaultValue) {
        if (containsKey(key)) {
            return get(key);
        }

        return defaultValue;
    }
}

I think that you should not override get(K key) method in your implementation, because of the reasons specified by Ed Staub in his comment and because you will break the contract of Map interface (this can potentially lead to some hard-to-find bugs).

Using pickle.dump - TypeError: must be str, not bytes

The output file needs to be opened in binary mode:

f = open('varstor.txt','w')

needs to be:

f = open('varstor.txt','wb')

Export table data from one SQL Server to another

If you don't have permission to link servers, here are the steps to import a table from one server to another using Sql Server Import/Export Wizard:

  • Right click on the source database you want to copy from.
  • Select Tasks - Export Data.
  • Select Sql Server Native Client in the data source.
  • Select your authentication type (Sql Server or Windows authentication).
  • Select the source database.
  • Next, choose the Destination: Sql Server Native Client
  • Type in your Server Name (the server you want to copy the table to).
  • Select your authentication type (Sql Server or Windows authentication).
  • Select the destination database.
  • Select Copy data.
  • Select your table from the list.
  • Hit Next, Select Run immediately, or optionally, you can also save the package to a file or Sql Server if you want to run it later.
  • Finish

Calculate execution time of a SQL query?

try this

DECLARE @StartTime DATETIME
SET @StartTime = GETDATE()

  SET @EndTime = GETDATE()
  PRINT 'StartTime = ' + CONVERT(VARCHAR(30),@StartTime,121)
  PRINT '  EndTime = ' + CONVERT(VARCHAR(30),@EndTime,121)
  PRINT ' Duration = ' + CONVERT(VARCHAR(30),@EndTime -@starttime,114)

If that doesn't do it, then try SET STATISTICS TIME ON

How to use forEach in vueJs?

In VueJS you can loop through an array like this : const array1 = ['a', 'b', 'c'];

Array.from(array1).forEach(element => 
 console.log(element)
      );

in my case I want to loop through files and add their types to another array:

 Array.from(files).forEach((file) => {
       if(this.mediaTypes.image.includes(file.type)) {
            this.media.images.push(file)
             console.log(this.media.images)
       }
   }

TypeScript and React - children type?

The function component return type is limited to JSXElement | null in TypeScript. This is a current type limitation, pure React allows more return types.

Minimal demonstration snippet

You can either use a type assertion or Fragments as workaround:

const Aux = (props: AuxProps) => <>props.children</>; 
const Aux2 = (props: AuxProps) => props.children as ReactElement; 

ReactNode

children: React.ReactNode might be suboptimal, if the goal is to have strong types for Aux.

Almost anything can be assigned to current ReactNode type, which is equivalent to {} | undefined | null. A safer type for your case could be:

interface AuxProps {
  children: ReactElement | ReactElement[]
}

Example:

Given Aux needs React elements as children, we accidently added a string to it. Then above solution would error in contrast to ReactNode - take a look at the linked playgrounds.

Typed children are also useful for non-JSX props, like a Render Prop callback.

update to python 3.7 using anaconda

run conda navigator, you can upgrade your packages easily in the friendly GUI

PHP - SSL certificate error: unable to get local issuer certificate

Finally got this to work!

  1. Download the certificate bundle.

  2. Put it somewhere. In my case, that was c:\wamp\ directory (if you are using Wamp 64 bit then it's c:\wamp64\).

  3. Enable mod_ssl in Apache and php_openssl.dll in php.ini (uncomment them by removing ; at the beginning). But be careful, my problem was that I had two php.ini files and I need to do this in both of them. One is the one you get from your WAMP taskbar icon, and another one is, in my case, in C:\wamp\bin\php\php5.5.12\

  4. Add these lines to your cert in both php.ini files:

    curl.cainfo="C:/wamp/cacert.pem"
    openssl.cafile="C:/wamp/cacert.pem"
    
  5. Restart Wamp services.

How can I create and style a div using JavaScript?

You can just use the method below:

document.write()

It is very simple, in the doc below I explain

_x000D_
_x000D_
document.write("<div class='div'>Some content inside the div (It is styled!)</div>")
_x000D_
.div {
  background-color: red;
  padding: 5px;
  color: #fff;
  font-family: Arial;
  cursor: pointer;
}

.div:hover {
  background-color: blue;
  padding: 10px;
}

.div:hover:before {
  content: 'Hover! ';
}

.div:active {
  background-color: green;
  padding: 15px;
}

.div:active:after {
  content: ' Active! or clicked...';
}
_x000D_
<p>Below or above well show the div</p>
<p>Try pointing hover it and clicking on it. Those are tha styles aplayed. The text and background color changes.</p>
_x000D_
_x000D_
_x000D_

Twitter bootstrap scrollable modal

None of this will work as expected.. The correct way is to change position: fixed to position: absolute for .modal class

org.hibernate.MappingException: Unknown entity

I encountered the same problem when I switched to AnnotationSessionFactoryBean. I was using entity.hbm.xml before.

I found that My class was missing following annotation which resolved the issue in my case:

@Entity
@Table(name = "MyTestEntity")
@XmlRootElement

Hadoop: «ERROR : JAVA_HOME is not set»

You can add in your .bashrc file:

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")

and it will dynamically change when you update your packages.

Inserting a text where cursor is using Javascript/jquery

The code above didn't work for me in IE. Here's some code based on this answer.

I took out the getElementById so I could reference the element in a different way.

_x000D_
_x000D_
function insertAtCaret(element, text) {_x000D_
  if (document.selection) {_x000D_
    element.focus();_x000D_
    var sel = document.selection.createRange();_x000D_
    sel.text = text;_x000D_
    element.focus();_x000D_
  } else if (element.selectionStart || element.selectionStart === 0) {_x000D_
    var startPos = element.selectionStart;_x000D_
    var endPos = element.selectionEnd;_x000D_
    var scrollTop = element.scrollTop;_x000D_
    element.value = element.value.substring(0, startPos) +_x000D_
      text + element.value.substring(endPos, element.value.length);_x000D_
    element.focus();_x000D_
    element.selectionStart = startPos + text.length;_x000D_
    element.selectionEnd = startPos + text.length;_x000D_
    element.scrollTop = scrollTop;_x000D_
  } else {_x000D_
    element.value += text;_x000D_
    element.focus();_x000D_
  }_x000D_
}
_x000D_
input{width:100px}_x000D_
label{display:block;margin:10px 0}
_x000D_
<label for="in2copy">Copy text from: <input id="in2copy" type="text" value="x"></label>_x000D_
<label for="in2ins">Element to insert: <input id="in2ins" type="text" value="1,2,3" autofocus></label>_x000D_
<button onclick="insertAtCaret(document.getElementById('in2ins'),document.getElementById('in2copy').value)">Insert</button>
_x000D_
_x000D_
_x000D_

EDIT: Added a running snippet, jQuery is not being used.

Does a valid XML file require an XML declaration?

In XML 1.0, the XML Declaration is optional. See section 2.8 of the XML 1.0 Recommendation, where it says it "should" be used -- which means it is recommended, but not mandatory. In XML 1.1, however, the declaration is mandatory. See section 2.8 of the XML 1.1 Recommendation, where it says "MUST" be used. It even goes on to state that if the declaration is absent, that automatically implies the document is an XML 1.0 document.

Note that in an XML Declaration the encoding and standalone are both optional. Only the version is mandatory. Also, these are not attributes, so if they are present they must be in that order: version, followed by any encoding, followed by any standalone.

<?xml version="1.0"?>
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" standalone="yes"?>
<?xml version="1.0" encoding="UTF-16" standalone="yes"?>

If you don't specify the encoding in this way, XML parsers try to guess what encoding is being used. The XML 1.0 Recommendation describes one possible way character encoding can be autodetected. In practice, this is not much of a problem if the input is encoded as UTF-8, UTF-16 or US-ASCII. Autodetection doesn't work when it encounters 8-bit encodings that use characters outside the US-ASCII range (e.g. ISO 8859-1) -- avoid creating these if you can.

The standalone indicates whether the XML document can be correctly processed without the DTD or not. People rarely use it. These days, it is a bad to design an XML format that is missing information without its DTD.

Update:

A "prolog error/invalid utf-8 encoding" error indicates that the actual data the parser found inside the file did not match the encoding that the XML declaration says it is. Or in some cases the data inside the file did not match the autodetected encoding.

Since your file contains a byte-order-mark (BOM) it should be in UTF-16 encoding. I suspect that your declaration says <?xml version="1.0" encoding="UTF-8"?> which is obviously incorrect when the file has been changed into UTF-16 by NotePad. The simple solution is to remove the encoding and simply say <?xml version="1.0"?>. You could also edit it to say encoding="UTF-16" but that would be wrong for the original file (which wasn't in UTF-16) or if the file somehow gets changed back to UTF-8 or some other encoding.

Don't bother trying to remove the BOM -- that's not the cause of the problem. Using NotePad or WordPad to edit XML is the real problem!

What does 'x packages are looking for funding' mean when running `npm install`?

npm fund [<pkg>]

This command retrieves information on how to fund the dependencies of a given project. If no package name is provided, it will list all dependencies that are looking for funding in a tree-structure in which are listed the type of funding and the url to visit.
The message can be disabled using: npm install --no-fund