Programs & Examples On #Imgur

Imgur is a free and popular image hosting service that does not require registration to use.

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

I got the same error, but when i did as below, it resolved the issue.
Instead of writing like this:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

use the below one:

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

How to rollback a specific migration?

To rollback the last migration you can do:

rake db:rollback

If you want to rollback a specific migration with a version you should do:

rake db:migrate:down VERSION=YOUR_MIGRATION_VERSION

For e.g. if the version is 20141201122027, you will do:

rake db:migrate:down VERSION=20141201122027

to rollback that specific migration.

Safe width in pixels for printing web pages?

I doubt there is one... It depends on browser, on printer (physical max dpi) and its driver, on paper size as you point out (and I might want to print on B5 paper too...), on settings (landscape or portrait?), plus you often can change the scale (percentage), etc.
Let the users tweak their settings...

Finding elements not in a list

Using list comprehension:

print [x for x in item if x not in Z]

or using filter function :

filter(lambda x: x not in Z, item)

Using set in any form may create a bug if the list being checked contains non-unique elements, e.g.:

print item

Out[39]: [0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print Z

Out[40]: [3, 4, 5, 6]

set(item) - set(Z)

Out[41]: {0, 1, 2, 7, 8, 9}

vs list comprehension as above

print [x for x in item if x not in Z]

Out[38]: [0, 1, 1, 2, 7, 8, 9]

or filter function:

filter(lambda x: x not in Z, item)

Out[38]: [0, 1, 1, 2, 7, 8, 9]

How to count the number of rows in excel with data?

Dim RowNumber As Integer
RowNumber = ActiveSheet.Range("A65536").End(xlUp).Row

In your case it should return #9

Still Reachable Leak detected by Valgrind

You don't appear to understand what still reachable means.

Anything still reachable is not a leak. You don't need to do anything about it.

How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#?

I was able to figure it out. In case someone wants to know below the code that worked for me:

ASCIIEncoding ascii = new ASCIIEncoding();
byte[] byteArray = Encoding.UTF8.GetBytes(sOriginal);
byte[] asciiArray = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, byteArray);
string finalString = ascii.GetString(asciiArray);

Let me know if there is a simpler way o doing it.

Control the size of points in an R scatterplot?

As rcs stated, cex will do the job in base graphics package. I reckon that you're not willing to do your graph in ggplot2 but if you do, there's a size aesthetic attribute, that you can easily control (ggplot2 has user-friendly function arguments: instead of typing cex (character expansion), in ggplot2 you can type e.g. size = 2 and you'll get 2mm point).

Here's the example:

### base graphics ###
plot(mpg ~ hp, data = mtcars, pch = 16, cex = .9)

### ggplot2 ###
# with qplot()
qplot(mpg, hp, data = mtcars, size = I(2))
# or with ggplot() + geom_point()
ggplot(mtcars, aes(mpg, hp), size = 2) + geom_point()
# or another solution:
ggplot(mtcars, aes(mpg, hp)) + geom_point(size = 2)

How can I make a jQuery UI 'draggable()' div draggable for touchscreen?

After wasting many hours, I came across this!

jquery-ui-touch-punch

It translates tap events as click events. Remember to load the script after jquery.

I got this working on the iPad and iPhone

$('#movable').draggable({containment: "parent"});

Java 8 Lambda function that throws exception?

I'm the author of a tiny lib with some generic magic to throw any Java Exception anywhere without the need of catching them nor wrapping them into RuntimeException.

Usage: unchecked(() -> methodThrowingCheckedException())

public class UncheckedExceptions {

    /**
     * throws {@code exception} as unchecked exception, without wrapping exception.
     *
     * @return will never return anything, return type is set to {@code exception} only to be able to write <code>throw unchecked(exception)</code>
     * @throws T {@code exception} as unchecked exception
     */
    @SuppressWarnings("unchecked")
    public static <T extends Throwable> T unchecked(Exception exception) throws T {
        throw (T) exception;
    }


    @FunctionalInterface
    public interface UncheckedFunction<R> {
        R call() throws Exception;
    }

    /**
     * Executes given function,
     * catches and rethrows checked exceptions as unchecked exceptions, without wrapping exception.
     *
     * @return result of function
     * @see #unchecked(Exception)
     */
    public static <R> R unchecked(UncheckedFunction<R> function) {
        try {
            return function.call();
        } catch (Exception e) {
            throw unchecked(e);
        }
    }


    @FunctionalInterface
    public interface UncheckedMethod {
        void call() throws Exception;
    }

    /**
     * Executes given method,
     * catches and rethrows checked exceptions as unchecked exceptions, without wrapping exception.
     *
     * @see #unchecked(Exception)
     */
    public static void unchecked(UncheckedMethod method) {
        try {
            method.call();
        } catch (Exception e) {
            throw unchecked(e);
        }
    }
}

source: https://github.com/qoomon/unchecked-exceptions-java

How to validate domain credentials?

using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices.AccountManagement;

class WindowsCred
{
    private const string SPLIT_1 = "\\";

    public static bool ValidateW(string UserName, string Password)
    {
        bool valid = false;
        string Domain = "";

        if (UserName.IndexOf("\\") != -1)
        {
            string[] arrT = UserName.Split(SPLIT_1[0]);
            Domain = arrT[0];
            UserName = arrT[1];
        }

        if (Domain.Length == 0)
        {
            Domain = System.Environment.MachineName;
        }

        using (PrincipalContext context = new PrincipalContext(ContextType.Domain, Domain)) 
        {
            valid = context.ValidateCredentials(UserName, Password);
        }

        return valid;
    }
}

Kashif Mushtaq Ottawa, Canada

Case insensitive std::string.find()

wxWidgets has a very rich string API wxString

it can be done with (using the case conversion way)

int Contains(const wxString& SpecProgramName, const wxString& str)
{
  wxString SpecProgramName_ = SpecProgramName.Upper();
  wxString str_ = str.Upper();
  int found = SpecProgramName.Find(str_);
  if (wxNOT_FOUND == found)
  {
    return 0;
  }
  return 1;
}

How to load all the images from one of my folder into my web page, using Jquery/Javascript

$(document).ready(function(){
  var dir = "test/"; // folder location
  var fileextension = ".jpg"; // image format
  var i = "1";

  $(function imageloop(){
    $("<img />").attr('src', dir + i + fileextension ).appendTo(".testing");
    if (i==13){
      alert('loaded');
    }
    else{
      i++;
      imageloop();
    };
  });   
});

For this script, I have named my image files in a folder as 1.jpg, 2.jpg, 3.jpg, ... to 13.jpg.

You can change directory and file names as you wish.

"Android library projects cannot be launched"?

From Android's Developer Documentation on Managing Projects from Eclipse with ADT:

Setting up a Library Project

Next, set the project's Properties to indicate that it is a library project:

  1. In the Package Explorer, right-click the library project and select Properties.
  2. In the Properties window, select the "Android" properties group at left and locate the Library properties at right.
  3. Select the "is Library" checkbox and click Apply.
  4. Click OK to close the Properties window.

So, open your project properties, un-select the "Is Library" checkbox, and click Apply to make your project a normal Android project (not a library project).

Difference between numpy dot() and Python 3.5+ matrix multiplication @

My experience with MATMUL and DOT

I was constantly getting "ValueError: Shape of passed values is (200, 1), indices imply (200, 3)" when trying to use MATMUL. I wanted a quick workaround and found DOT to deliver the same functionality. I don't get any error using DOT. I get the correct answer

with MATMUL

X.shape
>>>(200, 3)

type(X)

>>>pandas.core.frame.DataFrame

w

>>>array([0.37454012, 0.95071431, 0.73199394])

YY = np.matmul(X,w)

>>>  ValueError: Shape of passed values is (200, 1), indices imply (200, 3)"

with DOT

YY = np.dot(X,w)
# no error message
YY
>>>array([ 2.59206877,  1.06842193,  2.18533396,  2.11366346,  0.28505879, …

YY.shape

>>> (200, )

How to remove MySQL root password

I have also been through this problem,

First i tried setting my password of root to blank using command :

SET PASSWORD FOR root@localhost=PASSWORD('');

But don't be happy , PHPMYADMIN uses 127.0.0.1 not localhost , i know you would say both are same but that is not the case , use the command mentioned underneath and you are done.

SET PASSWORD FOR [email protected]=PASSWORD('');

Just replace localhost with 127.0.0.1 and you are done .

How to get text from each cell of an HTML table?

Thanks for the earlier reply.

I figured out the solutions using selenium 2.0 classes.

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class WebTableExample 
{
    public static void main(String[] args) 
    {
        WebDriver driver = new InternetExplorerDriver();
        driver.get("http://localhost/test/test.html");      

        WebElement table_element = driver.findElement(By.id("testTable"));
        List<WebElement> tr_collection=table_element.findElements(By.xpath("id('testTable')/tbody/tr"));

        System.out.println("NUMBER OF ROWS IN THIS TABLE = "+tr_collection.size());
        int row_num,col_num;
        row_num=1;
        for(WebElement trElement : tr_collection)
        {
            List<WebElement> td_collection=trElement.findElements(By.xpath("td"));
            System.out.println("NUMBER OF COLUMNS="+td_collection.size());
            col_num=1;
            for(WebElement tdElement : td_collection)
            {
                System.out.println("row # "+row_num+", col # "+col_num+ "text="+tdElement.getText());
                col_num++;
            }
            row_num++;
        } 
    }
}

Convert String to equivalent Enum value

I might've over-engineered my own solution without realizing that Type.valueOf("enum string") actually existed.

I guess it gives more granular control but I'm not sure it's really necessary.

public enum Type {
    DEBIT,
    CREDIT;

    public static Map<String, Type> typeMapping = Maps.newHashMap();
    static {
        typeMapping.put(DEBIT.name(), DEBIT);
        typeMapping.put(CREDIT.name(), CREDIT);
    }

    public static Type getType(String typeName) {
        if (typeMapping.get(typeName) == null) {
            throw new RuntimeException(String.format("There is no Type mapping with name (%s)"));
        }
        return typeMapping.get(typeName);
    }
}

I guess you're exchanging IllegalArgumentException for RuntimeException (or whatever exception you wish to throw) which could potentially clean up code.

How do I return clean JSON from a WCF Service?

I faced the same problem, and resolved it by changing the BodyStyle attribut value to "WebMessageBodyStyle.Bare" :

[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetProjectWithGeocodings/{projectId}")]
GeoCod_Project GetProjectWithGeocodings(string projectId);

The returned object will no longer be wrapped.

Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

Since you say that any language is acceptable, the natural choice is PostGIS:

SELECT * FROM places
WHERE ST_DistanceSpheroid(geom, $location, $spheroid) < $max_metres;

If you want to use WGS datum, you should set $spheroid to 'SPHEROID["WGS 84",6378137,298.257223563]'

Assuming that you have indexed places by the geom column, this should be reasonably efficient.

Target class controller does not exist - Laravel 8

I had this error

(Illuminate\Contracts\Container\BindingResolutionException Target class [App\Http\Controllers\ControllerFileName] does not exist.

Solution: just check your class Name, it should be the exact same of your file name.

PHP ternary operator vs null coalescing operator

If you use the shortcut ternary operator like this, it will cause a notice if $_GET['username'] is not set:

$val = $_GET['username'] ?: 'default';

So instead you have to do something like this:

$val = isset($_GET['username']) ? $_GET['username'] : 'default';

The null coalescing operator is equivalent to the above statement, and will return 'default' if $_GET['username'] is not set or is null:

$val = $_GET['username'] ?? 'default';

Note that it does not check truthiness. It checks only if it is set and not null.

You can also do this, and the first defined (set and not null) value will be returned:

$val = $input1 ?? $input2 ?? $input3 ?? 'default';

Now that is a proper coalescing operator.

How do I merge my local uncommitted changes into another Git branch?

WARNING: Not for git newbies.

This comes up enough in my workflow that I've almost tried to write a new git command for it. The usual git stash flow is the way to go but is a little awkward. I usually make a new commit first since if I have been looking at the changes, all the information is fresh in my mind and it's better to just start git commit-ing what I found (usually a bugfix belonging on master that I discover while working on a feature branch) right away.

It is also helpful—if you run into situations like this a lot—to have another working directory alongside your current one that always have the master branch checked out.

So how I achieve this goes like this:

  1. git commit the changes right away with a good commit message.
  2. git reset HEAD~1 to undo the commit from current branch.
  3. (optional) continue working on the feature.

Sometimes later (asynchronously), or immediately in another terminal window:

  1. cd my-project-master which is another WD sharing the same .git
  2. git reflog to find the bugfix I've just made.
  3. git cherry-pick SHA1 of the commit.

Optionally (still asynchronous) you can then rebase (or merge) your feature branch to get the bugfix, usually when you are about to submit a PR and have cleaned your feature branch and WD already:

  1. cd my-project which is the main WD I'm working on.
  2. git rebase master to get the bugfixes.

This way I can keep working on the feature uninterrupted and not have to worry about git stash-ing anything or having to clean my WD before a git checkout (and then having the check the feature branch backout again.) and still have all my bugfixes goes to master instead of hidden in my feature branch.

IMO git stash and git checkout is a real PIA when you are in the middle of working on some big feature.

ffprobe or avprobe not found. Please install one

What worked for me (youtube-dl version 2018.03.03, ffprobe 0.5, no avprobe, 3.4.1-tessus, in Hi-Sierra/iMac) was:

brew install libav

(thanks to marciovsena's post on GitHub).

I saw elsewhere that libav might be deprecated in the future, but I'll worry about it when we get there.

adding text to an existing text element in javascript via DOM

remove .textContent from var t = document.getElementById("p").textContent;

_x000D_
_x000D_
var t = document.getElementById("p");_x000D_
var y = document.createTextNode("This just got added");_x000D_
_x000D_
t.appendChild(y);
_x000D_
<p id ="p">This is some text</p>
_x000D_
_x000D_
_x000D_

How to draw circle by canvas in Android?

@Override
public void onDraw(Canvas canvas){
    canvas.drawCircle(xPos, yPos,radius, paint);
}

Above is the code to render a circle. Tweak the parameters to your suiting.

Include PHP inside JavaScript (.js) files

PHP and JS are not compatible; you may not simply include a PHP function in JS. What you probably want to do is to issue an AJAX Request from JavaScript and send a JSON response using PHP.

#pragma mark in Swift?

Xcode 8 now handles it as followed and shows up like this in the method dropdown:

enter image description here

What is C# equivalent of <map> in C++?

Take a look at the Dictionary class in System::Collections::Generic.

Dictionary<myComplex, int> myMap = new Dictionary<myComplex, int>();

What does this GCC error "... relocation truncated to fit..." mean?

Remember to tackle error messages in order. In my case, the error above this one was "undefined reference", and I visually skipped over it to the more interesting "relocation truncated" error. In fact, my problem was an old library that was causing the "undefined reference" message. Once I fixed that, the "relocation truncated" went away also.

How to run a cronjob every X minutes?

2 steps to check if a cronjob is working :

  1. Login on the server with the user that execute the cronjob
  2. Manually run php command :

    /usr/bin/php /mydomain.in/cromail.php

And check if any error is displayed

Why does NULL = NULL evaluate to false in SQL server

The concept of NULL is questionable, to say the least. Codd introduced the relational model and the concept of NULL in context (and went on to propose more than one kind of NULL!) However, relational theory has evolved since Codd's original writings: some of his proposals have since been dropped (e.g. primary key) and others never caught on (e.g. theta operators). In modern relational theory (truly relational theory, I should stress) NULL simply does not exist. See The Third Manifesto. http://www.thethirdmanifesto.com/

The SQL language suffers the problem of backwards compatibility. NULL found its way into SQL and we are stuck with it. Arguably, the implementation of NULL in SQL is flawed (SQL Server's implementation makes things even more complicated due to its ANSI_NULLS option).

I recommend avoiding the use of NULLable columns in base tables.


Although perhaps I shouldn't be tempted, I just wanted to assert a corrections of my own about how NULL works in SQL:

NULL = NULL evaluates to UNKNOWN.

UNKNOWN is a logical value.

NULL is a data value.

This is easy to prove e.g.

SELECT NULL = NULL

correctly generates an error in SQL Server. If the result was a data value then we would expect to see NULL, as some answers here (wrongly) suggest we would.

The logical value UNKNOWN is treated differently in SQL DML and SQL DDL respectively.

In SQL DML, UNKNOWN causes rows to be removed from the resultset.

For example:

CREATE TABLE MyTable
(
 key_col INTEGER NOT NULL UNIQUE, 
 data_col INTEGER
 CHECK (data_col = 55)
);

INSERT INTO MyTable (key_col, data_col)
   VALUES (1, NULL);

The INSERT succeeds for this row, even though the CHECK condition resolves to NULL = NULL. This is due defined in the SQL-92 ("ANSI") Standard:

11.6 table constraint definition

3)

If the table constraint is a check constraint definition, then let SC be the search condition immediately contained in the check constraint definition and let T be the table name included in the corresponding table constraint descriptor; the table constraint is not satisfied if and only if

EXISTS ( SELECT * FROM T WHERE NOT ( SC ) )

is true.

Read that again carefully, following the logic.

In plain English, our new row above is given the 'benefit of the doubt' about being UNKNOWN and allowed to pass.

In SQL DML, the rule for the WHERE clause is much easier to follow:

The search condition is applied to each row of T. The result of the where clause is a table of those rows of T for which the result of the search condition is true.

In plain English, rows that evaluate to UNKNOWN are removed from the resultset.

bootstrap 3 navbar collapse button not working

In my case the issue was due to how I build my Nav bar. I was doing it through a jQuery plugin so I can quickly build Bootstrap components through javascript.

To cut a long story short binding the data elements of the button through jQuery .data() resulted in a collapse button that didn't work, doing it via .attr() fixed the issue.

This doesn't work:

$this.addClass("navbar navbar-default")
  .append($("<div />").addClass("container-fluid")
    .append($("<div />").addClass("navbar-header")
      .append($("<button />").addClass("navbar-toggle collapsed")
        .attr("type","button")
        .attr("aria-expanded", "false")
        .data("target","#" + id)
        .data("toggle","collapse")
        .html("<span class='sr-only'>Toggle navigation</span>"
            + "<span class='icon-bar'></span>"
            + "<span class='icon-bar'></span>"
            + "<span class='icon-bar'></span>"))
        .append($("<a href='#' />").addClass("navbar-brand")
          .append(document.createTextNode(settings.label))))
    .append($("<div />").addClass("collapse navbar-collapse").attr("id",id)));

But this does (with the changes left in comments):

$this.addClass("navbar navbar-default")
  .append($("<div />").addClass("container-fluid")
    .append($("<div />").addClass("navbar-header")
      .append($("<button />").addClass("navbar-toggle collapsed")
        .attr("type","button")
        .attr("aria-expanded", "false")
        .attr("data-target", "#" + id) //.data("target","#" + id)
        .attr("data-toggle", "collapse") // .data("toggle","collapse")
        .html("<span class='sr-only'>Toggle navigation</span>"
            + "<span class='icon-bar'></span>"
            + "<span class='icon-bar'></span>"
            + "<span class='icon-bar'></span>"))
        .append($("<a href='#' />").addClass("navbar-brand")
          .append(document.createTextNode(settings.label))))
    .append($("<div />").addClass("collapse navbar-collapse").attr("id",id)));

I can only assume that this is related to the way jQuery binds .data(), it doesn't write the attributes out to the elements, but just attaches them to the jQuery object. Using the .data() version resulted in HTML:

<button class="navbar-toggle collapsed" aria-expanded="false" type="button" >

Where as the .attr() version gives:

<button class="navbar-toggle collapsed" aria-expanded="false" type="button" data-toggle="collapse" data-target="#6a2034fe-8922-4edd-920e-6bd0ea0b2caf">

It seems that Bootstrap needs the data-nnn attribute in the HTML.

How do I concatenate a boolean to a string in Python?

answer = “True”

myvars = “the answer is” + answer

print(myvars)

That should give you the answer is True easily as you have stored answer as a string by using the quotation marks

Object variable or With block variable not set (Error 91)

As I wrote in my comment, the solution to your problem is to write the following:

Set hyperLinkText = hprlink.Range

Set is needed because TextRange is a class, so hyperLinkText is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.

How many significant digits do floats and doubles have in java?

A 32-bit float has about 7 digits of precision and a 64-bit double has about 16 digits of precision

Long answer:

Floating-point numbers have three components:

  1. A sign bit, to determine if the number is positive or negative.
  2. An exponent, to determine the magnitude of the number.
  3. A fraction, which determines how far between two exponent values the number is. This is sometimes called “the significand, mantissa, or coefficient”

Essentially, this works out to sign * 2^exponent * (1 + fraction). The “size” of the number, it’s exponent, is irrelevant to us, because it only scales the value of the fraction portion. Knowing that log10(n) gives the number of digits of n,† we can determine the precision of a floating point number with log10(largest_possible_fraction). Because each bit in a float stores 2 possibilities, a binary number of n bits can store a number up to 2n - 1 (a total of 2n values where one of the values is zero). This gets a bit hairier, because it turns out that floating point numbers are stored with one less bit of fraction than they can use, because zeroes are represented specially and all non-zero numbers have at least one non-zero binary bit.‡

Combining this, the digits of precision for a floating point number is log10(2n), where n is the number of bits of the floating point number’s fraction. A 32-bit float has 24 bits of fraction for ˜7.22 decimal digits of precision, and a 64-bit double has 53 bits of fraction for ˜15.95 decimal digits of precision.

For more on floating point accuracy, you might want to read about the concept of a machine epsilon.


† For n = 1 at least — for other numbers your formula will look more like ?log10(|n|)? + 1.

‡ “This rule is variously called the leading bit convention, the implicit bit convention, or the hidden bit convention.” (Wikipedia)

Changing the color of a clicked table row using jQuery

jQuery :

$("#data td").toggle(function(){
    $(this).css('background-color','blue')
},function(){
    $(this).css('background-color','ur_default_color')
});

How do I select an element that has a certain class?

h2.myClass is only valid for h2 elements which got the class myClass directly assigned.

Your want to note it like this:

.myClass h2

Which selects all children of myClass which have the tagname h2

jQuery: If this HREF contains

It doesn't work because it's syntactically nonsensical. You simply can't do that in JavaScript like that.

You can, however, use jQuery:

  if ($(this).is('[href$=?]'))

You can also just look at the "href" value:

  if (/\?$/.test(this.href))

Understanding implicit in Scala

Why and when you should mark the request parameter as implicit:

Some methods that you will make use of in the body of your action have an implicit parameter list like, for example, Form.scala defines a method:

def bindFromRequest()(implicit request: play.api.mvc.Request[_]): Form[T] = { ... }

You don't necessarily notice this as you would just call myForm.bindFromRequest() You don't have to provide the implicit arguments explicitly. No, you leave the compiler to look for any valid candidate object to pass in every time it comes across a method call that requires an instance of the request. Since you do have a request available, all you need to do is to mark it as implicit.

You explicitly mark it as available for implicit use.

You hint the compiler that it's "OK" to use the request object sent in by the Play framework (that we gave the name "request" but could have used just "r" or "req") wherever required, "on the sly".

myForm.bindFromRequest()

see it? it's not there, but it is there!

It just happens without your having to slot it in manually in every place it's needed (but you can pass it explicitly, if you so wish, no matter if it's marked implicit or not):

myForm.bindFromRequest()(request)

Without marking it as implicit, you would have to do the above. Marking it as implicit you don't have to.

When should you mark the request as implicit? You only really need to if you are making use of methods that declare an implicit parameter list expecting an instance of the Request. But to keep it simple, you could just get into the habit of marking the request implicit always. That way you can just write beautiful terse code.

Make a Bash alias that takes a parameter?

As has already been pointed out by others, using a function should be considered best practice.

However, here is another approach, leveraging xargs:

alias junk="xargs -I "{}" -- mv "{}" "~/.Trash" <<< "

Note that this has side effects regarding redirection of streams.

Typescript interface default values

It's best practice in case you have many parameters to let the user insert only few parameters and not in specific order.

For example, bad practice:

foo(a, b, c, d, e)

Good practice:

foo({d=3})

The way to do it is through interfaces. You need to define the parameter as an interface like:

interface Arguments {
    a?;
    b?; 
    c?;
    d?;
    e?;
}

And define the function like:

foo(arguments: Arguments)

Now interfaces variables can't get default values, so how do we define default values?

Simple, we define default value for the whole interface:

foo({
        a,
        b=1,
        c=99,
        d=88,
        e                    
    }: Arguments)

Now if the user pass:

foo({d=3})

The actual parameters will be:

{
    a,
    b=1,
    c=99,
    d=3,
    e                    
}

I understood it from the following link so big credit :) https://medium.com/better-programming/named-parameters-in-typescript-e32c763d2b2e

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

TL;DR $PATH fix

  1. Use pip install --user package_name to install a package that should include CLI executables.
  2. Launch a python shell and import package_name
  3. Find where lib/python/... occurs in the output and replace it all with bin
  4. It's likely to be $HOME/Library/Python/2.7/bin

Details

Because of the new System Integrity Protection in macOS 10.11 El Capitan, you can no longer sudo pip install. We won't debate the merits of that here.

Another answer explains that you should pip install --user which is correct. But they sent you to the back alleys to figure out what to do about your $PATH so that you could get access to installed executables. Luckily, I've already solved a similar need for an unrelated question.

Here is a transcript of how I solved the problem on one of my systems. I'm including it all rather just than the $PATH that worked for me, because your system may be different from mine. This process should work for everybody.

$ pip install --user jp
Collecting jp
  Downloading jp-0.2.4.tar.gz
Installing collected packages: jp
  Running setup.py install for jp ... done
Successfully installed jp-0.2.4

$ python -c 'import jp; print jp'
<module 'jp' from '/Users/bbronosky/Library/Python/2.7/lib/python/site-packages/jp/__init__.pyc'>

$ find /Users/bbronosky/Library/Python -type f -perm -100
/Users/bbronosky/Library/Python/2.7/bin/jp

$ which jp

$ echo -e '\n''export PATH=$HOME/Library/Python/2.7/bin:$PATH' >> ~/.bashrc

$ bash # starting a new bash process for demo, but you should open a new terminal

$ which jp
/Users/bbronosky/Library/Python/2.7/bin/jp

$ jp
usage: jp <expression> <filepath>

pip install failing with: OSError: [Errno 13] Permission denied on directory

Option a) Create a virtualenv, activate it and install:

virtualenv .venv
source .venv/bin/activate
pip install -r requirements.txt

Option b) Install in your homedir:

pip install --user -r requirements.txt

My recommendation use safe (a) option, so that requirements of this project do not interfere with other projects requirements.

How to return a boolean method in java?

Best way would be to declare Boolean variable within the code block and return it at end of code, like this:

public boolean Test(){
    boolean booleanFlag= true; 
    if (A>B)
    {booleanFlag= true;}
    else 
    {booleanFlag = false;}
    return booleanFlag;

}

I find this the best way.

Disable automatic sorting on the first column when using jQuery DataTables

Set the aaSorting option to an empty array. It will disable initial sorting, whilst still allowing manual sorting when you click on a column.

"aaSorting": []

The aaSorting array should contain an array for each column to be sorted initially containing the column's index and a direction string ('asc' or 'desc').

How do I clear the content of a div using JavaScript?

Just Javascript (as requested)

Add this function somewhere on your page (preferably in the <head>)

function clearBox(elementID)
{
    document.getElementById(elementID).innerHTML = "";
}

Then add the button on click event:

<button onclick="clearBox('cart_item')" />

In JQuery (for reference)

If you prefer JQuery you could do:

$("#cart_item").html("");

Is there a query language for JSON?

PythonQL offers an embedded syntax that IMHO is an improvement on SQL, principally because group, window, where, let, etc. can be freely intermixed.

$ cat x.py
#coding: pythonql
data = [{"x": 2, "y": 0}, {"x": 3, "y": 1}, {"x": 4, "y": 1}]
q = [x match {'x': as x, 'y': as y} in data where y > 0]
print(sum(q))
print(list(q))

q = [x match {'x': as x, 'y': as y} as d in data where d['y'] > 0]
print(sum(q))

This code shows two different answers to your question, depending on your need to handle the entire structure or just the value. Execution gives you the expected result.

$ python x.py
7
[3, 4]
7

SQLite table constraint - unique on multiple columns

Well, your syntax doesn't match the link you included, which specifies:

 CREATE TABLE name (column defs) 
    CONSTRAINT constraint_name    -- This is new
    UNIQUE (col_name1, col_name2) ON CONFLICT REPLACE

How to send a POST request from node.js Express?

in your server side the code looks like:

var request = require('request');

app.post('/add', function(req, res){
  console.log(req.body);
  request.post(
    {
    url:'http://localhost:6001/add',
    json: {
      unit_name:req.body.unit_name,
      unit_price:req.body.unit_price
        },
    headers: {
        'Content-Type': 'application/json'
    }
    },
  function(error, response, body){
    // console.log(error);
    // console.log(response);
    console.log(body);
    res.send(body);
  });
  // res.send("body");
});

in receiving end server code looks like:

app.post('/add', function(req, res){
console.log('received request')
console.log(req.body);
let adunit = new AdUnit(req.body);
adunit.save()
.then(game => {
res.status(200).json({'adUnit':'AdUnit is added successfully'})
})
.catch(err => {
res.status(400).send('unable to save to database');
})
});

Schema is just two properties unit_name and unit_price.

Switch case: can I use a range instead of a one number

To complete the thread, here is the syntax with C# 8 :

  var percent = price switch
  {
    var n when n >= 1000000 => 7f,
    var n when n >= 900000 => 7.1f,
    var n when n >= 800000 => 7.2f,
    _ => 0f // default value
  };

If you want to specify the ranges :

  var percent2 = price switch
  {
    var n when n >= 1000000 => 7f,
    var n when n < 1000000 && n >= 900000 => 7.1f,
    var n when n < 900000 && n >= 800000 => 7.2f,
    _ => 0f // default value
  };

Getting the 'external' IP address in Java

All this are still up and working smoothly! (as of 23 Sep 2019)

Piece of advice: Do not direcly depend only on one of them; try to use one but have a contigency plan considering others! The more you use, the better!

Good luck!

Git undo changes in some files

Source : http://git-scm.com/book/en/Git-Basics-Undoing-Things

git checkout -- modifiedfile.java


1)$ git status

you will see the modified file

2)$git checkout -- modifiedfile.java

3)$git status

Setting values on a copy of a slice from a DataFrame

This warning comes because your dataframe x is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.

You can either create a proper dataframe out of x by doing

x = x.copy()

This will remove the warning, but it is not the proper way

You should be using the DataFrame.loc method, as the warning suggests, like this:

x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)

How do I use the conditional operator (? :) in Ruby?

A simple example where the operator checks if player's id is 1 and sets enemy id depending on the result

player_id=1
....
player_id==1? enemy_id=2 : enemy_id=1
# => enemy=2

And I found a post about to the topic which seems pretty helpful.

What is the best way to search the Long datatype within an Oracle database?

First convert LONG type column to CLOB type then use LIKE condition, for example:

CREATE TABLE tbl_clob AS
   SELECT to_lob(long_col) lob_col FROM tbl_long;

SELECT * FROM tbl_clob WHERE lob_col LIKE '%form%';

Google Play error "Error while retrieving information from server [DF-DFERH-01]"

I had the same issue. Solved it simply; I have (2) google accounts linked to my Play Store. It just so happens that I installed "an" app from "account B", and I was trying to rate it from "account A". So, switched accounts, and voilá.

Row names & column names in R

And another expansion:

# create dummy matrix
set.seed(10)
m <- matrix(round(runif(25, 1, 5)), 5)
d <- as.data.frame(m)

If you want to assign new column names you can do following on data.frame:

# an identical effect can be achieved with colnames()   
names(d) <- LETTERS[1:5]
> d
  A B C D E
1 3 2 4 3 4
2 2 2 3 1 3
3 3 2 1 2 4
4 4 3 3 3 2
5 1 3 2 4 3

If you, however run previous command on matrix, you'll mess things up:

names(m) <- LETTERS[1:5]
> m
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    2    4    3    4
[2,]    2    2    3    1    3
[3,]    3    2    1    2    4
[4,]    4    3    3    3    2
[5,]    1    3    2    4    3
attr(,"names")
 [1] "A" "B" "C" "D" "E" NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA 
[20] NA  NA  NA  NA  NA  NA 

Since matrix can be regarded as two-dimensional vector, you'll assign names only to first five values (you don't want to do that, do you?). In this case, you should stick with colnames().

So there...

How to solve javax.net.ssl.SSLHandshakeException Error?

Now I solved this issue in this way,

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.OutputStream; 

// Create a trust manager that does not validate certificate chains like the default 

TrustManager[] trustAllCerts = new TrustManager[]{
        new X509TrustManager() {

            public java.security.cert.X509Certificate[] getAcceptedIssuers()
            {
                return null;
            }
            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
            {
                //No need to implement.
            }
            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
            {
                //No need to implement.
            }
        }
};

// Install the all-trusting trust manager
try 
{
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} 
catch (Exception e) 
{
    System.out.println(e);
}

Of course this solution should only be used in scenarios, where it is not possible to install the required certifcates using keytool e.g. local testing with temporary certifcates.

How to load my app from Eclipse to my Android phone instead of AVD

The USB drivers in \extras\google\usb_driver didn't work for me.

However the official drivers from Samsung did: http://developer.samsung.com/android/tools-sdks/Samsung-Andorid-USB-Driver-for-Windows

Note: I'm using a Samsung Galaxy S2 with Android 4.0 on Windows 7 64bit

Converting rows into columns and columns into rows using R

Here is a tidyverse option that might work depending on the data, and some caveats on its usage:

library(tidyverse)

starting_df %>% 
  rownames_to_column() %>% 
  gather(variable, value, -rowname) %>% 
  spread(rowname, value)

rownames_to_column() is necessary if the original dataframe has meaningful row names, otherwise the new column names in the new transposed dataframe will be integers corresponding to the orignal row number. If there are no meaningful row names you can skip rownames_to_column() and replace rowname with the name of the first column in the dataframe, assuming those values are unique and meaningful. Using the tidyr::smiths sample data would be:

smiths %>% 
    gather(variable, value, -subject) %>% 
    spread(subject, value)

Using the example starting_df with the tidyverse approach will throw a warning message about dropping attributes. This is related to converting columns with different attribute types into a single character column. The smiths data will not give that warning because all columns except for subject are doubles.

The earlier answer using as.data.frame(t()) will convert everything to a factor if there are mixed column types unless stringsAsFactors = FALSE is added, whereas the tidyverse option converts everything to a character by default if there are mixed column types.

Create a hexadecimal colour based on a string with JavaScript

I find that generating random colors tends to create colors that do not have enough contrast for my taste. The easiest way I have found to get around that is to pre-populate a list of very different colors. For every new string, assign the next color in the list:

// Takes any string and converts it into a #RRGGBB color.
var StringToColor = (function(){
    var instance = null;

    return {
    next: function stringToColor(str) {
        if(instance === null) {
            instance = {};
            instance.stringToColorHash = {};
            instance.nextVeryDifferntColorIdx = 0;
            instance.veryDifferentColors = ["#000000","#00FF00","#0000FF","#FF0000","#01FFFE","#FFA6FE","#FFDB66","#006401","#010067","#95003A","#007DB5","#FF00F6","#FFEEE8","#774D00","#90FB92","#0076FF","#D5FF00","#FF937E","#6A826C","#FF029D","#FE8900","#7A4782","#7E2DD2","#85A900","#FF0056","#A42400","#00AE7E","#683D3B","#BDC6FF","#263400","#BDD393","#00B917","#9E008E","#001544","#C28C9F","#FF74A3","#01D0FF","#004754","#E56FFE","#788231","#0E4CA1","#91D0CB","#BE9970","#968AE8","#BB8800","#43002C","#DEFF74","#00FFC6","#FFE502","#620E00","#008F9C","#98FF52","#7544B1","#B500FF","#00FF78","#FF6E41","#005F39","#6B6882","#5FAD4E","#A75740","#A5FFD2","#FFB167","#009BFF","#E85EBE"];
        }

        if(!instance.stringToColorHash[str])
            instance.stringToColorHash[str] = instance.veryDifferentColors[instance.nextVeryDifferntColorIdx++];

            return instance.stringToColorHash[str];
        }
    }
})();

// Get a new color for each string
StringToColor.next("get first color");
StringToColor.next("get second color");

// Will return the same color as the first time
StringToColor.next("get first color");

While this has a limit to only 64 colors, I find most humans can't really tell the difference after that anyway. I suppose you could always add more colors.

While this code uses hard-coded colors, you are at least guaranteed to know during development exactly how much contrast you will see between colors in production.

Color list has been lifted from this SO answer, there are other lists with more colors.

Interface type check with Typescript

Based on Fenton's answer, here's my implementation of a function to verify if a given object has the keys an interface has, both fully or partially.

Depending on your use case, you may also need to check the types of each of the interface's properties. The code below doesn't do that.

function implementsTKeys<T>(obj: any, keys: (keyof T)[]): obj is T {
    if (!obj || !Array.isArray(keys)) {
        return false;
    }

    const implementKeys = keys.reduce((impl, key) => impl && key in obj, true);

    return implementKeys;
}

Example of usage:

interface A {
    propOfA: string;
    methodOfA: Function;
}

let objectA: any = { propOfA: '' };

// Check if objectA partially implements A
let implementsA = implementsTKeys<A>(objectA, ['propOfA']);

console.log(implementsA); // true

objectA.methodOfA = () => true;

// Check if objectA fully implements A
implementsA = implementsTKeys<A>(objectA, ['propOfA', 'methodOfA']);

console.log(implementsA); // true

objectA = {};

// Check again if objectA fully implements A
implementsA = implementsTKeys<A>(objectA, ['propOfA', 'methodOfA']);

console.log(implementsA); // false, as objectA now is an empty object

Lua string to int

tonumber (e [, base])

tonumber takes two arguments, first is string which is converted to number and second is base of e.

Return value tonumber is in base 10.

If no base is provided it converts number to base 10.

> a = '101'
> tonumber(a)
101

If base is provided, it converts it to the given base.

> a = '101'
> 
> tonumber(a, 2)
5
> tonumber(a, 8)
65
> tonumber(a, 10)
101
> tonumber(a, 16)
257
> 

If e contains invalid character then it returns nil.

> --[[ Failed because base 2 numbers consist (0 and 1) --]]
> a = '112'
> tonumber(a, 2)
nil
> 
> --[[ similar to above one, this failed because --]]
> --[[ base 8 consist (0 - 7) --]]
> --[[ base 10 consist (0 - 9) --]]
> a = 'AB'
> tonumber(a, 8)
nil
> tonumber(a, 10)
nil
> tonumber(a, 16)
171

I answered considering Lua5.3

Why is the time complexity of both DFS and BFS O( V + E )

I think every edge has been considered twice and every node has been visited once, so the total time complexity should be O(2E+V).

SQL-Server: Error - Exclusive access could not be obtained because the database is in use

Setting the DB to single-user mode didn't work for me, but taking it offline, and then bringing it back online did work. It's in the right-click menu of the DB, under Tasks.

Be sure to check the 'Drop All Active Connections' option in the dialog.

Version of Apache installed on a Debian machine

Try apachectl -V:

$ apachectl -V
Server version: Apache/2.2.9 (Unix)
Server built:   Sep 18 2008 21:54:05
Server's Module Magic Number: 20051115:15
Server loaded:  APR 1.2.7, APR-Util 1.2.7
Compiled using: APR 1.2.7, APR-Util 1.2.7
... etc ...

If it does not work for you, run the command with sudo.

How to write file in UTF-8 format?

This works for me. :)

$f=fopen($filename,"w"); 
# Now UTF-8 - Add byte order mark 
fwrite($f, pack("CCC",0xef,0xbb,0xbf)); 
fwrite($f,$content); 
fclose($f); 

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

For similar assembly binding errors , following steps may help:

  1. Right click on your Solution and click Manage Nuget Packages for Solution ...
  2. go to Consolidate Tab (last tab) and check if any any differences between packages installed in different projects inside your solution. specially pay attention to your referenced projects which may have lower versions because they usually are less noticed)
  3. consolidate specially packages related to your assembly error and note that many packages are dependent on some other packages like *.code & *.api & ...
  4. after resolving all suspected consolidations , rebuild and rerun the app and see if the assembly bindings are resolved.

array of string with unknown size

If you will later know the length of the array you can create the initial array like this:

String[] array;

And later when you know the length you can finish initializing it like this

array = new String[42];

MVC 4 Razor adding input type date

You will get it by tag type="date"...then it will render beautiful calendar and all...

@Html.TextBoxFor(model => model.EndTime, new { type = "date" })

Cannot read property 'length' of null (javascript)

if (capital.touched && capital != undefined && capital.length < 1 ) { 
//capital does exists
}

Adding a right click menu to an item

Having just messed around with this, it's useful to kjnow that the e.X / e.Y points are relative to the control, so if (as I was) you are adding a context menu to a listview or something similar, you will want to adjust it with the form's origin. In the example below I've added 20 to the x/y so that the menu appears slightly to the right and under the cursor.

cmDelete.Show(this, new Point(e.X + ((Control)sender).Left+20, e.Y + ((Control)sender).Top+20));

Open Source HTML to PDF Renderer with Full CSS Support

I've always used it on the command line and not as a library, but HTMLDOC gives me excellent results, and it handles at least some CSS (I couldn't easily see how much).

Here's a sample command line

htmldoc --webpage -t pdf --size letter --fontsize 10pt index.html > index.pdf

IF function with 3 conditions

You can simplify the 5 through 21 part:

=IF(E9>21,"Text1",IF(E9>4,"Text2","Text3"))

Find package name for Android apps to use Intent to launch Market app from web

Here are easy way to get app's full package. we can use astro file manager app. You can get it on android market. Astro app manager show us app's full package.

What is the difference between tree depth and height?

I learned that depth and height are properties of a node:

  • The depth of a node is the number of edges from the node to the tree's root node.
    A root node will have a depth of 0.

  • The height of a node is the number of edges on the longest path from the node to a leaf.
    A leaf node will have a height of 0.

Properties of a tree:

  • The height of a tree would be the height of its root node,
    or equivalently, the depth of its deepest node.

  • The diameter (or width) of a tree is the number of nodes on the longest path between any two leaf nodes. The tree below has a diameter of 6 nodes.

A tree, with height and depth of each node

Show current assembly instruction in GDB

You can do

display/i $pc

and every time GDB stops, it will display the disassembly of the next instruction.

GDB-7.0 also supports set disassemble-next-line on, which will disassemble the entire next line, and give you more of the disassembly context.

AngularJS: How to run additional code after AngularJS has rendered a template?

Neither $scope.$evalAsync() or $timeout(fn, 0) worked reliably for me.

I had to combine the two. I made a directive and also put a priority higher than the default value for good measure. Here's a directive for it (Note I use ngInject to inject dependencies):

app.directive('postrenderAction', postrenderAction);

/* @ngInject */
function postrenderAction($timeout) {
    // ### Directive Interface
    // Defines base properties for the directive.
    var directive = {
        restrict: 'A',
        priority: 101,
        link: link
    };
    return directive;

    // ### Link Function
    // Provides functionality for the directive during the DOM building/data binding stage.
    function link(scope, element, attrs) {
        $timeout(function() {
            scope.$evalAsync(attrs.postrenderAction);
        }, 0);
    }
}

To call the directive, you would do this:

<div postrender-action="functionToRun()"></div>

If you want to call it after an ng-repeat is done running, I added an empty span in my ng-repeat and ng-if="$last":

<li ng-repeat="item in list">
    <!-- Do stuff with list -->
    ...

    <!-- Fire function after the last element is rendered -->
    <span ng-if="$last" postrender-action="$ctrl.postRender()"></span>
</li>

How to check if an element exists in the xml using xpath?

take look at my example

<tocheading language="EN"> 
     <subj-group> 
         <subject>Editors Choice</subject> 
         <subject>creative common</subject> 
     </subj-group> 
</tocheading> 

now how to check if creative common is exist

tocheading/subj-group/subject/text() = 'creative common'

hope this help you

MongoDB: How to update multiple documents with a single command?

The following command can update multiple records of a collection

db.collection.update({}, 
{$set:{"field" : "value"}}, 
{ multi: true, upsert: false}
)

Sending a mail from a linux shell script

Another option for in a bash script:

mailbody="Testmail via bash script"
echo "From: [email protected]" > /tmp/mailtest
echo "To: [email protected]" >> /tmp/mailtest
echo "Subject: Mailtest subject" >> /tmp/mailtest
echo "" >> /tmp/mailtest
echo $mailbody >> /tmp/mailtest
cat /tmp/mailtest | /usr/sbin/sendmail -t
  • The file /tmp/mailtest is overwritten everytime this script is used.
  • The location of sendmail may differ per system.
  • When using this in a cron script, you have to use the absolute path for the sendmail command.

How to run binary file in Linux

full path for binary file. For example: /home/vitaliy2034/binary_file_name. Or use directive "./+binary_file_name". './' in unix system it return full path to directory, in which you open terminal(shell). I hope it helps. Sorry, for my english language)

Loading all images using imread from a given folder

To add onto the answer from Rishabh and make it able to handle files that are not images that are found in the folder.

import matplotlib.image as mpimg

images = []
folder = './your/folder/'
for filename in os.listdir(folder):
    try:
        img = mpimg.imread(os.path.join(folder, filename))
        if img is not None:
            images.append(img)
    except:
        print('Cant import ' + filename)
images = np.asarray(images)

Using DataContractSerializer to serialize, but can't deserialize back

This best for XML Deserialize

 public static object Deserialize(string xml, Type toType)
    {

        using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
        {
            System.IO.StreamReader str = new System.IO.StreamReader(memoryStream);
            System.Xml.Serialization.XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(toType);
            return xSerializer.Deserialize(str);
        }

    }

Getting the name of the currently executing method

Thread.currentThread().getStackTrace() will usually contain the method you’re calling it from but there are pitfalls (see Javadoc):

Some virtual machines may, under some circumstances, omit one or more stack frames from the stack trace. In the extreme case, a virtual machine that has no stack trace information concerning this thread is permitted to return a zero-length array from this method.

Launching Spring application Address already in use

I was getting same issue, i.e. protocol handler start failed. Cause was port is already in use. I found whether the port was in use or not. It was. So I killed the process that was running on that port and restarted my spring boot application. And it worked. :)

How can I know when an EditText loses focus?

Kotlin way

editText.setOnFocusChangeListener { _, hasFocus ->
    if (!hasFocus) {  }
}

Min / Max Validator in Angular 2 Final

In my template driven form (Angular 6) I have the following workaround:

 <div class='col-sm-2 form-group'>
            <label for='amount'>Amount</label>
            <input type='number' 
                   id='amount' 
                   name='amount' 
                   required 
                   [ngModel] = 1
                   [pattern] = "'^[1-9][0-9]*$'"
                   class='form-control' 
                   #amountInput='ngModel'/>
            <span class='text-danger' *ngIf="amountInput.touched && amountInput.invalid">
              <p *ngIf="amountInput.errors?.required">This field is <b>required</b>!</p>
              <p *ngIf="amountInput.errors?.pattern">This minimum amount is <b>1</b>!</p>
            </span>
        </div>

Alot of the above examples make use of directives and custom classes which do scale better in more complex forms, but if your looking for a simple numeric min, utilize pattern as a directive and impose a regex restriction on positive numbers only.

Split string into tokens and save them in an array

#include <stdio.h>
#include <string.h>

int main ()
{
    char buf[] ="abc/qwe/ccd";
    int i = 0;
    char *p = strtok (buf, "/");
    char *array[3];

    while (p != NULL)
    {
        array[i++] = p;
        p = strtok (NULL, "/");
    }

    for (i = 0; i < 3; ++i) 
        printf("%s\n", array[i]);

    return 0;
}

R apply function with multiple parameters

If your function have two vector variables and must compute itself on each value of them (as mentioned by @Ari B. Friedman) you can use mapply as follows:

vars1<-c(1,2,3)
vars2<-c(10,20,30)
mult_one<-function(var1,var2)
{
   var1*var2
}
mapply(mult_one,vars1,vars2)

which gives you:

> mapply(mult_one,vars1,vars2)
[1] 10 40 90

How do you test to see if a double is equal to NaN?

You might want to consider also checking if a value is finite via Double.isFinite(value). Since Java 8 there is a new method in Double class where you can check at once if a value is not NaN and infinity.

/**
 * Returns {@code true} if the argument is a finite floating-point
 * value; returns {@code false} otherwise (for NaN and infinity
 * arguments).
 *
 * @param d the {@code double} value to be tested
 * @return {@code true} if the argument is a finite
 * floating-point value, {@code false} otherwise.
 * @since 1.8
 */
public static boolean isFinite(double d)

How to utilize date add function in Google spreadsheet?

what's wrong with simple add and convert back?

if A1 is a date field, and A2 hold the number of days to add: =TO_DATE((DATEVALUE(A1)+A2)

Get the date (a day before current time) in Bash

yesterday=`date -d "-1 day" %F`

Puts yesterday's date in YYYY-MM-DD format into variable $yesterday.

How to trigger Jenkins builds remotely and to pass parameters

See Jenkins documentation: Parameterized Build

Below is the line you are interested in:

http://server/job/myjob/buildWithParameters?token=TOKEN&PARAMETER=Value

Intercept a form submit in JavaScript and prevent normal submission

You cannot attach events before the elements you attach them to has loaded

This works -

Plain JS

DEMO

Recommended to use eventListener

_x000D_
_x000D_
// Should only be triggered on first page load
console.log('ho');

window.addEventListener("load", function() {
  document.getElementById('my-form').addEventListener("submit", function(e) {
    e.preventDefault(); // before the code
    /* do what you want with the form */

    // Should be triggered on form submit
    console.log('hi');
  })
});
_x000D_
<form id="my-form">
  <input type="text" name="in" value="some data" />
  <button type="submit">Go</button>
</form>
_x000D_
_x000D_
_x000D_

but if you do not need more than one listener you can use onload and onsubmit

_x000D_
_x000D_
// Should only be triggered on first page load
console.log('ho');

window.onload = function() {
  document.getElementById('my-form').onsubmit = function() {
    /* do what you want with the form */

    // Should be triggered on form submit
    console.log('hi');
    // You must return false to prevent the default form behavior
    return false;
  }
}
_x000D_
    <form id="my-form">
      <input type="text" name="in" value="some data" />
      <button type="submit">Go</button>
    </form>
_x000D_
_x000D_
_x000D_

jQuery

_x000D_
_x000D_
// Should only be triggered on first page load
console.log('ho');

$(function() {
  $('#my-form').on("submit", function(e) {
    e.preventDefault(); // cancel the actual submit

    /* do what you want with the form */

    // Should be triggered on form submit

    console.log('hi');
  });
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="my-form">
  <input type="text" name="in" value="some data" />
  <button type="submit">Go</button>
</form>
_x000D_
_x000D_
_x000D_

Practical uses for the "internal" keyword in C#

the only thing i have ever used the internal keyword on is the license-checking code in my product ;-)

How to download file in swift?

Here is the Swift 4 version:

static func loadFileAsync(url: URL, completion: @escaping (String?, Error?) -> Void)
{
    let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

    let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)

    if FileManager().fileExists(atPath: destinationUrl.path)
    {
        completion(destinationUrl.path, nil)
    }
    else
    {
        let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        let task = session.dataTask(with: request, completionHandler:
        {
            data, response, error in
            if error == nil
            {
                if let response = response as? HTTPURLResponse
                {
                    if response.statusCode == 200
                    {
                        if let data = data
                        {
                            if let _ = try? data.write(to: destinationUrl, options: Data.WritingOptions.atomic)
                            {
                                completion(destinationUrl.path, error)
                            }
                            else
                            {
                                completion(destinationUrl.path, error)
                            }
                        }
                        else
                        {
                            completion(destinationUrl.path, error)
                        }
                    }
                }
            }
            else
            {
                completion(destinationUrl.path, error)
            }
        })
        task.resume()
    }
}

In Bootstrap open Enlarge image in modal

So I have put together a very rough modal in jsfiddle for you to take hints from.

JSFiddle

$("#pop").on("click", function(e) {
  // e.preventDefault() this is stopping the redirect to the image its self
  e.preventDefault();
  // #the-modal is the img tag that I use as the modal.
  $('#the-modal').modal('toggle');
});

The part that you are missing is the hidden modal that you want to display when the link is clicked. In the example I used a second image as the modal and added the Bootstap classes.

How to find topmost view controller on iOS

Great solution in Swift, implement in AppDelegate

func getTopViewController()->UIViewController{
    return topViewControllerWithRootViewController(UIApplication.sharedApplication().keyWindow!.rootViewController!)
}
func topViewControllerWithRootViewController(rootViewController:UIViewController)->UIViewController{
    if rootViewController is UITabBarController{
        let tabBarController = rootViewController as! UITabBarController
        return topViewControllerWithRootViewController(tabBarController.selectedViewController!)
    }
    if rootViewController is UINavigationController{
        let navBarController = rootViewController as! UINavigationController
        return topViewControllerWithRootViewController(navBarController.visibleViewController)
    }
    if let presentedViewController = rootViewController.presentedViewController {
        return topViewControllerWithRootViewController(presentedViewController)
    }
    return rootViewController
}

angular 2 how to return data from subscribe

Two ways I know of:

export class SomeComponent implements OnInit
{
    public localVar:any;

    ngOnInit(){
        this.http.get(Path).map(res => res.json()).subscribe(res => this.localVar = res);
    }
}

This will assign your result into local variable once information is returned just like in a promise. Then you just do {{ localVar }}

Another Way is to get a observable as a localVariable.

export class SomeComponent
{
    public localVar:any;

    constructor()
    {
        this.localVar = this.http.get(path).map(res => res.json());
    }
}

This way you're exposing a observable at which point you can do in your html is to use AsyncPipe {{ localVar | async }}

Please try it out and let me know if it works. Also, since angular 2 is pretty new, feel free to comment if something is wrong.

Hope it helps

C# Macro definitions in Preprocessor

Luckily, C# has no C/C++-style preprocessor - only conditional compilation and pragmas (and possibly something else I cannot recall) are supported. Unfortunatelly, C# has no metaprogramming capabilities (this may actually relate to your question to some extent).

Print commit message of a given commit in git

I started to use

git show-branch --no-name <hash>

It seems to be faster than

git show -s --format=%s <hash>

Both give the same result

I actually wrote a small tool to see the status of all my repos. You can find it on github.

enter image description here

Model Binding to a List MVC 4

This is how I do it if I need a form displayed for each item, and inputs for various properties. Really depends on what I'm trying to do though.

ViewModel looks like this:

public class MyViewModel
{
   public List<Person> Persons{get;set;}
}

View(with BeginForm of course):

@model MyViewModel


@for( int i = 0; i < Model.Persons.Count(); ++i)
{
    @Html.HiddenFor(m => m.Persons[i].PersonId)
    @Html.EditorFor(m => m.Persons[i].FirstName) 
    @Html.EditorFor(m => m.Persons[i].LastName)         
}

Action:

[HttpPost]public ViewResult(MyViewModel vm)
{
...

Note that on post back only properties which had inputs available will have values. I.e., if Person had a .SSN property, it would not be available in the post action because it wasn't a field in the form.

Note that the way MVC's model binding works, it will only look for consecutive ID's. So doing something like this where you conditionally hide an item will cause it to not bind any data after the 5th item, because once it encounters a gap in the IDs, it will stop binding. Even if there were 10 people, you would only get the first 4 on the postback:

@for( int i = 0; i < Model.Persons.Count(); ++i)
{
    if(i != 4)//conditionally hide 5th item, 
    { //but BUG occurs on postback, all items after 5th will not be bound to the the list
      @Html.HiddenFor(m => m.Persons[i].PersonId)
      @Html.EditorFor(m => m.Persons[i].FirstName) 
      @Html.EditorFor(m => m.Persons[i].LastName)           
    }
}

Write a file in UTF-8 using FileWriter (Java)?

Since Java 7 there is an easy way to handle character encoding of BufferedWriter and BufferedReaders. You can create a BufferedWriter directly by using the Files class instead of creating various instances of Writer. You can simply create a BufferedWriter, which considers character encoding, by calling:

Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8);

You can find more about it in JavaDoc:

Docker-compose: node_modules not present in a volume after npm install succeeds

If you want the node_modules folder available to the host during development, you could install the dependencies when you start the container instead of during build-time. I do this to get syntax highlighting working in my editor.

Dockerfile

# We're using a multi-stage build so that we can install dependencies during build-time only for production.

# dev-stage
FROM node:14-alpine AS dev-stage
WORKDIR /usr/src/app
COPY package.json ./
COPY . .
# `yarn install` will run every time we start the container. We're using yarn because it's much faster than npm when there's nothing new to install
CMD ["sh", "-c", "yarn install && yarn run start"]

# production-stage
FROM node:14-alpine AS production-stage
WORKDIR /usr/src/app
COPY package.json ./
RUN yarn install
COPY . .

.dockerignore

Add node_modules to .dockerignore to prevent it from being copied when the Dockerfile runs COPY . .. We use volumes to bring in node_modules.

**/node_modules

docker-compose.yml

node_app:
    container_name: node_app
    build:
        context: ./node_app
        target: dev-stage # `production-stage` for production
    volumes:
        # For development:
        #   If node_modules already exists on the host, they will be copied
        #   into the container here. Since `yarn install` runs after the
        #   container starts, this volume won't override the node_modules.
        - ./node_app:/usr/src/app
        # For production:
        #   
        - ./node_app:/usr/src/app
        - /usr/src/app/node_modules

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

  1. You could use CLR based UDFs or do a CONTAINS query using all the digits on the search column.

Calculating bits required to store decimal number

Keep dividing the number by 2 until you get a quotient of 0.

How to get a file or blob from an object URL?

Maybe someone finds this useful when working with React/Node/Axios. I used this for my Cloudinary image upload feature with react-dropzone on the UI.

    axios({
        method: 'get',
        url: file[0].preview, // blob url eg. blob:http://127.0.0.1:8000/e89c5d87-a634-4540-974c-30dc476825cc
        responseType: 'blob'
    }).then(function(response){
         var reader = new FileReader();
         reader.readAsDataURL(response.data); 
         reader.onloadend = function() {
             var base64data = reader.result;
             self.props.onMainImageDrop(base64data)
         }

    })

git ahead/behind info between master and branch?

You can also use awk to make it a little bit prettier:

git rev-list --left-right --count  origin/develop...feature-branch | awk '{print "Behind "$1" - Ahead "$2""}'

You can even make an alias that always fetches origin first and then compares the branches

commit-diff = !"git fetch &> /dev/null && git rev-list --left-right --count"

django no such table:

sqlall just prints the SQL, it doesn't execute it. syncdb will create tables that aren't already created, but it won't modify existing tables.

NTFS performance and large volumes of files and directories

I had real experience with about 100 000 files (each several MBs) on NTFS in a directory while copying one online library.

It takes about 15 minutes to open the directory with Explorer or 7-zip.

Writing site copy with winhttrack will always get stuck after some time. It dealt also with directory, containing about 1 000 000 files. I think the worst thing is that the MFT can only by traversed sequentially.

Opening the same under ext2fsd on ext3 gave almost the same timing. Probably moving to reiserfs (not reiser4fs) can help.

Trying to avoid this situation is probably the best.

For your own programs using blobs w/o any fs could be beneficial. That's the way Facebook does for storing photos.

android set button background programmatically

The answer you're looking for in 2020 and beyond:

  • setColorFilter(color, mode) is deprecated since API 29 (as discussed here)
  • button.setBackgroundColor(color) messes with the button style

Now the proper way to set a buttons color is using BlendModeColorFilter() (see documentation).

Usage:

btn.background.colorFilter = BlendModeColorFilter(color, BlendMode.MULTIPLY)

If you work with older APIs too:

fun setButtonColor(btn: Button, color: Int) {
    if (Build.VERSION.SDK_INT >= 29)
        btn.background.colorFilter = BlendModeColorFilter(color, BlendMode.MULTIPLY)
    else
        btn.background.setColorFilter(color, PorterDuff.Mode.MULTIPLY)
}

Please vote to help others finding this answer - it took me quite a while figuring this out ^^

Android Studio - Failed to apply plugin [id 'com.android.application']

delete C:\Users\username\.gradle\caches folder.

Passing bash variable to jq

Consider also passing in the shell variable (EMAILID) as a jq variable (here also EMAILID, for the sake of illustration):

   projectID=$(jq -r --arg EMAILID "$EMAILID" '
        .resource[]
        | select(.username==$EMAILID) 
        | .id' file.json)

Postscript

For the record, another possibility would be to use jq's env function for accessing environment variables. For example, consider this sequence of bash commands:

[email protected]  # not exported
EMAILID="$EMAILID" jq -n 'env.EMAILID'

The output is a JSON string:

"[email protected]"

Parsing a pcap file in python

You might want to start with scapy.

What is the difference between DSA and RSA?

Referring, https://web.archive.org/web/20140212143556/http://courses.cs.tamu.edu:80/pooch/665_spring2008/Australian-sec-2006/less19.html

RSA
RSA encryption and decryption are commutative
hence it may be used directly as a digital signature scheme
given an RSA scheme {(e,R), (d,p,q)}
to sign a message M, compute:
S = M power d (mod R)
to verify a signature, compute:
M = S power e(mod R) = M power e.d(mod R) = M(mod R)

RSA can be used both for encryption and digital signatures, simply by reversing the order in which the exponents are used: the secret exponent (d) to create the signature, the public exponent (e) for anyone to verify the signature. Everything else is identical.

DSA (Digital Signature Algorithm)
DSA is a variant on the ElGamal and Schnorr algorithms. It creates a 320 bit signature, but with 512-1024 bit security again rests on difficulty of computing discrete logarithms has been quite widely accepted.

DSA Key Generation
firstly shared global public key values (p,q,g) are chosen:
choose a large prime p = 2 power L
where L= 512 to 1024 bits and is a multiple of 64
choose q, a 160 bit prime factor of p-1
choose g = h power (p-1)/q
for any h<p-1, h(p-1)/q(mod p)>1
then each user chooses a private key and computes their public key:
choose x<q
compute y = g power x(mod p)

DSA key generation is related to, but somewhat more complex than El Gamal. Mostly because of the use of the secondary 160-bit modulus q used to help speed up calculations and reduce the size of the resulting signature.

DSA Signature Creation and Verification

to sign a message M
generate random signature key k, k<q
compute
r = (g power k(mod p))(mod q)
s = k-1.SHA(M)+ x.r (mod q)
send signature (r,s) with message

to verify a signature, compute:
w = s-1(mod q)
u1= (SHA(M).w)(mod q)
u2= r.w(mod q)
v = (g power u1.y power u2(mod p))(mod q)
if v=r then the signature is verified

Signature creation is again similar to ElGamal with the use of a per message temporary signature key k, but doing calc first mod p, then mod q to reduce the size of the result. Note that the use of the hash function SHA is explicit here. Verification also consists of comparing two computations, again being a bit more complex than, but related to El Gamal.
Note that nearly all the calculations are mod q, and hence are much faster.
But, In contrast to RSA, DSA can be used only for digital signatures

DSA Security
The presence of a subliminal channel exists in many schemes (any that need a random number to be chosen), not just DSA. It emphasises the need for "system security", not just a good algorithm.

Genymotion Android emulator - adb access?

Connect didn't work for me, The problem was that Genymotion uses its own dk-tools and you need to change it to custom SDK tools.

More info: https://stackoverflow.com/a/26630862/4154438

Add items to comboBox in WPF

Its better to build ObservableCollection and take advantage of it

public ObservableCollection<string> list = new ObservableCollection<string>();
list.Add("a");
list.Add("b");
list.Add("c");
this.cbx.ItemsSource = list;

cbx is comobobox name

Also Read : Difference between List, ObservableCollection and INotifyPropertyChanged

How can I get the current screen orientation?

In some devices void onConfigurationChanged() may crash. User will use this code to get current screen orientation.

public int getScreenOrientation()
{
    Display getOrient = getActivity().getWindowManager().getDefaultDisplay();
    int orientation = Configuration.ORIENTATION_UNDEFINED;
    if(getOrient.getWidth()==getOrient.getHeight()){
        orientation = Configuration.ORIENTATION_SQUARE;
    } else{ 
        if(getOrient.getWidth() < getOrient.getHeight()){
            orientation = Configuration.ORIENTATION_PORTRAIT;
        }else { 
             orientation = Configuration.ORIENTATION_LANDSCAPE;
        }
    }
    return orientation;
}

And use

if (orientation==1)        // 1 for Configuration.ORIENTATION_PORTRAIT
{                          // 2 for Configuration.ORIENTATION_LANDSCAPE
   //your code             // 0 for Configuration.ORIENTATION_SQUARE
}

Enter key press in C#

Try this:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
        switch (e.Key.ToString())
        {
                case "Return":
                        MessageBox.Show(" Enter pressed ");
                        break;
         }
}

How to get date and time from server

You should set the timezone to the one of the timezones you want. let set the Indian timezone

// set default timezone
date_default_timezone_set('Asia/Kolkata');

$info = getdate();
$date = $info['mday'];
$month = $info['mon'];
$year = $info['year'];
$hour = $info['hours'];
$min = $info['minutes'];
$sec = $info['seconds'];

$current_date = "$date/$month/$year == $hour:$min:$sec";

What are ABAP and SAP?

SAP is really a big Company that offers incredible solutions oriented to medium-large companies.

Actually, I can say that the main IT products are: ERP, WEB, Human Resources, Integration, BI, Reports, Machine Learning, Mobile, Cloud, Robotics, and so on.

On the cloud, you can even find solutions using Cloud Foundry, NodeJS, HTML5, Java, etc.

It's really huge the solutions that offers to their customers.

Split string with delimiters in C

Here is my two cents:

int split (const char *txt, char delim, char ***tokens)
{
    int *tklen, *t, count = 1;
    char **arr, *p = (char *) txt;

    while (*p != '\0') if (*p++ == delim) count += 1;
    t = tklen = calloc (count, sizeof (int));
    for (p = (char *) txt; *p != '\0'; p++) *p == delim ? *t++ : (*t)++;
    *tokens = arr = malloc (count * sizeof (char *));
    t = tklen;
    p = *arr++ = calloc (*(t++) + 1, sizeof (char *));
    while (*txt != '\0')
    {
        if (*txt == delim)
        {
            p = *arr++ = calloc (*(t++) + 1, sizeof (char *));
            txt++;
        }
        else *p++ = *txt++;
    }
    free (tklen);
    return count;
}

Usage:

char **tokens;
int count, i;
const char *str = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";

count = split (str, ',', &tokens);
for (i = 0; i < count; i++) printf ("%s\n", tokens[i]);

/* freeing tokens */
for (i = 0; i < count; i++) free (tokens[i]);
free (tokens);

Logical XOR operator in C++?

Use a simple:

return ((op1 ? 1 : 0) ^ (op2 ? 1 : 0));

What's the difference between compiled and interpreted language?

Interpreted language is executed at the run time according to the instructions like in shell scripting and compiled language is one which is compiled (changed into Assembly language, which CPU can understand ) and then executed like in c++.

Duplicate line in Visual Studio Code

Another 2 very usefull shortcuts are to move lines selected up and down, like sublime text does...

{
  "key" : "ctrl+shift+down", "command" : "editor.action.moveLinesDownAction",
  "when" : "editorTextFocus && !editorReadonly"
},

and

{
  "key" : "ctrl+shift+up", "command" : "editor.action.moveLinesUpAction",
  "when" : "editorTextFocus && !editorReadonly"
}

What are the differences between the different saving methods in Hibernate?

+-------------------------------------------------------------------------------+
¦    METHOD    ¦            TRANSIENT          ¦            DETACHED            ¦
¦--------------+-------------------------------+--------------------------------¦
¦              ¦       sets id if doesn't      ¦   sets new id even if object   ¦
¦    save()    ¦     exist, persists to db,    ¦    already has it, persists    ¦
¦              ¦    returns attached object    ¦ to DB, returns attached object ¦
¦--------------+-------------------------------+--------------------------------¦
¦              ¦       sets id on object       ¦             throws             ¦
¦   persist()  ¦     persists object to DB     ¦       PersistenceException     ¦
¦              ¦                               ¦                                ¦
¦--------------+-------------------------------+--------------------------------¦
¦              ¦                               ¦                                ¦
¦   update()   ¦           Exception           ¦     persists and reattaches    ¦
¦              ¦                               ¦                                ¦
¦--------------+-------------------------------+--------------------------------¦
¦              ¦  copy the state of object in  ¦    copy the state of obj in    ¦
¦    merge()   ¦     DB, doesn't attach it,    ¦      DB, doesn't attach it,    ¦
¦              ¦    returns attached object    ¦     returns attached object    ¦
¦--------------+-------------------------------+--------------------------------¦
¦              ¦                               ¦                                ¦
¦saveOrUpdate()¦           as save()           ¦            as update()         ¦
¦              ¦                               ¦                                ¦
+-------------------------------------------------------------------------------+

How do I create my own URL protocol? (e.g. so://...)

You don't really have to do any registering as such. I've seen many programs, like emule, create their own protocol specificier (that's what I think it's called). After that, you basically just have to set some values in the registry as to what program handles that protocol. I'm not sure if there's any official registry of protocol specifiers. There isn't really much to stop you from creating your own protocol specifier for your own application if you want people to open your app from their browser.

Comment out HTML and PHP together

Instead of using HTML comments (which have no effect on PHP code -- which will still be executed), you should use PHP comments:

<?php /*
<tr>
      <td><?php echo $entry_keyword; ?></td>
      <td><input type="text" name="keyword" value="<?php echo $keyword; ?>" /></td>
    </tr>
    <tr>
      <td><?php echo $entry_sort_order; ?></td>
      <td><input name="sort_order" value="<?php echo $sort_order; ?>" size="1" /></td>
    </tr>
*/ ?>


With that, the PHP code inside the HTML will not be executed; and nothing (not the HTML, not the PHP, not the result of its non-execution) will be displayed.


Just one note: you cannot nest C-style comments... which means the comment will end at the first */ encountered.

Creating a new DOM element from an HTML string using built-in DOM methods or Prototype

HTML 5 introduced the <template> element which can be used for this purpose (as now described in the WhatWG spec and MDN docs).

A <template> element is used to declare fragments of HTML that can be utilized in scripts. The element is represented in the DOM as a HTMLTemplateElement which has a .content property of DocumentFragment type, to provide access to the template's contents. This means that you can convert an HTML string to DOM elements by setting the innerHTML of a <template> element, then reaching into the template's .content property.

Examples:

/**
 * @param {String} HTML representing a single element
 * @return {Element}
 */
function htmlToElement(html) {
    var template = document.createElement('template');
    html = html.trim(); // Never return a text node of whitespace as the result
    template.innerHTML = html;
    return template.content.firstChild;
}

var td = htmlToElement('<td>foo</td>'),
    div = htmlToElement('<div><span>nested</span> <span>stuff</span></div>');

/**
 * @param {String} HTML representing any number of sibling elements
 * @return {NodeList} 
 */
function htmlToElements(html) {
    var template = document.createElement('template');
    template.innerHTML = html;
    return template.content.childNodes;
}

var rows = htmlToElements('<tr><td>foo</td></tr><tr><td>bar</td></tr>');

Note that similar approaches that use a different container element such as a div don't quite work. HTML has restrictions on what element types are allowed to exist inside which other element types; for instance, you can't put a td as a direct child of a div. This causes these elements to vanish if you try to set the innerHTML of a div to contain them. Since <template>s have no such restrictions on their content, this shortcoming doesn't apply when using a template.

However, template is not supported in some old browsers. As of January 2018, Can I use... estimates 90% of users globally are using a browser that supports templates. In particular, no version of Internet Explorer supports them; Microsoft did not implement template support until the release of Edge.

If you're lucky enough to be writing code that's only targeted at users on modern browsers, go ahead and use them right now. Otherwise, you may have to wait a while for users to catch up.

Format cell color based on value in another sheet and cell

Here's how I did it in Excel 2003 using conditional formatting.

To apply conditional formatting to Sheet1 using values from Sheet2, you need to mirror the values into Sheet1.

Creating a mirror of Sheet2, column B in Sheet 1

  1. Go to Sheet1.
  2. Insert a new column by right-clicking column A's header and selecting "Insert".
  3. Enter the following formula into A1:

    =IF(ISBLANK(Sheet2!B1),"",Sheet2!B1)

  4. Copy A1 by right-clicking it and selecting "Copy".
  5. Paste the formula into column A by right-clicking its header and selecting "Paste".

Sheet1, column A should now exactly mirror the values in Sheet2, column B.

(Note: if you don't like it in column A, it works just as well to have it in column Z or anywhere else.)

Applying the conditional formatting

  1. Stay on Sheet1.
  2. Select column B by left-clicking its header.
  3. Select the menu item Format > Conditional Formatting...
  4. Change Condition 1 to "Formula is" and enter this formula:

    =MATCH(B1,$A:$A,0)

  5. Click the Format... button and select a green background.

You should now see the green background applied to the matching cells in Sheet1.

Hiding the mirror column

  1. Stay on Sheet1.
  2. Right-click the header on column A and select "Hide".

This should automatically update Sheet1 whenever anything in Sheet2 is changed.

Not able to start Genymotion device

I had this same issue and here are the specific configuration that I needed to get this to work.

First, go to the VirtualBox preferences -> Network.

enter image description here

enter image description here

enter image description here

For the "Host-only Networks" tab, focus on the vboxnet0.

enter image description here

Click the icon on the left that looks like a screwdriver. For the Adapter tab, fill in the IPv4 Network Address as 192.168.56.1 Fill in the IPv4 Network Mask as 255.255.255.0

enter image description here

For the DHCP Server tab, select the check box for Enable Server to enable the server Fill in the Server Address as 192.168.56.100 Fill in the Server Mask as 255.255.255.0 Fill in the Lower Address Bound as 192.168.56.101 Fill in the Upper Address Bound as 192.168.56.254

enter image description here

The DHCP server part is what was not correct for me and it fixed my problem.

How do I get the month and day with leading 0's in SQL? (e.g. 9 => 09)

DECLARE @day CHAR(2)

SET @day = right('0'+ cast(day(getdate())as nvarchar(2)),2)

print @day

How do I get a computer's name and IP address using VB.NET?

Use the My Class :)

My.Computer.Name

as for the IP address quick google search

Private Sub GetIPAddress()

Dim strHostName As String

Dim strIPAddress As String



strHostName = System.Net.Dns.GetHostName()

strIPAddress = System.Net.Dns.GetHostByName(strHostName).AddressList(0).ToString()


MessageBox.Show("Host Name: " & strHostName & "; IP Address: " & strIPAddress)

End Sub

How to copy a string of std::string type in C++?

Caesar's solution is the best in my opinion, but if you still insist to use the strcpy function, then after you have your strings ready:

string a = "text";
string b = "image";

You can try either:

strcpy(a.data(), b.data());

or

strcpy(a.c_str(), b.c_str());

Just call either the data() or c_str() member functions of the std::string class, to get the char* pointer of the string object.

The strcpy() function doesn't have overload to accept two std::string objects as parameters. It has only one overload to accept two char* pointers as parameters.

Both data and c_str return what does strcpy() want exactly.

SQL Server IIF vs CASE

IIF is a non-standard T-SQL function. It was added to SQL SERVER 2012, so that Access could migrate to SQL Server without refactoring the IIF's to CASE before hand. Once the Access db is fully migrated into SQL Server, you can refactor.

Xcode error - Thread 1: signal SIGABRT

SIGABRT means in general that there is an uncaught exception. There should be more information on the console.

Windows Bat file optional argument parsing

The selected answer works, but it could use some improvement.

  • The options should probably be initialized to default values.
  • It would be nice to preserve %0 as well as the required args %1 and %2.
  • It becomes a pain to have an IF block for every option, especially as the number of options grows.
  • It would be nice to have a simple and concise way to quickly define all options and defaults in one place.
  • It would be good to support stand-alone options that serve as flags (no value following the option).
  • We don't know if an arg is enclosed in quotes. Nor do we know if an arg value was passed using escaped characters. Better to access an arg using %~1 and enclose the assignment within quotes. Then the batch can rely on the absence of enclosing quotes, but special characters are still generally safe without escaping. (This is not bullet proof, but it handles most situations)

My solution relies on the creation of an OPTIONS variable that defines all of the options and their defaults. OPTIONS is also used to test whether a supplied option is valid. A tremendous amount of code is saved by simply storing the option values in variables named the same as the option. The amount of code is constant regardless of how many options are defined; only the OPTIONS definition has to change.

EDIT - Also, the :loop code must change if the number of mandatory positional arguments changes. For example, often times all arguments are named, in which case you want to parse arguments beginning at position 1 instead of 3. So within the :loop, all 3 become 1, and 4 becomes 2.

@echo off
setlocal enableDelayedExpansion

:: Define the option names along with default values, using a <space>
:: delimiter between options. I'm using some generic option names, but 
:: normally each option would have a meaningful name.
::
:: Each option has the format -name:[default]
::
:: The option names are NOT case sensitive.
::
:: Options that have a default value expect the subsequent command line
:: argument to contain the value. If the option is not provided then the
:: option is set to the default. If the default contains spaces, contains
:: special characters, or starts with a colon, then it should be enclosed
:: within double quotes. The default can be undefined by specifying the
:: default as empty quotes "".
:: NOTE - defaults cannot contain * or ? with this solution.
::
:: Options that are specified without any default value are simply flags
:: that are either defined or undefined. All flags start out undefined by
:: default and become defined if the option is supplied.
::
:: The order of the definitions is not important.
::
set "options=-username:/ -option2:"" -option3:"three word default" -flag1: -flag2:"

:: Set the default option values
for %%O in (%options%) do for /f "tokens=1,* delims=:" %%A in ("%%O") do set "%%A=%%~B"

:loop
:: Validate and store the options, one at a time, using a loop.
:: Options start at arg 3 in this example. Each SHIFT is done starting at
:: the first option so required args are preserved.
::
if not "%~3"=="" (
  set "test=!options:*%~3:=! "
  if "!test!"=="!options! " (
    rem No substitution was made so this is an invalid option.
    rem Error handling goes here.
    rem I will simply echo an error message.
    echo Error: Invalid option %~3
  ) else if "!test:~0,1!"==" " (
    rem Set the flag option using the option name.
    rem The value doesn't matter, it just needs to be defined.
    set "%~3=1"
  ) else (
    rem Set the option value using the option as the name.
    rem and the next arg as the value
    set "%~3=%~4"
    shift /3
  )
  shift /3
  goto :loop
)

:: Now all supplied options are stored in variables whose names are the
:: option names. Missing options have the default value, or are undefined if
:: there is no default.
:: The required args are still available in %1 and %2 (and %0 is also preserved)
:: For this example I will simply echo all the option values,
:: assuming any variable starting with - is an option.
::
set -

:: To get the value of a single parameter, just remember to include the `-`
echo The value of -username is: !-username!

There really isn't that much code. Most of the code above is comments. Here is the exact same code, without the comments.

@echo off
setlocal enableDelayedExpansion

set "options=-username:/ -option2:"" -option3:"three word default" -flag1: -flag2:"

for %%O in (%options%) do for /f "tokens=1,* delims=:" %%A in ("%%O") do set "%%A=%%~B"
:loop
if not "%~3"=="" (
  set "test=!options:*%~3:=! "
  if "!test!"=="!options! " (
      echo Error: Invalid option %~3
  ) else if "!test:~0,1!"==" " (
      set "%~3=1"
  ) else (
      set "%~3=%~4"
      shift /3
  )
  shift /3
  goto :loop
)
set -

:: To get the value of a single parameter, just remember to include the `-`
echo The value of -username is: !-username!


This solution provides Unix style arguments within a Windows batch. This is not the norm for Windows - batch usually has the options preceding the required arguments and the options are prefixed with /.

The techniques used in this solution are easily adapted for a Windows style of options.

  • The parsing loop always looks for an option at %1, and it continues until arg 1 does not begin with /
  • Note that SET assignments must be enclosed within quotes if the name begins with /.
    SET /VAR=VALUE fails
    SET "/VAR=VALUE" works. I am already doing this in my solution anyway.
  • The standard Windows style precludes the possibility of the first required argument value starting with /. This limitation can be eliminated by employing an implicitly defined // option that serves as a signal to exit the option parsing loop. Nothing would be stored for the // "option".


Update 2015-12-28: Support for ! in option values

In the code above, each argument is expanded while delayed expansion is enabled, which means that ! are most likely stripped, or else something like !var! is expanded. In addition, ^ can also be stripped if ! is present. The following small modification to the un-commented code removes the limitation such that ! and ^ are preserved in option values.

@echo off
setlocal enableDelayedExpansion

set "options=-username:/ -option2:"" -option3:"three word default" -flag1: -flag2:"

for %%O in (%options%) do for /f "tokens=1,* delims=:" %%A in ("%%O") do set "%%A=%%~B"
:loop
if not "%~3"=="" (
  set "test=!options:*%~3:=! "
  if "!test!"=="!options! " (
      echo Error: Invalid option %~3
  ) else if "!test:~0,1!"==" " (
      set "%~3=1"
  ) else (
      setlocal disableDelayedExpansion
      set "val=%~4"
      call :escapeVal
      setlocal enableDelayedExpansion
      for /f delims^=^ eol^= %%A in ("!val!") do endlocal&endlocal&set "%~3=%%A" !
      shift /3
  )
  shift /3
  goto :loop
)
goto :endArgs
:escapeVal
set "val=%val:^=^^%"
set "val=%val:!=^!%"
exit /b
:endArgs

set -

:: To get the value of a single parameter, just remember to include the `-`
echo The value of -username is: !-username!

Easiest way to develop simple GUI in Python

Try with Kivy! kivy.org It's quite easy, multi platform and a really good documentation

Check if a Windows service exists and delete in PowerShell

You can use WMI or other tools for this since there is no Remove-Service cmdlet until Powershell 6.0 (See Remove-Service doc)

For example:

$service = Get-WmiObject -Class Win32_Service -Filter "Name='servicename'"
$service.delete()

Or with the sc.exe tool:

sc.exe delete ServiceName

Finally, if you do have access to PowerShell 6.0:

Remove-Service -Name ServiceName

How to filter empty or NULL names in a QuerySet?

From Django 1.8,

from django.db.models.functions import Length

Name.objects.annotate(alias_length=Length('alias')).filter(alias_length__gt=0)

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

Found one more way of doing it

 if let parameters = route.parameters {

                    for (key, value) in parameters {
                         if value is String {
                            if let temp = value as? String {
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                        }
                        else if value is NSArray {
                            if let temp = value as? [Double]{
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                            else if let temp = value as? [Int]{
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                            else if let temp = value as? [String]{
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                        }
                        else if CFGetTypeID(value as CFTypeRef) == CFNumberGetTypeID() {
                            if let temp = value as? Int {
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                        }
                        else if CFGetTypeID(value as CFTypeRef) == CFBooleanGetTypeID(){
                            if let temp = value as? Bool {
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                        }
                    }
                }

                if let items: [MultipartData] = route.multipartData{
                    for item in items {
                        if let value = item.value{
                            multipartFormData.append(value, withName: item.key, fileName: item.fileName, mimeType: item.mimeType)
                        }
                    }
                }

How to remove specific substrings from a set of strings in Python?

If list

I was doing something for a list which is a set of strings and you want to remove all lines that have a certain substring you can do this

import re
def RemoveInList(sub,LinSplitUnOr):
    indices = [i for i, x in enumerate(LinSplitUnOr) if re.search(sub, x)]
    A = [i for j, i in enumerate(LinSplitUnOr) if j not in indices]
    return A

where sub is a patter that you do not wish to have in a list of lines LinSplitUnOr

for example

A=['Apple.good','Orange.good','Pear.bad','Pear.good','Banana.bad','Potato.bad']
sub = 'good'
A=RemoveInList(sub,A)

Then A will be

enter image description here

What are type hints in Python 3.5?

Type hints are for maintainability and don't get interpreted by Python. In the code below, the line def add(self, ic:int) doesn't result in an error until the next return... line:

class C1:
    def __init__(self):
        self.idn = 1
    def add(self, ic: int):
        return self.idn + ic

c1 = C1()
c1.add(2)

c1.add(c1)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 5, in add
TypeError: unsupported operand type(s) for +: 'int' and 'C1'

@angular/material/index.d.ts' is not a module

After upgrading to Angular 9 (released today), I ran into this issue as well and found that they made the breaking change mentioned in the answer. I can't find a reason for why they made this change.

I have a material.module.ts file that I import / export all the material components (not the most efficient, but useful for quick development). I went through and updated all my imports to the individual material folders, although an index.ts barrel might be better. Again, not sure why they made this change, but I'm guessing it has to do with tree-shaking efficiencies.

Including my material.module.ts below in case it helps anyone, it's inspired off other material modules I've found:

NOTE: As other blog posts have mentioned and from my personal experience, be careful when using a shared module like below. I have 5~ different feature modules (lazy loaded) in my app that I imported my material module into. Out of curiosity, I stopped using the shared module and instead only imported the individual material components each feature module needed. This reduced my bundle size quite a bit, almost a 200kb reduction. I assumed that the build optimization process would properly drop any component not used by my modules, but it doesn't seem to be the case...

// material.module.ts
import { ModuleWithProviders, NgModule} from "@angular/core";
import { MAT_LABEL_GLOBAL_OPTIONS, MatNativeDateModule, MAT_DATE_LOCALE } from '@angular/material/core';
import { MatIconRegistry } from '@angular/material/icon';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatBadgeModule } from '@angular/material/badge';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatChipsModule } from '@angular/material/chips';
import { MatStepperModule } from '@angular/material/stepper';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatDialogModule } from '@angular/material/dialog';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list';
import { MatMenuModule } from '@angular/material/menu';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatRadioModule } from '@angular/material/radio';
import { MatRippleModule } from '@angular/material/core';
import { MatSelectModule } from '@angular/material/select';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatSliderModule } from '@angular/material/slider';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatSortModule } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
import { MatTabsModule } from '@angular/material/tabs';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatTreeModule } from '@angular/material/tree';

@NgModule({
    imports: [
        MatAutocompleteModule,
        MatBadgeModule,
        MatButtonModule,
        MatButtonToggleModule,
        MatCardModule,
        MatCheckboxModule,
        MatChipsModule,
        MatStepperModule,
        MatDatepickerModule,
        MatDialogModule,
        MatExpansionModule,
        MatFormFieldModule,
        MatGridListModule,
        MatIconModule,
        MatInputModule,
        MatListModule,
        MatMenuModule,
        MatPaginatorModule,
        MatProgressBarModule,
        MatProgressSpinnerModule,
        MatRadioModule,
        MatRippleModule,
        MatSelectModule,
        MatSidenavModule,
        MatSliderModule,
        MatSlideToggleModule,
        MatSnackBarModule,
        MatSortModule,
        MatTableModule,
        MatTabsModule,
        MatToolbarModule,
        MatTooltipModule,
        MatTreeModule,
        MatNativeDateModule
    ],
    exports: [
        MatAutocompleteModule,
        MatBadgeModule,
        MatButtonModule,
        MatButtonToggleModule,
        MatCardModule,
        MatCheckboxModule,
        MatChipsModule,
        MatStepperModule,
        MatDatepickerModule,
        MatDialogModule,
        MatExpansionModule,
        MatFormFieldModule,
        MatGridListModule,
        MatIconModule,
        MatInputModule,
        MatListModule,
        MatMenuModule,
        MatPaginatorModule,
        MatProgressBarModule,
        MatProgressSpinnerModule,
        MatRadioModule,
        MatRippleModule,
        MatSelectModule,
        MatSidenavModule,
        MatSliderModule,
        MatSlideToggleModule,
        MatSnackBarModule,
        MatSortModule,
        MatTableModule,
        MatTabsModule,
        MatToolbarModule,
        MatTooltipModule,
        MatTreeModule,
        MatNativeDateModule
    ],
    providers: [     
    ]
})
export class MaterialModule {
    constructor(public matIconRegistry: MatIconRegistry) {
        // matIconRegistry.registerFontClassAlias('fontawesome', 'fa');
    }

    static forRoot(): ModuleWithProviders<MaterialModule> {
        return {
            ngModule: MaterialModule,
            providers: [MatIconRegistry]
        };
    }
}

Check if a property exists in a class

I got this error: "Type does not contain a definition for GetProperty" when tying the accepted answer.

This is what i ended up with:

using System.Reflection;

if (productModel.GetType().GetTypeInfo().GetDeclaredProperty(propertyName) != null)
{

}

Textarea Auto height

html

<textarea id="wmd-input" name="md-content"></textarea>

js

var textarea = $('#wmd-input'),
    top = textarea.scrollTop(),
    height = textarea.height();
    if(top > 0){
       textarea.css("height",top + height)
    }

css

#wmd-input{
    width: 100%;
    overflow: hidden;
    padding: 10px;
}

How to convert entire dataframe to numeric while preserving decimals?

df2 <- data.frame(apply(df1, 2, function(x) as.numeric(as.character(x))))

https connection using CURL from command line

I actually had this kind of problem and I solve it by these steps:

  1. Get the bundle of root CA certificates from here: https://curl.haxx.se/ca/cacert.pem and save it on local

  2. Find the php.ini file

  3. Set the curl.cainfo to be the path of the certificates. So it will something like:

curl.cainfo = /path/of/the/keys/cacert.pem

Does Java read integers in little endian or big endian?

I stumbled here via Google and got my answer that Java is big endian.

Reading through the responses I'd like to point out that bytes do indeed have an endian order, although mercifully, if you've only dealt with “mainstream” microprocessors you are unlikely to have ever encountered it as Intel, Motorola, and Zilog all agreed on the shift direction of their UART chips and that MSB of a byte would be 2**7 and LSB would be 2**0 in their CPUs (I used the FORTRAN power notation to emphasize how old this stuff is :) ).

I ran into this issue with some Space Shuttle bit serial downlink data 20+ years ago when we replaced a $10K interface hardware with a Mac computer. There is a NASA Tech brief published about it long ago. I simply used a 256 element look up table with the bits reversed (table[0x01]=0x80 etc.) after each byte was shifted in from the bit stream.

A potentially dangerous Request.Form value was detected from the client

You should use the Server.HtmlEncode method to protect your site from dangerous input.

More info here

Using Keras & Tensorflow with AMD GPU

This is an old question, but since I spent the last few weeks trying to figure it out on my own:

  1. OpenCL support for Theano is hit and miss. They added a libgpuarray back-end which appears to still be buggy (i.e., the process runs on the GPU but the answer is wrong--like 8% accuracy on MNIST for a DL model that gets ~95+% accuracy on CPU or nVidia CUDA). Also because ~50-80% of the performance boost on the nVidia stack comes from the CUDNN libraries now, OpenCL will just be left in the dust. (SEE BELOW!) :)
  2. ROCM appears to be very cool, but the documentation (and even a clear declaration of what ROCM is/what it does) is hard to understand. They're doing their best, but they're 4+ years behind. It does NOT NOT NOT work on an RX550 (as of this writing). So don't waste your time (this is where 1 of the weeks went :) ). At first, it appears ROCM is a new addition to the driver set (replacing AMDGPU-Pro, or augmenting it), but it is in fact a kernel module and set of libraries that essentially replace AMDGPU-Pro. (Think of this as the equivalent of Nvidia-381 driver + CUDA some libraries kind of). https://rocm.github.io/dl.html (Honestly I still haven't tested the performance or tried to get it to work with more recent Mesa drivers yet. I will do that sometime.
  3. Add MiOpen to ROCM, and that is essentially CUDNN. They also have some pretty clear guides for migrating. But better yet.
  4. They created "HIP" which is an automagical translator from CUDA/CUDNN to MiOpen. It seems to work pretty well since they lined the API's up directly to be translatable. There are concepts that aren't perfect maps, but in general it looks good.

Now, finally, after 3-4 weeks of trying to figure out OpenCL, etc, I found this tutorial to help you get started quickly. It is a step-by-step for getting hipCaffe up and running. Unlike nVidia though, please ensure you have supported hardware!!!! https://rocm.github.io/hardware.html. Think you can get it working without their supported hardware? Good luck. You've been warned. Once you have ROCM up and running (AND RUN THE VERIFICATION TESTS), here is the hipCaffe tutorial--if you got ROCM up you'll be doing an MNIST validation test within 10 minutes--sweet! https://rocm.github.io/ROCmHipCaffeQuickstart.html

How to update record using Entity Framework 6?

So you have an entity that is updated, and you want to update it in the database with the least amount of code...

Concurrency is always tricky, but I am assuming that you just want your updates to win. Here is how I did it for my same case and modified the names to mimic your classes. In other words, just change attach to add, and it works for me:

public static void SaveBook(Model.Book myBook)
{
    using (var ctx = new BookDBContext())
    {
        ctx.Books.Add(myBook);
        ctx.Entry(myBook).State = System.Data.Entity.EntityState.Modified;
        ctx.SaveChanges();
    }
}

How do I pass a list as a parameter in a stored procedure?

The preferred method for passing an array of values to a stored procedure in SQL server is to use table valued parameters.

First you define the type like this:

CREATE TYPE UserList AS TABLE ( UserID INT );

Then you use that type in the stored procedure:

create procedure [dbo].[get_user_names]
@user_id_list UserList READONLY,
@username varchar (30) output
as
select last_name+', '+first_name 
from user_mstr
where user_id in (SELECT UserID FROM @user_id_list)

So before you call that stored procedure, you fill a table variable:

DECLARE @UL UserList;
INSERT @UL VALUES (5),(44),(72),(81),(126)

And finally call the SP:

EXEC dbo.get_user_names @UL, @username OUTPUT;

Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from/to central (http://repo1.maven.org/maven2)

  1. Update Maven Project and check the option "Force update of Snapshots/Releases", it will remove errors.
  2. If not, Maven clean and install the Project.
  3. Still the error isn't removed, repeat step 1.

It worked for me :)

Launch Minecraft from command line - username and password as prefix

You can do this, you just need to circumvent the launcher.

In %appdata%\.minecraft\bin (or ~/.minecraft/bin on unixy systems), there is a minecraft.jar file. This is the actual game - the launcher runs this.

Invoke it like so:

java -Xms512m -Xmx1g -Djava.library.path=natives/ -cp "minecraft.jar;lwjgl.jar;lwjgl_util.jar" net.minecraft.client.Minecraft <username> <sessionID>

Set the working directory to .minecraft/bin.

To get the session ID, POST (request this page):

https://login.minecraft.net?user=<username>&password=<password>&version=13

You'll get a response like this:

1343825972000:deprecated:SirCmpwn:7ae9007b9909de05ea58e94199a33b30c310c69c:dba0c48e1c584963b9e93a038a66bb98

The fourth field is the session ID. More details here. Read those details, this answer is outdated

Here's an example of logging in to minecraft.net in C#.

Where is Developer Command Prompt for VS2013?

From VS2013 Menu Select "Tools", then Select "External Tools". Enter as below:

  • Title: "VS2013 Native Tools-Command Prompt" would be good
  • Command: C:\Windows\System32\cmd.exe
  • Arguments: /k "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\VsDevCmd.bat"
  • Initial Directory: Select as suits your needs.

Click OK. Now you have command prompt access under the Tools Menu.

How can I remove space (margin) above HTML header?

To prevent unexpected margins and other browser-specific behavior in the future, I'd recommend to include reset.css in your stylesheets.

Be aware that you'll have to set the h[1..6] font size and weight to make headings look like headings again after that, and many other things.

Performance differences between ArrayList and LinkedList

Even they seem to identical(same implemented inteface List - non thread-safe),they give different results in terms of performance in add/delete and searching time and consuming memory (LinkedList consumes more).

LinkedLists can be used if you use highly insertion/deletion with performance O(1). ArrayLists can be used if you use direct access operations with performance O(1)

This code may make clear of these comments and you can try to understand performance results. (Sorry for boiler plate code)

public class Test {

    private static Random rnd;


    static {
        rnd = new Random();
    }


    static List<String> testArrayList;
    static List<String> testLinkedList;
    public static final int COUNT_OBJ = 2000000;

    public static void main(String[] args) {
        testArrayList = new ArrayList<>();
        testLinkedList = new LinkedList<>();

        insertSomeDummyData(testLinkedList);
        insertSomeDummyData(testArrayList);

        checkInsertionPerformance(testLinkedList);  //O(1)
        checkInsertionPerformance(testArrayList);   //O(1) -> O(n)

        checkPerformanceForFinding(testArrayList);  // O(1)
        checkPerformanceForFinding(testLinkedList); // O(n)

    }


    public static void insertSomeDummyData(List<String> list) {
        for (int i = COUNT_OBJ; i-- > 0; ) {
            list.add(new String("" + i));
        }
    }

    public static void checkInsertionPerformance(List<String> list) {

        long startTime, finishedTime;
        startTime = System.currentTimeMillis();
        int rndIndex;
        for (int i = 200; i-- > 0; ) {
            rndIndex = rnd.nextInt(100000);
            list.add(rndIndex, "test");
        }
        finishedTime = System.currentTimeMillis();
        System.out.println(String.format("%s time passed at insertion:%d", list.getClass().getSimpleName(), (finishedTime - startTime)));
    }

    public static void checkPerformanceForFinding(List<String> list) {

        long startTime, finishedTime;
        startTime = System.currentTimeMillis();
        int rndIndex;
        for (int i = 200; i-- > 0; ) {
            rndIndex = rnd.nextInt(100000);
            list.get(rndIndex);
        }
        finishedTime = System.currentTimeMillis();
        System.out.println(String.format("%s time passed at searching:%d", list.getClass().getSimpleName(), (finishedTime - startTime)));

    }

}

How to get duplicate items from a list using LINQ?

I wrote this extension method based off @Lee's response to the OP. Note, a default parameter was used (requiring C# 4.0). However, an overloaded method call in C# 3.0 would suffice.

/// <summary>
/// Method that returns all the duplicates (distinct) in the collection.
/// </summary>
/// <typeparam name="T">The type of the collection.</typeparam>
/// <param name="source">The source collection to detect for duplicates</param>
/// <param name="distinct">Specify <b>true</b> to only return distinct elements.</param>
/// <returns>A distinct list of duplicates found in the source collection.</returns>
/// <remarks>This is an extension method to IEnumerable&lt;T&gt;</remarks>
public static IEnumerable<T> Duplicates<T>
         (this IEnumerable<T> source, bool distinct = true)
{
     if (source == null)
     {
        throw new ArgumentNullException("source");
     }

     // select the elements that are repeated
     IEnumerable<T> result = source.GroupBy(a => a).SelectMany(a => a.Skip(1));

     // distinct?
     if (distinct == true)
     {
        // deferred execution helps us here
        result = result.Distinct();
     }

     return result;
}

Error: class X is public should be declared in a file named X.java

The name of the public class within a file has to be the same as the name of that file.

So if your file declares class WeatherArray, it needs to be named WeatherArray.java

Write variable to file, including name

You can use pickle

import pickle
dict = {'one': 1, 'two': 2}
file = open('dump.txt', 'wb')
pickle.dump(dict, file)
file.close()

and to read it again

file = open('dump.txt', 'rb')
dict = pickle.load(file)

EDIT: Guess I misread your question, sorry ... but pickle might help all the same. :)

Clear the form field after successful submission of php form

Here is the solution for when the for is submitted with the successful message all form fields to get cleared. for that set the values equals to false check the code below

<?php
$result_success = '';
$result_error = '';
$full_Name_error = $email_error = $msg_error = '';
$full_Name = $email = $msg = $phoneNumber = '';
$full_Name_test = $email_test = $msg_test = '';

//when the form is submitted POST Method and must be clicked on submit button

if ($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['form-submit'])) {
    $full_Name = $_POST['fullName'];
    $email = $_POST['email'];
    $phoneNumber = $_POST['phoneNumber'];
    $msg = $_POST['message'];
    // Form Validation for fullname
    if (empty($full_Name)) {
        $full_Name_error = "Name is required";
    } else {
        $full_Name_test = test_input($full_Name);
        if (!preg_match("/^[a-z A-Z]*$/", $full_Name_test)) {
            $full_Name_error = "Only letters and white spaces are allowed";
        }
    }
    //Form Validation for email
    if (empty($email)) {
        $email_error = "Email is required";
    } else {
        $email_test = test_input($email);
        if (!filter_var($email_test, FILTER_VALIDATE_EMAIL)) {
            $email_error = "Invalid Email format";
        }
    }
    //Form Validation for message
    if (empty($msg)) {
        $msg_error = "Say atleast Hello!";
    } else {
        $msg_test = test_input($msg);
    }
    if ($full_Name_error == '' and $email_error == '' and $msg_error == '') {
        // Here starts PHP Mailer 
        date_default_timezone_set('Etc/UTC');
        // Edit this path if PHPMailer is in a different location.
        require './PHPMailer/PHPMailerAutoload.php';
        $mail = new PHPMailer;
        $mail->isSMTP();
        /*Server Configuration*/
        $mail->Host = 'smtp.gmail.com'; // Which SMTP server to use.
        $mail->Port = 587; // Which port to use, 587 is the default port for TLS security.
        $mail->SMTPSecure = 'tls'; // Which security method to use. TLS is most secure.
        $mail->SMTPAuth = true; // Whether you need to login. This is almost always required.
        $mail->Username = ""; // Your Gmail address.
        $mail->Password = ""; // Your Gmail login password or App Specific Password.
        /*Message Configuration*/
        $mail->setFrom($email, $full_Name); // Set the sender of the message.
        $mail->addAddress(''); // Set the recipient of the message.
        $mail->Subject = 'Contact form submission from your Website'; // The subject of the message
        /*Message Content - Choose simple text or HTML email*/
        $mail->isHTML(true);
        // Choose to send either a simple text email...
        $mail->Body = 'Name: ' . $full_Name . '<br>' . 'PhoneNumber:  ' . $phoneNumber . '<br>' . 'Email:  ' . $email . '<br><br>' . 'Message:  ' . '<h4>' . $msg . '</h4>'; // Set a plain text body.
        // ... or send an email with HTML.
        //$mail->msgHTML(file_get_contents('contents.html'));
        // Optional when using HTML: Set an alternative plain text message for email clients who prefer that.
        //$mail->AltBody = 'This is a plain-text message body'; 
        // Optional: attach a file
        //$mail->addAttachment('images/phpmailer_mini.png');
        if ($mail->send()) {
            $result_success = "Your message was sent successfully!  " . 
            //Here is the solution for when the for is submitted with the successful message all form fields to get cleared.
            $full_Name;
            $full_Name = false;
            $email = false;
            $phoneNumber = false;
            $msg = false;
        } else {
            $result_error = "Something went wrong. Check your Network connection and Please try again.";
        }
    }
}
function test_input($data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

How to ssh from within a bash script?

What you need to do is to exchange the SSH keys for the user the script runs as. Have a look at this tutorial

After doing so, your scripts will run without the need for entering a password. But, for security's sake, you don't want to do this for root users!

Populate one dropdown based on selection in another

Setup mine within a closure and with straight JavaScript, explanation provided in comments

_x000D_
_x000D_
(function() {_x000D_
_x000D_
  //setup an object fully of arrays_x000D_
  //alternativly it could be something like_x000D_
  //{"yes":[{value:sweet, text:Sweet}.....]}_x000D_
  //so you could set the label of the option tag something different than the name_x000D_
  var bOptions = {_x000D_
    "yes": ["sweet", "wohoo", "yay"],_x000D_
    "no": ["you suck!", "common son"]_x000D_
  };_x000D_
_x000D_
  var A = document.getElementById('A');_x000D_
  var B = document.getElementById('B');_x000D_
_x000D_
  //on change is a good event for this because you are guarenteed the value is different_x000D_
  A.onchange = function() {_x000D_
    //clear out B_x000D_
    B.length = 0;_x000D_
    //get the selected value from A_x000D_
    var _val = this.options[this.selectedIndex].value;_x000D_
    //loop through bOption at the selected value_x000D_
    for (var i in bOptions[_val]) {_x000D_
      //create option tag_x000D_
      var op = document.createElement('option');_x000D_
      //set its value_x000D_
      op.value = bOptions[_val][i];_x000D_
      //set the display label_x000D_
      op.text = bOptions[_val][i];_x000D_
      //append it to B_x000D_
      B.appendChild(op);_x000D_
    }_x000D_
  };_x000D_
  //fire this to update B on load_x000D_
  A.onchange();_x000D_
_x000D_
})();
_x000D_
<select id='A' name='A'>_x000D_
  <option value='yes' selected='selected'>yes_x000D_
  <option value='no'> no_x000D_
</select>_x000D_
<select id='B' name='B'>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Manually Set Value for FormBuilder Control

  let cloneObj = Object.assign({}, this.form.getRawValue(), someClass);
  this.form.complexForm.patchValue(cloneObj);

If you don't want manually set each field.

How to add a changed file to an older (not last) commit in Git

Use git rebase. Specifically:

  1. Use git stash to store the changes you want to add.
  2. Use git rebase -i HEAD~10 (or however many commits back you want to see).
  3. Mark the commit in question (a0865...) for edit by changing the word pick at the start of the line into edit. Don't delete the other lines as that would delete the commits.[^vimnote]
  4. Save the rebase file, and git will drop back to the shell and wait for you to fix that commit.
  5. Pop the stash by using git stash pop
  6. Add your file with git add <file>.
  7. Amend the commit with git commit --amend --no-edit.
  8. Do a git rebase --continue which will rewrite the rest of your commits against the new one.
  9. Repeat from step 2 onwards if you have marked more than one commit for edit.

[^vimnote]: If you are using vim then you will have to hit the Insert key to edit, then Esc and type in :wq to save the file, quit the editor, and apply the changes. Alternatively, you can configure a user-friendly git commit editor with git config --global core.editor "nano".

executing a function in sql plus

One option would be:

SET SERVEROUTPUT ON

EXEC DBMS_OUTPUT.PUT_LINE(your_fn_name(your_fn_arguments));

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

I faced the same problem.

Just removed the server from configuration and added it back after restarting eclipse by adding it to the server runtime environment.

Execution failed for task ':app:processDebugResources' even with latest build tools

I changed the target=android-26 to target=android-23

project.properties

this works great for me.

Check if inputs form are empty jQuery

Define a helper function like this

function checkWhitespace(inputString){

    let stringArray = inputString.split(' ');

    let output = true;

    for (let el of stringArray){
        if (el!=''){
            output=false;
        }
    }

    return output;
}

Then check your input field value by passing through as an argument. If function returns true, that means value is only white space.

As an example

let inputValue = $('#firstName').val();
if(checkWhitespace(inputValue)) {
  // Show Warnings or return warnings
}else {
  // // Block of code-probably store input value into database
}

How can I return to a parent activity correctly?

What worked for me was adding:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onBackPressed() {
        finish();
    }

to TheRelevantActivity.java and now it is working as expected

and yeah don't forget to add:

getSupportActionbar.setDisplayHomeAsUpEnabled(true); in onCreate() method

Split text with '\r\n'

I think the problem is in your text file. It's probably already split into too many lines and when you read it, it "adds" additional \r and/or \n characters (as they exist in file). Check your what is read into text variable.

The code below (on a local variable with your text) works fine and splits into 2 lines:

string[] stringSeparators = new string[] { "\r\n" };
string text = "somet interesting text\nsome text that should be in the same line\r\nsome text should be in another line";
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);

Putting HTML inside Html.ActionLink(), plus No Link Text?

My solution using bootstrap components:

<a class="btn btn-primary" href="@Url.Action("resetpassword", "Account")">
    <span class="glyphicon glyphicon-user"></span> Reset Password
</a>

Is there an opposite of include? for Ruby Arrays?

module Enumerable
  def does_not_include?(item)
    !include?(item)
  end
end

Ok, but seriously, the unless works fine.

Unable to establish SSL connection upon wget on Ubuntu 14.04 LTS

you must be using old version of wget i had same issue. i was using wget 1.12.so to solve this issue there are 2 way: Update wget or use curl

curl -LO 'https://example.com/filename.tar.gz'

Why does CSS not support negative padding?

Because the designers of CSS didn't have the foresight to imagine the flexibility this would bring. There are plenty of reasons to expand the content area of a box without affecting its relationship to neighbouring elements. If you think it's not possible, put some long nowrap'd text in a box, set a width on the box, and watch how the overflowed content does nothing to the layout.

Yes, this is still relevant with CSS3 in 2019; case in point: flexbox layouts. Flexbox items' margins do not collapse, so in order to space them evenly and align them with the visual edge of the container, one must subtract the items' margins from their container's padding. If any result is < 0, you must use a negative margin on the container, or sum that negative with the existing margin. I.e. the content of the element effects how one defines the margins for it, which is backwards. Summing doesn't work cleanly when flex elements' content have margins defined in different units or are affected by a different font-size, etc.

The example below should, ideally have aligned and evenly spaced grey boxes but, sadly they aren't.

_x000D_
_x000D_
body {_x000D_
  font-family: sans-serif;_x000D_
  margin: 2rem;_x000D_
}_x000D_
body > * {_x000D_
  margin: 2rem 0 0;_x000D_
}_x000D_
body > :first-child {_x000D_
  margin-top: 0;_x000D_
}_x000D_
h1,_x000D_
li,_x000D_
p {_x000D_
  padding: 10px;_x000D_
  background: lightgray;_x000D_
}_x000D_
ul {_x000D_
  list-style: none;_x000D_
  display: flex;_x000D_
  flex-wrap: wrap;_x000D_
  padding: 0;/* just to reset */_x000D_
  padding: -5px;/* would allow correct alignment */_x000D_
}_x000D_
li {_x000D_
  flex: 1 1 auto;_x000D_
  margin: 5px;_x000D_
}
_x000D_
<h1>Cras facilisis orci ligula</h1>_x000D_
_x000D_
<ul>_x000D_
  <li>a lacinia purus porttitor eget</li>_x000D_
  <li>donec ut nunc lorem</li>_x000D_
  <li>duis in est dictum</li>_x000D_
  <li>tempor metus non</li>_x000D_
  <li>dapibus sapien</li>_x000D_
  <li>phasellus bibendum tincidunt</li>_x000D_
  <li>quam vitae accumsan</li>_x000D_
  <li>ut interdum eget nisl in eleifend</li>_x000D_
  <li>maecenas sodales interdum quam sed accumsan</li>_x000D_
</ul>_x000D_
_x000D_
<p>Fusce convallis, arcu vel elementum pulvinar, diam arcu tempus dolor, nec venenatis sapien diam non dui. Nulla mollis velit dapibus magna pellentesque, at tempor sapien blandit. Sed consectetur nec orci ac lobortis.</p>_x000D_
_x000D_
<p>Integer nibh purus, convallis eget tincidunt id, eleifend id lectus. Vivamus tristique orci finibus, feugiat eros id, semper augue.</p>
_x000D_
_x000D_
_x000D_

I have encountered enough of these little issues over the years where a little negative padding would have gone a long way, but instead I'm forced to add non-semantic markup, use calc(), or CSS preprocessors which only work when the units are the same, etc.

Internet Explorer 11 detection

A pretty safe & concise way to detect IE 11 only is

if(window.msCrypto) {
    // I'm IE11 for sure
}

or something like this

var IE11= !!window.msCrypto;

msCrypto is a prefixed version of the window.crypto object and only implemented in IE 11.
https://developer.mozilla.org/en-US/docs/Web/API/Window/crypto

cURL not working (Error #77) for SSL connections on CentOS for non-root users

Windows users, add this to PHP.ini:

curl.cainfo = "C:/cacert.pem";

Path needs to be changed to your own and you can download cacert.pem from a google search

(yes I know its a CentOS question)

How to return dictionary keys as a list in Python?

Python >= 3.5 alternative: unpack into a list literal [*newdict]

New unpacking generalizations (PEP 448) were introduced with Python 3.5 allowing you to now easily do:

>>> newdict = {1:0, 2:0, 3:0}
>>> [*newdict]
[1, 2, 3]

Unpacking with * works with any object that is iterable and, since dictionaries return their keys when iterated through, you can easily create a list by using it within a list literal.

Adding .keys() i.e [*newdict.keys()] might help in making your intent a bit more explicit though it will cost you a function look-up and invocation. (which, in all honesty, isn't something you should really be worried about).

The *iterable syntax is similar to doing list(iterable) and its behaviour was initially documented in the Calls section of the Python Reference manual. With PEP 448 the restriction on where *iterable could appear was loosened allowing it to also be placed in list, set and tuple literals, the reference manual on Expression lists was also updated to state this.


Though equivalent to list(newdict) with the difference that it's faster (at least for small dictionaries) because no function call is actually performed:

%timeit [*newdict]
1000000 loops, best of 3: 249 ns per loop

%timeit list(newdict)
1000000 loops, best of 3: 508 ns per loop

%timeit [k for k in newdict]
1000000 loops, best of 3: 574 ns per loop

with larger dictionaries the speed is pretty much the same (the overhead of iterating through a large collection trumps the small cost of a function call).


In a similar fashion, you can create tuples and sets of dictionary keys:

>>> *newdict,
(1, 2, 3)
>>> {*newdict}
{1, 2, 3}

beware of the trailing comma in the tuple case!

simple way to display data in a .txt file on a webpage?

You can add it as script file. save the txt file with js suffix

in the head section add

_x000D_
_x000D_
<script src="fileName.js"></script>
_x000D_
_x000D_
_x000D_

How to perform Unwind segue programmatically?

FYI: In order for @Vadim's answer to work with a manual unwind seque action called from within a View Controller you must place the command:

[self performSegueWithIdentifier:(NSString*) identifier sender:(id) sender];

inside of the overriden class method viewDidAppear like so:

-(void) viewDidAppear:(BOOL) animated
{
    [super viewDidAppear: animated];

    [self performSegueWithIdentifier:@"SomeSegueIdentifier" sender:self];
}

If you put it in other ViewController methods like viewDidLoad or viewWillAppear it will be ignored.

Can we open pdf file using UIWebView on iOS?

use this for open pdf file in webview

NSString *path = [[NSBundle mainBundle] pathForResource:@"mypdf" ofType:@"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
UIWebView *webView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
[[webView scrollView] setContentOffset:CGPointMake(0,500) animated:YES];
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.scrollTo(0.0, 50.0)"]];
[webView loadRequest:request];
[self.view addSubview:webView];
[webView release];

Setting selected option in laravel form

Try this

<select class="form-control" name="country_code" value="{{ old('country_code') }}">
   @foreach (\App\SystemCountry::orderBy('country')->get() as $country)
       <option value="{{ $country->country_code }}"
           @if ($country->country_code == "LKA")
             {{'selected="selected"'}}
           @endif
       >
          {{ $country->country }}
       </option>
   @endforeach
</select>

How can I use Guzzle to send a POST request in JSON?

For Guzzle 5, 6 and 7 you do it like this:

use GuzzleHttp\Client;

$client = new Client();

$response = $client->post('url', [
    GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar'] // or 'json' => [...]
]);

Docs

How to Copy Text to Clip Board in Android?

Try the following code. It will support the latest API:

ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                        if (clipboard.hasPrimaryClip()) {
                            android.content.ClipDescription description = clipboard.getPrimaryClipDescription();
                            android.content.ClipData data = clipboard.getPrimaryClip();
                            if (data != null && description != null && description.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN))
                            {
                                String url= (String) clipboard.getText();
                                searchText.setText(url);
                                System.out.println("data="+data+"description="+description+"url="+url);
                            }}

How to stick text to the bottom of the page?

An old thread, but...Answer of Konerak works, but why would you even set size of a container by default. What I prefer is to use code wherever no matter of hog big page size is. So this my code:

<style>
   #container {
    position: relative;
    height: 100%;
 }
 #footer {
    position: absolute;
    bottom: 0;
 }
</style>

</HEAD>

<BODY>

 <div id="container">

    <h1>Some heading</h1>

<p>Some text you have</p> 

<br>
<br>

<div id="footer"><p>Rights reserved</p></div>

</div>

</BODY>
</HTML>

The trick is in <br> where you break new line. So, when page is small you'll see footer at bottom of page, as you want.

BUT, when a page is big SO THAT YOU MUST SCROLL IT DOWN, then your footer is going to be 2 new lines under the whole content above. And If you will then make page bigger, your footer is allways going to go DOWN. I hope somebody will find this useful.

Excel VBA: Copying multiple sheets into new workbook

This worked for me (I added an "if sheet visible" because in my case I wanted to skip hidden sheets)

   Sub Create_new_file()

Application.DisplayAlerts = False

Dim wb As Workbook
Dim wbNew As Workbook
Dim sh As Worksheet
Dim shNew As Worksheet
Dim pname, parea As String


Set wb = ThisWorkbook
Workbooks.Add
Set wbNew = ActiveWorkbook

For Each sh In wb.Worksheets

    pname = sh.Name


    If sh.Visible = True Then

    sh.Copy After:=wbNew.Sheets(Sheets.Count)

    wbNew.Sheets(Sheets.Count).Cells.ClearContents
    wbNew.Sheets(Sheets.Count).Cells.ClearFormats
    wb.Sheets(sh.Name).Activate
    Range(sh.PageSetup.PrintArea).Select
    Selection.Copy

    wbNew.Sheets(pname).Activate
    Range("A1").Select

    With Selection

        .PasteSpecial (xlValues)
        .PasteSpecial (xlFormats)
        .PasteSpecial (xlPasteColumnWidths)

    End With

    ActiveSheet.Name = pname

    End If


Next

wbNew.Sheets("Hoja1").Delete

Application.DisplayAlerts = True

End Sub

Share application "link" in Android

To be more exact

   Intent intent = new Intent(Intent.ACTION_VIEW);
   intent.setData(Uri.parse("https://play.google.com/store/apps/details?id=com.android.example"));
   startActivity(intent);

or if you want to share your other apps from your dev. account you can do something like this

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://play.google.com/store/apps/developer?id=Your_Publisher_Name"));
startActivity(intent);

PhpMyAdmin not working on localhost

Try starting MySQL and Apache in Xampp. Verify Port Number assigned to Apache (By default it should be 80). Now load localhost/phpmyadmin. It solved my problem.

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

Added MSSQLSERVER full access to the folder, diskadmin and bulkadmin server roles.

In my c# application, when preparing for the bulk insert command,

string strsql = "BULK INSERT PWCR_Contractor_vw_TEST FROM '" + strFileName + "' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\\n')";

And I get this error - Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 8 (STATUS).

I looked at my logfile and found that the terminator becomes ' ' instead of '\n'. The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did not give any information about the error:

Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)". Query :BULK INSERT PWCR_Contractor_vw_TEST FROM 'G:\NEWSTAGEWWW\CalAtlasToPWCR\Results\parsedRegistration.csv' WITH (FIELDTERMINATOR = ',', **ROWTERMINATOR = ''**)

So I added extra escape to the rowterminator - string strsql = "BULK INSERT PWCR_Contractor_vw_TEST FROM '" + strFileName + "' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\\n')";

And now it inserts successfully.

Bulk Insert SQL -   --->  BULK INSERT PWCR_Contractor_vw_TEST FROM 'G:\\NEWSTAGEWWW\\CalAtlasToPWCR\\Results\\parsedRegistration.csv' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
Bulk Insert to PWCR_Contractor_vw_TEST successful...  --->  clsDatase.PerformBulkInsert

Count distinct value pairs in multiple columns in SQL

Having to return the count of a unique Bill of Materials (BOM) where each BOM have multiple positions, I dd something like this:

select t_item, t_pono, count(distinct ltrim(rtrim(t_item)) + cast(t_pono as varchar(3))) as [BOM Pono Count]
from BOMMaster
where t_pono = 1
group by t_item, t_pono

Given t_pono is a smallint datatype and t_item is a varchar(16) datatype

Stateless vs Stateful

We make Webapps statefull by overriding HTTP stateless behaviour by using session objects.When we use session objets state is carried but we still use HTTP only.

Vue.JS: How to call function after page loaded?

You import the function from outside the main instance, and don't add it to the methods block. so the context of this is not the vm.

Either do this:

ready() {
  checkAuth.call(this)
}

or add the method to your methods first (which will make Vue bind this correctly for you) and call this method:

methods: {
  checkAuth: checkAuth
},
ready() {
  this.checkAuth()
}

How should the ViewModel close the form?

FYI, I ran into this same problem and I think I figured out a work around that doesn't require globals or statics, although it may not be the best answer. I let the you guys decide that for yourself.

In my case, the ViewModel that instantiates the Window to be displayed (lets call it ViewModelMain) also knows about the LoginFormViewModel (using the situation above as an example).

So what I did was to create a property on the LoginFormViewModel that was of type ICommand (Lets call it CloseWindowCommand). Then, before I call .ShowDialog() on the Window, I set the CloseWindowCommand property on the LoginFormViewModel to the window.Close() method of the Window I instantiated. Then inside the LoginFormViewModel all I have to do is call CloseWindowCommand.Execute() to close the window.

It is a bit of a workaround/hack I suppose, but it works well without really breaking the MVVM pattern.

Feel free to critique this process as much as you like, I can take it! :)