Programs & Examples On #Copywithzone

Laravel 5.2 - pluck() method returns array

laravel pluck returns an array

if your query is:

 $name = DB::table('users')->where('name', 'John')->pluck('name');

then the array is like this (key is the index of the item. auto incremented value):

[
    1 => "name1",
    2 => "name2",
    .
    .
    .
    100 => "name100"
]

but if you do like this:

$name = DB::table('users')->where('name', 'John')->pluck('name','id');

then the key is actual index in the database.

key||value
[
    1 => "name1",
    2 => "name2",
    .
    .
    .
    100 => "name100"
]

you can set any value as key.

Why is my asynchronous function returning Promise { <pending> } instead of a value?

I know this question was asked 2 years ago, but I run into the same issue and the answer for the problem is since ES2017, that you can simply await the functions return value (as of now, only works in async functions), like:

let AuthUser = function(data) {
  return google.login(data.username, data.password).then(token => { return token } )
}

let userToken = await AuthUser(data)
console.log(userToken) // your data

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

Split String into an array of String

String[] result = "hi i'm paul".split("\\s+"); to split across one or more cases.

Or you could take a look at Apache Common StringUtils. It has StringUtils.split(String str) method that splits string using white space as delimiter. It also has other useful utility methods

remove empty lines from text file with PowerShell

This will remove empty lines or lines with only whitespace characters (tabs/spaces).

[IO.File]::ReadAllText("FileWithEmptyLines.txt") -replace '\s+\r\n+', "`r`n" | Out-File "c:\FileWithNoEmptyLines.txt"

Multiple models in a view

Do I need to make another view which holds these 2 views?

Answer:No

Isn't there another way such as (without the BigViewModel):

Yes, you can use Tuple (brings magic in view having multiple model).

Code:

 @model Tuple<LoginViewModel, RegisterViewModel>


    @using (Html.BeginForm("Login", "Auth", FormMethod.Post))
    {
     @Html.TextBoxFor(tuple=> tuple.Item.Name)
     @Html.TextBoxFor(tuple=> tuple.Item.Email)
     @Html.PasswordFor(tuple=> tuple.Item.Password)
    }


    @using (Html.BeginForm("Login", "Auth", FormMethod.Post))
     {
      @Html.TextBoxFor(tuple=> tuple.Item1.Email)
      @Html.PasswordFor(tuple=> tuple.Item1.Password)
     }

read input separated by whitespace(s) or newline...?

std::getline( stream, where to?, delimiter ie

std::string in;
std::getline(std::cin, in, ' '); //will split on space

or you can read in a line, then tokenize it based on whichever delimiter you wish.

Why can't I center with margin: 0 auto?

We can set the width for ul tag then it will align center.

#header ul {
    display: block;
    margin: 0 auto;
    width: 420px;
    max-width: 100%;
}

Parse query string into an array

You can use the PHP string function parse_str() followed by foreach loop.

$str="pg_id=2&parent_id=2&document&video";
parse_str($str,$my_arr);
foreach($my_arr as $key=>$value){
  echo "$key => $value<br>";
}
print_r($my_arr);

Postgresql column reference "id" is ambiguous

SELECT (vg.id, name) FROM v_groups vg 
INNER JOIN people2v_groups p2vg ON vg.id = p2vg.v_group_id
WHERE p2vg.people_id = 0;

How to override equals method in Java

When comparing objects in Java, you make a semantic check, comparing the type and identifying state of the objects to:

  • itself (same instance)
  • itself (clone, or reconstructed copy)
  • other objects of different types
  • other objects of the same type
  • null

Rules:

  • Symmetry: a.equals(b) == b.equals(a)
  • equals() always yields true or false, but never a NullpointerException, ClassCastException or any other throwable

Comparison:

  • Type check: both instances need to be of the same type, meaning you have to compare the actual classes for equality. This is often not correctly implemented, when developers use instanceof for type comparison (which only works as long as there are no subclasses, and violates the symmetry rule when A extends B -> a instanceof b != b instanceof a).
  • Semantic check of identifying state: Make sure you understand by which state the instances are identified. Persons may be identified by their social security number, but not by hair color (can be dyed), name (can be changed) or age (changes all the time). Only with value objects should you compare the full state (all non-transient fields), otherwise check only what identifies the instance.

For your Person class:

public boolean equals(Object obj) {

    // same instance
    if (obj == this) {
        return true;
    }
    // null
    if (obj == null) {
        return false;
    }
    // type
    if (!getClass().equals(obj.getClass())) {
        return false;
    }
    // cast and compare state
    Person other = (Person) obj;
    return Objects.equals(name, other.name) && Objects.equals(age, other.age);
}

Reusable, generic utility class:

public final class Equals {

    private Equals() {
        // private constructor, no instances allowed
    }

    /**
     * Convenience equals implementation, does the object equality, null and type checking, and comparison of the identifying state
     *
     * @param instance       object instance (where the equals() is implemented)
     * @param other          other instance to compare to
     * @param stateAccessors stateAccessors for state to compare, optional
     * @param <T>            instance type
     * @return true when equals, false otherwise
     */
    public static <T> boolean as(T instance, Object other, Function<? super T, Object>... stateAccessors) {
        if (instance == null) {
            return other == null;
        }
        if (instance == other) {
            return true;
        }
        if (other == null) {
            return false;
        }
        if (!instance.getClass().equals(other.getClass())) {
            return false;
        }
        if (stateAccessors == null) {
            return true;
        }
        return Stream.of(stateAccessors).allMatch(s -> Objects.equals(s.apply(instance), s.apply((T) other)));
    }
}

For your Person class, using this utility class:

public boolean equals(Object obj) {
    return Equals.as(this, obj, t -> t.name, t -> t.age);
}

How do I split a string on a delimiter in Bash?

Two bourne-ish alternatives where neither require bash arrays:

Case 1: Keep it nice and simple: Use a NewLine as the Record-Separator... eg.

IN="[email protected]
[email protected]"

while read i; do
  # process "$i" ... eg.
    echo "[email:$i]"
done <<< "$IN"

Note: in this first case no sub-process is forked to assist with list manipulation.

Idea: Maybe it is worth using NL extensively internally, and only converting to a different RS when generating the final result externally.

Case 2: Using a ";" as a record separator... eg.

NL="
" IRS=";" ORS=";"

conv_IRS() {
  exec tr "$1" "$NL"
}

conv_ORS() {
  exec tr "$NL" "$1"
}

IN="[email protected];[email protected]"
IN="$(conv_IRS ";" <<< "$IN")"

while read i; do
  # process "$i" ... eg.
    echo -n "[email:$i]$ORS"
done <<< "$IN"

In both cases a sub-list can be composed within the loop is persistent after the loop has completed. This is useful when manipulating lists in memory, instead storing lists in files. {p.s. keep calm and carry on B-) }

With ng-bind-html-unsafe removed, how do I inject HTML?

You can create your own simple unsafe html binding, of course if you use user input it could be a security risk.

App.directive('simpleHtml', function() {
  return function(scope, element, attr) {
    scope.$watch(attr.simpleHtml, function (value) {
      element.html(scope.$eval(attr.simpleHtml));
    })
  };
})

How to get the current date and time

tl;dr

Instant.now()

java.time

The java.util.Date class has been outmoded by the new java.time package (Tutorial) in Java 8 and later. The old java.util.Date/.Calendar classes are notoriously troublesome, confusing, and flawed. Avoid them.

ZonedDateTime

Get the current moment in java.time.

ZonedDateTime now = ZonedDateTime.now();

A ZonedDateTime encapsulates:

  • Date.
  • Time-of-day, with a fraction of a second to nanosecond resolution.
  • Time zone.

If no time zone is specified, your JVM’s current default time zone is assigned silently. Better to specify your desired/expected time zone than rely implicitly on default.

ZoneId z = ZoneId.of( "Pacific/Auckland" );
ZonedDateTime zdt = ZonedDateTime.now( z );

UTC

Generally better to get in the habit of doing your back-end work (business logic, database, storage, data exchange) all in UTC time zone. The code above relies implicitly on the JVM’s current default time zone.

The Instant class represents a moment in the timeline in UTC with a resolution of nanoseconds.

Instant instant = Instant.now();

The Instant class is a basic building-block class in java.time and may be used often in your code.

When you need more flexibility in formatting, transform into an OffsetDateTime. Specify a ZoneOffset object. For UTC use the handy constant for UTC.

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );

Time Zone

You easily adjust to another time zone for presentation to the user. Use a proper time zone name, never the 3-4 letter codes such as EST or IST.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime nowMontreal = instant.atZone( z );

Generate a String representation of that date-time value, localized.

String output = DateTimeFormatter
    .ofLocalizedDate( FormatStyle.FULL )
    .withLocale( Locale.CANADA_FRENCH )
    .format ( nowMontreal );

Instant

Or, to stay in UTC, use Instant. An Instant object represents a moment on the timeline, to nanosecond resolution, always in UTC. This provides the building block for a zoned date-time, along with a time zone assignment. You can think of it conceptually this way:

ZonedDateTime = Instant + ZoneId

You can extract an Instant from a ZonedDateTime.

Instant instantNow = zdt.toInstant();

You can start with an Instant. No need to specify a time zone here, as Instant is always in UTC.

Instant now = Instant.now();

asp.net mvc3 return raw html to view

That looks fine, unless you want to pass it as Model string

public class HomeController : Controller
{
    public ActionResult Index()
    {
        string model = "<HTML></HTML>";
        return View(model);
    }
}

@model string
@{
    ViewBag.Title = "Index";
}

@Html.Raw(Model)

Generate random colors (RGB)

A neat way to generate RGB triplets within the 256 (aka 8-byte) range is

color = list(np.random.choice(range(256), size=3))

color is now a list of size 3 with values in the range 0-255. You can save it in a list to record if the color has been generated before or no.

C#: New line and tab characters in strings

    StringBuilder SqlScript = new StringBuilder();

    foreach (var file in lstScripts)
    {
        var input = File.ReadAllText(file.FilePath);
        SqlScript.AppendFormat(input, Environment.NewLine);
    }

http://afzal-gujrat.blogspot.com/

How can foreign key constraints be temporarily disabled using T-SQL?

One script to rule them all: this combines truncate and delete commands with sp_MSforeachtable so that you can avoid dropping and recreating constraints - just specify the tables that need to be deleted rather than truncated and for my purposes I have included an extra schema filter for good measure (tested in 2008r2)

declare @schema nvarchar(max) = 'and Schema_Id=Schema_id(''Value'')'
declare @deletiontables nvarchar(max) = '(''TableA'',''TableB'')'
declare @truncateclause nvarchar(max) = @schema + ' and o.Name not in ' +  + @deletiontables;
declare @deleteclause nvarchar(max) = @schema + ' and o.Name in ' + @deletiontables;        

exec sp_MSforeachtable 'alter table ? nocheck constraint all', @whereand=@schema
exec sp_MSforeachtable 'truncate table ?', @whereand=@truncateclause
exec sp_MSforeachtable 'delete from ?', @whereand=@deleteclause
exec sp_MSforeachtable 'alter table ? with check check constraint all', @whereand=@schema

How does the JPA @SequenceGenerator annotation work

sequenceName is the name of the sequence in the DB. This is how you specify a sequence that already exists in the DB. If you go this route, you have to specify the allocationSize which needs to be the same value that the DB sequence uses as its "auto increment".

Usage:

@GeneratedValue(generator="my_seq")
@SequenceGenerator(name="my_seq",sequenceName="MY_SEQ", allocationSize=1)

If you want, you can let it create a sequence for you. But to do this, you must use SchemaGeneration to have it created. To do this, use:

@GeneratedValue(strategy=GenerationType.SEQUENCE)

Also, you can use the auto-generation, which will use a table to generate the IDs. You must also use SchemaGeneration at some point when using this feature, so the generator table can be created. To do this, use:

@GeneratedValue(strategy=GenerationType.AUTO)

How to strip all whitespace from string

Try a regex with re.sub. You can search for all whitespace and replace with an empty string.

\s in your pattern will match whitespace characters - and not just a space (tabs, newlines, etc). You can read more about it in the manual.

Getting "net::ERR_BLOCKED_BY_CLIENT" error on some AJAX calls

As it has been explained here, beside of multiple extensions that perform ad or script blocking you may aware that this may happen by file names as below:

Particularly in the AdBlock Plus the character string "-300x600" is causing the Failed to Load Resource ERR_BLOCKED_BY_CLIENT problem.

As shown in the picture, some of the images were blocked because of the '-300x600' pattern in their name, that particular text pattern matches an expression list pattern in the AdBlock Plus.

ERR_BLOCKED_BY_CLIENT problem

Assign multiple values to array in C

With code like this:

const int node_ct = 8;
const int expected[node_ct] = { 1, 3, 4, 2, 5, 6, 7, 8 };

And in the configure.ac

AC_PROG_CC_C99

The compiler on my dev box was happy. The compiler on the server complained with:

error: variable-sized object may not be initialized
   const int expected[node_ct] = { 1, 3, 4, 2, 5, 6, 7, 8 };

and

warning: excess elements in array initializer
   const int expected[node_ct] = { 1, 3, 4, 2, 5, 6, 7, 8 };

for each element

It doesn't complain at all about, for example:

int expected[] = { 1, 2, 3, 4, 5 };

however, I decided that I like the check on size.

Rather than fighting, I went with a varargs initializer:

#include <stdarg.h>

void int_array_init(int *a, const int ct, ...) {
  va_list args;
  va_start(args, ct);
  for(int i = 0; i < ct; ++i) {
    a[i] = va_arg(args, int);
  }
  va_end(args);
}

called like,

const int node_ct = 8;
int expected[node_ct];
int_array_init(expected, node_ct, 1, 3, 4, 2, 5, 6, 7, 8);

As such, the varargs support is more robust than the support for the array initializer.

Someone might be able to do something like this in a macro.

Find PR with sample code at https://github.com/wbreeze/davenport/pull/15/files

Regarding https://stackoverflow.com/a/3535455/608359 from @paxdiablo, I liked it; but, felt insecure about having the number of times the initializaion pointer advances synchronized with the number of elements allocated to the array. Worst case, the initializing pointer moves beyond the allocated length. As such, the diff in the PR contains,

  int expected[node_ct];
- int *p = expected;
- *p++ = 1; *p++ = 2; *p++ = 3; *p++ = 4;
+ int_array_init(expected, node_ct, 1, 2, 3, 4);

The int_array_init method will safely assign junk if the number of arguments is fewer than the node_ct. The junk assignment ought to be easier to catch and debug.

Assets file project.assets.json not found. Run a NuGet package restore

Cause of this defect: you have to remove the injected Nuget in file explorer. Solution: Once you remove that Nuget in your system, then remove from following location. select Tool=>Options=>NuGet Package Manager=> Package Sources then uncheck Microsoft Visual Studio Offline Packages Option

Using getResources() in non-activity class

here is my answer:

public class WigetControl {
private Resources res;

public WigetControl(Resources res) 
{
    this.res = res;
}

public void setButtonDisable(Button mButton)
{
    mButton.setBackgroundColor(res.getColor(R.color.loginbutton_unclickable));
    mButton.setEnabled(false);
}

}

and the call can be like this:

        WigetControl control = new WigetControl(getResources());
        control.setButtonDisable(btNext);

Regexp Java for password validation

I think this can do it also (as a simpler mode):

^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])[^\s]{8,}$

[Regex Demo]

Is there a way to change the spacing between legend items in ggplot2?

ggplot2 v3.0.0 released in July 2018 has working options to modify legend.spacing.x, legend.spacing.y and legend.text.

Example: Increase horizontal spacing between legend keys

library(ggplot2)

ggplot(mtcars, aes(factor(cyl), fill = factor(cyl))) + 
  geom_bar() +
  coord_flip() +
  scale_fill_brewer("Cyl", palette = "Dark2") +
  theme_minimal(base_size = 14) +
  theme(legend.position = 'top', 
        legend.spacing.x = unit(1.0, 'cm'))

Note: If you only want to expand the spacing to the right of the legend text, use stringr::str_pad()

Example: Move the legend key labels to the bottom and increase vertical spacing

ggplot(mtcars, aes(factor(cyl), fill = factor(cyl))) + 
  geom_bar() +
  coord_flip() +
  scale_fill_brewer("Cyl", palette = "Dark2") +
  theme_minimal(base_size = 14) +
  theme(legend.position = 'top', 
        legend.spacing.x = unit(1.0, 'cm'),
        legend.text = element_text(margin = margin(t = 10))) +
  guides(fill = guide_legend(title = "Cyl",
                             label.position = "bottom",
                             title.position = "left", title.vjust = 1)) 

Example: for scale_fill_xxx & guide_colorbar

ggplot(mtcars, aes(mpg, wt)) +
  geom_point(aes(fill = hp), pch = I(21), size = 5)+
  scale_fill_viridis_c(guide = FALSE) +
  theme_classic(base_size = 14) +
  theme(legend.position = 'top', 
        legend.spacing.x = unit(0.5, 'cm'),
        legend.text = element_text(margin = margin(t = 10))) +
  guides(fill = guide_colorbar(title = "HP",
                               label.position = "bottom",
                               title.position = "left", title.vjust = 1,
                               # draw border around the legend
                               frame.colour = "black",
                               barwidth = 15,
                               barheight = 1.5)) 


For vertical legends, settinglegend.key.size only increases the size of the legend keys, not the vertical space between them

ggplot(mtcars) +
  aes(x = cyl, fill = factor(cyl)) +
  geom_bar() +
  scale_fill_brewer("Cyl", palette = "Dark2") +
  theme_minimal(base_size = 14) +
  theme(legend.key.size = unit(1, "cm"))

In order to increase the distance between legend keys, modification of the legend-draw.r function is needed. See this issue for more info

# function to increase vertical spacing between legend keys
# @clauswilke
draw_key_polygon3 <- function(data, params, size) {
  lwd <- min(data$size, min(size) / 4)
  
  grid::rectGrob(
    width = grid::unit(0.6, "npc"),
    height = grid::unit(0.6, "npc"),
    gp = grid::gpar(
      col = data$colour,
      fill = alpha(data$fill, data$alpha),
      lty = data$linetype,
      lwd = lwd * .pt,
      linejoin = "mitre"
    ))
}

### this step is not needed anymore per tjebo's comment below
### see also: https://ggplot2.tidyverse.org/reference/draw_key.html
# register new key drawing function, 
# the effect is global & persistent throughout the R session
# GeomBar$draw_key = draw_key_polygon3

ggplot(mtcars) +
  aes(x = cyl, fill = factor(cyl)) +
  geom_bar(key_glyph = "polygon3") +
  scale_fill_brewer("Cyl", palette = "Dark2") +
  theme_minimal(base_size = 14) +
  theme(legend.key = element_rect(color = NA, fill = NA),
        legend.key.size = unit(1.5, "cm")) +
  theme(legend.title.align = 0.5)

How can I auto increment the C# assembly version via our CI platform (Hudson)?

My solution doesn't require the addition of external tools or scripting languages --it's pretty much guaranteed to work on your build machine. I solve this problem in several parts. First, I have created a BUILD.BAT file that converts the Jenkins BUILD_NUMBER parameter into an environment variable. I use Jenkins's "Execute Windows batch command" function to run the build batch file by entering the following information for the Jenkins build:

     ./build.bat --build_id %BUILD_ID% -build_number %BUILD_NUMBER%

In the build environment, I have a build.bat file that starts as follows:

     rem build.bat
     set BUILD_ID=Unknown
     set BUILD_NUMBER=0
     :parse_command_line
     IF NOT "%1"=="" (
         IF "%1"=="-build_id" (
             SET BUILD_ID=%2
             SHIFT
             )
         IF "%1"=="-build_number" (
             SET BUILD_NUMBER=%2
             SHIFT
         )
         SHIFT
         GOTO :parse_command_line
     )
     REM your build continues with the environmental variables set
     MSBUILD.EXE YourProject.sln

Once I did that, I right-clicked on the project to be built in Visual Studio's Solution Explorer pane and selected Properties, select Build Events, and entered the following information as the Pre-Build Event Command Line, which automatically creates a .cs file containing build number information based on current environment variable settings:

     set VERSION_FILE=$(ProjectDir)\Properties\VersionInfo.cs
     if !%BUILD_NUMBER%==! goto no_buildnumber_set
     goto buildnumber_set
     :no_buildnumber_set
     set BUILD_NUMBER=0
     :buildnumber_set
     if not exist %VERSION_FILE% goto no_version_file
     del /q %VERSION_FILE%
     :no_version_file
     echo using System.Reflection; >> %VERSION_FILE%
     echo using System.Runtime.CompilerServices; >> %VERSION_FILE%
     echo using System.Runtime.InteropServices; >> %VERSION_FILE%
     echo [assembly: AssemblyVersion("0.0.%BUILD_NUMBER%.1")] >> %VERSION_FILE%
     echo [assembly: AssemblyFileVersion("0.0.%BUILD_NUMBER%.1")] >> %VERSION_FILE%

You may need to adjust to your build taste. I build the project manually once to generate an initial Version.cs file in the Properties directory of the main project. Lastly, I manually include the Version.cs file into the Visual Studio solution by dragging it into the Solution Explorer pane, underneath the Properties tab for that project. In future builds, Visual Studio then reads that .cs file at Jenkins build time and gets the correct build number information out of it.

HashMap(key: String, value: ArrayList) returns an Object instead of ArrayList?

I suppose your dictMap is of type HashMap, which makes it default to HashMap<Object, Object>. If you want it to be more specific, declare it as HashMap<String, ArrayList>, or even better, as HashMap<String, ArrayList<T>>

How do I break a string in YAML over multiple lines?

You might not believe it, but YAML can do multi-line keys too:

?
 >
 multi
 line
 key
:
  value

HTML 5 Video "autoplay" not automatically starting in CHROME

Try this:

<video src="{{ asset('path/to/your_video.mp4' )}}" muted autoplay loop playsinline></video>

And put this js after that:

window.addEventListener('load', async () => {
  let video = document.querySelector('video[muted][autoplay]');
  try {
    await video.play();
  } catch (err) {
    video.controls = true;
  }
});

md-table - How to update the column width

You can also use the element selectors:

mat-header-cell:nth-child(1), mat-cell:nth-child(1) {
    flex: 0 0 64px;
}

But jymdman's answer is the most recommended way to go in most cases.

how to get the child node in div using javascript

If you give your table a unique id, its easier:

<div id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a"
    onmouseup="checkMultipleSelection(this,event);">
       <table id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table" 
              cellpadding="0" cellspacing="0" border="0" width="100%">
           <tr>
              <td style="width:50px; text-align:left;">09:15 AM</td>
              <td style="width:50px; text-align:left;">Item001</td>
              <td style="width:50px; text-align:left;">10</td>
              <td style="width:50px; text-align:left;">Address1</td>
              <td style="width:50px; text-align:left;">46545465</td>
              <td style="width:50px; text-align:left;">ref1</td>
           </tr>
       </table>
</div>


var multiselect = 
    document.getElementById(
               'ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table'
            ).rows[0].cells,
    timeXaddr = [multiselect[0].innerHTML, multiselect[2].innerHTML];

//=> timeXaddr now an array containing ['09:15 AM', 'Address1'];

Java Date - Insert into database

Granted, PreparedStatement will make your code better, but to answer your question you need to tell the DBMS the format of your string representation of the Date. In Oracle (you don't name your database vendor) a string date is converted to Date using the TO_DATE() function:

INSERT INTO TABLE_NAME(
  date_column
)values(
  TO_DATE('06/06/2006', 'mm/dd/yyyy')
)

Faster way to zero memory than with memset?

Nowadays your compiler should do all the work for you. At least of what I know gcc is very efficient in optimizing calls to memset away (better check the assembler, though).

Then also, avoid memset if you don't have to:

  • use calloc for heap memory
  • use proper initialization (... = { 0 }) for stack memory

And for really large chunks use mmap if you have it. This just gets zero initialized memory from the system "for free".

How to change the color of a SwitchCompat from AppCompat library

AppCompat tinting attributs:

First, you should take a look to appCompat lib article there and to different attributs you can set:

colorPrimary: The primary branding color for the app. By default, this is the color applied to the action bar background.

colorPrimaryDark: Dark variant of the primary branding color. By default, this is the color applied to the status bar (via statusBarColor) and navigation bar (via navigationBarColor).

colorAccent: Bright complement to the primary branding color. By default, this is the color applied to framework controls (via colorControlActivated).

colorControlNormal: The color applied to framework controls in their normal state.

colorControlActivated: The color applied to framework controls in their activated (ex. checked, switch on) state.

colorControlHighlight: The color applied to framework control highlights (ex. ripples, list selectors).

colorButtonNormal: The color applied to framework buttons in their normal state.

colorSwitchThumbNormal: The color applied to framework switch thumbs in their normal state. (switch off)


If all custom switches are the same in a single activity:

With previous attributes you can define your own theme for each activity:

<style name="Theme.MyActivityTheme" parent="Theme.AppCompat.Light">
    <!-- colorPrimary is used for the default action bar background -->
    <item name="colorPrimary">@color/my_awesome_color</item>

    <!-- colorPrimaryDark is used for the status bar -->
    <item name="colorPrimaryDark">@color/my_awesome_darker_color</item>

    <!-- colorAccent is used as the default value for colorControlActivated,
         which is used to tint widgets -->
    <item name="colorAccent">@color/accent</item>

    <!-- You can also set colorControlNormal, colorControlActivated
         colorControlHighlight, and colorSwitchThumbNormal. -->

</style>

and :

<manifest>
...
    <activity
        android:name=".MainActivity" 
        android:theme="@style/Theme.MyActivityTheme">
    </activity>
...
</manifest>

If you want to have differents custom switches in a single activity:

As widget tinting in appcompat works by intercepting any layout inflation and inserting a special tint-aware version of the widget in its place (See Chris Banes post about it) you can not apply a custom style to each switch of your layout xml file. You have to set a custom Context that will tint switch with right colors.

--

To do so for pre-5.0 you need to create a Context that overlays global theme with customs attributs and then create your switches programmatically:

ContextThemeWrapper ctw = ContextThemeWrapper(getActivity(), R.style.Color1SwitchStyle); 
SwitchCompat sc = new SwitchCompat(ctw)

As of AppCompat v22.1 you can use the following XML to apply a theme to the switch widget:

<RelativeLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    ...>

    <android.support.v7.widget.SwitchCompat
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:theme="@style/Color1SwitchStyle"/>

Your custom switch theme:

<style name="Color1SwitchStyle">
    <item name="colorControlActivated">@color/my_awesome_color</item>
</style>

--

On Android 5.0 it looks like a new view attribut comes to life : android:theme (same as one use for activity declaration in manifest). Based on another Chris Banes post, with the latter you should be able to define a custom theme directly on a view from your layout xml:

<android.support.v7.widget.SwitchCompat
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/Color1SwitchStyle"/>

To change the track color of a SwitchCompat

Thanks to vine'th I complete my answer with a link to SO answer that explains how to specify the Foreground of the Track when Switch is Off, it's there.

How to get the position of a character in Python?

more_itertools.locate is a third-party tool that finds all indicies of items that satisfy a condition.

Here we find all index locations of the letter "i".

import more_itertools as mit


s = "supercalifragilisticexpialidocious"
list(mit.locate(s, lambda x: x == "i"))
# [8, 13, 15, 18, 23, 26, 30]

ModuleNotFoundError: No module named 'sklearn'

SOLVED:

The above did not help. Then I simply installed sklearn from within Jypyter-lab, even though sklearn 0.0 shows in 'pip list':

!pip install sklearn
import sklearn

What I learned later is that pip installs, in my case, packages in a different folder than Jupyter. This can be seen by executing:

import sys
print(sys.path)

Once from within Jupyter_lab notebook, and once from the command line using 'py notebook.py'.

In my case Jupyter list of paths where subfolders of 'anaconda' whereas Python list where subfolders of c:\users[username]...

Select SQL results grouped by weeks

Base on @increddibelly answer, I applied to my query as below.

I share for whom concerned.

My table structure FamilyData(Id, nodeTime, totalEnergy)

select
   sum(totalEnergy) as TotalEnergy,
   DATEPART ( week, nodeTime ) as weeknr
from FamilyData
group by DATEPART (week, nodeTime)

Application not picking up .css file (flask/python)

One more point to add on to this thread.

If you add an underscore in your .css file name, then it wouldn't work.

Export Postgresql table data using pgAdmin

Just right click on a table and select "backup". The popup will show various options, including "Format", select "plain" and you get plain SQL.

pgAdmin is just using pg_dump to create the dump, also when you want plain SQL.

It uses something like this:

pg_dump --user user --password --format=plain --table=tablename --inserts --attribute-inserts etc.

Select Tag Helper in ASP.NET Core MVC

My answer below doesn't solve the question but it relates to.

If someone is using enum instead of a class model, like this example:

public enum Counter
{
    [Display(Name = "Number 1")]
    No1 = 1,
    [Display(Name = "Number 2")]
    No2 = 2,
    [Display(Name = "Number 3")]
    No3 = 3
}

And a property to get the value when submiting:

public int No { get; set; }

In the razor page, you can use Html.GetEnumSelectList<Counter>() to get the enum properties.

<select asp-for="No" asp-items="@Html.GetEnumSelectList<Counter>()"></select>

It generates the following HTML:

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

Action Bar's onClick listener for the Home button

if anyone else need the solution

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == android.R.id.home) {
        onBackPressed();  return true;
    }

    return super.onOptionsItemSelected(item);
}

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

How can I move HEAD back to a previous location? (Detached head) & Undo commits

Quickest possible solution (just 1 step)

Use git checkout -

You will see Switched to branch <branch_name>. Confirm it's the branch you want.


Brief explanation: this command will move HEAD back to its last position. See note on outcomes at the end of this answer.


Mnemonic: this approach is a lot like using cd - to return to your previously visited directory. Syntax and the applicable cases are a pretty good match (e.g. it's useful when you actually want HEAD to return to where it was).


More methodical solution (2-steps, but memorable)

The quick approach solves the OP's question. But what if your situation is slightly different: say you have restarted Bash then found yourself with HEAD detached. In that case, here are 2 simple, easily remembered steps.

1. Pick the branch you need

Use git branch -v

You see a list of existing local branches. Grab the branch name that suits your needs.

2. Move HEAD to it

Use git checkout <branch_name>

You will see Switched to branch <branch_name>. Success!


Outcomes

With either method, you can now continue adding and committing your work as before: your next changes will be tracked on <branch_name>.

Note that both git checkout - and git checkout <branch_name> will give additional instructions if you have committed changes while HEAD was detached.

How to parse Excel (XLS) file in Javascript/HTML5

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/jszip.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js"></script>_x000D_
<script>_x000D_
    var ExcelToJSON = function() {_x000D_
_x000D_
      this.parseExcel = function(file) {_x000D_
        var reader = new FileReader();_x000D_
_x000D_
        reader.onload = function(e) {_x000D_
          var data = e.target.result;_x000D_
          var workbook = XLSX.read(data, {_x000D_
            type: 'binary'_x000D_
          });_x000D_
          workbook.SheetNames.forEach(function(sheetName) {_x000D_
            // Here is your object_x000D_
            var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);_x000D_
            var json_object = JSON.stringify(XL_row_object);_x000D_
            console.log(JSON.parse(json_object));_x000D_
            jQuery( '#xlx_json' ).val( json_object );_x000D_
          })_x000D_
        };_x000D_
_x000D_
        reader.onerror = function(ex) {_x000D_
          console.log(ex);_x000D_
        };_x000D_
_x000D_
        reader.readAsBinaryString(file);_x000D_
      };_x000D_
  };_x000D_
_x000D_
  function handleFileSelect(evt) {_x000D_
    _x000D_
    var files = evt.target.files; // FileList object_x000D_
    var xl2json = new ExcelToJSON();_x000D_
    xl2json.parseExcel(files[0]);_x000D_
  }_x000D_
_x000D_
_x000D_
 _x000D_
</script>_x000D_
_x000D_
<form enctype="multipart/form-data">_x000D_
    <input id="upload" type=file  name="files[]">_x000D_
</form>_x000D_
_x000D_
    <textarea class="form-control" rows=35 cols=120 id="xlx_json"></textarea>_x000D_
_x000D_
    <script>_x000D_
        document.getElementById('upload').addEventListener('change', handleFileSelect, false);_x000D_
_x000D_
    </script>
_x000D_
_x000D_
_x000D_

How to add System.Windows.Interactivity to project?

If you are working with MVVM Light you have to use the System.Windows.Interactivity Version 4.0 (the NuGet .dll wont work) that you can find under :

PathToProjectFolder\Software\packages\MvvmLightLibs.5.4.1.1\lib\net45\System.Windows.Interactivity.dll

Just add this .dll manually as Reference and it should be fine.

if statement checks for null but still throws a NullPointerException

The | and & check both the sides everytime.

if (str == null | str.length() == 0)

here we have high possibility to get NullPointerException

Logical || and && check the right hand side only if necessary.

but with logical operator

no chance to get NPE because it will not check RHS

How to convert string to Date in Angular2 \ Typescript?

You can use date filter to convert in date and display in specific format.

In .ts file (typescript):

let dateString = '1968-11-16T00:00:00' 
let newDate = new Date(dateString);

In HTML:

{{dateString |  date:'MM/dd/yyyy'}}

Below are some formats which you can implement :

Backend:

public todayDate = new Date();

HTML :

<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>   
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>      
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option> 
</select>

Center image horizontally within a div

This is what I ended up doing:

<div style="height: 600px">
   <img src="assets/zzzzz.png" alt="Error" style="max-width: 100%; 
        max-height: 100%; display:block; margin:auto;" />
</div>

Which will limit the image height to 600px and will horizontally-center (or resize down if the parent width is smaller) to the parent container, maintaining proportions.

PHP: how can I get file creation date?

Unfortunately if you are running on linux you cannot access the information as only the last modified date is stored.

It does slightly depend on your filesystem tho. I know that ext2 and ext3 do not support creation time but I think that ext4 does.

Setting log level of message at runtime in slf4j

Try switching to Logback and use

ch.qos.logback.classic.Logger rootLogger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
rootLogger.setLevel(Level.toLevel("info"));

I believe this will be the only call to Logback and the rest of your code will remain unchanged. Logback uses SLF4J and the migration will be painless, just the xml config files will have to be changed.

Remember to set the log level back after you're done.

Android Studio installation on Windows 7 fails, no JDK found

You need 1.7 JDK installed on your system. Add a system variable with:

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I get the same error on my JSP and the bad rated answer was correct

I had the folowing line:

<c:forEach var="agent" items=" ${userList}" varStatus="rowCounter">

and get the folowing error:

javax.el.PropertyNotFoundException: Property 'agent' not found on type java.lang.String

deleting the space before ${userList} solved my problem

If some have the same problem, he will find quickly this post and does not waste 3 days in googeling to find help.

How to right-align form input boxes?

Try use this:

<html>
<body>
   <input type="text" style="direction: rtl;" value="1">
   <input type="text" style="direction: rtl;" value="10">
   <input type="text" style="direction: rtl;" value="100">
</body>
</html>

Difference between __getattr__ vs __getattribute__

New-style classes are ones that subclass "object" (directly or indirectly). They have a __new__ class method in addition to __init__ and have somewhat more rational low-level behavior.

Usually, you'll want to override __getattr__ (if you're overriding either), otherwise you'll have a hard time supporting "self.foo" syntax within your methods.

Extra info: http://www.devx.com/opensource/Article/31482/0/page/4

How to access to a child method from the parent in vue.js

Ref and event bus both has issues when your control render is affected by v-if. So, I decided to go with a simpler method.

The idea is using an array as a queue to send methods that needs to be called to the child component. Once the component got mounted, it will process this queue. It watches the queue to execute new methods.

(Borrowing some code from Desmond Lua's answer)

Parent component code:

import ChildComponent from './components/ChildComponent'

new Vue({
  el: '#app',
  data: {
    item: {},
    childMethodsQueue: [],
  },
  template: `
  <div>
     <ChildComponent :item="item" :methods-queue="childMethodsQueue" />
     <button type="submit" @click.prevent="submit">Post</button>
  </div>
  `,
  methods: {
    submit() {
      this.childMethodsQueue.push({name: ChildComponent.methods.save.name, params: {}})
    }
  },
  components: { ChildComponent },
})

This is code for ChildComponent

<template>
 ...
</template>

<script>
export default {
  name: 'ChildComponent',
  props: {
    methodsQueue: { type: Array },
  },
  watch: {
    methodsQueue: function () {
      this.processMethodsQueue()
    },
  },
  mounted() {
    this.processMethodsQueue()
  },
  methods: {
    save() {
        console.log("Child saved...")
    },
    processMethodsQueue() {
      if (!this.methodsQueue) return
      let len = this.methodsQueue.length
      for (let i = 0; i < len; i++) {
        let method = this.methodsQueue.shift()
        this[method.name](method.params)
      }
    },
  },
}
</script>

And there is a lot of room for improvement like moving processMethodsQueue to a mixin...

How can I monitor the thread count of a process on linux?

$ ps H p pid-id

H - Lists all the individual threads in a process

or

$cat /proc/pid-id/status

pid-id is the Process ID

eg.. (Truncated the below output)

root@abc:~# cat /proc/8443/status
Name:   abcdd
State:  S (sleeping)
Tgid:   8443
VmSwap:        0 kB
Threads:    4
SigQ:   0/256556
SigPnd: 0000000000000000

Repeat each row of data.frame the number of times specified in a column

Use expandRows() from the splitstackshape package:

library(splitstackshape)
expandRows(df, "freq")

Simple syntax, very fast, works on data.frame or data.table.

Result:

    var1 var2
1      a    d
2      b    e
2.1    b    e
3      c    f
3.1    c    f
3.2    c    f

How to change the blue highlight color of a UITableViewCell?

1- Add a view to the content view of your cell.
2- Right click your cell.
3- Make the added view as "selectedBackgroundView" enter image description here

Java Delegates?

Yes & No, but delegate pattern in Java could be thought of this way. This video tutorial is about data exchange between activity - fragments, and it has great essence of delegate sorta pattern using interfaces.

Java Interface

Is Java's assertEquals method reliable?

"The == operator checks to see if two Objects are exactly the same Object."

http://leepoint.net/notes-java/data/strings/12stringcomparison.html

String is an Object in java, so it falls into that category of comparison rules.

Submitting a multidimensional array via POST with php

On submitting, you would get an array as if created like this:

$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );

However, I would suggest changing your form names to this format instead:

name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...

Using that format, it's much easier to loop through the values.

if ( isset( $_POST['diameters'] ) )
{
    echo '<table>';
    foreach ( $_POST['diameters'] as $diam )
    {
        // here you have access to $diam['top'] and $diam['bottom']
        echo '<tr>';
        echo '  <td>', $diam['top'], '</td>';
        echo '  <td>', $diam['bottom'], '</td>';
        echo '</tr>';
    }
    echo '</table>';
}

How can I stop the browser back button using JavaScript?

In a modern browser this seems to work:

// https://developer.mozilla.org/en-US/docs/Web/API/History_API
let popHandler = () => {
  if (confirm('Go back?')) {
    window.history.back() 
  } else {
    window.history.forward()
    setTimeout(() => {
      window.addEventListener('popstate', popHandler, {once: true})
    }, 50) // delay needed since the above is an async operation for some reason
  }
}
window.addEventListener('popstate', popHandler, {once: true})
window.history.pushState(null,null,null)

Using print statements only to debug

A better way to debug the code is, by using module clrprint

It prints a color full output only when pass parameter debug=True

from clrprint import *
clrprint('ERROR:', information,clr=['r','y'], debug=True)

Chain-calling parent initialisers in python

You can simply write :

class A(object):

    def __init__(self):
        print "Initialiser A was called"

class B(A):

    def __init__(self):
        A.__init__(self)
        # A.__init__(self,<parameters>) if you want to call with parameters
        print "Initialiser B was called"

class C(B):

    def __init__(self):
        # A.__init__(self) # if you want to call most super class...
        B.__init__(self)
        print "Initialiser C was called"

Connect to SQL Server Database from PowerShell

Assuming you can use integrated security, you can remove the user id and pass:

$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;"

What's the best way to get the current URL in Spring MVC?

Instead of using RequestContextHolder directly, you can also use ServletUriComponentsBuilder and its static methods:

  • ServletUriComponentsBuilder.fromCurrentContextPath()
  • ServletUriComponentsBuilder.fromCurrentServletMapping()
  • ServletUriComponentsBuilder.fromCurrentRequestUri()
  • ServletUriComponentsBuilder.fromCurrentRequest()

They use RequestContextHolder under the hood, but provide additional flexibility to build new URLs using the capabilities of UriComponentsBuilder.

Example:

ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentRequestUri();
builder.scheme("https");
builder.replaceQueryParam("someBoolean", false);
URI newUri = builder.build().toUri();

How to prevent custom views from losing state across screen orientation changes

Here is another variant that uses a mix of the two above methods. Combining the speed and correctness of Parcelable with the simplicity of a Bundle:

@Override
public Parcelable onSaveInstanceState() {
    Bundle bundle = new Bundle();
    // The vars you want to save - in this instance a string and a boolean
    String someString = "something";
    boolean someBoolean = true;
    State state = new State(super.onSaveInstanceState(), someString, someBoolean);
    bundle.putParcelable(State.STATE, state);
    return bundle;
}

@Override
public void onRestoreInstanceState(Parcelable state) {
    if (state instanceof Bundle) {
        Bundle bundle = (Bundle) state;
        State customViewState = (State) bundle.getParcelable(State.STATE);
        // The vars you saved - do whatever you want with them
        String someString = customViewState.getText();
        boolean someBoolean = customViewState.isSomethingShowing());
        super.onRestoreInstanceState(customViewState.getSuperState());
        return;
    }
    // Stops a bug with the wrong state being passed to the super
    super.onRestoreInstanceState(BaseSavedState.EMPTY_STATE); 
}

protected static class State extends BaseSavedState {
    protected static final String STATE = "YourCustomView.STATE";

    private final String someText;
    private final boolean somethingShowing;

    public State(Parcelable superState, String someText, boolean somethingShowing) {
        super(superState);
        this.someText = someText;
        this.somethingShowing = somethingShowing;
    }

    public String getText(){
        return this.someText;
    }

    public boolean isSomethingShowing(){
        return this.somethingShowing;
    }
}

R Markdown - changing font size and font type in html output

I would definitely use html markers to achieve this. Just surround your text with <p></p> or <font></font> and add the desired attributes. See the following example:

<p style="font-family: times, serif; font-size:11pt; font-style:italic">
    Why did we use these specific parameters during the calculation of the fingerprints?
</p>

This will produce the following output

Font Output

compared to

Default Output

This would work with Jupyter Notebook as well as Typora, but I'm not sure if it is universal.

Lastly, be aware that the html marker overrides the font styling used by Markdown.

How to center horizontally div inside parent div

<div id='parent' style='width: 100%;text-align:center;'>
 <div id='child' style='width:50px; height:100px;margin:0px auto;'>Text</div>
</div>

How to create a md5 hash of a string in C?

All of the existing answers use the deprecated MD5Init(), MD5Update(), and MD5Final().

Instead, use EVP_DigestInit_ex(), EVP_DigestUpdate(), and EVP_DigestFinal_ex(), e.g.

// example.c
//
// gcc example.c -lssl -lcrypto -o example

#include <openssl/evp.h>
#include <stdio.h>
#include <string.h>

void bytes2md5(const char *data, int len, char *md5buf) {
  // Based on https://www.openssl.org/docs/manmaster/man3/EVP_DigestUpdate.html
  EVP_MD_CTX *mdctx = EVP_MD_CTX_new();
  const EVP_MD *md = EVP_md5();
  unsigned char md_value[EVP_MAX_MD_SIZE];
  unsigned int md_len, i;
  EVP_DigestInit_ex(mdctx, md, NULL);
  EVP_DigestUpdate(mdctx, data, len);
  EVP_DigestFinal_ex(mdctx, md_value, &md_len);
  EVP_MD_CTX_free(mdctx);
  for (i = 0; i < md_len; i++) {
    snprintf(&(md5buf[i * 2]), 16 * 2, "%02x", md_value[i]);
  }
}

int main(void) {
  const char *hello = "hello";
  char md5[33]; // 32 characters + null terminator
  bytes2md5(hello, strlen(hello), md5);
  printf("%s\n", md5);
}

How can I create a progress bar in Excel VBA?

You can add a Form and name it as Form1, add a Frame to it as Frame1 as well as Label1 too. Set Frame1 width to 200, Back Color to Blue. Place the code in the module and check if it helps.

    Sub Main()
    Dim i As Integer
    Dim response
    Form1.Show vbModeless
    Form1.Frame1.Width = 0
    For i = 10 To 10000
        With Form1
            .Label1.Caption = Round(i / 100, 0) & "%"
            .Frame1.Width = Round(i / 100, 0) * 2
             DoEvents
        End With
    Next i

    Application.Wait Now + 0.0000075

    Unload Form1

    response = MsgBox("100% Done", vbOKOnly)

    End Sub

If you want to display on the Status Bar then you can use other way that's simpler:

   Sub Main()
   Dim i As Integer
   Dim response
   For i = 10 To 10000
        Application.StatusBar = Round(i / 100, 0) & "%"
   Next i

   Application.Wait Now + 0.0000075

   response = MsgBox("100% Done", vbOKOnly)

   End Sub

How to compare character ignoring case in primitive types

You can't actually do the job quite right with toLowerCase, either on a string or in a character. The problem is that there are variant glyphs in either upper or lower case, and depending on whether you uppercase or lowercase your glyphs may or may not be preserved. It's not even clear what you mean when you say that two variants of a lower-case glyph are compared ignoring case: are they or are they not the same? (Note that there are also mixed-case glyphs: \u01c5, \u01c8, \u01cb, \u01f2 or ?, ?, ?, ?, but any method suggested here will work on those as long as they should count as the same as their fully upper or full lower case variants.)

There is an additional problem with using Char: there are some 80 code points not representable with a single Char that are upper/lower case variants (40 of each), at least as detected by Java's code point upper/lower casing. You therefore need to get the code points and change the case on these.

But code points don't help with the variant glyphs.

Anyway, here's a complete list of the glyphs that are problematic due to variants, showing how they fare against 6 variant methods:

  1. Character toLowerCase
  2. Character toUpperCase
  3. String toLowerCase
  4. String toUpperCase
  5. String equalsIgnoreCase
  6. Character toLowerCase(toUpperCase) (or vice versa)

For these methods, S means that the variants are treated the same as each other, D means the variants are treated as different from each other.

Behavior     Unicode                             Glyphs
===========  ==================================  =========
1 2 3 4 5 6  Upper  Lower  Var Up Var Lo Vr Lo2  U L u l l2
- - - - - -  ------ ------ ------ ------ ------  - - - - -
D D D D S S  \u0049 \u0069 \u0130 \u0131         I i I i   
S D S D S S  \u004b \u006b \u212a                K k K     
D S D S S S  \u0053 \u0073        \u017f         S s   ?   
D S D S S S  \u039c \u03bc        \u00b5         ? µ   µ   
S D S D S S  \u00c5 \u00e5 \u212b                Å å Å     
D S D S S S  \u0399 \u03b9        \u0345 \u1fbe  ? ?   ? ? 
D S D S S S  \u0392 \u03b2        \u03d0         ? ß   ?   
D S D S S S  \u0395 \u03b5        \u03f5         ? e   ?   
D D D D S S  \u0398 \u03b8 \u03f4 \u03d1         T ? ? ?   
D S D S S S  \u039a \u03ba        \u03f0         ? ?   ?   
D S D S S S  \u03a0 \u03c0        \u03d6         ? p   ?   
D S D S S S  \u03a1 \u03c1        \u03f1         ? ?   ?   
D S D S S S  \u03a3 \u03c3        \u03c2         S s   ?   
D S D S S S  \u03a6 \u03c6        \u03d5         F f   ?   
S D S D S S  \u03a9 \u03c9 \u2126                O ? ?     
D S D S S S  \u1e60 \u1e61        \u1e9b         ? ?   ?   

Complicating this still further is that there is no way to get the Turkish I's right (i.e. the dotted versions are different than the undotted versions) unless you know you're in Turkish; none of these methods give correct behavior and cannot unless you know the locale (i.e. non-Turkish: i and I are the same ignoring case; Turkish, not).

Overall, using toUpperCase gives you the closest approximation, since you have only five uppercase variants (or four, not counting Turkish).

You can also try to specifically intercept those five troublesome cases and call toUpperCase(toLowerCase(c)) on them alone. If you choose your guards carefully (just toUpperCase if c < 0x130 || c > 0x212B, then work through the other alternatives) you can get only a ~20% speed penalty for characters in the low range (as compared to ~4x if you convert single characters to strings and equalsIgnoreCase them) and only about a 2x penalty if you have a lot in the danger zone. You still have the locale problem with dotted I, but otherwise you're in decent shape. Of course if you can use equalsIgnoreCase on a larger string, you're better off doing that.

Here is sample Scala code that does the job:

def elevateCase(c: Char): Char = {
  if (c < 0x130 || c > 0x212B) Character.toUpperCase(c)
  else if (c == 0x130 || c == 0x3F4 || c == 0x2126 || c >= 0x212A)
    Character.toUpperCase(Character.toLowerCase(c))
  else Character.toUpperCase(c)
}

htmlentities() vs. htmlspecialchars()

htmlspecialchars may be used:

  1. When there is no need to encode all characters which have their HTML equivalents.

    If you know that the page encoding match the text special symbols, why would you use htmlentities? htmlspecialchars is much straightforward, and produce less code to send to the client.

    For example:

    echo htmlentities('<Il était une fois un être>.');
    // Output: &lt;Il &eacute;tait une fois un &ecirc;tre&gt;.
    //                ^^^^^^^^                 ^^^^^^^
    
    echo htmlspecialchars('<Il était une fois un être>.');
    // Output: &lt;Il était une fois un être&gt;.
    //                ^                 ^
    

    The second one is shorter, and does not cause any problems if ISO-8859-1 charset is set.

  2. When the data will be processed not only through a browser (to avoid decoding HTML entities),

  3. If the output is XML (see the answer by Artefacto).

Python function to convert seconds into minutes, hours, and days

To convert seconds (as string) into datetime, this could also help. You get number of days and seconds. Seconds can be further converted into minutes and hours.

from datetime import datetime, timedelta
sec = timedelta(seconds=(int(input('Enter the number of seconds: '))))
time = str(sec)

PHP: Update multiple MySQL fields in single query

Add your multiple columns with comma separations:

UPDATE settings SET postsPerPage = $postsPerPage, style= $style WHERE id = '1'

However, you're not sanitizing your inputs?? This would mean any random hacker could destroy your database. See this question: What's the best method for sanitizing user input with PHP?

Also, is style a number or a string? I'm assuming a string, so it would need to be quoted.

Count how many files in directory PHP

You can get the filecount like so:

$directory = "/path/to/dir/";
$filecount = 0;
$files = glob($directory . "*");
if ($files){
 $filecount = count($files);
}
echo "There were $filecount files";

where the "*" is you can change that to a specific filetype if you want like "*.jpg" or you could do multiple filetypes like this:

glob($directory . "*.{jpg,png,gif}",GLOB_BRACE)

the GLOB_BRACE flag expands {a,b,c} to match 'a', 'b', or 'c'

Regular expression to match a word or its prefix

[ ] defines a character class. So every character you set there, will match. [012] will match 0 or 1 or 2 and [0-2] behaves the same.

What you want is groupings to define a or-statement. Use (s|season) for your issue.

Btw. you have to watch out. Metacharacters in normal regex (or inside a grouping) are different from character class. A character class is like a sub-language. [$A] will only match $ or A, nothing else. No escaping here for the dollar.

Image vs zImage vs uImage

What is the difference between them?

Image: the generic Linux kernel binary image file.

zImage: a compressed version of the Linux kernel image that is self-extracting.

uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.


Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:

Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.

(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)


Which type of kernel image do I have to use?

You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.

ADDENDUM

I know that u-boot needs a kernel in uImage format.

That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF

everyone comment about SQL, but what hapend in EntityFramework? I spent reading the whole post and no one solved EF. So after a few days a found solution: EF Core in the context to create the model there is an instruction like this: modelBuilder.Entity<Cliente>(entity => { entity.Property(e => e.Id).ValueGeneratedNever();

this produces the error too, solution: you have to change by ValueGeneratedOnAdd() and its works!

How to define multiple CSS attributes in jQuery?

if you want to change multiple css attributes then you have to use object structure as below:

$(document).ready(function(){
   $('#message').css({
                   "background-color": "#0F0",
                   "color":"red",
                   "font-family":"verdana"
                });
});

but it get worse when we want to change lots of style, so what i suggest to you is adding a class instead of changing css using jQuery, and adding a class is more readable too.

see below example:

CSS

<style>
    .custom-class{
       font-weight: bold;
       background: #f5f5f5;
       text-align: center;
       font-size: 18px;
       color:red;
    }
</style>

jQuery

$(document).ready(function(){
   $('#message').addclass('custom-class');
});

One advantage of latter example over former is if you want to add some css onclick of something and want to remove that css on second click then in latter example you can use .toggleClass('custom-class')

where in former example you have to set all css with different values which you have set before and it will be complicated, so using class option will be better solution.

How can I view the allocation unit size of a NTFS partition in Vista?

Open an administrator command prompt, and do this command:

fsutil fsinfo ntfsinfo [your drive]

The Bytes Per Cluster is the equivalent of the allocation unit.

The program can't start because MSVCR110.dll is missing from your computer

You can download the required files from the Microsoft website or online or reinstall the Visual studio 2012 to fix this.

Calling Member Functions within Main C++

From your question it is unclear if you want to be able use the class without an identity or if calling the method requires you to create an instance of the class. This depends on whether you want the printInformation member to write some general information or more specific about the object identity.

Case 1: You want to use the class without creating an instance. The members of that class should be static, using this keyword you tell the compiler that you want to be able to call the method without having to create a new instance of the class.

class MyClass
{
public:
    static void printInformation();
};

Case 2: You want the class to have an instance, you first need to create an object so that the class has an identity, once that is done you can use the object his methods.

Myclass m;
m.printInformation();

// Or, in the case that you want to use pointers:
Myclass * m = new Myclass();
m->printInformation();

If you don't know when to use pointers, read Pukku's summary in this Stack Overflow question.
Please note that in the current case you would not need a pointer. :-)

How can I create numbered map markers in Google Maps V3?

You may want to download a set of numbered icons from the sources provided at this site:

Then you should be able to do the following:

<!DOCTYPE html>
<html> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
    <title>Google Maps Demo</title> 
    <script type="text/javascript"
            src="http://maps.google.com/maps/api/js?sensor=false"></script> 

    <script type="text/javascript"> 
    function initialize() {

      var myOptions = {
        zoom: 11,
        center: new google.maps.LatLng(-33.9, 151.2),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }

      var map = new google.maps.Map(document.getElementById("map"), myOptions);

      var locations = [
        ['Bondi Beach', -33.890542, 151.274856, 4],
        ['Coogee Beach', -33.923036, 151.259052, 5],
        ['Cronulla Beach', -34.028249, 151.157507, 3],
        ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
        ['Maroubra Beach', -33.950198, 151.259302, 1]
      ];

      for (var i = 0; i < locations.length; i++) {
          var image = new google.maps.MarkerImage('marker' + i + '.png',
                      new google.maps.Size(20, 34),
                      new google.maps.Point(0, 0),
                      new google.maps.Point(10, 34));

          var location = locations[i];
          var myLatLng = new google.maps.LatLng(location[1], location[2]);
          var marker = new google.maps.Marker({
              position: myLatLng,
              map: map,
              icon: image,
              title: location[0],
              zIndex: location[3]
          });
      }
    }
    </script> 
</head> 
<body style="margin:0px; padding:0px;" onload="initialize();"> 
    <div id="map" style="width:400px; height:500px;"></div> 
</body> 
</html>

Screenshot from the above example:

Google Numbered Marker Icons

Note that you can easily add a shadow behind the markers. You may want to check the example at the Google Maps API Reference: Complex Markers for more info about this.

Superscript in CSS only?

Here's the exact way sup uses:

.superscript{
    vertical-align:super;
    font-size:smaller;
}

Found this via google chrome inspect element.

Console output in a Qt GUI app?

After a rather long struggle with exactly the same problem I found that simply

CONFIG   += console

really does the trick. It won't work until you explicitly tell QtCreator to execute qmake on the project (right click on project) AND change something inside the source file, then rebuild. Otherwise compilation is skipped and you still won't see the output on the command line. Now my program works in both GUI and cmd line mode.

swift How to remove optional String Character

import UIKit

let characters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]

var a: String = characters.randomElement()!
var b: String = characters.randomElement()!
var c: String = characters.randomElement()!
var d: String = characters.randomElement()!
var e: String = characters.randomElement()!
var f: String = characters.randomElement()!
var password = ("\(a)" + "\(b)" + "\(c)" + "\(d)" + "\(e)" + "\(f)")

    print ( password)

Angular.js: How does $eval work and why is it different from vanilla eval?

$eval and $parse don't evaluate JavaScript; they evaluate AngularJS expressions. The linked documentation explains the differences between expressions and JavaScript.

Q: What exactly is $eval doing? Why does it need its own mini parsing language?

From the docs:

Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by $parse service.

It's a JavaScript-like mini-language that limits what you can run (e.g. no control flow statements, excepting the ternary operator) as well as adds some AngularJS goodness (e.g. filters).

Q: Why isn't plain old javascript "eval" being used?

Because it's not actually evaluating JavaScript. As the docs say:

If ... you do want to run arbitrary JavaScript code, you should make it a controller method and call the method. If you want to eval() an angular expression from JavaScript, use the $eval() method.

The docs linked to above have a lot more information.

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

I am also looking for an answer to this question, (to clarify, I want to be able to draw an image with user defined opacity such as how you can draw shapes with opacity) if you draw with primitive shapes you can set fill and stroke color with alpha to define the transparency. As far as I have concluded right now, this does not seem to affect image drawing.

//works with shapes but not with images
ctx.fillStyle = "rgba(255, 255, 255, 0.5)";

I have concluded that setting the globalCompositeOperation works with images.

//works with images
ctx.globalCompositeOperation = "lighter";

I wonder if there is some kind third way of setting color so that we can tint images and make them transparent easily.

EDIT:

After further digging I have concluded that you can set the transparency of an image by setting the globalAlpha parameter BEFORE you draw the image:

//works with images
ctx.globalAlpha = 0.5

If you want to achieve a fading effect over time you need some kind of loop that changes the alpha value, this is fairly easy, one way to achieve it is the setTimeout function, look that up to create a loop from which you alter the alpha over time.

How do you synchronise projects to GitHub with Android Studio?

Open the project you want to push in Android Studio.

Click VCS -> Enable version Control Integration -> Git

There doesn't seem to be a way to add a remote through the GUI. So open Git Bash in the root of the project and do git remote add <remote_name> <remote_url>

Now when you do VCS -> Commit changes -> Commit & Push you should see your remote and everything should work through the GUI.


If you are getting the error: fatal: remote <remote_name> already exists that means you already added it. To see your remotes do git remote -v and git remote rm <remote_name> to remove.


See these pages for details:

http://www.jetbrains.com/idea/webhelp/using-git-integration.html

http://gitref.org/remotes/

How to turn off the Eclipse code formatter for certain sections of Java code?

If you put the plus sign on the beginning of the line, it formats differently:

String query = 
    "SELECT FOO, BAR, BAZ" 
    +    "  FROM ABC"           
    +    " WHERE BAR > 4";

no default constructor exists for class

If you define a class without any constructor, the compiler will synthesize a constructor for you (and that will be a default constructor -- i.e., one that doesn't require any arguments). If, however, you do define a constructor, (even if it does take one or more arguments) the compiler will not synthesize a constructor for you -- at that point, you've taken responsibility for constructing objects of that class, so the compiler "steps back", so to speak, and leaves that job to you.

You have two choices. You need to either provide a default constructor, or you need to supply the correct parameter when you define an object. For example, you could change your constructor to look something like:

Blowfish(BlowfishAlgorithm algorithm = CBC);

...so the ctor could be invoked without (explicitly) specifying an algorithm (in which case it would use CBC as the algorithm).

The other alternative would be to explicitly specify the algorithm when you define a Blowfish object:

class GameCryptography { 
    Blowfish blowfish_;
public:
    GameCryptography() : blowfish_(ECB) {}
    // ...
};

In C++ 11 (or later) you have one more option available. You can define your constructor that takes an argument, but then tell the compiler to generate the constructor it would have if you didn't define one:

class GameCryptography { 
public:

    // define our ctor that takes an argument
    GameCryptography(BlofishAlgorithm); 

    // Tell the compiler to do what it would have if we didn't define a ctor:
    GameCryptography() = default;
};

As a final note, I think it's worth mentioning that ECB, CBC, CFB, etc., are modes of operation, not really encryption algorithms themselves. Calling them algorithms won't bother the compiler, but is unreasonably likely to cause a problem for others reading the code.

How to convert an IPv4 address into a integer in C#?

Try this ones:

private int IpToInt32(string ipAddress)
{
   return BitConverter.ToInt32(IPAddress.Parse(ipAddress).GetAddressBytes().Reverse().ToArray(), 0);
}

private string Int32ToIp(int ipAddress)
{
   return new IPAddress(BitConverter.GetBytes(ipAddress).Reverse().ToArray()).ToString();
}

SQL Server - after insert trigger - update another column in the same table

Use a computed column instead. It is almost always a better idea to use a computed column than a trigger.

See Example below of a computed column using the UPPER function:

create table #temp (test varchar (10), test2 AS upper(test))
insert #temp (test)
values ('test')
select * from #temp

And not to sound like a broken record or anything, but this is critically important. Never write a trigger that will not work correctly on multiple record inserts/updates/deletes. This is an extremely poor practice as sooner or later one of these will happen and your trigger will cause data integrity problems asw it won't fail precisely it will only run the process on one of the records. This can go a long time until someone discovers the mess and by themn it is often impossible to correctly fix the data.

Create a batch file to run an .exe with an additional parameter

You can use

start "" "%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"

or

start "" /D "%USERPROFILE%\Desktop\BGInfo" bginfo.exe dc_bginfo.bgi

or

"%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"

or

cd /D "%USERPROFILE%\Desktop\BGInfo"
bginfo.exe dc_bginfo.bgi

Help on commands start and cd is output by executing in a command prompt window help start or start /? and help cd or cd /?.

But I do not understand why you need a batch file at all for starting the application with the additional parameter. Create a shortcut (*.lnk) on your desktop for this application. Then right click on the shortcut, left click on Properties and append after a space character "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi" as parameter.

How can I force input to uppercase in an ASP.NET textbox?

I just did something similar today. Here is the modified version:

<asp:TextBox ID="txtInput" runat="server"></asp:TextBox>
<script type="text/javascript">
    function setFormat() {
        var inp = document.getElementById('ctl00_MainContent_txtInput');
        var x = inp.value;
        inp.value = x.toUpperCase();
    }

    var inp = document.getElementById('ctl00_MainContent_txtInput');
    inp.onblur = function(evt) {
        setFormat();
    };
</script>

Basically, the script attaches an event that fires when the text box loses focus.

How to detect Esc Key Press in React and how to handle it

Another way to accomplish this in a functional component, is to use useEffect and useFunction, like this:

import React, { useEffect } from 'react';

const App = () => {


  useEffect(() => {
    const handleEsc = (event) => {
       if (event.keyCode === 27) {
        console.log('Close')
      }
    };
    window.addEventListener('keydown', handleEsc);

    return () => {
      window.removeEventListener('keydown', handleEsc);
    };
  }, []);

  return(<p>Press ESC to console log "Close"</p>);
}

Instead of console.log, you can use useState to trigger something.

how to iterate through dictionary in a dictionary in django template?

This answer didn't work for me, but I found the answer myself. No one, however, has posted my question. I'm too lazy to ask it and then answer it, so will just put it here.

This is for the following query:

data = Leaderboard.objects.filter(id=custom_user.id).values(
    'value1',
    'value2',
    'value3')

In template:

{% for dictionary in data %}
  {% for key, value in dictionary.items %}
    <p>{{ key }} : {{ value }}</p>
  {% endfor %}
{% endfor %}

Change <select>'s option and trigger events with JavaScript

Fiddle of my solution is here. But just in case it expires I will paste the code as well.

HTML:

<select id="sel">
  <option value='1'>One</option>
  <option value='2'>Two</option>
  <option value='3'>Three</option>
</select>
<input type="button" id="button" value="Change option to 2" />

JS:

var sel = document.getElementById('sel'),
    button = document.getElementById('button');

button.addEventListener('click', function (e) {
    sel.options[1].selected = true;

    // firing the event properly according to StackOverflow
    // http://stackoverflow.com/questions/2856513/how-can-i-trigger-an-onchange-event-manually
    if ("createEvent" in document) {
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent("change", false, true);
        sel.dispatchEvent(evt);
    }
    else {
        sel.fireEvent("onchange");
    }
});

sel.addEventListener('change', function (e) {
    alert('changed');
});

Database corruption with MariaDB : Table doesn't exist in engine

I've just had this problem with MariaDB/InnoDB and was able to fix it by

  • create the required table in the correct database in another MySQL/MariaDB instance
  • stop both servers
  • copy .ibd, .frm files to original server
  • start both servers
  • drop problem table on both servers

How to get height of Keyboard?

I had to do this. this is a bit of hackery. not suggested.
but i found this very helpful

I made extension and struct

ViewController Extension + Struct

import UIKit
struct viewGlobal{
    static var bottomConstraint : NSLayoutConstraint = NSLayoutConstraint()
}

extension UIViewController{ //keyboardHandler
 func hideKeyboardWhenTappedAround() {
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
    tap.cancelsTouchesInView = false
    view.addGestureRecognizer(tap)
 }
 func listenerKeyboard(bottomConstraint: NSLayoutConstraint) {
    viewGlobal.bottomConstraint = bottomConstraint
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
    // Register your Notification, To know When Key Board Hides.
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
 }
 //Dismiss Keyboard
 @objc func dismissKeyboard() {
    view.endEditing(true)
 }
 @objc func keyboardWillShow(notification:NSNotification) {
    let userInfo:NSDictionary = notification.userInfo! as NSDictionary
    let keyboardFrame:NSValue = userInfo.value(forKey: UIResponder.keyboardFrameEndUserInfoKey) as! NSValue
    let keyboardRectangle = keyboardFrame.cgRectValue
    let keyboardHeight = keyboardRectangle.height
    UIView.animate(withDuration: 0.5){
        viewGlobal.bottomConstraint.constant = keyboardHeight
    }
 }

 @objc func keyboardWillHide(notification:NSNotification) {
    UIView.animate(withDuration: 0.5){
        viewGlobal.bottomConstraint.constant = 0
    }
 }
}

Usage:
get most bottom constraint

@IBOutlet weak var bottomConstraint: NSLayoutConstraint! // default 0

call the function inside viewDidLoad()

override func viewDidLoad() {
    super.viewDidLoad()

    hideKeyboardWhenTappedAround()
    listenerKeyboard(bottomConstraint: bottomConstraint)

    // Do any additional setup after loading the view.
}

Hope this help.
-you keyboard will now auto close when user tap outside of textfield and
-it will push all view to above keyboard when keyboard appear.
-you could also used dismissKeyboard() when ever you need it

How to make a <svg> element expand or contract to its parent container?

What's worked for me recently is to remove all height="" and width="" attributes from the <svg> tag and all child tags. Then you can use scaling using a percentage of the parent container's height or width.

Before:

<svg width="3212" height="3212" viewBox="0 0 3212 3212" fill="none" xmlns="http://www.w3.org/2000/svg">
   circle cx="1606" cy="1606" r="1387" stroke="black" stroke-width="438"/>
</svg>

After:

<svg viewBox="0 0 3212 3212" fill="none" xmlns="http://www.w3.org/2000/svg">
   circle cx="1606" cy="1606" r="1387" stroke="black" stroke-width="438"/>
</svg>

How does the modulus operator work?

This JSFiddle project could help you to understand how modulus work: http://jsfiddle.net/elazar170/7hhnagrj

The modulus function works something like this:

     function modulus(x,y){
       var m = Math.floor(x / y);
       var r = m * y;
       return x - r;
     }

How to display two digits after decimal point in SQL Server

You can also do something much shorter:

SELECT FORMAT(2.3332232,'N2')

How to run mysql command on bash?

I have written a shell script which will read data from properties file and then run mysql script on shell script. sharing this may help to others.

#!/bin/bash
    PROPERTY_FILE=filename.properties

    function getProperty {
       PROP_KEY=$1
       PROP_VALUE=`cat $PROPERTY_FILE | grep "$PROP_KEY" | cut -d'=' -f2`
       echo $PROP_VALUE
    }

    echo "# Reading property from $PROPERTY_FILE"
    DB_USER=$(getProperty "db.username")
    DB_PASS=$(getProperty "db.password")
    ROOT_LOC=$(getProperty "root.location")
    echo $DB_USER
    echo $DB_PASS
    echo $ROOT_LOC
    echo "Writing on DB ... "
    mysql -u$DB_USER -p$DB_PASS dbname<<EOFMYSQL

    update tablename set tablename.value_ = "$ROOT_LOC" where tablename.name_="Root directory location";
    EOFMYSQL
    echo "Writing root location($ROOT_LOC) is done ... "
    counter=`mysql -u${DB_USER} -p${DB_PASS} dbname -e "select count(*) from tablename where tablename.name_='Root directory location' and tablename.value_ = '$ROOT_LOC';" | grep -v "count"`;

    if [ "$counter" = "1" ]
    then
    echo "ROOT location updated"
    fi

How do I find out my root MySQL password?

Here is the best way to set your root password : Source Link Step 3 is working perfectly for me.

Commands for You

  1. sudo mysql
  2. SELECT user,authentication_string,plugin,host FROM mysql.user;
  3. ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
  4. FLUSH PRIVILEGES;
  5. SELECT user,authentication_string,plugin,host FROM mysql.user;
  6. exit

Now you can use the Password for the root user is 'password' :

  1. mysql -u root -p
  2. CREATE USER 'sammy'@'localhost' IDENTIFIED BY 'password';
  3. GRANT ALL PRIVILEGES ON . TO 'sammy'@'localhost' WITH GRANT OPTION;
  4. FLUSH PRIVILEGES;
  5. exit

Test your MySQL Service and Version:

systemctl status mysql.service
sudo mysqladmin -p -u root version

Moment JS start and end of given month

Try the following code:

moment(startDate).startOf('months')
moment(startDate).endOf('months')

XML Carriage return encoding

xml:space="preserve" has to work for all compliant XML parsers.

However, note that in HTML the line break is just whitespace and NOT a line break (this is represented with the <br /> (X)HTML tag, maybe this is the problem which you are facing.

You can also add &#10; and/or &#13; to insert CR/LF characters.

How To Add An "a href" Link To A "div"?

Try creating a class named overlay and apply the following css to it:

a.overlay { width: 100%; height:100%; position: absolute; }

Make sure it is placed in a positioned element.

Now simply place an <a> tag with that class inside the div you want to be linkable:

<div id="buttonOne">
  <a class="overlay" href="......."></a>
    <div id="linkedinB">
       <img src="img/linkedinB.png" alt="never forget the alt tag" width="40" height="40"/>
    </div>
 </div>

PhilipK's suggestion might work but it won't validate because you can't place a block element (div) inside an inline element (a). And when your website doesn't validate the W3C Ninja's will come for you!

An other advice would be to try avoiding inline styling.

SELECT DISTINCT on one column

Try this:

SELECT * FROM [TestData] WHERE Id IN(SELECT DISTINCT MIN(Id) FROM [TestData] GROUP BY Product)   

Get Selected value from Multi-Value Select Boxes by jquery-select2?

Try this:

  $('.select').on('select2:selecting select2:unselecting', function(e) {

      var value = e.params.args.data.id;

  });

Python IndentationError: unexpected indent

Simply copy your script and put under """ your entire code """ ...

specify this line in a variable.. like,

a = """ your entire code """
print a.replace('    ','    ') # first 4 spaces tab second four space from space bar

print a.replace('here please press tab button it will insert some space"," here simply press space bar four times")
# here we replacing tab space by four char space as per pep 8 style guide..

now execute this code, in sublime using ctrl+b, now it will print indented code in console. that's it

Set a cookie to never expire

Maximum value: 2147483647

setcookie("CookieName", "CookieValue", 2147483647);

To avoid integer overflow the timestamp should be set to:

2^31 - 1 = 2147483647 = 2038-01-19 04:14:07

Setting a higher value might cause problems with older browsers.

Also see the RFC about cookies:

Max-Age=value
  OPTIONAL.  The value of the Max-Age attribute is delta-seconds,
  the lifetime of the cookie in seconds, a decimal non-negative
  integer.  To handle cached cookies correctly, a client SHOULD
  calculate the age of the cookie according to the age calculation
  rules in the HTTP/1.1 specification [RFC2616].  When the age is
  greater than delta-seconds seconds, the client SHOULD discard the
  cookie.  A value of zero means the cookie SHOULD be discarded
  immediately.

and RFC 2616, 14.6 Age:

If a cache receives a value larger than the largest positive integer it can represent, or if any of its age calculations overflows, it MUST transmit an Age header with a value of 2147483648 (2^31).

http://www.faqs.org/rfcs/rfc2616.html

SQL Server - Case Statement

We can use case statement Like this

select Name,EmailId,gender=case 
when gender='M' then 'F'
when gender='F' then 'M'
end
 from [dbo].[Employees]

WE can also it as follow.

select Name,EmailId,case gender
when 'M' then 'F'
when 'F' then 'M'
end
 from [dbo].[Employees]

How to handle onchange event on input type=file in jQuery?

Try to use this:

HTML:

<input ID="fileUpload1" runat="server" type="file">

JavaScript:

$("#fileUpload1").on('change',function() {
    alert('Works!!');
});

?

Invalid date in safari

Arriving late to the party but in our case we were getting this issue in Safari & iOS when using ES6 back tick instead of String() to type cast

This was giving 'invalid date' error

const dateString = '2011-11-18';
const dateObj = new Date(`${dateString}`); 

But this works

const dateObj = new Date(String(dateString)); 

Creating a PDF from a RDLC Report in the Background

You can instanciate LocalReport

                FicheInscriptionBean fiche = new FicheInscriptionBean();
                fiche.ToFicheInscriptionBean(inscription);List<FicheInscriptionBean> list = new List<FicheInscriptionBean>();
                list.Add(fiche);
                ReportDataSource rds = new ReportDataSource();
                rds = new ReportDataSource("InscriptionDataSet", list);
                // attachement du QrCode.
                string stringToCode = numinscription + "," + inscription.Nom + "," + inscription.Prenom + "," + inscription.Cin;
                Bitmap BitmapCaptcha = PostulerFiche.GenerateQrCode(fiche.NumInscription + ":" + fiche.Cin, Brushes.Black, Brushes.White, 200);
                MemoryStream ms = new MemoryStream();
                BitmapCaptcha.Save(ms, ImageFormat.Gif);
                var base64Data = Convert.ToBase64String(ms.ToArray());
                string QR_IMG = base64Data;
                ReportParameter parameter = new ReportParameter("QR_IMG", QR_IMG, true);

                LocalReport report = new LocalReport();
                report.ReportPath = Page.Server.MapPath("~/rdlc/FicheInscription.rdlc");
                report.DataSources.Clear();
                report.SetParameters(new ReportParameter[] { parameter });
                report.DataSources.Add(rds);
                report.Refresh();

                string FileName = "FichePreinscription_" + numinscription + ".pdf";
                string extension;
                string encoding;
                string mimeType;
                string[] streams;
                Warning[] warnings;
                Byte[] mybytes = report.Render("PDF", null,
                              out extension, out encoding,
                              out mimeType, out streams, out warnings);
                using (FileStream fs = File.Create(Server.MapPath("~/rdlc/Reports/" + FileName)))
                {
                    fs.Write(mybytes, 0, mybytes.Length);
                }
                Response.ClearHeaders();
                Response.ClearContent();
                Response.Buffer = true;
                Response.Clear();
                Response.Charset = "";
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", "attachment;filename=\"" + FileName + "\"");
                Response.WriteFile(Server.MapPath("~/rdlc/Reports/" + FileName));

                Response.Flush();
                File.Delete(Server.MapPath("~/rdlc/Reports/" + FileName));
                Response.Close();
                Response.End();

encapsulation vs abstraction real world example

Encapsulation helps in adhering to Single Responsibility principle and Abstraction helps in adhering to Code to Interface and not to implement.

Say I have a class for Car : Service Provider Class and Driver Class : Service Consumer Class.

For Abstraction : we define abstract Class for CAR and define all the abstract methods in it , which are function available in the car like : changeGear(), applyBrake().

Now the actual Car (Concrete Class i.e. like Mercedes , BMW will implement these methods in their own way and abstract the execution and end user will still apply break and change gear for particular concrete car instance and polymorphically the execution will happen as defined in concrete class.

For Encapsulation : Now say Mercedes come up with new feature/technology: Anti Skid Braking, while implementing the applyBrake(), it will encapsulate this feature in applyBrake() method and thus providing cohesion, and service consumer will still access by same method applyBrake() of the car object. Thus Encapsulation lets further in same concrete class implementation.

@RequestParam in Spring MVC handling optional parameters

You need to give required = false for name and password request parameters as well. That's because, when you provide just the logout parameter, it actually expects for name and password as well as they are still mandatory.

It worked when you just gave name and password because logout wasn't a mandatory parameter thanks to required = false already given for logout.

String.Format like functionality in T-SQL?

I have created a user defined function to mimic the string.format functionality. You can use it.

stringformat-in-sql

UPDATE:
This version allows the user to change the delimitter.

-- DROP function will loose the security settings.
IF object_id('[dbo].[svfn_FormatString]') IS NOT NULL
    DROP FUNCTION [dbo].[svfn_FormatString]
GO

CREATE FUNCTION [dbo].[svfn_FormatString]
(
    @Format NVARCHAR(4000),
    @Parameters NVARCHAR(4000),
    @Delimiter CHAR(1) = ','
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    /*
        Name: [dbo].[svfn_FormatString]
        Creation Date: 12/18/2020

        Purpose: Returns the formatted string (Just like in C-Sharp)

        Input Parameters:   @Format         = The string to be Formatted
                            @Parameters     = The comma separated list of parameters
                            @Delimiter      = The delimitter to be used in the formatting process

        Format:             @Format         = N'Hi {0}, Welcome to our site {1}. Thank you {0}'
                            @Parameters     = N'Karthik,google.com'
                            @Delimiter      = ','           
        Examples:
            SELECT dbo.svfn_FormatString(N'Hi {0}, Welcome to our site {1}. Thank you {0}', N'Karthik,google.com', default)
            SELECT dbo.svfn_FormatString(N'Hi {0}, Welcome to our site {1}. Thank you {0}', N'Karthik;google.com', ';')
    */
    DECLARE @Message NVARCHAR(400)
    DECLARE @ParamTable TABLE ( Id INT IDENTITY(0,1), Paramter VARCHAR(1000))

    SELECT @Message = @Format

    ;WITH CTE (StartPos, EndPos) AS
    (
        SELECT 1, CHARINDEX(@Delimiter, @Parameters)
        UNION ALL
        SELECT EndPos + (LEN(@Delimiter)), CHARINDEX(@Delimiter, @Parameters, EndPos + (LEN(@Delimiter)))
        FROM CTE
        WHERE EndPos > 0
    )

    INSERT INTO @ParamTable ( Paramter )
    SELECT
        [Id] = SUBSTRING(@Parameters, StartPos, CASE WHEN EndPos > 0 THEN EndPos - StartPos ELSE 4000 END )
    FROM CTE

    UPDATE @ParamTable 
    SET 
        @Message = REPLACE(@Message, '{'+ CONVERT(VARCHAR, Id) + '}', Paramter )

    RETURN @Message
END

Creating a simple XML file using python

Yattag http://www.yattag.org/ or https://github.com/leforestier/yattag provides an interesting API to create such XML document (and also HTML documents).

It's using context manager and with keyword.

from yattag import Doc, indent

doc, tag, text = Doc().tagtext()

with tag('root'):
    with tag('doc'):
        with tag('field1', name='blah'):
            text('some value1')
        with tag('field2', name='asdfasd'):
            text('some value2')

result = indent(
    doc.getvalue(),
    indentation = ' '*4,
    newline = '\r\n'
)

print(result)

so you will get:

<root>
    <doc>
        <field1 name="blah">some value1</field1>
        <field2 name="asdfasd">some value2</field2>
    </doc>
</root>

Find the max of 3 numbers in Java with different data types

Java 8 way. Works for multiple parameters:

Stream.of(first, second, third).max(Integer::compareTo).get()

How do I create test and train samples from one dataframe with pandas?

If you need to split your data with respect to the lables column in your data set you can use this:

def split_to_train_test(df, label_column, train_frac=0.8):
    train_df, test_df = pd.DataFrame(), pd.DataFrame()
    labels = df[label_column].unique()
    for lbl in labels:
        lbl_df = df[df[label_column] == lbl]
        lbl_train_df = lbl_df.sample(frac=train_frac)
        lbl_test_df = lbl_df.drop(lbl_train_df.index)
        print '\n%s:\n---------\ntotal:%d\ntrain_df:%d\ntest_df:%d' % (lbl, len(lbl_df), len(lbl_train_df), len(lbl_test_df))
        train_df = train_df.append(lbl_train_df)
        test_df = test_df.append(lbl_test_df)

    return train_df, test_df

and use it:

train, test = split_to_train_test(data, 'class', 0.7)

you can also pass random_state if you want to control the split randomness or use some global random seed.

Possible to change where Android Virtual Devices are saved?

ANDROID_SDK_HOME also worked for me on Windows 8 x64 also find all location (in my case it was d:\.android) and delete it. You won't need it anymore.

Xcode 9 error: "iPhone has denied the launch request"

I'have tried all the answers nothing worked for me, The problem is coming form Xcode itself and has nothing to do with profiles and certificate :

Product > Scheme > Edit Scheme

In Run (Section) / info (tab) [select] the Release instead of debug as Build Configuration as follow :

enter image description here

It's a regression since Xcode 10.1


Config : Xcode Version 10.1 (10B61) Iphone X / IOS 12.1.4

Can I get all methods of a class?

Straight from the source: http://java.sun.com/developer/technicalArticles/ALT/Reflection/ Then I modified it to be self contained, not requiring anything from the command line. ;-)

import java.lang.reflect.*;

/** 
Compile with this:
C:\Documents and Settings\glow\My Documents\j>javac DumpMethods.java

Run like this, and results follow
C:\Documents and Settings\glow\My Documents\j>java DumpMethods
public void DumpMethods.foo()
public int DumpMethods.bar()
public java.lang.String DumpMethods.baz()
public static void DumpMethods.main(java.lang.String[])
*/

public class DumpMethods {

    public void foo() { }

    public int bar() { return 12; }

    public String baz() { return ""; }

    public static void main(String args[]) {
        try {
            Class thisClass = DumpMethods.class;
            Method[] methods = thisClass.getDeclaredMethods();

            for (int i = 0; i < methods.length; i++) {
                System.out.println(methods[i].toString());
            }
        } catch (Throwable e) {
            System.err.println(e);
        }
    }
}

How to screenshot website in JavaScript client-side / how Google did it? (no need to access HDD)

I needed to snapshot a div on the page (for a webapp I wrote) that is protected by JWT's and makes very heavy use of Angular.

I had no luck with any of the above methods.

I ended up taking the outerHTML of the div I needed, cleaning it up a little (*) and then sending it to the server where I run wkhtmltopdf against it.

This is working very well for me.

(*) various input devices in my pages didn't render as checked or have their text values when viewed in the pdf... So I run a little bit of jQuery on the html before I send it up for rendering. ex: for text input items -- I copy their .val()'s into 'value' attributes, which then can be seen by wkhtmlpdf

Printing PDFs from Windows Command Line

@ECHO off set "dir1=C:\TicketDownload" 
FOR %%X in ("%dir1%*.pdf") DO ( "C:\Program Files (x86)\Adobe\Reader 9.0\Reader\AcroRd32.exe" /t "%%~dpnX.pdf" "Microsoft XPS Document Writer" ) 
FOR %%X in ("%dir1%*.pdf") DO (move "%%~dpnX.pdf" p/)

Try this..May be u have some other version of Reader so that is the problem..

'node' is not recognized as an internal or external command

Node is missing from the SYSTEM PATH, try this in your command line

SET PATH=C:\Program Files\Nodejs;%PATH%

and then try running node

To set this system wide you need to set in the system settings - cf - http://banagale.com/changing-your-system-path-in-windows-vista.htm

To be very clean, create a new system variable NODEJS

NODEJS="C:\Program Files\Nodejs"

Then edit the PATH in system variables and add %NODEJS%

PATH=%NODEJS%;...

Static linking vs dynamic linking

Best example for dynamic linking is, when the library is dependent on the used hardware. In ancient times the C math library was decided to be dynamic, so that each platform can use all processor capabilities to optimize it.

An even better example might be OpenGL. OpenGl is an API that is implemented differently by AMD and NVidia. And you are not able to use an NVidia implementation on an AMD card, because the hardware is different. You cannot link OpenGL statically into your program, because of that. Dynamic linking is used here to let the API be optimized for all platforms.

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

Hello Thanks for the question; To resolve: "Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'"

In Windows Features check all for .NET 4 Advanced Services & .NET 3.5

enter image description here

Just like Nicolas Gago I tried aspnet_regiis.exe -iru but it didn't work. After the features were on then it yellow screen error was gone. Thanks;

Keep SSH session alive

The ssh daemon (sshd), which runs server-side, closes the connection from the server-side if the client goes silent (i.e., does not send information). To prevent connection loss, instruct the ssh client to send a sign-of-life signal to the server once in a while.

The configuration for this is in the file $HOME/.ssh/config, create the file if it does not exist (the config file must not be world-readable, so run chmod 600 ~/.ssh/config after creating the file). To send the signal every e.g. four minutes (240 seconds) to the remote host, put the following in that configuration file:

Host remotehost
    HostName remotehost.com
    ServerAliveInterval 240

To enable sending a keep-alive signal for all hosts, place the following contents in the configuration file:

Host *
    ServerAliveInterval 240

How to push a new folder (containing other folders and files) to an existing git repo?

You need to git add my_project to stage your new folder. Then git add my_project/* to stage its contents. Then commit what you've staged using git commit and finally push your changes back to the source using git push origin master (I'm assuming you wish to push to the master branch).

How can I check for existence of element in std::vector, in one line?

int elem = 42;
std::vector<int> v;
v.push_back(elem);
if(std::find(v.begin(), v.end(), elem) != v.end())
{
  //elem exists in the vector
} 

Is a view faster than a simple query?

Generally speaking, no. Views are primarily used for convenience and security, and won't (by themselves) produce any speed benefit.

That said, SQL Server 2000 and above do have a feature called Indexed Views that can greatly improve performance, with a few caveats:

  1. Not every view can be made into an indexed view; they have to follow a specific set of guidelines, which (among other restrictions) means you can't include common query elements like COUNT, MIN, MAX, or TOP.
  2. Indexed views use physical space in the database, just like indexes on a table.

This article describes additional benefits and limitations of indexed views:

You Can…

  • The view definition can reference one or more tables in the same database.
  • Once the unique clustered index is created, additional nonclustered indexes can be created against the view.
  • You can update the data in the underlying tables – including inserts, updates, deletes, and even truncates.

You Can’t…

  • The view definition can’t reference other views, or tables in other databases.
  • It can’t contain COUNT, MIN, MAX, TOP, outer joins, or a few other keywords or elements.
  • You can’t modify the underlying tables and columns. The view is created with the WITH SCHEMABINDING option.
  • You can’t always predict what the query optimizer will do. If you’re using Enterprise Edition, it will automatically consider the unique clustered index as an option for a query – but if it finds a “better” index, that will be used. You could force the optimizer to use the index through the WITH NOEXPAND hint – but be cautious when using any hint.

making a paragraph in html contain a text from a file

You'll want to use either JavaScript or a server-side language like PHP, ASP...etc

(supposedly can be done with HTML <embed> tag, which makes sense, but I haven't used, since PHP...etc is so simple/common)

Javascript can work: Here's a link to someone doing something similar via javascript on stackoverflow: How do I load the contents of a text file into a javascript variable?

PHP (as example of server-side language) is the easiest way to go though:

<div><p><?php include('myFile.txt'); ?></p></div>

To use this (if you're unfamiliar with PHP), you can:

1) check if you have php on your server

2) change the file extension of your .html file to .php

3) paste the code from my PHP example somewhere in the body of your newly-renamed PHP file

Calling javascript function in iframe

Call

window.frames['resultFrame'].Reset();

How can I tell if a VARCHAR variable contains a substring?

CONTAINS is for a Full Text Indexed field - if not, then use LIKE

How to create custom exceptions in Java?

public class MyException extends Exception {
        // special exception code goes here
}

Throw it as:

 throw new MyException ("Something happened")

Catch as:

catch (MyException e)
{
   // something
}

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

Align is the way to go is you have only one child.

If you have more, consider doing something like this :

return new Column(
  crossAxisAlignment: CrossAxisAlignment.center,
  mainAxisSize: MainAxisSize.max,
  mainAxisAlignment: MainAxisAlignment.end,
  children: <Widget>[
      //your elements here
  ],
);

Command-line tool for finding out who is locking a file

I have used Unlocker for years and really like it. It not only will identify programs and offer to unlock the folder\file, it will allow you to kill the processing that has the lock as well.

Additionally, it offers actions to do to the locked file in question such as deleting it.

Unlocker helps delete locked files with error messages including "cannot delete file," and "access is denied." Video tutorial available.

Some errors you might get that Unlocker can help with include:

  • Cannot delete file: Access is denied.
  • There has been a sharing violation.
  • The source or destination file may be in use.
  • The file is in use by another program or user.
  • Make sure the disk is not full or write-protected and that the file is not currently in use.

Inserting NOW() into Database with CodeIgniter's Active Record

putting NOW() in quotes won't work as Active Records will put escape the NOW() into a string and tries to push it into the db as a string of "NOW()"... you will need to use

$this->db->set('time', 'NOW()', FALSE); 

to set it correctly.

you can always check your sql afterward with

$this->db->last_query();

javascript setTimeout() not working

To make little more easy to understand use like below, which i prefer the most. Also it permits to call multiple function at once. Obviously

setTimeout(function(){
      startTimer();
      function2();
      function3();
}, startInterval);

"This project is incompatible with the current version of Visual Studio"

For me, I got this same error in VS 2015 and just installed the VS 2015 update 1, though from another answer, VS is actually up to Update 3, now (after which, they got the error and had to install .NET Core). Had issues when it hit certain packages, like the Windows SDK ones, and had to point the installer back at the paths in my original CD, and for some, even that didn't work and had to skip them and re-download from an internet-connected computer, transfer them over, and run them later manually (computer was not connected to the internet to be able to download updated versions of the packages), but after doing all that and doing a reboot, the error was gone and my project loaded fine.

Why is there no SortedList in Java?

List iterators guarantee first and foremost that you get the list's elements in the internal order of the list (aka. insertion order). More specifically it is in the order you've inserted the elements or on how you've manipulated the list. Sorting can be seen as a manipulation of the data structure, and there are several ways to sort the list.

I'll order the ways in the order of usefulness as I personally see it:

1. Consider using Set or Bag collections instead

NOTE: I put this option at the top because this is what you normally want to do anyway.

A sorted set automatically sorts the collection at insertion, meaning that it does the sorting while you add elements into the collection. It also means you don't need to manually sort it.

Furthermore if you are sure that you don't need to worry about (or have) duplicate elements then you can use the TreeSet<T> instead. It implements SortedSet and NavigableSet interfaces and works as you'd probably expect from a list:

TreeSet<String> set = new TreeSet<String>();
set.add("lol");
set.add("cat");
// automatically sorts natural order when adding

for (String s : set) {
    System.out.println(s);
}
// Prints out "cat" and "lol"

If you don't want the natural ordering you can use the constructor parameter that takes a Comparator<T>.

Alternatively, you can use Multisets (also known as Bags), that is a Set that allows duplicate elements, instead and there are third-party implementations of them. Most notably from the Guava libraries there is a TreeMultiset, that works a lot like the TreeSet.

2. Sort your list with Collections.sort()

As mentioned above, sorting of Lists is a manipulation of the data structure. So for situations where you need "one source of truth" that will be sorted in a variety of ways then sorting it manually is the way to go.

You can sort your list with the java.util.Collections.sort() method. Here is a code sample on how:

List<String> strings = new ArrayList<String>()
strings.add("lol");
strings.add("cat");

Collections.sort(strings);
for (String s : strings) {
    System.out.println(s);
}
// Prints out "cat" and "lol"

Using comparators

One clear benefit is that you may use Comparator in the sort method. Java also provides some implementations for the Comparator such as the Collator which is useful for locale sensitive sorting strings. Here is one example:

Collator usCollator = Collator.getInstance(Locale.US);
usCollator.setStrength(Collator.PRIMARY); // ignores casing

Collections.sort(strings, usCollator);

Sorting in concurrent environments

Do note though that using the sort method is not friendly in concurrent environments, since the collection instance will be manipulated, and you should consider using immutable collections instead. This is something Guava provides in the Ordering class and is a simple one-liner:

List<string> sorted = Ordering.natural().sortedCopy(strings);

3. Wrap your list with java.util.PriorityQueue

Though there is no sorted list in Java there is however a sorted queue which would probably work just as well for you. It is the java.util.PriorityQueue class.

Nico Haase linked in the comments to a related question that also answers this.

In a sorted collection you most likely don't want to manipulate the internal data structure which is why PriorityQueue doesn't implement the List interface (because that would give you direct access to its elements).

Caveat on the PriorityQueue iterator

The PriorityQueue class implements the Iterable<E> and Collection<E> interfaces so it can be iterated as usual. However, the iterator is not guaranteed to return elements in the sorted order. Instead (as Alderath points out in the comments) you need to poll() the queue until empty.

Note that you can convert a list to a priority queue via the constructor that takes any collection:

List<String> strings = new ArrayList<String>()
strings.add("lol");
strings.add("cat");

PriorityQueue<String> sortedStrings = new PriorityQueue(strings);
while(!sortedStrings.isEmpty()) {
    System.out.println(sortedStrings.poll());
}
// Prints out "cat" and "lol"

4. Write your own SortedList class

NOTE: You shouldn't have to do this.

You can write your own List class that sorts each time you add a new element. This can get rather computation heavy depending on your implementation and is pointless, unless you want to do it as an exercise, because of two main reasons:

  1. It breaks the contract that List<E> interface has because the add methods should ensure that the element will reside in the index that the user specifies.
  2. Why reinvent the wheel? You should be using the TreeSet or Multisets instead as pointed out in the first point above.

However, if you want to do it as an exercise here is a code sample to get you started, it uses the AbstractList abstract class:

public class SortedList<E> extends AbstractList<E> {

    private ArrayList<E> internalList = new ArrayList<E>();

    // Note that add(E e) in AbstractList is calling this one
    @Override 
    public void add(int position, E e) {
        internalList.add(e);
        Collections.sort(internalList, null);
    }

    @Override
    public E get(int i) {
        return internalList.get(i);
    }

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

}

Note that if you haven't overridden the methods you need, then the default implementations from AbstractList will throw UnsupportedOperationExceptions.

How to pass password to scp?

Use sshpass:

sshpass -p "password" scp -r [email protected]:/some/remote/path /some/local/path

or so the password does not show in the bash history

sshpass -f "/path/to/passwordfile" scp -r [email protected]:/some/remote/path /some/local/path

The above copies contents of path from the remote host to your local.

Install :

  • ubuntu/debian
    • apt install sshpass
  • centos/fedora
    • yum install sshpass
  • mac w/ macports
    • port install sshpass
  • mac w/ brew
    • brew install https://raw.githubusercontent.com/kadwanev/bigboybrew/master/Library/Formula/sshpass.rb

How to get difference between two dates in Year/Month/Week/Day?

I was trying to find a clear answer for Years, Months and Days, and I didn't find anything clear, If you are still looking check this method:

        public static string GetDifference(DateTime d1, DateTime d2)
        {
            int[] monthDay = new int[12] { 31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
            DateTime fromDate;
            DateTime toDate;
            int year;
            int month;
            int day; 
            int increment = 0;

            if (d1 > d2)
            {
                fromDate = d2;
                toDate = d1;
            }
            else
            {
                fromDate = d1;
                toDate = d2;
            } 

            // Calculating Days
            if (fromDate.Day > toDate.Day)
            {
                increment = monthDay[fromDate.Month - 1];
            }

            if (increment == -1)
            {
                if (DateTime.IsLeapYear(fromDate.Year))
                {
                    increment = 29;
                }
                else
                {
                    increment = 28;
                }
            }

            if (increment != 0)
            {
                day = (toDate.Day + increment) - fromDate.Day;
                increment = 1;
            }
            else
            {
                day = toDate.Day - fromDate.Day;
            }

            // Month Calculation
            if ((fromDate.Month + increment) > toDate.Month)
            {
                month = (toDate.Month + 12) - (fromDate.Month + increment);
                increment = 1;
            }
            else
            {
                month = (toDate.Month) - (fromDate.Month + increment);
                increment = 0;
            }

            // Year Calculation
            year = toDate.Year - (fromDate.Year + increment);

            return year + " years " + month + " months " + day + " days";
        }

How do you use "git --bare init" repository?

You could also ask git to create directory for you:

git init --bare test_repo.git

Run a single test method with maven

This command works !! mvn "-DTest=JoinTeamTestCases#validateJoinTeam" test Note that "-DTest" starts with UPPER CASE 'T'.

Uncaught ReferenceError: $ is not defined error in jQuery

Include the jQuery file first:

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
 <script type="text/javascript" src="./javascript.js"></script>
    <script
        src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCJnj2nWoM86eU8Bq2G4lSNz3udIkZT4YY&sensor=false">
    </script>

fatal: bad default revision 'HEAD'

just do an initial commit and the error will go away:

git commit -m "initial commit"

Django - Did you forget to register or load this tag?

In gameprofile.html please change the tag {% endblock content %} to {% endblock %} then it works otherwise django will not load the endblock and give error.

How can I rename a conda environment?

Based upon dwanderson's helpful comment, I was able to do this in a Bash one-liner:

conda create --name envpython2 --file <(conda list -n env1 -e )

My badly named env was "env1" and the new one I wish to clone from it is "envpython2".

Google Maps JS API v3 - Simple Multiple Marker Example

This is the working example map image

var arr = new Array();
    function initialize() { 
        var i;  
        var Locations = [
                {
                  lat:48.856614, 
                  lon:2.3522219000000177, 
                  address:'Paris',
                  gval:'25.5',
                  aType:'Non-Commodity',
                  title:'Paris',
                  descr:'Paris'           
                },        
                    {
                  lat: 55.7512419, 
                  lon: 37.6184217,
                  address:'Moscow',
                  gval:'11.5',
                  aType:'Non-Commodity',
                  title:'Moscow',
                  descr:'Moscow Airport'              
                },     

                {
              lat:-9.481553000000002, 
              lon:147.190242, 
              address:'Port Moresby',
              gval:'1',
              aType:'Oil',
              title:'Papua New Guinea',
              descr:'Papua New Guinea 123123123'              
            },
            {
           lat:20.5200,
           lon:77.7500,
           address:'Indore',
            gval:'1',
            aType:'Oil',
            title:'Indore, India',
            descr:'Airport India'
        }
    ];

    var myOptions = {
        zoom: 2,
        center: new google.maps.LatLng(51.9000,8.4731),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("map"), myOptions);

    var infowindow =  new google.maps.InfoWindow({
        content: ''
    });

    for (i = 0; i < Locations.length; i++) {
            size=15;        
            var img=new google.maps.MarkerImage('marker.png',           
                new google.maps.Size(size, size),
                new google.maps.Point(0,0),
                new google.maps.Point(size/2, size/2)
           );

        var marker = new google.maps.Marker({
            map: map,
            title: Locations[i].title,
            position: new google.maps.LatLng(Locations[i].lat, Locations[i].lon),           
                icon: img
        });

        bindInfoWindow(marker, map, infowindow, "<p>" + Locations[i].descr + "</p>",Locations[i].title);  

    }

}

function bindInfoWindow(marker, map, infowindow, html, Ltitle) { 
    google.maps.event.addListener(marker, 'mouseover', function() {
            infowindow.setContent(html); 
            infowindow.open(map, marker); 

    });
    google.maps.event.addListener(marker, 'mouseout', function() {
        infowindow.close();

    }); 
} 

Full working example. You can just copy, paste and use.

HTML Script tag: type or language (or omit both)?

The language attribute has been deprecated for a long time, and should not be used.

When W3C was working on HTML5, they discovered all browsers have "text/javascript" as the default script type, so they standardized it to be the default value. Hence, you don't need type either.

For pages in XHTML 1.0 or HTML 4.01 omitting type is considered invalid. Try validating the following:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://example.com/test.js"></script>
</head>
<body/>
</html>

You will be informed of the following error:

Line 4, Column 41: required attribute "type" not specified

So if you're a fan of standards, use it. It should have no practical effect, but, when in doubt, may as well go by the spec.

How to concatenate two MP4 files using FFmpeg?

this worked for me (on windows)

ffmpeg -i "concat:input1|input2" -codec copy output

an example...

ffmpeg -i "concat:01.mp4|02.mp4" -codec copy output.mp4

Python

Using some python code to do it with as many mp4 there are in a folder (install python from python.org, copy and paste and save this code into a file called mp4.py and run it from the cmd opened in the folder with python mp4.py and all the mp4 in the folder will be concatenated)

import glob
import os

stringa = ""
for f in glob.glob("*.mp4"):
    stringa += f + "|"
os.system("ffmpeg -i \"concat:" + stringa + "\" -codec copy output.mp4")

Version 2 with Python

Taken from my post on my blog, this is how I do it in python:

import os
import glob

def concatenate():
    stringa = "ffmpeg -i \"concat:"
    elenco_video = glob.glob("*.mp4")
    elenco_file_temp = []
    for f in elenco_video:
        file = "temp" + str(elenco_video.index(f) + 1) + ".ts"
        os.system("ffmpeg -i " + f + " -c copy -bsf:v h264_mp4toannexb -f mpegts " + file)
        elenco_file_temp.append(file)
    print(elenco_file_temp)
    for f in elenco_file_temp:
        stringa += f
        if elenco_file_temp.index(f) != len(elenco_file_temp)-1:
            stringa += "|"
        else:
            stringa += "\" -c copy  -bsf:a aac_adtstoasc output.mp4"
    print(stringa)
    os.system(stringa)

concatenate()

Can't use modulus on doubles?

Use fmod() from <cmath>. If you do not want to include the C header file:

template<typename T, typename U>
constexpr double dmod (T x, U mod)
{
    return !mod ? x : x - mod * static_cast<long long>(x / mod);
}

//Usage:
double z = dmod<double, unsigned int>(14.3, 4);
double z = dmod<long, float>(14, 4.6);
//This also works:
double z = dmod(14.7, 0.3);
double z = dmod(14.7, 0);
double z = dmod(0, 0.3f);
double z = dmod(myFirstVariable, someOtherVariable);

git remove merge commit from history

There are two ways to tackle this based on what you want:

Solution 1: Remove purple commits, preserving history (incase you want to roll back)

git revert -m 1 <SHA of merge>

-m 1 specifies which parent line to choose

Purple commits will still be there in history but since you have reverted, you will not see code from those commits.


Solution 2: Completely remove purple commits (disruptive change if repo is shared)

git rebase -i <SHA before branching out>

and delete (remove lines) corresponding to purple commits.

This would be less tricky if commits were not made after merge. Additional commits increase the chance of conflicts during revert/rebase.

How to prevent a click on a '#' link from jumping to top of page?

The #/ trick works, but adds a history event to the browser. So, clicking back doesn't work as the user may want/expect it to.

$('body').click('a[href="#"]', function(e) {e.preventDefault() }); is the way I went, as it works for already existing content, and any elements added to the DOM after load.

Specifically, I needed to do this in a bootstrap dropdown-menu inside of a .btn-group(Reference), so I did:

$('body').click('.dropdown-menu li a[href="#"]', function(e) {e.preventDefault() });

This way it was targeted, and didn't affect anything thing else on the page.

How do I get the full url of the page I am on in C#

Thanks guys, I used a combination of both your answers @Christian and @Jonathan for my specific need.

"http://" + Request.ServerVariables["SERVER_NAME"] +  Request.RawUrl.ToString()

I don't need to worry about secure http, needed the servername variable and the RawUrl handles the path from the domain name and includes the querystring if present.

How to make a flat list out of list of lists?

Don't reinvent the wheel if you use Django:

>>> from django.contrib.admin.utils import flatten
>>> l = [[1,2,3], [4,5], [6]]
>>> flatten(l)
>>> [1, 2, 3, 4, 5, 6]

...Pandas:

>>> from pandas.core.common import flatten
>>> list(flatten(l))

...Itertools:

>>> import itertools
>>> flatten = itertools.chain.from_iterable
>>> list(flatten(l))

...Matplotlib

>>> from matplotlib.cbook import flatten
>>> list(flatten(l))

...Unipath:

>>> from unipath.path import flatten
>>> list(flatten(l))

...Setuptools:

>>> from setuptools.namespaces import flatten
>>> list(flatten(l))

Python lookup hostname from IP with 1 second timeout

What you're trying to accomplish is called Reverse DNS lookup.

socket.gethostbyaddr("IP") 
# => (hostname, alias-list, IP)

http://docs.python.org/library/socket.html?highlight=gethostbyaddr#socket.gethostbyaddr

However, for the timeout part I have read about people running into problems with this. I would check out PyDNS or this solution for more advanced treatment.

invalid_client in google oauth2

Set/change your product name, I had this issue until I created a product name as same as project name.

The product name can be set in the Consent screen section of the Google Developers Console for your project. Look under APIs & auth in the left navigation and select Consent screen. You need also to set your email address in the box above the product name.

Xcode Simulator: how to remove older unneeded devices?

October 2020 update

As was mentioned, you can use xcrun to do a few things:

  • xcrun simctl list devices or xcrun simctl list --json to list all simulators
  • xcrun simctl delete <device udid> to delete specific device
  • xcrun simctl delete unavailable to remove old devices for runtimes that are no longer supported

More things you can do with xcrun (see code snippet)

_x000D_
_x000D_
- `xcrun simctl boot <device udid>` to launch (multiple) simulators
- `xcrun simctl io booted recordVideo — type=mp4 ./test.mp4` to record simulator video
- `xcrun simctl io booted screenshot ./screen.png` to make screenshot of simulator
- `xcrun simctl openurl booted https://google.com` to open URL in simulator
- `xcrun simctl addmedia booted ./test.mp4` to upload photo or video file (for photos app)
- `xcrun simctl get_app_container booted <your apps bundle identifier>` to find the app container (where identifier is like *com.bundle.identifier*)
- `xcrun simctl help` to explore **more** commands
_x000D_
_x000D_
_x000D_

Original Answer

September 2017, Xcode 9

Runtimes

You will find them here:

/Library/Developer/CoreSimulator/Profiles/Runtimes

enter image description here

Devices

To delete devices go here:

~/Library/Developer/CoreSimulator/Devices

Much easier to delete them use Xcode: Xcode->Window->Devices and Simulators enter image description here

Helping Xcode "forget" about runtimes and prevent from re-installing them - delete .dmg file(s) here:

~/Library/Caches/com.apple.dt.Xcode/Downloads

I hope it will help someone

Add x and y labels to a pandas plot

You can use do it like this:

import matplotlib.pyplot as plt 
import pandas as pd

plt.figure()
values = [[1, 2], [2, 5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], 
                   index=['Index 1', 'Index 2'])
df2.plot(lw=2, colormap='jet', marker='.', markersize=10,
         title='Video streaming dropout by category')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
plt.show()

Obviously you have to replace the strings 'xlabel' and 'ylabel' with what you want them to be.

npm install -g less does not work: EACCES: permission denied

I have tried all the suggested solutions but nothing worked.

I am using macOS Catalina 10.15.3

Go to /usr/local/

Select bin folder > Get Info

Add your user to Sharing & Permissions. Read & Write Permissions. enter image description here

And go to terminal and run npm install -g @ionic/cli

It has helped me.

Static constant string (class member)

To use that in-class initialization syntax, the constant must be a static const of integral or enumeration type initialized by a constant expression.

This is the restriction. Hence, in this case you need to define variable outside the class. refer answwer from @AndreyT

How to make a page redirect using JavaScript?

You can call a JavaScript function and use window.location = 'url';:

http://www.pageresource.com/jscript/jredir.htm

How to pass parameters to $http in angularjs?

Here is how you do it:

$http.get("/url/to/resource/", {params:{"param1": val1, "param2": val2}})
    .then(function (response) { /* */ })...

Angular takes care of encoding the parameters.

Maxim Shoustin's answer does not work ({method:'GET', url:'/search', jsonData} is not a valid JavaScript literal) and JeyTheva's answer, although simple, is dangerous as it allows XSS (unsafe values are not escaped when you concatenate them).

Creating a new ArrayList in Java

If you just want a list:

ArrayList<Class> myList = new ArrayList<Class>();

If you want an arraylist of a certain length (in this case size 10):

List<Class> myList = new ArrayList<Class>(10);

If you want to program against the interfaces (better for abstractions reasons):

List<Class> myList = new ArrayList<Class>();

Programming against interfaces is considered better because it's more abstract. You can change your Arraylist with a different list implementation (like a LinkedList) and the rest of your application doesn't need any changes.

How to write text in ipython notebook?

Simply Enter Esc and type m it will convert to text cell.

convert json ipython notebook(.ipynb) to .py file

From the notebook menu you can save the file directly as a python script. Go to the 'File' option of the menu, then select 'Download as' and there you would see a 'Python (.py)' option.

enter image description here

Another option would be to use nbconvert from the command line:

jupyter nbconvert --to script 'my-notebook.ipynb'

Have a look here.

Clearing my form inputs after submission

var btnClear = document.querySelector('button');
var inputs = document.querySelectorAll('input');
 
btnClear.addEventListener('click', () => {
    inputs.forEach(input =>  input.value = '');
});

How to write a full path in a batch file having a folder name with space?

Put double quotes around the path that has spaces like this:

REGSVR32 "E:\Documents and Settings\All Users\Application Data\xyz.dll"

Why isn't .ico file defined when setting window's icon?

So it looks like root.iconbitmap() only supports a fixed directory.
sys.argv[0] returns the directory that the file was read from so a simple code would work to create a fixed directory.

import sys
def get_dir(src):
    dir = sys.argv[0]
    dir = dir.split('/')
    dir.pop(-1)
    dir = '/'.join(dir)
    dir = dir+'/'+src
    return dir

This is the output

>>> get_dir('test.txt')
'C:/Users/Josua/Desktop/test.txt'

EDIT:
The only issue is that this method dosn't work on linux

josua@raspberrypi:~ $ python
Python 2.7.9 (default, Sep 17 2016, 20:26:04) [GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.argv[0]
''
>>>

How can I generate an ObjectId with mongoose?

You can create a new MongoDB ObjectId like this using mongoose:

var mongoose = require('mongoose');
var newId = new mongoose.mongo.ObjectId('56cb91bdc3464f14678934ca');
// or leave the id string blank to generate an id with a new hex identifier
var newId2 = new mongoose.mongo.ObjectId();

Viewing full output of PS command

you can set output format,eg to see only the command and the process id.

ps -eo pid,args

see the man page of ps for more output format. alternatively, you can use the -w or --width n options.

If all else fails, here's another workaround, (just to see your long cmds)

awk '{ split(FILENAME,f,"/") ; printf "%s: %s\n", f[3],$0 }' /proc/[0-9]*/cmdline

Best way to implement multi-language/globalization in large .NET project

We use a custom provider for multi language support and put all texts in a database table. It works well except we sometimes face caching problems when updating texts in the database without updating the web application.

Getting "project" nuget configuration is invalid error

NOTE: This is mentioned in the question but restarting Visual Studio fixes the issue in most cases.

Updating Visual Studio to 'Update 2' got it working again.

Tools -> Extensions and Updates ->Visual Studio Update 2

As mentioned in the question and the link i posted therein, I'd already updated NuGet Package Manager to 3.4.4 prior to this and restarted to no avail, so I don't know if the combination of both these actions worked.

Django: TemplateSyntaxError: Could not parse the remainder

also happens when you use jinja templates (which have different syntax for calling object methods) and you forget to set it in settings.py

How do I see what character set a MySQL database / table / column is?

For database : USE db_name; SELECT @@character_set_database;

How do I run a batch script from within a batch script?

Run parallelly on separate command windows in minimized state

dayStart.bat

start "startOfficialSoftwares" /min cmd /k call startOfficialSoftwares.bat
start "initCodingEnvironment" /min cmd /k call initCodingEnvironment.bat
start "updateProjectSource" /min cmd /k call updateProjectSource.bat
start "runCoffeeMachine" /min cmd /k call runCoffeeMachine.bat

Run sequentially on same window

release.bat

call updateDevelVersion.bat
call mergeDevelIntoMaster.bat
call publishProject.bat

Getting an element from a Set

Object objectToGet = ...
Map<Object, Object> map = new HashMap<Object, Object>(set.size());
for (Object o : set) {
    map.put(o, o);
}
Object objectFromSet = map.get(objectToGet);

If you only do one get this will not be very performing because you will loop over all your elements but when performing multiple retrieves on a big set you will notice the difference.

How do I replace a character in a string in Java?

You can use stream and flatMap to map & to &amp;

    String str = "begin&end";
    String newString = str.chars()
        .flatMap(ch -> (ch == '&') ? "&amp;".chars() : IntStream.of(ch))
        .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
        .toString();

CFLAGS vs CPPFLAGS

To add to those who have mentioned the implicit rules, it's best to see what make has defined implicitly and for your env using:

make -p

For instance:

%.o: %.c
    $(COMPILE.c) $(OUTPUT_OPTION) $<

which expands

COMPILE.c = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c

This will also print # environment data. Here, you will find GCC's include path among other useful info.

C_INCLUDE_PATH=/usr/include

In make, when it comes to search, the paths are many, the light is one... or something to that effect.

  1. C_INCLUDE_PATH is system-wide, set it in your shell's *.rc.
  2. $(CPPFLAGS) is for the preprocessor include path.
  3. If you need to add a general search path for make, use:
VPATH = my_dir_to_search

... or even more specific

vpath %.c src
vpath %.h include

make uses VPATH as a general search path so use cautiously. If a file exists in more than one location listed in VPATH, make will take the first occurrence in the list.

Finding the number of non-blank columns in an Excel sheet using VBA

Jean-François Corbett's answer is perfect. To be exhaustive I would just like to add that with some restrictons you could also use UsedRange.Columns.Count or UsedRange.Rows.Count.
The problem is that UsedRange is not always updated when deleting rows/columns (at least until you reopen the workbook).

What is the purpose of a plus symbol before a variable?

As explained in other answers it converts the variable to a number. Specially useful when d can be either a number or a string that evaluates to a number.

Example (using the addMonths function in the question):

addMonths(34,1,true);
addMonths("34",1,true);

then the +d will evaluate to a number in all cases. Thus avoiding the need to check for the type and take different code paths depending on whether d is a number, a function or a string that can be converted to a number.

matplotlib: plot multiple columns of pandas data frame on the bar chart

You can plot several columns at once by supplying a list of column names to the plot's y argument.

df.plot(x="X", y=["A", "B", "C"], kind="bar")

enter image description here

This will produce a graph where bars are sitting next to each other.

In order to have them overlapping, you would need to call plot several times, and supplying the axes to plot to as an argument ax to the plot.

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

y = np.random.rand(10,4)
y[:,0]= np.arange(10)
df = pd.DataFrame(y, columns=["X", "A", "B", "C"])

ax = df.plot(x="X", y="A", kind="bar")
df.plot(x="X", y="B", kind="bar", ax=ax, color="C2")
df.plot(x="X", y="C", kind="bar", ax=ax, color="C3")

plt.show()

enter image description here

Java: Enum parameter in method

I am not too sure I would go and use an enum as a full fledged class - this is an object oriented language, and one of the most basic tenets of object orientation is that a class should do one thing and do it well.

An enum is doing a pretty good job at being an enum, and a class is doing a good job as a class. Mixing the two I have a feeling will get you into trouble - for example, you can't pass an instance of an enum as a parameter to a method, primarily because you can't create an instance of an enum.

So, even though you might be able to enum.process() does not mean that you should.

Check if process returns 0 with batch file

You can use below command to check if it returns 0 or 1 :

In below example, I am checking for the string in the one particular file which will give you 1 if that particular word "Error" is not present in the file and if present then 0

find /i "| ERROR1 |" C:\myfile.txt
echo %errorlevel%

if %errorlevel% equ 1 goto notfound
goto found
:notfound
exit 1
:found
echo we found the text.

How to make a submit out of a <a href...>...</a> link?

We replace the submit button with this all the time on forms:

<form method="post" action="whatever.asp">
<input type=...n

<input type="image" name="Submit" src="/graphics/continue.gif" align="middle" border="0" alt="Continue">
</form>

Clicking the image submits the form. Hope that helps!

Use jQuery to change an HTML tag?

This is my solution. It allows to toggle between tags.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
 <title></title>_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>_x000D_
<script type="text/javascript">_x000D_
_x000D_
function wrapClass(klass){_x000D_
 return 'to-' + klass;_x000D_
}_x000D_
_x000D_
function replaceTag(fromTag, toTag){_x000D_
 _x000D_
 /** Create selector for all elements you want to change._x000D_
   * These should be in form: <fromTag class="to-toTag"></fromTag>_x000D_
   */_x000D_
 var currentSelector = fromTag + '.' + wrapClass(toTag);_x000D_
_x000D_
 /** Select all elements */_x000D_
 var $selected = $(currentSelector);_x000D_
_x000D_
 /** If you found something then do the magic. */_x000D_
 if($selected.size() > 0){_x000D_
_x000D_
  /** Replace all selected elements */_x000D_
  $selected.each(function(){_x000D_
_x000D_
   /** jQuery current element. */_x000D_
   var $this = $(this);_x000D_
_x000D_
   /** Remove class "to-toTag". It is no longer needed. */_x000D_
   $this.removeClass(wrapClass(toTag));_x000D_
_x000D_
   /** Create elements that will be places instead of current one. */_x000D_
   var $newElem = $('<' + toTag + '>');_x000D_
_x000D_
   /** Copy all attributes from old element to new one. */_x000D_
   var attributes = $this.prop("attributes");_x000D_
   $.each(attributes, function(){_x000D_
    $newElem.attr(this.name, this.value);_x000D_
   });_x000D_
_x000D_
   /** Add class "to-fromTag" so you can remember it. */_x000D_
   $newElem.addClass(wrapClass(fromTag));_x000D_
_x000D_
   /** Place content of current element to new element. */_x000D_
   $newElem.html($this.html());_x000D_
_x000D_
   /** Replace old with new. */_x000D_
   $this.replaceWith($newElem);_x000D_
  });_x000D_
_x000D_
  /** It is possible that current element has desired elements inside._x000D_
    * If so you need to look again for them._x000D_
    */_x000D_
  replaceTag(fromTag, toTag);_x000D_
 }_x000D_
}_x000D_
_x000D_
_x000D_
</script>_x000D_
_x000D_
<style type="text/css">_x000D_
 _x000D_
 section {_x000D_
  background-color: yellow;_x000D_
 }_x000D_
_x000D_
 div {_x000D_
  background-color: red;_x000D_
 }_x000D_
_x000D_
 .big {_x000D_
  font-size: 40px;_x000D_
 }_x000D_
_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<button onclick="replaceTag('div', 'section');">Section -> Div</button>_x000D_
<button onclick="replaceTag('section', 'div');">Div -> Section</button>_x000D_
_x000D_
<div class="to-section">_x000D_
 <p>Matrix has you!</p>_x000D_
 <div class="to-section big">_x000D_
  <p>Matrix has you inside!</p>_x000D_
 </div>_x000D_
</div>_x000D_
_x000D_
<div class="to-section big">_x000D_
 <p>Matrix has me too!</p>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Add tooltip to font awesome icon

In regards to this question, this can be easily achieved using a few lines of SASS;

HTML:

<a href="https://www.urbandictionary.com/define.php?term=techninja" data-tool-tip="What's a tech ninja?" target="_blank"><i class="fas fa-2x fa-user-ninja" id="tech--ninja"></i></a>

CSS output would be:

a[data-tool-tip]{
    position: relative;
    text-decoration: none;
    color: rgba(255,255,255,0.75);
}

a[data-tool-tip]::after{
    content: attr(data-tool-tip);
    display: block;
    position: absolute;
    background-color: dimgrey;
    padding: 1em 3em;
    color: white;
    border-radius: 5px;
    font-size: .5em;
    bottom: 0;
    left: -180%;
    white-space: nowrap;
    transform: scale(0);
    transition: 
    transform ease-out 150ms,
    bottom ease-out 150ms;
}

a[data-tool-tip]:hover::after{
    transform: scale(1);
    bottom: 200%;
}

Basically the attribute selector [data-tool-tip] selects the content of whatever's inside and allows you to animate it however you want.

Get file size, image width and height before upload

A working jQuery validate example:

   $(function () {
        $('input[type=file]').on('change', function() {
            var $el = $(this);
            var files = this.files;
            var image = new Image();
            image.onload = function() {
                $el
                    .attr('data-upload-width', this.naturalWidth)
                    .attr('data-upload-height', this.naturalHeight);
            }

            image.src = URL.createObjectURL(files[0]);
        });

        jQuery.validator.unobtrusive.adapters.add('imageminwidth', ['imageminwidth'], function (options) {
            var params = {
                imageminwidth: options.params.imageminwidth.split(',')
            };

            options.rules['imageminwidth'] = params;
            if (options.message) {
                options.messages['imageminwidth'] = options.message;
            }
        });

        jQuery.validator.addMethod("imageminwidth", function (value, element, param) {
            var $el = $(element);
            if(!element.files && element.files[0]) return true;
            return parseInt($el.attr('data-upload-width')) >=  parseInt(param["imageminwidth"][0]);
        });

    } (jQuery));

Why do we use volatile keyword?

In computer programming, particularly in the C, C++, and C# programming languages, a variable or object declared with the volatile keyword usually has special properties related to optimization and/or threading. Generally speaking, the volatile keyword is intended to prevent the (pseudo)compiler from applying any optimizations on the code that assume values of variables cannot change "on their own." (c) Wikipedia

http://en.wikipedia.org/wiki/Volatile_variable

Concatenating strings in Razor

the plus works just fine, i personally prefer using the concat function.

var s = string.Concat(string 1, string 2, string, 3, etc)

What are the differences between virtual memory and physical memory?

See here: Physical Vs Virtual Memory

Virtual memory is stored on the hard drive and is used when the RAM is filled. Physical memory is limited to the size of the RAM chips installed in the computer. Virtual memory is limited by the size of the hard drive, so virtual memory has the capability for more storage.