Programs & Examples On #Php qt

PHP-Qt is an extension for PHP5 that aims to write software with the Qt toolkit

"A connection attempt failed because the connected party did not properly respond after a period of time" using WebClient

I know it's an old post but I came across the exact same issue and I managed to use this by turning off MALWAREBYTES program which was causing the issue.

Pretty-Printing JSON with PHP

print_r pretty print for PHP

Example PHP

function print_nice($elem,$max_level=10,$print_nice_stack=array()){
    if(is_array($elem) || is_object($elem)){
        if(in_array($elem,$print_nice_stack,true)){
            echo "<font color=red>RECURSION</font>";
            return;
        }
        $print_nice_stack[]=&$elem;
        if($max_level<1){
            echo "<font color=red>nivel maximo alcanzado</font>";
            return;
        }
        $max_level--;
        echo "<table border=1 cellspacing=0 cellpadding=3 width=100%>";
        if(is_array($elem)){
            echo '<tr><td colspan=2 style="background-color:#333333;"><strong><font color=white>ARRAY</font></strong></td></tr>';
        }else{
            echo '<tr><td colspan=2 style="background-color:#333333;"><strong>';
            echo '<font color=white>OBJECT Type: '.get_class($elem).'</font></strong></td></tr>';
        }
        $color=0;
        foreach($elem as $k => $v){
            if($max_level%2){
                $rgb=($color++%2)?"#888888":"#BBBBBB";
            }else{
                $rgb=($color++%2)?"#8888BB":"#BBBBFF";
            }
            echo '<tr><td valign="top" style="width:40px;background-color:'.$rgb.';">';
            echo '<strong>'.$k."</strong></td><td>";
            print_nice($v,$max_level,$print_nice_stack);
            echo "</td></tr>";
        }
        echo "</table>";
        return;
    }
    if($elem === null){
        echo "<font color=green>NULL</font>";
    }elseif($elem === 0){
        echo "0";
    }elseif($elem === true){
        echo "<font color=green>TRUE</font>";
    }elseif($elem === false){
        echo "<font color=green>FALSE</font>";
    }elseif($elem === ""){
        echo "<font color=green>EMPTY STRING</font>";
    }else{
        echo str_replace("\n","<strong><font color=red>*</font></strong><br>\n",$elem);
    }
}

Atom menu is missing. How do I re-enable

Get cursor on top, where white header with file name, then press Alt. To set top menu by default always visible. You needed in top menu selected: FILE -> Config... -> autoHideMenuBar: true (change it to autoHideMenuBar: false) Save it.

fatal: ambiguous argument 'origin': unknown revision or path not in the working tree

This worked for me on win replace REL_PATH_TO_FILE with the relative path to the file to remove Removing sensitive data from a repository The docs say full path - but that errored for me -so I tried rel path and it worked.

<from the repo dir>git filter-branch --force --index-filter "git rm --cached --ignore-unmatch REL_PATH_TO_FILE" --prune-empty --tag-name-filter cat -- --all

How to install php-curl in Ubuntu 16.04

To Install cURL 7.49.0 on Ubuntu 16.04 and Derivatives

wget http://curl.haxx.se/download/curl-7.49.0.tar.gz
tar -xvf curl-7.49.0.tar.gz
cd curl-7.49.0/
./configure
make
sudo make install

Counting the number of option tags in a select tag in jQuery

Ok, i had a few problems because i was inside a

$('.my-dropdown').live('click', function(){  
});

I had multiples inside my page that's why i used a class.

My drop down was filled automatically by a ajax request when i clicked it, so i only had the element $(this)

so...

I had to do:

$('.my-dropdown').live('click', function(){
  total_tems = $(this).find('option').length;
});

nano error: Error opening terminal: xterm-256color

I had this problem connecting to http://sdf.org through Mac OS X Lion. I changed under Terminal Preferences (?+,) > Advanced pane, Declare Terminal as to VT-100.

I also marked Delete Sends Ctrl-H because this Mac connection was confusing zsh.

It appears to be working for my use case.

PHP function ssh2_connect is not working

You need to install ssh2 lib

sudo apt-get install libssh2-php && sudo /etc/init.d/apache2 restart

that should be enough to get you on the road

Using a dispatch_once singleton model in Swift

Use:

class UtilSingleton: NSObject {

    var iVal: Int = 0

    class var shareInstance: UtilSingleton {
        get {
            struct Static {
                static var instance: UtilSingleton? = nil
                static var token: dispatch_once_t = 0
            }
            dispatch_once(&Static.token, {
                Static.instance = UtilSingleton()
            })
            return Static.instance!
        }
    }
}

How to use:

UtilSingleton.shareInstance.iVal++
println("singleton new iVal = \(UtilSingleton.shareInstance.iVal)")

Change directory in Node.js command prompt

That isn't the Node.js command prompt window. That is a language shell to run JavaScript commands, also known as a REPL.

In Windows, there should be a Node.js command prompt in your Start menu or start screen:

Windows Search for node.js

Which will open a command prompt window that looks like this:

Node.js command prompt window

From there you can switch directories using the cd command.

Initialization of an ArrayList in one line

Actually, probably the "best" way to initialize the ArrayList is the method you wrote, as it does not need to create a new List in any way:

ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");

The catch is that there is quite a bit of typing required to refer to that list instance.

There are alternatives, such as making an anonymous inner class with an instance initializer (also known as an "double brace initialization"):

ArrayList<String> list = new ArrayList<String>() {{
    add("A");
    add("B");
    add("C");
}};

However, I'm not too fond of that method because what you end up with is a subclass of ArrayList which has an instance initializer, and that class is created just to create one object -- that just seems like a little bit overkill to me.

What would have been nice was if the Collection Literals proposal for Project Coin was accepted (it was slated to be introduced in Java 7, but it's not likely to be part of Java 8 either.):

List<String> list = ["A", "B", "C"];

Unfortunately it won't help you here, as it will initialize an immutable List rather than an ArrayList, and furthermore, it's not available yet, if it ever will be.

Keep getting No 'Access-Control-Allow-Origin' error with XMLHttpRequest

Your server's response allows the request to include three specific non-simple headers:

Access-Control-Allow-Headers:origin, x-requested-with, content-type

but your request has a header not allowed by the server's response:

Access-Control-Request-Headers:access-control-allow-origin, content-type

All non-simple headers sent in a CORS request must be explicitly allowed by the Access-Control-Allow-Headers response header. The unnecessary Access-Control-Allow-Origin header sent in your request is not allowed by the server's CORS response. This is exactly what the "...not allowed by Access-Control-Allow-Headers" error message was trying to tell you.

There is no reason for the request to have this header: it does nothing, because Access-Control-Allow-Origin is a response header, not a request header.

Solution: Remove the setRequestHeader call that adds a Access-Control-Allow-Origin header to your request.

Copy all values from fields in one class to another through reflection

I solved the above problem in Kotlin that works fine for me for my Android Apps Development:

 object FieldMapper {

fun <T:Any> copy(to: T, from: T) {
    try {
        val fromClass = from.javaClass

        val fromFields = getAllFields(fromClass)

        fromFields?.let {
            for (field in fromFields) {
                try {
                    field.isAccessible = true
                    field.set(to, field.get(from))
                } catch (e: IllegalAccessException) {
                    e.printStackTrace()
                }

            }
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }

}

private fun getAllFields(paramClass: Class<*>): List<Field> {

    var theClass:Class<*>? = paramClass
    val fields = ArrayList<Field>()
    try {
        while (theClass != null) {
            Collections.addAll(fields, *theClass?.declaredFields)
            theClass = theClass?.superclass
        }
    }catch (e:Exception){
        e.printStackTrace()
    }

    return fields
}

}

Laravel 4: Redirect to a given url

This worked for me in Laravel 5.8

return \Redirect::to('https://bla.com/?yken=KuQxIVTNRctA69VAL6lYMRo0');

Or instead of / you can use

use Redirect;

What causes "Unable to access jarfile" error?

For me it happen because i run it with default java version (7) and not with compiled java version (8) used to create this jar.

So i used:

%Java8_64%\bin\java -jar myjar.jar

Instead of java 7 version:

java -jar myjar.jar

set height of imageview as matchparent programmatically

For Kotlin Users

val params = mImageView?.layoutParams as FrameLayout.LayoutParams
params.width = FrameLayout.LayoutParams.MATCH_PARENT
params.height = FrameLayout.LayoutParams.MATCH_PARENT
mImageView?.layoutParams = params

Here I used FrameLayout.LayoutParams since my views( ImageView) parent is FrameLayout

Where is the IIS Express configuration / metabase file found?

To come full circle and include all versions of Visual Studio, @Myster originally stated that;

Pre Visual Studio 2015 the paths to applicationhost.config were:

%userprofile%\documents\iisexpress\config\applicationhost.config
%userprofile%\my documents\iisexpress\config\applicationhost.config

Visual Studio 2015/2017 path can be found at: (credit: @Talon)

$(solutionDir)\.vs\config\applicationhost.config

Visual Studio 2019 path can be found at: (credit: @Talon)

$(solutionDir)\.vs\config\$(ProjectName)\applicationhost.config

But the part that might get some people is that the project settings in the .sln file can repopulate the applicationhost.config for Visual Studio 2015+. (credit: @Lex Li)

So, if you make a change in the applicationhost.config you also have to make sure your changes match here:

$(solutionDir)\ProjectName.sln

The two important settings should look like:

Project("{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}") = "ProjectName", "ProjectPath\", "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"

and

VWDPort = "Port#"

What is important here is that the two settings in the .sln must match the name and bindingInformation respectively in the applicationhost.config file if you plan on making changes. There may be more places that link these two files and I will update as I find more links either by comments or more experience.

How to replace all strings to numbers contained in each string in Notepad++?

I have Notepad++ v6.8.8

Find: [([a-zA-Z])]

Replace: [\'\1\']

Will produce: $array[XYZ] => $array['XYZ']

Bootstrap 3 Multi-column within a single ul not floating properly

you are thinking too much... Take a look at this [i think this is what you wanted - if not let me know]

http://www.bootply.com/118886

css

.even{background: red; color:white;}
.odd{background: darkred; color:white;}

html

<div class="container">
  <ul class="list-unstyled">
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
  </ul>
</div>

Counting unique / distinct values by group in a data frame

This would also work but is less eloquent than the plyr solution:

x <- sapply(split(myvec, myvec$name),  function(x) length(unique(x[, 2]))) 
data.frame(names=names(x), number_of_distinct_orders=x, row.names = NULL)

How to search for a part of a word with ElasticSearch

Try the solution with is described here: Exact Substring Searches in ElasticSearch

{
    "mappings": {
        "my_type": {
            "index_analyzer":"index_ngram",
            "search_analyzer":"search_ngram"
        }
    },
    "settings": {
        "analysis": {
            "filter": {
                "ngram_filter": {
                    "type": "ngram",
                    "min_gram": 3,
                    "max_gram": 8
                }
            },
            "analyzer": {
                "index_ngram": {
                    "type": "custom",
                    "tokenizer": "keyword",
                    "filter": [ "ngram_filter", "lowercase" ]
                },
                "search_ngram": {
                    "type": "custom",
                    "tokenizer": "keyword",
                    "filter": "lowercase"
                }
            }
        }
    }
}

To solve the disk usage problem and the too-long search term problem short 8 characters long ngrams are used (configured with: "max_gram": 8). To search for terms with more than 8 characters, turn your search into a boolean AND query looking for every distinct 8-character substring in that string. For example, if a user searched for large yard (a 10-character string), the search would be:

"arge ya AND arge yar AND rge yard.

How to create a jQuery function (a new jQuery method or plugin)?

In spite of all the answers you already received, it is worth noting that you do not need to write a plugin to use jQuery in a function. Certainly if it's a simple, one-time function, I believe writing a plugin is overkill. It could be done much more easily by just passing the selector to the function as a parameter. Your code would look something like this:

function myFunction($param) {
   $param.hide();  // or whatever you want to do
   ...
}

myFunction($('#my_div'));

Note that the $ in the variable name $param is not required. It is just a habit of mine to make it easy to remember that that variable contains a jQuery selector. You could just use param as well.

How can I manually set an Angular form field as invalid?

I was trying to call setErrors() inside a ngModelChange handler in a template form. It did not work until I waited one tick with setTimeout():

template:

<input type="password" [(ngModel)]="user.password" class="form-control" 
 id="password" name="password" required (ngModelChange)="checkPasswords()">

<input type="password" [(ngModel)]="pwConfirm" class="form-control"
 id="pwConfirm" name="pwConfirm" required (ngModelChange)="checkPasswords()"
 #pwConfirmModel="ngModel">

<div [hidden]="pwConfirmModel.valid || pwConfirmModel.pristine" class="alert-danger">
   Passwords do not match
</div>

component:

@ViewChild('pwConfirmModel') pwConfirmModel: NgModel;

checkPasswords() {
  if (this.pwConfirm.length >= this.user.password.length &&
      this.pwConfirm !== this.user.password) {
    console.log('passwords do not match');
    // setErrors() must be called after change detection runs
    setTimeout(() => this.pwConfirmModel.control.setErrors({'nomatch': true}) );
  } else {
    // to clear the error, we don't have to wait
    this.pwConfirmModel.control.setErrors(null);
  }
}

Gotchas like this are making me prefer reactive forms.

Render Partial View Using jQuery in ASP.NET MVC

Using standard Ajax call to achieve same result

        $.ajax({
            url: '@Url.Action("_SearchStudents")?NationalId=' + $('#NationalId').val(),
            type: 'GET',
            error: function (xhr) {
                alert('Error: ' + xhr.statusText);

            },
            success: function (result) {

                $('#divSearchResult').html(result);
            }
        });




public ActionResult _SearchStudents(string NationalId)
        {

           //.......

            return PartialView("_SearchStudents", model);
        }

Difference between HashMap, LinkedHashMap and TreeMap

These are different implementations of the same interface. Each implementation has some advantages and some disadvantages (fast insert, slow search) or vice versa.

For details look at the javadoc of TreeMap, HashMap, LinkedHashMap.

How to delete and update a record in Hive

If you want to delete all records then as a workaround load an empty file into table in OVERWRITE mode

hive> LOAD DATA LOCAL INPATH '/root/hadoop/textfiles/empty.txt' OVERWRITE INTO TABLE employee;
Loading data to table default.employee
Table default.employee stats: [numFiles=1, numRows=0, totalSize=0, rawDataSize=0]
OK
Time taken: 0.19 seconds

hive> SELECT * FROM employee;
OK
Time taken: 0.052 seconds

How do I change Android Studio editor's background color?

You can change it by going File => Settings (Shortcut CTRL+ ALT+ S) , from Left panel Choose Appearance , Now from Right Panel choose theme.

enter image description here

Android Studio 2.1

Preference -> Search for Appearance -> UI options , Click on DropDown Theme

enter image description here

Android 2.2

Android studio -> File -> Settings -> Appearance & Behavior -> Look for UI Options

EDIT :

Import External Themes

You can download custom theme from this website. Choose your theme, download it. To set theme Go to Android studio -> File -> Import Settings -> Choose the .jar file downloaded.

Remove Primary Key in MySQL

First modify the column to remove the auto_increment field like this: alter table user_customer_permission modify column id int;

Next, drop the primary key. alter table user_customer_permission drop primary key;

Docker: Multiple Dockerfiles in project

In newer versions(>=1.8.0) of docker, you can do this

docker build -f Dockerfile.db .
docker build -f Dockerfile.web .

A big save.

EDIT: update versions per raksja's comment

EDIT: comment from @vsevolod: it's possible to get syntax highlighting in VS code by giving files .Dockerfile extension(instead of name) e.g. Prod.Dockerfile, Test.Dockerfile etc.

Unique device identification

You can use the fingerprintJS2 library, it helps a lot with calculating a browser fingerprint.

By the way, on Panopticlick you can see how unique this usually is.

Define a global variable in a JavaScript function

If you want the variable inside the function available outside of the function, return the results of the variable inside the function.

var x = function returnX { var x = 0; return x; } is the idea...

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript">

        var offsetfrommouse = [10, -20];
        var displayduration = 0;
        var obj_selected = 0;

        function makeObj(address) {
            var trailimage = [address, 50, 50];
            document.write('<img id="trailimageid" src="' + trailimage[0] + '" border="0"  style=" position: absolute; visibility:visible; left: 0px; top: 0px; width: ' + trailimage[1] + 'px; height: ' + trailimage[2] + 'px">');
            obj_selected = 1;
            return trailimage;
        }

        function truebody() {
            return (!window.opera && document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
        }

        function hidetrail() {
            var x = document.getElementById("trailimageid").style;
            x.visibility = "hidden";
            document.onmousemove = "";
        }

        function followmouse(e) {
            var xcoord = offsetfrommouse[0];
            var ycoord = offsetfrommouse[1];
            var x = document.getElementById("trailimageid").style;
            if (typeof e != "undefined") {
                xcoord += e.pageX;
                ycoord += e.pageY;
            }

            else if (typeof window.event != "undefined") {
                xcoord += truebody().scrollLeft + event.clientX;
                ycoord += truebody().scrollTop + event.clientY;
            }
            var docwidth = 1395;
            var docheight = 676;
            if (xcoord + trailimage[1] + 3 > docwidth || ycoord + trailimage[2] > docheight) {
                x.display = "none";
                alert("inja");
            }
            else
                x.display = "";
            x.left = xcoord + "px";
            x.top = ycoord + "px";
        }

        if (obj_selected = 1) {
            alert("obj_selected = true");
            document.onmousemove = followmouse;
            if (displayduration > 0)
                setTimeout("hidetrail()", displayduration * 1000);
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <img alt="" id="house" src="Pictures/sides/right.gif" style="z-index: 1; left: 372px; top: 219px; position: absolute; height: 138px; width: 120px" onclick="javascript:makeObj('Pictures/sides/sides-not-clicked.gif');" />
    </form>
</body>
</html>

I haven't tested this, but if your code worked prior to that small change, then it should work.

how do I use an enum value on a switch statement in C++

i had a similar issue using enum with switch cases later i resolved it on my own....below is the corrected code, perhaps this might help.

     //Menu Chooser Programe using enum
     #include<iostream>
     using namespace std;
     int main()
     {
        enum level{Novice=1, Easy, Medium, Hard};
        level diffLevel=Novice;
        int i;
        cout<<"\nenter a level: ";
        cin>>i;
        switch(i)
        {
        case Novice: cout<<"\nyou picked Novice\n"; break;
        case Easy: cout<<"\nyou picked Easy\n"; break;
        case Medium: cout<<"\nyou picked Medium\n"; break;
        case Hard: cout<<"\nyou picked Hard\n"; break;
        default: cout<<"\nwrong input!!!\n"; break;
        }
        return 0;
     }

Get most recent row for given ID

Building on @xQbert's answer's, you can avoid the subquery AND make it generic enough to filter by any ID

SELECT id, signin, signout
FROM dTable
INNER JOIN(
  SELECT id, MAX(signin) AS signin
  FROM dTable
  GROUP BY id
) AS t1 USING(id, signin)

How can I reverse a list in Python?

list_data = [1,2,3,4,5]
l = len(list_data)
i=l+1
rev_data = []
while l>0:
  j=i-l
  l-=1
  rev_data.append(list_data[-j])
print "After Rev:- %s" %rev_data 

Very Long If Statement in Python

Here is the example directly from PEP 8 on limiting line length:

class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):
        if (width == 0 and height == 0 and
                color == 'red' and emphasis == 'strong' or
                highlight > 100):
            raise ValueError("sorry, you lose")
        if width == 0 and height == 0 and (color == 'red' or
                                           emphasis is None):
            raise ValueError("I don't think so -- values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

Get checkbox list values with jQuery

Try this one..

var listCheck = [];
console.log($("input[name='YourCheckBokName[]']"));
$("input[name='YourCheckBokName[]']:checked").each(function() {
     console.log($(this).val());
     listCheck .push($(this).val());
});
console.log(listCheck);

how to increase the limit for max.print in R

set the function options(max.print=10000) in top of your program. since you want intialize this before it works. It is working for me.

How to declare Return Types for Functions in TypeScript

External return type declaration to use with multiple functions:

type ValidationReturnType = string | boolean;

function isEqual(number1: number, number2: number): ValidationReturnType {
    return number1 == number2 ? true : 'Numbers are not equal.';
}

Will Google Android ever support .NET?

Check this out xmlvm I think this is possible. May be can also check this video

SQL Server NOLOCK and joins

I was pretty sure that you need to specify the NOLOCK for each JOIN in the query. But my experience was limited to SQL Server 2005.

When I looked up MSDN just to confirm, I couldn't find anything definite. The below statements do seem to make me think, that for 2008, your two statements above are equivalent though for 2005 it is not the case:

[SQL Server 2008 R2]

All lock hints are propagated to all the tables and views that are accessed by the query plan, including tables and views referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.

[SQL Server 2005]

In SQL Server 2005, all lock hints are propagated to all the tables and views that are referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.

Additionally, point to note - and this applies to both 2005 and 2008:

The table hints are ignored if the table is not accessed by the query plan. This may be caused by the optimizer choosing not to access the table at all, or because an indexed view is accessed instead. In the latter case, accessing an indexed view can be prevented by using the OPTION (EXPAND VIEWS) query hint.

Most efficient method to groupby on an array of objects

just simple if you use lodash library

let temp = []
  _.map(yourCollectionData, (row) => {
    let index = _.findIndex(temp, { 'Phase': row.Phase })
    if (index > -1) {
      temp[index].Value += row.Value 
    } else {
      temp.push(row)
    }
  })

How to get main div container to align to centre?

Do not use the * selector as that will apply to all elements on the page. Suppose you have a structure like this:

...
<body>
    <div id="content">
        <b>This is the main container.</b>
    </div>
</body>
</html>

You can then center the #content div using:

#content {
    width: 400px;
    margin: 0 auto;
    background-color: #66ffff;
}

Don't know what you've seen elsewhere but this is the way to go. The * { margin: 0; padding: 0; } snippet you've seen is for resetting browser's default definitions for all browsers to make your site behave similarly on all browsers, this has nothing to do with centering the main container.

Most browsers apply a default margin and padding to some elements which usually isn't consistent with other browsers' implementations. This is why it is often considered smart to use this kind of 'resetting'. The reset snippet you presented is the most simplest of reset stylesheets, you can read more about the subject here:

How to throw an exception in C?

On Win with MSVC there's __try ... __except ... but it's really horrible and you don't want to use it if you can possibly avoid it. Better to say that there are no exceptions.

How do I format a Microsoft JSON date?

Another regex example you can try using:

var mydate = json.date
var date = new Date(parseInt(mydate.replace(/\/Date\((-?\d+)\)\//, '$1');
mydate = date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear();

date.getMonth() returns an integer 0 - 11 so we must add 1 to get the right month number wise

JavaScript dictionary with names

The main problem I see with what you have is that it's difficult to loop through, for populating a table.

Simply use an array of arrays:

var myMappings = [
    ["Name", "10%"], // Note the quotes around "10%"
    ["Phone", "10%"],
    // etc..
];

... which simplifies access:

myMappings[0][0]; // column name
myMappings[0][1]; // column width

Alternatively:

var myMappings = {
    names: ["Name", "Phone", etc...],
    widths: ["10%", "10%", etc...]
};

And access with:

myMappings.names[0];
myMappings.widths[0];

Cannot change version of project facet Dynamic Web Module to 3.0?

I had the same issue ,deleting the .settings folder resolved the issue

get enum name from enum value

Say we have:

public enum MyEnum {
  Test1, Test2, Test3
}

To get the name of a enum variable use name():

MyEnum e = MyEnum.Test1;
String name = e.name(); // Returns "Test1"

To get the enum from a (string) name, use valueOf():

String name = "Test1";
MyEnum e = Enum.valueOf(MyEnum.class, name);

If you require integer values to match enum fields, extend the enum class:

public enum MyEnum {
  Test1(1), Test2(2), Test3(3);

  public final int value;

  MyEnum(final int value) {
     this.value = value;
  }
}

Now you can use:

MyEnum e = MyEnum.Test1;
int value = e.value; // = 1

And lookup the enum using the integer value:

MyEnum getValue(int value) {
  for(MyEnum e: MyEunm.values()) {
    if(e.value == value) {
      return e;
    }
  }
  return null;// not found
}

Using querySelectorAll to retrieve direct children

I am just doing this without even trying it. Would this work?

myDiv = getElementById("myDiv");
myDiv.querySelectorAll(this.id + " > .foo");

Give it a try, maybe it works maybe not. Apolovies, but I am not on a computer now to try it (responding from my iPhone).

Angular CLI Error: The serve command requires to be run in an Angular project, but a project definition could not be found

As Usman said, i had a lot of trouble first time, I was following a tutorial. I had not set my directory to the project directory hence got this error.

I solved the issue by

  1. Setting the correct root directory to where my project was cd myproject
  2. Compile the app - ng serve

That was it.

Cannot catch toolbar home button click event

I have handled back and Home button in Navigation Drawer like

public class HomeActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    private ActionBarDrawerToggle drawerToggle;
    private DrawerLayout drawerLayout;
    NavigationView navigationView;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_home);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        resetActionBar();

        navigationView = (NavigationView) findViewById(R.id.navigation_view);
        navigationView.setNavigationItemSelectedListener(this);

        //showing first fragment on Start
        getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).replace(R.id.content_fragment, new FirstFragment()).commit();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //listener for home
        if(id==android.R.id.home)
        {  
            if (getSupportFragmentManager().getBackStackEntryCount() > 0)
                onBackPressed();
            else
                drawerLayout.openDrawer(navigationView);
            return  true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
       if (drawerLayout.isDrawerOpen(GravityCompat.START)) 
            drawerLayout.closeDrawer(GravityCompat.START);
       else 
            super.onBackPressed();
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Begin the transaction

        Fragment fragment = null;
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (id == R.id.nav_companies_list) {
            fragment = new FirstFragment();
            // Handle the action
        } 


        // Begin the transaction
        if(fragment!=null){

            if(item.isChecked()){
                if(getSupportFragmentManager().getBackStackEntryCount()==0){
                    drawer.closeDrawers();
            }else{
                    removeAllFragments();
                    getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.WikiCompany, fragment).commit();
                    drawer.closeDrawer(GravityCompat.START);
                }

            }else{
                removeAllFragments();
                getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.WikiCompany, fragment).commit();
                drawer.closeDrawer(GravityCompat.START);
            }
        }

        return true;
    }

    public void removeAllFragments(){
        getSupportFragmentManager().popBackStackImmediate(null,
                FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }

    public void replaceFragment(final Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                .replace(R.id.WikiCompany, fragment).addToBackStack("")
                .commit();
    }


    public void updateDrawerIcon() {
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.i("", "BackStackCount: " + getSupportFragmentManager().getBackStackEntryCount());
                    if (getSupportFragmentManager().getBackStackEntryCount() > 0)
                        drawerToggle.setDrawerIndicatorEnabled(false);
                    else
                        drawerToggle.setDrawerIndicatorEnabled(true);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }, 50);
    }

    public void resetActionBar()
    {
        //display home
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

    public void setActionBarTitle(String title) {
        getSupportActionBar().setTitle(title);
    }
}

and In each onViewCreated I call

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    ((HomeActivity)getActivity()).updateDrawerIcon();
    ((HomeActivity) getActivity()).setActionBarTitle("List");
}

Convert interface{} to int

I whole-heartedly agree with zzzz's type assertion answer and I strongly prefer that way over others. That said, here's what I've had to do when the preferred method has not worked... (long story related to cross-serialization of data). You can even chain this into a switch statement with case errInt == nil and similar expressions.

package main

import "fmt"
import "strconv"

func main() {
    var v interface{}
    v = "4"

    i, errInt := strconv.ParseInt(v.(string), 10, 64)

    if errInt == nil {
        fmt.Printf("%d is a int", i)
        /* do what you wish with "i" here */
    }
}

Like I said above, try type assertion first before trying this way.

How to write log file in c#?

public static void WriteLog(string strLog)
    {
        StreamWriter log;
        FileStream fileStream = null;
        DirectoryInfo logDirInfo = null;
        FileInfo logFileInfo;

        string logFilePath = "C:\\Logs\\";
        logFilePath = logFilePath + "Log-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";           
        logFileInfo = new FileInfo(logFilePath);
        logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName);
        if (!logDirInfo.Exists) logDirInfo.Create();
        if (!logFileInfo.Exists)
        {
            fileStream = logFileInfo.Create();
        }
        else
        {
            fileStream = new FileStream(logFilePath, FileMode.Append);
        }
        log = new StreamWriter(fileStream);
        log.WriteLine(strLog);
        log.Close();
    }   

Refer Link: blogspot.in

Bootstrap 4 - Inline List?

Shouldn't it be just the .list-group? See below,

<ul class="list-group">
  <li class="list-group-item active">Cras justo odio</li>
  <li class="list-group-item">Dapibus ac facilisis in</li>
  <li class="list-group-item">Morbi leo risus</li>
  <li class="list-group-item">Porta ac consectetur ac</li>
  <li class="list-group-item">Vestibulum at eros</li>
</ul>

Reference: Bootstrap 4 Basic Example of a List group

Which Protocols are used for PING?

Internet Control Message Protocol

http://en.wikipedia.org/wiki/Internet_Control_Message_Protocol

ICMP is built on top of a bunch of other protocols, so in that sense your TA is correct. However, ping itself is ICMP.

How to uninstall with msiexec using product id guid without .msi file present

"Reference-Style" Answer: This is an alternative answer to the one below with several different options shown. Uninstalling an MSI file from the command line without using msiexec.


The command you specify is correct: msiexec /x {A4BFF20C-A21E-4720-88E5-79D5A5AEB2E8}

If you get "This action is only valid for products that are currently installed" you have used an unrecognized product or package code, and you must find the right one. Often this can be caused by using an erroneous package code instead of a product code to uninstall - a package code changes with every rebuild of an MSI file, and is the only guid you see when you view an msi file's property page. It should work for uninstall, provided you use the right one. No room for error. If you want to find the product code instead, you need to open the MSI. The product code is found in the Property table.


UPDATE, Jan 2018:

With all the registry redirects going on, I am not sure the below registry-based approach is a viable option anymore. I haven't checked properly because I now rely on the following approach using PowerShell: How can I find the product GUID of an installed MSI setup?

Also check this reference-style answer describing different ways to uninstall an MSI package and ways to determine what product version you have installed: Uninstalling an MSI file from the command line without using msiexec


Legacy, registry option:

You can also find the product code by perusing the registry from this base key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall . Press F3 and search for your product name. (If it's a 32-bit installer on a 64-bit machine, it might be under HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall instead).

Legacy, PowerShell option: (largely similar to the new, linked answer above)

Finally, you can find the product code by using PowerShell:

get-wmiobject Win32_Product | Format-Table IdentifyingNumber, Name

enter image description here

Similar post: WiX - Doing a major upgrade on a multi instance install (screenshot of how to find the product code in the MSI).

How to print something when running Puppet client?

You could go a step further and break into the puppet code using a breakpoint.

http://logicminds.github.io/blog/2017/04/25/break-into-your-puppet-code/

This would only work with puppet apply or using a rspec test. Or you can manually type your code into the debugger console. Note: puppet still needs to know where your module code is at if you haven't set already.

gem install puppet puppet-debugger 
puppet module install nwops/debug
cat > test.pp <<'EOF'
$var1 = 'test'
debug::break()
EOF

Should show something like.

puppet apply test.pp
From file: test.pp
     1: $var1 = 'test'
     2: # add 'debug::break()' where you want to stop in your code
  => 3: debug::break()
1:>> $var1
=> "test"
2:>>

https://www.puppet-debugger.com

How to display multiple images in one figure correctly?

You could try the following:

import matplotlib.pyplot as plt
import numpy as np

def plot_figures(figures, nrows = 1, ncols=1):
    """Plot a dictionary of figures.

    Parameters
    ----------
    figures : <title, figure> dictionary
    ncols : number of columns of subplots wanted in the display
    nrows : number of rows of subplots wanted in the figure
    """

    fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows)
    for ind,title in zip(range(len(figures)), figures):
        axeslist.ravel()[ind].imshow(figures[title], cmap=plt.jet())
        axeslist.ravel()[ind].set_title(title)
        axeslist.ravel()[ind].set_axis_off()
    plt.tight_layout() # optional



# generation of a dictionary of (title, images)
number_of_im = 20
w=10
h=10
figures = {'im'+str(i): np.random.randint(10, size=(h,w)) for i in range(number_of_im)}

# plot of the images in a figure, with 5 rows and 4 columns
plot_figures(figures, 5, 4)

plt.show()

However, this is basically just copy and paste from here: Multiple figures in a single window for which reason this post should be considered to be a duplicate.

I hope this helps.

Programmatically scroll to a specific position in an Android ListView

I have set OnGroupExpandListener and override onGroupExpand() as:

and use setSelectionFromTop() method which Sets the selected item and positions the selection y pixels from the top edge of the ListView. (If in touch mode, the item will not be selected but it will still be positioned appropriately.) (android docs)

    yourlist.setOnGroupExpandListener (new ExpandableListView.OnGroupExpandListener()
    {

        @Override
        public void onGroupExpand(int groupPosition) {

            expList.setSelectionFromTop(groupPosition, 0);
            //your other code
        }
    });

How to advance to the next form input when the current input has a value?

If you have jQuery UI this little function allows basic tabbing

handlePseudoTab(direction) {
    if (!document.hasFocus() || !document.activeElement) {
        return;
    }
    const focusList = $(":focusable", $yourHTMLElement);
    const i = focusList.index(document.activeElement);
    if (i < 0) {
        focusList[0].focus(); // nothing is focussed so go to list item 0
    } else if (direction === 'next' && i + 1 < focusList.length) {
        focusList[i + 1].focus(); // advance one
    } else if (direction === 'prev' && i - 1 > -1) {
        focusList[i - 1].focus(); // go back one
    }
}

Connecting to SQL Server Express - What is my server name?

You should be able to see it in the Services panel. Look for a servicename like Sql Server (MSSQLSERVER). The name in the parentheses is your instance name.

How can I send a file document to the printer and have it print?

This is a slightly modified solution. The Process will be killed when it was idle for at least 1 second. Maybe you should add a timeof of X seconds and call the function from a separate thread.

private void SendToPrinter()
{
  ProcessStartInfo info = new ProcessStartInfo();
  info.Verb = "print";
  info.FileName = @"c:\output.pdf";
  info.CreateNoWindow = true;
  info.WindowStyle = ProcessWindowStyle.Hidden;

  Process p = new Process();
  p.StartInfo = info;
  p.Start();

  long ticks = -1;
  while (ticks != p.TotalProcessorTime.Ticks)
  {
    ticks = p.TotalProcessorTime.Ticks;
    Thread.Sleep(1000);
  }

  if (false == p.CloseMainWindow())
    p.Kill();
}

Linux command to check if a shell script is running or not

Adding to the answers above -

To use in a script, use the following :-

result=`ps aux | grep -i "myscript.sh" | grep -v "grep" | wc -l`
if [ $result -ge 1 ]
   then
        echo "script is running"
   else
        echo "script is not running"
fi

How to test if a double is an integer

Similar to SkonJeet's answer above, but the performance is better (at least in java):

Double zero = 0d;    
zero.longValue() == zero.doubleValue()

Import data into Google Colaboratory

If the Data-set size is less the 25mb, The easiest way to upload a CSV file is from your GitHub repository.

  1. Click on the data set in the repository
  2. Click on View Raw button
  3. Copy the link and store it in a variable
  4. load the variable into Pandas read_csv to get the dataframe

Example:

import pandas as pd
url = 'copied_raw_data_link'
df1 = pd.read_csv(url)
df1.head()

Set IDENTITY_INSERT ON is not working

The relevant part of the error message is

...when a column list is used...

You are not using a column list, you are using SELECT *. Use a column list instead:

SET IDENTITY_INSERT [MyDB].[dbo].[Equipment] ON 

INSERT INTO [MyDB].[dbo].[Equipment] (Col1, Col2, ...)
SELECT Col1, Col2, ... FROM [MyDBQA].[dbo].[Equipment] 

SET IDENTITY_INSERT [MyDB].[dbo].[Equipment] OFF 

How do I find duplicate values in a table in Oracle?

You don't need to even have the count in the returned columns if you don't need to know the actual number of duplicates. e.g.

SELECT column_name
FROM table
GROUP BY column_name
HAVING COUNT(*) > 1

Why java.security.NoSuchProviderException No such provider: BC?

For those who are using web servers make sure that the bcprov-jdk16-145.jar has been installed in you servers lib, for weblogic had to put the jar in:

<weblogic_jdk_home>\jre\lib\ext

When to use static methods

Static methods in java belong to the class (not an instance of it). They use no instance variables and will usually take input from the parameters, perform actions on it, then return some result. Instances methods are associated with objects and, as the name implies, can use instance variables.

How to set corner radius of imageView?

import UIKit

class BorderImage: UIImageView {

    override func awakeFromNib() {
        self.layoutIfNeeded()
        layer.cornerRadius = self.frame.height / 10.0
        layer.masksToBounds = true
    }
}

Based on @DCDC's answer

Javascript loading CSV file into an array

If your not overly worried about the size of the file then it may be easier for you to store the data as a JS object in another file and import it in your . Either synchronously or asynchronously using the syntax <script src="countries.js" async></script>. Saves on you needing to import the file and parse it.

However, i can see why you wouldnt want to rewrite 10000 entries so here's a basic object orientated csv parser i wrote.

function requestCSV(f,c){return new CSVAJAX(f,c);};
function CSVAJAX(filepath,callback)
{
    this.request = new XMLHttpRequest();
    this.request.timeout = 10000;
    this.request.open("GET", filepath, true);
    this.request.parent = this;
    this.callback = callback;
    this.request.onload = function() 
    {
        var d = this.response.split('\n'); /*1st separator*/
        var i = d.length;
        while(i--)
        {
            if(d[i] !== "")
                d[i] = d[i].split(','); /*2nd separator*/
            else
                d.splice(i,1);
        }
        this.parent.response = d;
        if(typeof this.parent.callback !== "undefined")
            this.parent.callback(d);
    };
    this.request.send();
};

Which can be used like this;

var foo = requestCSV("csvfile.csv",drawlines(lines)); 

The first parameter is the file, relative to the position of your html file in this case. The second parameter is an optional callback function the runs when the file has been completely loaded.

If your file has non-separating commmas then it wont get on with this, as it just creates 2d arrays by chopping at returns and commas. You might want to look into regexp if you need that functionality.

//THIS works 

"1234","ABCD" \n
"!@£$" \n

//Gives you 
[
 [
  1234,
  'ABCD'
 ],
 [
  '!@£$'
 ]
]

//This DOESN'T!

"12,34","AB,CD" \n
"!@,£$" \n

//Gives you

[
 [
  '"12',
  '34"',
  '"AB',
  'CD'
 ]
 [
  '"!@',
  '£$'
 ]
]

If your not used to the OO methods; they create a new object (like a number, string, array) with their own local functions and variables via a 'constructor' function. Very handy in certain situations. This function could be used to load 10 different files with different callbacks all at the same time(depending on your level of csv love! )

'negative' pattern matching in python

and(re.search("bla_bla_pattern", str_item, re.IGNORECASE) == None)

is working.

How to get MAC address of client using PHP?

To get client's device ip and mac address

{
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';

    $macCommandString   =   "arp " . $ipaddress . " | awk 'BEGIN{ i=1; } { i++; if(i==3) print $3 }'";

    $mac = exec($macCommandString);

    return ['ip' => $ipaddress, 'mac' => $mac];
}

CFNetwork SSLHandshake failed iOS 9

If your backend uses a secure connection ant you get using NSURLSession

CFNetwork SSLHandshake failed (-9801)
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9801)

you need to check your server configuration especially to get ATS version and SSL certificate Info:

Instead of just Allowing Insecure Connection by setting NSExceptionAllowsInsecureHTTPLoads = YES , instead you need to Allow Lowered Security in case your server do not meet the min requirement (v1.2) for ATS (or better to fix server side).

Allowing Lowered Security to a Single Server

<key>NSExceptionDomains</key>
<dict>
    <key>api.yourDomaine.com</key>
    <dict>
        <key>NSExceptionMinimumTLSVersion</key>
        <string>TLSv1.0</string>
        <key>NSExceptionRequiresForwardSecrecy</key>
        <false/>
    </dict>
</dict>

use openssl client to investigate certificate and get your server configuration using openssl client :

openssl s_client  -connect api.yourDomaine.com:port //(you may need to specify port or  to try with https://... or www.)

..find at the end

SSL-Session:
    Protocol  : TLSv1
    Cipher    : AES256-SHA
    Session-ID: //
    Session-ID-ctx: 
    Master-Key: //
    Key-Arg   : None
    Start Time: 1449693038
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)

App Transport Security (ATS) require Transport Layer Security (TLS) protocol version 1.2.

Requirements for Connecting Using ATS:

The requirements for a web service connection to use App Transport Security (ATS) involve the server, connection ciphers, and certificates, as follows:

Certificates must be signed with one of the following types of keys:

  • Secure Hash Algorithm 2 (SHA-2) key with a digest length of at least 256 (that is, SHA-256 or greater)

  • Elliptic-Curve Cryptography (ECC) key with a size of at least 256 bits

  • Rivest-Shamir-Adleman (RSA) key with a length of at least 2048 bits An invalid certificate results in a hard failure and no connection.

The following connection ciphers support forward secrecy (FS) and work with ATS:

TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA

Update: it turns out that openssl only provide the minimal protocol version Protocol : TLSv1 links

Can I add and remove elements of enumeration at runtime in Java

Behind the curtain, enums are POJOs with a private constructor and a bunch of public static final values of the enum's type (see here for an example). In fact, up until Java5, it was considered best-practice to build your own enumeration this way, and Java5 introduced the enum keyword as a shorthand. See the source for Enum<T> to learn more.

So it should be no problem to write your own 'TypeSafeEnum' with a public static final array of constants, that are read by the constructor or passed to it.

Also, do yourself a favor and override equals, hashCode and toString, and if possible create a values method

The question is how to use such a dynamic enumeration... you can't read the value "PI=3.14" from a file to create enum MathConstants and then go ahead and use MathConstants.PI wherever you want...

Cleanest Way to Invoke Cross-Thread Events

You can try to develop some sort of a generic component that accepts a SynchronizationContext as input and uses it to invoke the events.

Show datalist labels but submit the actual value

Note that datalist is not the same as a select. It allows users to enter a custom value that is not in the list, and it would be impossible to fetch an alternate value for such input without defining it first.

Possible ways to handle user input are to submit the entered value as is, submit a blank value, or prevent submitting. This answer handles only the first two options.

If you want to disallow user input entirely, maybe select would be a better choice.


To show only the text value of the option in the dropdown, we use the inner text for it and leave out the value attribute. The actual value that we want to send along is stored in a custom data-value attribute:

To submit this data-value we have to use an <input type="hidden">. In this case we leave out the name="answer" on the regular input and move it to the hidden copy.

<input list="suggestionList" id="answerInput">
<datalist id="suggestionList">
    <option data-value="42">The answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">

This way, when the text in the original input changes we can use javascript to check if the text also present in the datalist and fetch its data-value. That value is inserted into the hidden input and submitted.

document.querySelector('input[list]').addEventListener('input', function(e) {
    var input = e.target,
        list = input.getAttribute('list'),
        options = document.querySelectorAll('#' + list + ' option'),
        hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden'),
        inputValue = input.value;

    hiddenInput.value = inputValue;

    for(var i = 0; i < options.length; i++) {
        var option = options[i];

        if(option.innerText === inputValue) {
            hiddenInput.value = option.getAttribute('data-value');
            break;
        }
    }
});

The id answer and answer-hidden on the regular and hidden input are needed for the script to know which input belongs to which hidden version. This way it's possible to have multiple inputs on the same page with one or more datalists providing suggestions.

Any user input is submitted as is. To submit an empty value when the user input is not present in the datalist, change hiddenInput.value = inputValue to hiddenInput.value = ""


Working jsFiddle examples: plain javascript and jQuery

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

As mentioned in earlier responses, this error can occur when interacting with a SOAP service over an HTTPS connection, and an issue is identified with the connection. The issue may be on the remote end (invalid cert) or on the client (in case of missing CA or PEM files). See http://php.net/manual/en/context.ssl.php for all possible SSL context settings. In my case, setting the path to my local certificate resolved the issue:

$context = ['ssl' => [
    'local_cert' => '/path/to/pem/file',
]];

$params = [
    'soap_version' => SOAP_1_2, 
    'trace' => 1, 
    'exceptions' => 1, 
    'connection_timeout' => 180, 
    'stream_context' => stream_context_create($context), 
    'cache_wsdl' => WSDL_CACHE_NONE, // eliminate possible issue from cached wsdl
];

$client = new SoapClient('https://remoteservice/wsdl', $params);

Accessing JPEG EXIF rotation data in JavaScript on the client side

Check out a module I've written (you can use it in browser) which converts exif orientation to CSS transform: https://github.com/Sobesednik/exif2css

There is also this node program to generate JPEG fixtures with all orientations: https://github.com/Sobesednik/generate-exif-fixtures

Stretch Image to Fit 100% of Div Height and Width

You're mixing notations. It should be:

<img src="folder/file.jpg" width="200" height="200">

(note, no px). Or:

<img src="folder/file.jpg" style="width: 200px; height: 200px;">

(using the style attribute) The style attribute could be replaced with the following CSS:

#mydiv img {
    width: 200px;
    height: 200px;
}

or

#mydiv img {
    width: 100%;
    height: 100%;
}

When using SASS how can I import a file from a different directory?

You could use the -I command line switch or :load_paths option from Ruby code to add sub_directory_a to Sass's load path. So if you're running Sass from root_directory, do something like this:

sass -I sub_directory_a --watch sub_directory_b:sub_directory_b

Then you can simply use @import "common" in more_styles.scss.

How to Logout of an Application Where I Used OAuth2 To Login With Google?

this code will work to sign out

    <script>
      function signOut() 
      {
        var auth2 = gapi.auth2.getAuthInstance();
        auth2.signOut().then(function () {   
        console.log('User signed out.');   
        auth2.disconnect();   
      }); 
        auth2.disconnect();
      } 
    </script>

What is the most efficient way of finding all the factors of a number in Python?

The solution presented by @agf is great, but one can achieve ~50% faster run time for an arbitrary odd number by checking for parity. As the factors of an odd number always are odd themselves, it is not necessary to check these when dealing with odd numbers.

I've just started solving Project Euler puzzles myself. In some problems, a divisor check is called inside two nested for loops, and the performance of this function is thus essential.

Combining this fact with agf's excellent solution, I've ended up with this function:

from math import sqrt
def factors(n):
        step = 2 if n%2 else 1
        return set(reduce(list.__add__,
                    ([i, n//i] for i in range(1, int(sqrt(n))+1, step) if n % i == 0)))

However, on small numbers (~ < 100), the extra overhead from this alteration may cause the function to take longer.

I ran some tests in order to check the speed. Below is the code used. To produce the different plots, I altered the X = range(1,100,1) accordingly.

import timeit
from math import sqrt
from matplotlib.pyplot import plot, legend, show

def factors_1(n):
    step = 2 if n%2 else 1
    return set(reduce(list.__add__,
                ([i, n//i] for i in range(1, int(sqrt(n))+1, step) if n % i == 0)))

def factors_2(n):
    return set(reduce(list.__add__,
                ([i, n//i] for i in range(1, int(sqrt(n)) + 1) if n % i == 0)))

X = range(1,100000,1000)
Y = []
for i in X:
    f_1 = timeit.timeit('factors_1({})'.format(i), setup='from __main__ import factors_1', number=10000)
    f_2 = timeit.timeit('factors_2({})'.format(i), setup='from __main__ import factors_2', number=10000)
    Y.append(f_1/f_2)
plot(X,Y, label='Running time with/without parity check')
legend()
show()

X = range(1,100,1) X = range(1,100,1)

No significant difference here, but with bigger numbers, the advantage is obvious:

X = range(1,100000,1000) (only odd numbers) X = range(1,100000,1000) (only odd numbers)

X = range(2,100000,100) (only even numbers) X = range(2,100000,100) (only even numbers)

X = range(1,100000,1001) (alternating parity) X = range(1,100000,1001) (alternating parity)

Removing whitespace from strings in Java

st.replaceAll("\\s+","") removes all whitespaces and non-visible characters (e.g., tab, \n).


st.replaceAll("\\s+","") and st.replaceAll("\\s","") produce the same result.

The second regex is 20% faster than the first one, but as the number consecutive spaces increases, the first one performs better than the second one.


Assign the value to a variable, if not used directly:

st = st.replaceAll("\\s+","")

How can I add a Google search box to my website?

No need to embed! Just simply send the user to google and add the var in the search like this: (Remember, code might not work on this, so try in a browser if it doesn't.) Hope it works!

<textarea id="Blah"></textarea><button onclick="search()">Search</button>
<script>
function search() {
var Blah = document.getElementById("Blah").value;
location.replace("https://www.google.com/search?q=" + Blah + "");
}
</script>

_x000D_
_x000D_
    function search() {_x000D_
    var Blah = document.getElementById("Blah").value;_x000D_
    location.replace("https://www.google.com/search?q=" + Blah + "");_x000D_
    }
_x000D_
<textarea id="Blah"></textarea><button onclick="search()">Search</button>
_x000D_
_x000D_
_x000D_

Angular 6 Material mat-select change method removed

If you're using Reactive forms you can listen for changes to the select control like so..

this.form.get('mySelectControl').valueChanges.subscribe(value => { ... do stuff ... })

How to show particular image as thumbnail while implementing share on Facebook?

I was having the same problems and believe I have solved it. I used the link meta tag as mentioned here to point to the image I wanted, but the key is that if you do that FB won't pull any other images as choices. Also if your image is too big, you won't have any choices at all.

Here's how I fixed my site http://gnorml.com/blog/facebook-link-thumbnails/

How can I find out which server hosts LDAP on my windows domain?

AD registers Service Location (SRV) resource records in its DNS server which you can query to get the port and the hostname of the responsible LDAP server in your domain.

Just try this on the command-line:

C:\> nslookup 
> set types=all
> _ldap._tcp.<<your.AD.domain>>
_ldap._tcp.<<your.AD.domain>>  SRV service location:
      priority       = 0
      weight         = 100
      port           = 389
      svr hostname   = <<ldap.hostname>>.<<your.AD.domain>>

(provided that your nameserver is the AD nameserver which should be the case for the AD to function properly)

Please see Active Directory SRV Records and Windows 2000 DNS white paper for more information.

Trying to include a library, but keep getting 'undefined reference to' messages

The trick here is to put the library AFTER the module you are compiling. The problem is a reference thing. The linker resolves references in order, so when the library is BEFORE the module being compiled, the linker gets confused and does not think that any of the functions in the library are needed. By putting the library AFTER the module, the references to the library in the module are resolved by the linker.

How to insert programmatically a new line in an Excel cell in C#?

Actually, it is really simple.

You may edit an xml version of excel. Edit a cell to give it new line between your text, then save it. Later you may open the file in editor, then you will see a new line is represented by &#10;

Have a try....

Connecting to TCP Socket from browser using javascript

In order to achieve what you want, you would have to write two applications (in either Java or Python, for example):

  1. Bridge app that sits on the client's machine and can deal with both TCP/IP sockets and WebSockets. It will interact with the TCP/IP socket in question.

  2. Server-side app (such as a JSP/Servlet WAR) that can talk WebSockets. It includes at least one HTML page (including server-side processing code if need be) to be accessed by a browser.

It should work like this

  1. The Bridge will open a WS connection to the web app (because a server can't connect to a client).
  2. The Web app will ask the client to identify itself
  3. The bridge client sends some ID information to the server, which stores it in order to identify the bridge.
    1. The browser-viewable page connects to the WS server using JS.
    2. Repeat step 3, but for the JS-based page
    3. The JS-based page sends a command to the server, including to which bridge it must go.
    4. The server forwards the command to the bridge.
    5. The bridge opens a TCP/IP socket and interacts with it (sends a message, gets a response).
    6. The Bridge sends a response to the server through the WS
    7. The WS forwards the response to the browser-viewable page
    8. The JS processes the response and reacts accordingly
    9. Repeat until either client disconnects/unloads

Note 1: The above steps are a vast simplification and do not include information about error handling and keepAlive requests, in the event that either client disconnects prematurely or the server needs to inform clients that it is shutting down/restarting.

Note 2: Depending on your needs, it might be possible to merge these components into one if the TCP/IP socket server in question (to which the bridge talks) is on the same machine as the server app.

Why does "npm install" rewrite package-lock.json?

Update 3: As other answers point out as well, the npm ci command got introduced in npm 5.7.0 as additional way to achieve fast and reproducible builds in the CI context. See the documentation and npm blog for further information.


Update 2: The issue to update and clarify the documentation is GitHub issue #18103.


Update 1: The behaviour that was described below got fixed in npm 5.4.2: the currently intended behaviour is outlined in GitHub issue #17979.


Original answer: The behaviour of package-lock.json was changed in npm 5.1.0 as discussed in issue #16866. The behaviour that you observe is apparently intended by npm as of version 5.1.0.

That means that package.json can override package-lock.json whenever a newer version is found for a dependency in package.json. If you want to pin your dependencies effectively, you now must specify the versions without a prefix, e.g., you need to write them as 1.2.0 instead of ~1.2.0 or ^1.2.0. Then the combination of package.json and package-lock.json will yield reproducible builds. To be clear: package-lock.json alone no longer locks the root level dependencies!

Whether this design decision was good or not is arguable, there is an ongoing discussion resulting from this confusion on GitHub in issue #17979. (In my eyes it is a questionable decision; at least the name lock doesn't hold true any longer.)

One more side note: there is also a restriction for registries that don’t support immutable packages, such as when you pull packages directly from GitHub instead of npmjs.org. See this documentation of package locks for further explanation.

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

This is the solution for my old question:

I implemented my own ContextResolver in order to enable the DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY feature.

package org.lig.hadas.services.mapper;

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;

@Produces(MediaType.APPLICATION_JSON)
@Provider
public class ObjectMapperProvider implements ContextResolver<ObjectMapper>
{
   ObjectMapper mapper;

   public ObjectMapperProvider(){
       mapper = new ObjectMapper();
       mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
   }
   @Override
   public ObjectMapper getContext(Class<?> type) {
       return mapper;
   }
}

And in the web.xml I registered my package into the servlet definition...

<servlet>
    <servlet-name>...</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>...;org.lig.hadas.services.mapper</param-value>        
    </init-param>
    ...
</servlet>

... all the rest is transparently done by jersey/jackson.

how to set imageview src?

What you are looking for is probably this:

ImageView myImageView;
myImageView = mDialog.findViewById(R.id.image_id);
String src = "imageFileName"

int drawableId = this.getResources().getIdentifier(src, "drawable", context.getPackageName())
popupImageView.setImageResource(drawableId);

Let me know if this was helpful :)

Possible reason for NGINX 499 error codes

I know this is an old thread, but it exactly matches what recently happened to me and I thought I'd document it here. The setup (in Docker) is as follows:

  • nginx_proxy
  • nginx
  • php_fpm running the actual app.

The symptom was a "502 Gateway Timeout" on the application login prompt. Examination of logs found:

  • the button works via an HTTP POST to /login ... and so ...
  • nginx-proxy got the /login request, and eventually reported a timeout.
  • nginx returned a 499 response, which of course means "the host died."
  • the /login request did not appear at all(!) in the FPM server's logs!
  • there were no tracebacks or error-messages in FPM ... nada, zero, zippo, none.

It turned out that the problem was a failure to connect to the database to verify the login. But how to figure that out turned out to be pure guesswork.

The complete absence of application traceback logs ... or even a record that the request had been received by FPM ... was a complete (and, devastating ...) surprise to me. Yes, the application is supposed to log failures, but in this case it looks like the FPM worker process died with a runtime error, leading to the 499 response from nginx. Now, this obviously is a problem in our application ... somewhere. But I wanted to record the particulars of what happened for the benefit of the next folks who face something like this.

How do I evenly add space between a label and the input field regardless of length of text?

This can be accomplished using the brand new CSS display: grid (browser support)

HTML:

<div class='container'>
  <label for="dummy1">title for dummy1:</label>
  <input id="dummy1" name="dummy1" value="dummy1">
  <label for="dummy2">longer title for dummy2:</label>
  <input id="dummy2" name="dummy2" value="dummy2">
  <label for="dummy3">even longer title for dummy3:</label>
  <input id="dummy3" name="dummy3" value="dummy3">
</div>

CSS:

.container {
  display: grid;
  grid-template-columns: 1fr 3fr;
}

When using css grid, by default elements are laid out column by column then row by row. The grid-template-columns rule creates two grid columns, one which takes up 1/4 of the total horizontal space and the other which takes up 3/4 of the horizontal space. This creates the desired effect.

grid

JS-FIDDLE

Android - running a method periodically using postDelayed() call

You should set andrid:allowRetainTaskState="true" to Launch Activity in Manifest.xml. If this Activty is not Launch Activity. you should set android:launchMode="singleTask" at this activity

How can I enter latitude and longitude in Google Maps?

First is latitude, second longitude. Different than many constructors in mapbox.

Here are examples of formats that work:

  • Degrees, minutes, and seconds (DMS): 41°24'12.2"N 2°10'26.5"E
  • Degrees and decimal minutes (DMM): 41 24.2028, 2 10.4418
  • Decimal degrees (DD): 41.40338, 2.17403

Tips for formatting your coordinates

  • Use the degree symbol instead of “d”.
  • Use periods as decimals, not commas.
    • Incorrect: 41,40338, 2,17403.
    • Correct: 41.40338, 2.17403.
  • List your latitude coordinates before longitude coordinates.
  • Check that the first number in your latitude coordinate is between -90 and 90 and the first number in your longitude coordinate is between -180 and 180.

https://support.google.com/maps/answer/18539

Automatically open Chrome developer tools when new tab/new window is opened

Under the Chrome DevTools settings you enable:

Under Network -> Preserve Log Under DevTools -> Auto-open DevTools for popups

How should I pass multiple parameters to an ASP.Net Web API GET?

I know this is really old, but I wanted the same thing recently and here's what I found...

    public HttpResponseMessage Get([FromUri] string var, [FromUri] string test) {
        var retStr = new HttpResponseMessage(HttpStatusCode.OK);
        if (var.ToLower() == "getnew" && test.ToLower() == "test") {
            retStr.Content = new StringContent("Found Test", System.Text.Encoding.UTF8, "text/plain");
        } else {
            retStr.Content = new StringContent("Couldn't Find that test", System.Text.Encoding.UTF8, "text/plain");
        }

        return retStr;
    }

So now in your address/URI/...

http(s)://myURL/api/myController/?var=getnew&test=test

Result: "Found Test"


http(s)://myURL/api/myController/?var=getnew&test=anything

Result: "Couldn't Find that test"

Send SMTP email using System.Net.Mail via Exchange Online (Office 365)

Have you seen this? Sending email using Smtp.mail.microsoftonline.com

Setting the UseDefaultCredentials after setting the Credentials would be resetting your Credentials property.

Failed to load AppCompat ActionBar with unknown error in android studio

I also had this problem and it's solved as change line from res/values/styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

to

  1. <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
  2. <style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">

both solutions worked

Does static constexpr variable inside a function make sense?

In addition to given answer, it's worth noting that compiler is not required to initialize constexpr variable at compile time, knowing that the difference between constexpr and static constexpr is that to use static constexpr you ensure the variable is initialized only once.

Following code demonstrates how constexpr variable is initialized multiple times (with same value though), while static constexpr is surely initialized only once.

In addition the code compares the advantage of constexpr against const in combination with static.

#include <iostream>
#include <string>
#include <cassert>
#include <sstream>

const short const_short = 0;
constexpr short constexpr_short = 0;

// print only last 3 address value numbers
const short addr_offset = 3;

// This function will print name, value and address for given parameter
void print_properties(std::string ref_name, const short* param, short offset)
{
    // determine initial size of strings
    std::string title = "value \\ address of ";
    const size_t ref_size = ref_name.size();
    const size_t title_size = title.size();
    assert(title_size > ref_size);

    // create title (resize)
    title.append(ref_name);
    title.append(" is ");
    title.append(title_size - ref_size, ' ');

    // extract last 'offset' values from address
    std::stringstream addr;
    addr << param;
    const std::string addr_str = addr.str();
    const size_t addr_size = addr_str.size();
    assert(addr_size - offset > 0);

    // print title / ref value / address at offset
    std::cout << title << *param << " " << addr_str.substr(addr_size - offset) << std::endl;
}

// here we test initialization of const variable (runtime)
void const_value(const short counter)
{
    static short temp = const_short;
    const short const_var = ++temp;
    print_properties("const", &const_var, addr_offset);

    if (counter)
        const_value(counter - 1);
}

// here we test initialization of static variable (runtime)
void static_value(const short counter)
{
    static short temp = const_short;
    static short static_var = ++temp;
    print_properties("static", &static_var, addr_offset);

    if (counter)
        static_value(counter - 1);
}

// here we test initialization of static const variable (runtime)
void static_const_value(const short counter)
{
    static short temp = const_short;
    static const short static_var = ++temp;
    print_properties("static const", &static_var, addr_offset);

    if (counter)
        static_const_value(counter - 1);
}

// here we test initialization of constexpr variable (compile time)
void constexpr_value(const short counter)
{
    constexpr short constexpr_var = constexpr_short;
    print_properties("constexpr", &constexpr_var, addr_offset);

    if (counter)
        constexpr_value(counter - 1);
}

// here we test initialization of static constexpr variable (compile time)
void static_constexpr_value(const short counter)
{
    static constexpr short static_constexpr_var = constexpr_short;
    print_properties("static constexpr", &static_constexpr_var, addr_offset);

    if (counter)
        static_constexpr_value(counter - 1);
}

// final test call this method from main()
void test_static_const()
{
    constexpr short counter = 2;

    const_value(counter);
    std::cout << std::endl;

    static_value(counter);
    std::cout << std::endl;

    static_const_value(counter);
    std::cout << std::endl;

    constexpr_value(counter);
    std::cout << std::endl;

    static_constexpr_value(counter);
    std::cout << std::endl;
}

Possible program output:

value \ address of const is               1 564
value \ address of const is               2 3D4
value \ address of const is               3 244

value \ address of static is              1 C58
value \ address of static is              1 C58
value \ address of static is              1 C58

value \ address of static const is        1 C64
value \ address of static const is        1 C64
value \ address of static const is        1 C64

value \ address of constexpr is           0 564
value \ address of constexpr is           0 3D4
value \ address of constexpr is           0 244

value \ address of static constexpr is    0 EA0
value \ address of static constexpr is    0 EA0
value \ address of static constexpr is    0 EA0

As you can see yourself constexpr is initilized multiple times (address is not the same) while static keyword ensures that initialization is performed only once.

Ignore files that have already been committed to a Git repository

To untrack a file that has already been added/initialized to your repository, ie stop tracking the file but not delete it from your system use: git rm --cached filename

Getting CheckBoxList Item values

Try to use this.

        for (int i = 0; i < chBoxListTables.Items.Count; i++)
        {
            if (chBoxListTables.Items[i].Selected)
            {
                string str = chBoxListTables.Items[i].Text;
                MessageBox.Show(str);

                var itemValue = chBoxListTables.Items[i].Value;
            }
        }

The "V" should be in CAPS in Value.

Here is another code example used in WinForm app and runs properly.

        var chBoxList= new CheckedListBox();
        chBoxList.Items.Add(new ListItem("One", "1"));
        chBoxList.Items.Add(new ListItem("Two", "2"));
        chBoxList.SetItemChecked(1, true);

        var checkedItems = chBoxList.CheckedItems;
        var chkText = ((ListItem)checkedItems[0]).Text;
        var chkValue = ((ListItem)checkedItems[0]).Value;
        MessageBox.Show(chkText);
        MessageBox.Show(chkValue);

How to run a shell script on a Unix console or Mac terminal?

The file extension .command is assigned to Terminal.app. Double-clicking on any .command file will execute it.

Is not an enclosing class Java

What I would suggest is not converting the non-static class to a static class because in that case, your inner class can't access the non-static members of outer class.

Example :

class Outer
{
    class Inner
    {
        //...
    }
}

So, in such case, you can do something like:

Outer o = new Outer();
Outer.Inner obj = o.new Inner();

How to create a pulse effect using -webkit-animation - outward rings

You have a lot of unnecessary keyframes. Don't think of keyframes as individual frames, think of them as "steps" in your animation and the computer fills in the frames between the keyframes.

Here is a solution that cleans up a lot of code and makes the animation start from the center:

.gps_ring {
    border: 3px solid #999;
    -webkit-border-radius: 30px;
    height: 18px;
    width: 18px;
    position: absolute;
    left:20px;
    top:214px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    opacity: 0.0
}
@-webkit-keyframes pulsate {
    0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
    50% {opacity: 1.0;}
    100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}

You can see it in action here: http://jsfiddle.net/Fy8vD/

HTML5 Email input pattern attribute

I had this exact problem with HTML5s email input, using Alwin Keslers answer above I added the regex to the HTML5 email input so the user must have .something at the end.

<input type="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" />

How do I use ROW_NUMBER()?

SQL Row_Number() function is to sort and assign an order number to data rows in related record set. So it is used to number rows, for example to identify the top 10 rows which have the highest order amount or identify the order of each customer which is the highest amount, etc.

If you want to sort the dataset and number each row by seperating them into categories we use Row_Number() with Partition By clause. For example, sorting orders of each customer within itself where the dataset contains all orders, etc.

SELECT
    SalesOrderNumber,
    CustomerId,
    SubTotal,
    ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY SubTotal DESC) rn
FROM Sales.SalesOrderHeader

But as I understand you want to calculate the number of rows of grouped by a column. To visualize the requirement, if you want to see the count of all orders of the related customer as a seperate column besides order info, you can use COUNT() aggregation function with Partition By clause

For example,

SELECT
    SalesOrderNumber,
    CustomerId,
    COUNT(*) OVER (PARTITION BY CustomerId) CustomerOrderCount
FROM Sales.SalesOrderHeader

Embed Youtube video inside an Android app

Embedding the YouTube player in Android is very simple & it hardly takes you 10 minutes,

1) Enable YouTube API from Google API console
2) Download YouTube player Jar file
3) Start using it in Your app

Here are the detailed steps http://www.feelzdroid.com/2017/01/embed-youtube-video-player-android-app-example.html.

Just refer it & if you face any problem, let me know, ill help you

PHP regular expressions: No ending delimiter '^' found in

PHP regex strings need delimiters. Try:

$numpattern="/^([0-9]+)$/";

Also, note that you have a lower case o, not a zero. In addition, if you're just validating, you don't need the capturing group, and can simplify the regex to /^\d+$/.

Example: http://ideone.com/Ec3zh

See also: PHP - Delimiters

Uncaught TypeError : cannot read property 'replace' of undefined In Grid

In my case, I was using a View that I´ve converted to partial view and I forgot to remove the template from "@section scripts". Removing the section block, solved my problem. This is because the sections aren´t rendered in partial views.

What is the most elegant way to check if all values in a boolean array are true?

public static boolean areAllTrue(boolean[] array)
{
    for(boolean b : array) if(!b) return false;
    return true;
}

Onclick event to remove default value in a text input field

Use onclick="this.value=''":

<input name="Name" value="Enter Your Name" onclick="this.value=''">

ReCaptcha API v2 Styling

I am just adding this kind of solution / quick fix so it won't get lost in case of a broken link.

Link to this solution "Want to add link How to resize the Google noCAPTCHA reCAPTCHA | The Geek Goddess" was provided by Vikram Singh Saini and simply outlines that you could use inline CSS to enforce framing of the iframe.

// Scale the frame using inline CSS
 <div class="g-recaptcha" data-theme="light" 
 data-sitekey="XXXXXXXXXXXXX" 

 style="transform:scale(0.77);
 -webkit-transform:scale(0.77);
 transform-origin:0 0;
  -webkit-transform-origin:0 0;

 ">
</div> 

// Scale the images using a stylesheet
<style>
#rc-imageselect, .g-recaptcha {
  transform:scale(0.77);
  -webkit-transform:scale(0.77);
  transform-origin:0 0;
  -webkit-transform-origin:0 0;
}
</style>

How to fluently build JSON in Java?

See the Java EE 7 Json specification. This is the right way:

String json = Json.createObjectBuilder()
            .add("key1", "value1")
            .add("key2", "value2")
            .build()
            .toString();

Copy/Paste from Excel to a web page

In response to the answer by Tatu I have created a quick jsFiddle for showcasing his solution:

http://jsfiddle.net/duwood/sTX7y/

HTML

<p>Paste excel data here:</p>  
<textarea name="excel_data" style="width:250px;height:150px;"></textarea><br>
<input type="button" onclick="javascript:generateTable()" value="Genereate Table"/>
<br><br>
    <p>Table data will appear below</p>
<hr>
<div id="excel_table"></div>

JS

function generateTable() {
    var data = $('textarea[name=excel_data]').val();
    console.log(data);
    var rows = data.split("\n");

    var table = $('<table />');

    for(var y in rows) {
    var cells = rows[y].split("\t");
    var row = $('<tr />');
    for(var x in cells) {
        row.append('<td>'+cells[x]+'</td>');
    }
    table.append(row);
}

// Insert into DOM
$('#excel_table').html(table);
}

Refresh certain row of UITableView based on Int in Swift

For a soft impact animation solution:

Swift 3:

let indexPath = IndexPath(item: row, section: 0)
tableView.reloadRows(at: [indexPath], with: .fade)

Swift 2.x:

let indexPath = NSIndexPath(forRow: row, inSection: 0)
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

This is another way to protect the app from crashing:

Swift 3:

let indexPath = IndexPath(item: row, section: 0)
if let visibleIndexPaths = tableView.indexPathsForVisibleRows?.index(of: indexPath as IndexPath) {
    if visibleIndexPaths != NSNotFound {
        tableView.reloadRows(at: [indexPath], with: .fade)
    }
}

Swift 2.x:

let indexPath = NSIndexPath(forRow: row, inSection: 0)
if let visibleIndexPaths = tableView.indexPathsForVisibleRows?.indexOf(indexPath) {
   if visibleIndexPaths != NSNotFound {
      tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
   }
}

What is the difference between ( for... in ) and ( for... of ) statements?

The for-in loop

for-in loop is used to traverse through enumerable properties of a collection, in an arbitrary order. A collection is a container type object whose items can be using an index or a key.

_x000D_
_x000D_
var myObject = {a: 1, b: 2, c: 3};_x000D_
var myArray = [1, 2, 3];_x000D_
var myString = "123";_x000D_
_x000D_
console.log( myObject[ 'a' ], myArray[ 1 ], myString[ 2 ] );
_x000D_
_x000D_
_x000D_

for-in loop extracts the enumerable properties (keys) of a collection all at once and iterates over it one at a time. An enumerable property is the property of a collection that can appear in for-in loop.

By default, all properties of an Array and Object appear in for-in loop. However, we can use Object.defineProperty method to manually configure the properties of a collection.

_x000D_
_x000D_
var myObject = {a: 1, b: 2, c: 3};_x000D_
var myArray = [1, 2, 3];_x000D_
_x000D_
Object.defineProperty( myObject, 'd', { value: 4, enumerable: false } );_x000D_
Object.defineProperty( myArray, 3, { value: 4, enumerable: false } );_x000D_
_x000D_
for( var i in myObject ){ console.log( 'myObject:i =>', i ); }_x000D_
for( var i in myArray ){ console.log( 'myArray:i  =>', i ); }
_x000D_
_x000D_
_x000D_

In the above example, the property d of the myObject and the index 3 of myArray does not appear in for-in loop because they are configured with enumerable: false.

There are few issues with for-in loops. In the case of Arrays, for-in loop will also consider methods added on the array using myArray.someMethod = f syntax, however, myArray.length remains 4.

The for-of loop

It is a misconception that for-of loop iterate over the values of a collection. for-of loop iterates over an Iterable object. An iterable is an object that has the method with the name Symbol.iterator directly on it one on one of its prototypes.

Symbol.iterator method should return an Iterator. An iterator is an object which has a next method. This method when called return value and done properties.

When we iterate an iterable object using for-of loop, the Symbol.iterator the method will be called once get an iterator object. For every iteration of for-of loop, next method of this iterator object will be called until done returned by the next() call returns false. The value received by the for-of loop for every iteration if the value property returned by the next() call.

_x000D_
_x000D_
var myObject = { a: 1, b: 2, c: 3, d: 4 };_x000D_
_x000D_
// make `myObject` iterable by adding `Symbol.iterator` function directlty on it_x000D_
myObject[ Symbol.iterator ] = function(){_x000D_
  console.log( `LOG: called 'Symbol.iterator' method` );_x000D_
  var _myObject = this; // `this` points to `myObject`_x000D_
  _x000D_
  // return an iterator object_x000D_
  return {_x000D_
    keys: Object.keys( _myObject ), _x000D_
    current: 0,_x000D_
    next: function() {_x000D_
      console.log( `LOG: called 'next' method: index ${ this.current }` );_x000D_
      _x000D_
      if( this.current === this.keys.length ){_x000D_
        return { done: true, value: null }; // Here, `value` is ignored by `for-of` loop_x000D_
      } else {_x000D_
        return { done: false, value: _myObject[ this.keys[ this.current++ ] ] };_x000D_
      }_x000D_
    }_x000D_
  };_x000D_
}_x000D_
_x000D_
// use `for-of` loop on `myObject` iterable_x000D_
for( let value of myObject ) {_x000D_
  console.log( 'myObject: value => ', value );_x000D_
}
_x000D_
_x000D_
_x000D_

The for-of loop is new in ES6 and so are the Iterable and Iterables. The Array constructor type has Symbol.iterator method on its prototype. The Object constructor sadly doesn't have it but Object.keys(), Object.values() and Object.entries() methods return an iterable (you can use console.dir(obj) to check prototype methods). The benefit of the for-of loop is that any object can be made iterable, even your custom Dog and Animal classes.

The easy way to make an object iterable is by implementing ES6 Generator instead of custom iterator implementation.

Unlike for-in, for-of loop can wait for an async task to complete in each iteration. This is achieved using await keyword after for statement documentation.

Another great thing about for-of loop is that it has Unicode support. According to ES6 specifications, strings are stored with UTF-16 encoding. Hence, each character can take either 16-bit or 32-bit. Traditionally, strings were stored with UCS-2 encoding which has supports for characters that can be stored within 16 bits only.

Hence, String.length returns number of 16-bit blocks in a string. Modern characters like an Emoji character takes 32 bits. Hence, this character would return length of 2. for-in loop iterates over 16-bit blocks and returns the wrong index. However, for-of loop iterates over the individual character based on UTF-16 specifications.

_x000D_
_x000D_
var emoji = "";_x000D_
_x000D_
console.log( 'emoji.length', emoji.length );_x000D_
_x000D_
for( var index in emoji ){ console.log( 'for-in: emoji.character', emoji[index] ); }_x000D_
for( var character of emoji ){ console.log( 'for-of: emoji.character', character ); }
_x000D_
_x000D_
_x000D_

Wireshark vs Firebug vs Fiddler - pros and cons?

Wireshark, Firebug, Fiddler all do similar things - capture network traffic.

  • Wireshark captures any kind of network packet. It can capture packet details below TCP/IP (HTTP is at the top). It does have filters to reduce the noise it captures.

  • Firebug tracks each request the browser page makes and captures the associated headers and the time taken for each stage of the request (DNS, receiving, sending, ...).

  • Fiddler works as an HTTP/HTTPS proxy. It captures every HTTP request the computer makes and records everything associated with it. It does allow things like converting post variables to a table form and editing/replaying requests. It doesn't, by default, capture localhost traffic in IE, see the FAQ for the workaround.

how do you view macro code in access?

In Access 2010, go to the Create tab on the ribbon. Click Macro. An "Action Catalog" panel should appear on the right side of the screen. Underneath, there's a section titled "In This Database." Clicking on one of the macro names should display its code.

Drawing an SVG file on a HTML5 canvas

As Simon says above, using drawImage shouldn't work. But, using the canvg library and:

var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
ctx.drawSvg(SVG_XML_OR_PATH_TO_SVG, dx, dy, dw, dh);

This comes from the link Simon provides above, which has a number of other suggestions and points out that you want to either link to, or download canvg.js and rgbcolor.js. These allow you to manipulate and load an SVG, either via URL or using inline SVG code between svg tags, within JavaScript functions.

What is the purpose of Order By 1 in SQL select statement?

This is useful when you use set based operators e.g. union

select cola
  from tablea
union
select colb
  from tableb
order by 1;

Eclipse: Set maximum line length for auto formatting?

Comments have their own line length setting at the bottom of the setting page java->code style->formatter-> Edit... ->comments

Polymorphism vs Overriding vs Overloading

I think guys your are mixing concepts. Polymorphism is the ability of an object to behave differently at run time. For achieving this, you need two requisites:

  1. Late Binding
  2. Inheritance.

Having said that overloading means something different to overriding depending on the language you are using. For example in Java does not exist overriding but overloading. Overloaded methods with different signature to its base class are available in the subclass. Otherwise they would be overridden (please, see that I mean now the fact of there is no way to call your base class method from outside the object).

However in C++ that is not so. Any overloaded method, independently whether the signature is the same or not (diffrrent amount, different type) is as well overridden. That is to day, the base class' method is no longer available in the subclass when being called from outside the subclass object, obviously.

So the answer is when talking about Java use overloading. In any other language may be different as it happens in c++

How to determine CPU and memory consumption from inside a process?

QNX

Since this is like a "wikipage of code" I want to add some code from the QNX Knowledge base (note: this is not my work, but I checked it and it works fine on my system):

How to get CPU usage in %: http://www.qnx.com/support/knowledgebase.html?id=50130000000P9b5

#include <atomic.h>
#include <libc.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/iofunc.h>
#include <sys/neutrino.h>
#include <sys/resmgr.h>
#include <sys/syspage.h>
#include <unistd.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/debug.h>
#include <sys/procfs.h>
#include <sys/syspage.h>
#include <sys/neutrino.h>
#include <sys/time.h>
#include <time.h>
#include <fcntl.h>
#include <devctl.h>
#include <errno.h>

#define MAX_CPUS 32

static float Loads[MAX_CPUS];
static _uint64 LastSutime[MAX_CPUS];
static _uint64 LastNsec[MAX_CPUS];
static int ProcFd = -1;
static int NumCpus = 0;


int find_ncpus(void) {
    return NumCpus;
}

int get_cpu(int cpu) {
    int ret;
    ret = (int)Loads[ cpu % MAX_CPUS ];
    ret = max(0,ret);
    ret = min(100,ret);
    return( ret );
}

static _uint64 nanoseconds( void ) {
    _uint64 sec, usec;
    struct timeval tval;
    gettimeofday( &tval, NULL );
    sec = tval.tv_sec;
    usec = tval.tv_usec;
    return( ( ( sec * 1000000 ) + usec ) * 1000 );
}

int sample_cpus( void ) {
    int i;
    debug_thread_t debug_data;
    _uint64 current_nsec, sutime_delta, time_delta;
    memset( &debug_data, 0, sizeof( debug_data ) );
    
    for( i=0; i<NumCpus; i++ ) {
        /* Get the sutime of the idle thread #i+1 */
        debug_data.tid = i + 1;
        devctl( ProcFd, DCMD_PROC_TIDSTATUS,
        &debug_data, sizeof( debug_data ), NULL );
        /* Get the current time */
        current_nsec = nanoseconds();
        /* Get the deltas between now and the last samples */
        sutime_delta = debug_data.sutime - LastSutime[i];
        time_delta = current_nsec - LastNsec[i];
        /* Figure out the load */
        Loads[i] = 100.0 - ( (float)( sutime_delta * 100 ) / (float)time_delta );
        /* Flat out strange rounding issues. */
        if( Loads[i] < 0 ) {
            Loads[i] = 0;
        }
        /* Keep these for reference in the next cycle */
        LastNsec[i] = current_nsec;
        LastSutime[i] = debug_data.sutime;
    }
    return EOK;
}

int init_cpu( void ) {
    int i;
    debug_thread_t debug_data;
    memset( &debug_data, 0, sizeof( debug_data ) );
/* Open a connection to proc to talk over.*/
    ProcFd = open( "/proc/1/as", O_RDONLY );
    if( ProcFd == -1 ) {
        fprintf( stderr, "pload: Unable to access procnto: %s\n",strerror( errno ) );
        fflush( stderr );
        return -1;
    }
    i = fcntl(ProcFd,F_GETFD);
    if(i != -1){
        i |= FD_CLOEXEC;
        if(fcntl(ProcFd,F_SETFD,i) != -1){
            /* Grab this value */
            NumCpus = _syspage_ptr->num_cpu;
            /* Get a starting point for the comparisons */
            for( i=0; i<NumCpus; i++ ) {
                /*
                * the sutime of idle thread is how much
                * time that thread has been using, we can compare this
                * against how much time has passed to get an idea of the
                * load on the system.
                */
                debug_data.tid = i + 1;
                devctl( ProcFd, DCMD_PROC_TIDSTATUS, &debug_data, sizeof( debug_data ), NULL );
                LastSutime[i] = debug_data.sutime;
                LastNsec[i] = nanoseconds();
            }
            return(EOK);
        }
    }
    close(ProcFd);
    return(-1);
}

void close_cpu(void){
    if(ProcFd != -1){
        close(ProcFd);
        ProcFd = -1;
    }
}

int main(int argc, char* argv[]){
    int i,j;
    init_cpu();
    printf("System has: %d CPUs\n", NumCpus);
    for(i=0; i<20; i++) {
        sample_cpus();
        for(j=0; j<NumCpus;j++)
        printf("CPU #%d: %f\n", j, Loads[j]);
        sleep(1);
    }
    close_cpu();
}

How to get the free (!) memory: http://www.qnx.com/support/knowledgebase.html?id=50130000000mlbx

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <err.h>
#include <sys/stat.h>
#include <sys/types.h>

int main( int argc, char *argv[] ){
    struct stat statbuf;
    paddr_t freemem;
    stat( "/proc", &statbuf );
    freemem = (paddr_t)statbuf.st_size;
    printf( "Free memory: %d bytes\n", freemem );
    printf( "Free memory: %d KB\n", freemem / 1024 );
    printf( "Free memory: %d MB\n", freemem / ( 1024 * 1024 ) );
    return 0;
} 

Why is MySQL InnoDB insert so slow?

The default value for InnoDB is actually pretty bad. InnoDB is very RAM dependent, you might find better result if you tweak the settings. Here's a guide that I used InnoDB optimization basic

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

here is a example to get video-Id only .i.e (6oL687G0Iso) from the whole URL in swift

let str = "https://www.youtube.com/watch?v=6oL687G0Iso&list=PLKmzL8Ib1gsT-5LN3V2h2H14wyBZTyvVL&index=2"
var arrSaprate = str.componentsSeparatedByString("v=")
let start = arrSaprate[1]
let rangeOfID = Range(start: start.startIndex,end:start.startIndex.advancedBy(11))
let substring = start[rangeOfID]
print(substring)

Reference to a non-shared member requires an object reference occurs when calling public sub

You either have to make the method Shared or use an instance of the class General:

Dim gen = New General()
gen.updateDynamics(get_prospect.dynamicsID)

or

General.updateDynamics(get_prospect.dynamicsID)

Public Shared Sub updateDynamics(dynID As Int32)
    ' ... '
End Sub

Shared(VB.NET)

Animate background image change with jQuery

<style type="text/css">
    #homepage_outter { position:relative; width:100%; height:100%;}
    #homepage_inner { position:absolute; top:0; left:0; z-index:10; width:100%; height:100%;}
    #homepage_underlay { position:absolute; top:0; left:0; z-index:9; width:800px; height:500px; display:none;}
</style>

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

        $('a').hover(function () {

            $('#homepage_underlay').fadeOut('slow', function () {

                $('#homepage_underlay').css({ 'background-image': 'url("http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/nutrition_background.jpg")' });

                $('#homepage_underlay').fadeIn('slow');
            });

        }, function () {

            $('#homepage_underlay').fadeOut('slow', function () {

                $('#homepage_underlay').css({ 'background-image': 'url("http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/default_background.jpg")' });

                $('#homepage_underlay').fadeIn('slow');
            });


        });

    });

</script>


<body>
<div id="homepage_outter">
    <div id="homepage_inner">
        <a href="#" id="run">run</a>
    </div>
    <div id="homepage_underlay"></div>
</div>

Prevent Sequelize from outputting SQL to the console on execution of query?

Based on this discussion, I built this config.json that works perfectly:

{
  "development": {
    "username": "root",
    "password": null,
    "logging" : false,
    "database": "posts_db_dev",
    "host": "127.0.0.1",
    "dialect": "mysql",
    "operatorsAliases": false 
  }
}

From Now() to Current_timestamp in Postgresql

Use an interval instead of an integer:

SELECT *
FROM table
WHERE auth_user.lastactivity > CURRENT_TIMESTAMP - INTERVAL '100 days'

How to sort an object array by date property?

Thanks for those brilliant answers on top. I have thought a slightly complicated answer. Just for those who want to compare different answers.

const data = [
    '2-2018', '1-2018',
    '3-2018', '4-2018',
    '1-2019', '2-2019',
    '3-2019', '4-2019',
    '1-2020', '3-2020',
    '4-2020', '1-2021'
]

let eachYearUniqueMonth = data.reduce((acc, elem) => {
    const uniqueDate = Number(elem.match(/(\d+)\-(\d+)/)[1])
    const uniqueYear = Number(elem.match(/(\d+)\-(\d+)/)[2])


    if (acc[uniqueYear] === undefined) {
        acc[uniqueYear] = []        
    } else{    
       if (acc[uniqueYear]  && !acc[uniqueYear].includes(uniqueDate)) {
          acc[uniqueYear].push(uniqueDate)
      }
    }

    return acc;
}, {})


let group = Object.keys(eachYearUniqueMonth).reduce((acc,uniqueYear)=>{
    eachYearUniqueMonth[uniqueYear].forEach(uniqueMonth=>{
    acc.push(`${uniqueYear}-${uniqueMonth}`)
  })
  
  return acc;
},[])

console.log(group);   //["2018-1", "2018-3", "2018-4", "2019-2", "2019-3", "2019-4", "2020-3", "2020-4"]


Substring in excel

In Excel, the substring function is called MID function, and indexOf is called FIND for case-sensitive location and SEARCH function for non-case-sensitive location. For the first portion of your text parsing the LEFT function may also be useful.

See all the text functions here: Text Functions (reference).

Full worksheet function reference lists available at:

    Excel functions (by category)
    Excel functions (alphabetical)

Remote debugging a Java application

Steps:

  1. Start your remote java application with debugging options as said in above post.
  2. Configure Eclipse for remote debugging by specifying host and port.
  3. Start remote debugging in Eclipse and wait for connection to succeed.
  4. Setup breakpoint and debug.
  5. If you want to debug from start of application use suspend=y , this will keep remote application suspended until you connect from eclipse.

See Step by Step guide on Java remote debugging for full details.

typedef fixed length array

To use the array type properly as a function argument or template parameter, make a struct instead of a typedef, then add an operator[] to the struct so you can keep the array like functionality like so:

typedef struct type24 {
  char& operator[](int i) { return byte[i]; }
  char byte[3];
} type24;

type24 x;
x[2] = 'r';
char c = x[2];

How to round float numbers in javascript?

Number((6.688689).toFixed(1)); // 6.7

var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

Use toFixed() function.

(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

How to echo with different colors in the Windows command line

An alternative is to use NodeJS.

Here is an example:

const os = require('os');
const colors = require('colors');

console.log("Operative System:".green,os.type(),os.release());
console.log("Uptime:".blue,os.uptime());

And this is the result:

enter image description here

Running Python on Windows for Node.js dependencies

I had the same issue and none of these answers did help. In my case PYTHON variable was set correctly. However python was installed too deep, i.e. has too long path. So, I did the following:

  1. reinstalled python to c:\python
  2. set environmental variable PYTHON to C:\python\python.exe

And that’s it!

Recyclerview and handling different type of row inflation

It is quite tricky but that much hard, just copy the below code and you are done

package com.yuvi.sample.main;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;


import com.yuvi.sample.R;

import java.util.List;

/**
 * Created by yubraj on 6/17/15.
 */

public class NavDrawerAdapter extends RecyclerView.Adapter<NavDrawerAdapter.MainViewHolder> {
    List<MainOption> mainOptionlist;
    Context context;
    private static final int TYPE_PROFILE = 1;
    private static final int TYPE_OPTION_MENU = 2;
    private int selectedPos = 0;
    public NavDrawerAdapter(Context context){
        this.mainOptionlist = MainOption.getDrawableDataList();
        this.context = context;
    }

    @Override
    public int getItemViewType(int position) {
        return (position == 0? TYPE_PROFILE : TYPE_OPTION_MENU);
    }

    @Override
    public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType){
            case TYPE_PROFILE:
                return new ProfileViewHolder(LayoutInflater.from(context).inflate(R.layout.row_profile, parent, false));
            case TYPE_OPTION_MENU:
                return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.row_nav_drawer, parent, false));
        }
        return null;
    }

    @Override
    public void onBindViewHolder(MainViewHolder holder, int position) {
        if(holder.getItemViewType() == TYPE_PROFILE){
            ProfileViewHolder mholder = (ProfileViewHolder) holder;
            setUpProfileView(mholder);
        }
        else {
            MyViewHolder mHolder = (MyViewHolder) holder;
            MainOption mo = mainOptionlist.get(position);
            mHolder.tv_title.setText(mo.title);
            mHolder.iv_icon.setImageResource(mo.icon);
            mHolder.itemView.setSelected(selectedPos == position);
        }
    }

    private void setUpProfileView(ProfileViewHolder mholder) {

    }

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




public class MyViewHolder extends MainViewHolder{
    TextView tv_title;
    ImageView iv_icon;

    public MyViewHolder(View v){
        super(v);
        this.tv_title = (TextView) v.findViewById(R.id.tv_title);
        this.iv_icon = (ImageView) v.findViewById(R.id.iv_icon);
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Redraw the old selection and the new
                notifyItemChanged(selectedPos);
                selectedPos = getLayoutPosition();
                notifyItemChanged(selectedPos);
            }
        });
    }
}
    public class ProfileViewHolder extends MainViewHolder{
        TextView tv_name, login;
        ImageView iv_profile;

        public ProfileViewHolder(View v){
            super(v);
            this.tv_name = (TextView) v.findViewById(R.id.tv_profile);
            this.iv_profile = (ImageView) v.findViewById(R.id.iv_profile);
            this.login = (TextView) v.findViewById(R.id.tv_login);
        }
    }

    public void trace(String tag, String message){
        Log.d(tag , message);
    }
    public class MainViewHolder extends  RecyclerView.ViewHolder {
        public MainViewHolder(View v) {
            super(v);
        }
    }


}

enjoy !!!!

CodeIgniter: How to use WHERE clause and OR clause

Active record method or_where is to be used:

$this->db->select("*")
->from("table_name")
->where("first", $first)
->or_where("second", $second);

Renaming branches remotely in Git

You can create a new branch based on old-name branch. Just like this, then delete the old branch, over!!! enter image description here

Remove Datepicker Function dynamically

You can try the enable/disable methods instead of using the option method:

$("#txtSearch").datepicker("enable");
$("#txtSearch").datepicker("disable");

This disables the entire textbox. So may be you can use datepicker.destroy() instead:

$(document).ready(function() {
    $("#ddlSearchType").change(function() {
        if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date") {
            $("#txtSearch").datepicker();
        }
        else {
            $("#txtSearch").datepicker("destroy");
        }
    }).change();
});

Demo here.

The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

You will also get this error message when you accidentally forget to define a setter for a property. For example:

public class Building
{
    public string Description { get; }
}

var query = 
    from building in context.Buildings
    select new
    {
        Desc = building.Description
    };
int count = query.ToList();

The call to ToList will give the same error message. This one is a very subtle error and very hard to detect.

jQuery.css() - marginLeft vs. margin-left?

jQuery's underlying code passes these strings to the DOM, which allows you to specify the CSS property name or the DOM property name in a very similar way:

element.style.marginLeft = "10px";

is equivalent to:

element.style["margin-left"] = "10px";

Why has jQuery allowed for marginLeft as well as margin-left? It seems pointless and uses more resources to be converted to the CSS margin-left?

jQuery's not really doing anything special. It may alter or proxy some strings that you pass to .css(), but in reality there was no work put in from the jQuery team to allow either string to be passed. There's no extra resources used because the DOM does the work.

curl_exec() always returns false

In my case I need to set VERIFYHOST and VERIFYPEER to false, like this:

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

before the call to curl_exec($ch).

Because i am working between two development environments with self-assigned certificates. With valid certificates there is no need to set VERIFYHOST and VERIFYPEER to false because the curl_exec($ch) method will work and return the response you expect.

How do I remove trailing whitespace using a regular expression?

Regex to find trailing and leading whitespaces:

^[ \t]+|[ \t]+$

JavaScript: IIF like statement

'<option value="' + col + '"'+ (col === "screwdriver" ? " selected " : "") +'>Very roomy</option>';

Single Page Application: advantages and disadvantages

I would like to make the case for SPA being best for Data Driven Applications. gmail, of course is all about data and thus a good candidate for a SPA.

But if your page is mostly for display, for example, a terms of service page, then a SPA is completely overkill.

I think the sweet spot is having a site with a mixture of both SPA and static/MVC style pages, depending on the particular page.

For example, on one site I am building, the user lands on a standard MVC index page. But then when they go to the actual application, then it calls up the SPA. Another advantage to this is that the load-time of the SPA is not on the home page, but on the app page. The load time being on the home page could be a distraction to first time site users.

This scenario is a little bit like using Flash. After a few years of experience, the number of Flash only sites dropped to near zero due to the load factor. But as a page component, it is still in use.

add id to dynamically created <div>

Use Jquery for append the value for creating dynamically

eg:

var user_image1='<img src="{@user_image}" class="img-thumbnail" alt="Thumbnail Image" 
style="width:125px; height:125px">';

$("#userphoto").append(user_image1.replace("{@user_image}","http://127.0.0.1:50075/webhdfs/v1/PATH/"+user_image+"?op=OPEN")); 

HTML :

<div id="userphoto">

Angular ui-grid dynamically calculate height of the grid

I use ui-grid - v3.0.0-rc.20 because a scrolling issue is fixed when you go full height of container. Use the ui.grid.autoResize module will dynamically auto resize the grid to fit your data. To calculate the height of your grid use the function below. The ui-if is optional to wait until your data is set before rendering.

_x000D_
_x000D_
angular.module('app',['ui.grid','ui.grid.autoResize']).controller('AppController', ['uiGridConstants', function(uiGridConstants) {_x000D_
    ..._x000D_
    _x000D_
    $scope.gridData = {_x000D_
      rowHeight: 30, // set row height, this is default size_x000D_
      ..._x000D_
    };_x000D_
  _x000D_
    ..._x000D_
_x000D_
    $scope.getTableHeight = function() {_x000D_
       var rowHeight = 30; // your row height_x000D_
       var headerHeight = 30; // your header height_x000D_
       return {_x000D_
          height: ($scope.gridData.data.length * rowHeight + headerHeight) + "px"_x000D_
       };_x000D_
    };_x000D_
      _x000D_
    ...
_x000D_
<div ui-if="gridData.data.length>0" id="grid1" ui-grid="gridData" class="grid" ui-grid-auto-resize ng-style="getTableHeight()"></div>
_x000D_
_x000D_
_x000D_

jquery .on() method with load event

To run function onLoad

jQuery(window).on("load", function(){
    ..code..
});

To run code onDOMContentLoaded (also called onready)

jQuery(document).ready(function(){
    ..code..
});

or the recommended shorthand for onready

jQuery(function($){
    ..code.. ($ is the jQuery object)
});

onready fires when the document has loaded

onload fires when the document and all the associated content, like the images on the page have loaded.

Git fast forward VS no fast forward merge

When we work on development environment and merge our code to staging/production branch then Git no fast forward can be a better option. Usually when we work in development branch for a single feature we tend to have multiple commits. Tracking changes with multiple commits can be inconvenient later on. If we merge with staging/production branch using Git no fast forward then it will have only 1 commit. Now anytime we want to revert the feature, just revert that commit. Life is easy.

OOP vs Functional Programming vs Procedural

These paradigms don't have to be mutually exclusive. If you look at python, it supports functions and classes, but at the same time, everything is an object, including functions. You can mix and match functional/oop/procedural style all in one piece of code.

What I mean is, in functional languages (at least in Haskell, the only one I studied) there are no statements! functions are only allowed one expression inside them!! BUT, functions are first-class citizens, you can pass them around as parameters, along with a bunch of other abilities. They can do powerful things with few lines of code.

While in a procedural language like C, the only way you can pass functions around is by using function pointers, and that alone doesn't enable many powerful tasks.

In python, a function is a first-class citizen, but it can contain arbitrary number of statements. So you can have a function that contains procedural code, but you can pass it around just like functional languages.

Same goes for OOP. A language like Java doesn't allow you to write procedures/functions outside of a class. The only way to pass a function around is to wrap it in an object that implements that function, and then pass that object around.

In Python, you don't have this restriction.

Fail to create Android virtual Device, "No system image installed for this Target"

In order to create an Android Wear emulator you need to follow the instructions below:

  1. If your version of Android SDK Tools is lower than 22.6, you must update

  2. Under Android 4.4.2, select Android Wear ARM EABI v7a System Image and install it.

  3. Under Extras, ensure that you have the latest version of the Android Support Library. If an update is available, select Android Support Library. If you're using Android Studio, also select Android Support Repository.

Below is the snapshot of what it should look like:

Screenshot1

Then you must check the following in order to create a Wearable AVD:

  1. For the Device, select Android Wear Square or Android Wear Round.

  2. For the Target, select Android 4.4.2 - API Level 19 (or higher, otherwise corresponding system image will not show up.).

  3. For the CPU/ABI, select Android Wear ARM (armeabi-v7a).

  4. For the Skin, select AndroidWearSquare or AndroidWearRound.

  5. Leave all other options set to their defaults and click OK.

Screenshot2

Then you are good to go. For more information you can always refer to the developer site.

Get Time from Getdate()

You will be able to get the time using below query:

select left((convert(time(0), GETDATE ())),5)

JSON string to JS object

Some modern browsers have support for parsing JSON into a native object:

var var1 = '{"cols": [{"i" ....... 66}]}';
var result = JSON.parse(var1);

For the browsers that don't support it, you can download json2.js from json.org for safe parsing of a JSON object. The script will check for native JSON support and if it doesn't exist, provide the JSON global object instead. If the faster, native object is available it will just exit the script leaving it intact. You must, however, provide valid JSON or it will throw an error — you can check the validity of your JSON with http://jslint.com or http://jsonlint.com.

Creating Dynamic button with click event in JavaScript

Wow you're close. Edits in comments:

_x000D_
_x000D_
function add(type) {_x000D_
  //Create an input type dynamically.   _x000D_
  var element = document.createElement("input");_x000D_
  //Assign different attributes to the element. _x000D_
  element.type = type;_x000D_
  element.value = type; // Really? You want the default value to be the type string?_x000D_
  element.name = type; // And the name too?_x000D_
  element.onclick = function() { // Note this is a function_x000D_
    alert("blabla");_x000D_
  };_x000D_
_x000D_
  var foo = document.getElementById("fooBar");_x000D_
  //Append the element in page (in span).  _x000D_
  foo.appendChild(element);_x000D_
}_x000D_
document.getElementById("btnAdd").onclick = function() {_x000D_
  add("text");_x000D_
};
_x000D_
<input type="button" id="btnAdd" value="Add Text Field">_x000D_
<p id="fooBar">Fields:</p>
_x000D_
_x000D_
_x000D_

Now, instead of setting the onclick property of the element, which is called "DOM0 event handling," you might consider using addEventListener (on most browsers) or attachEvent (on all but very recent Microsoft browsers) — you'll have to detect and handle both cases — as that form, called "DOM2 event handling," has more flexibility. But if you don't need multiple handlers and such, the old DOM0 way works fine.


Separately from the above: You might consider using a good JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others. They smooth over browsers differences like the addEventListener / attachEvent thing, provide useful utility features, and various other things. Obviously there's nothing a library can do that you can't do without one, as the libraries are just JavaScript code. But when you use a good library with a broad user base, you get the benefit of a huge amount of work already done by other people dealing with those browsers differences, etc.

How do I push amended commit to the remote Git repository?

If you know nobody has pulled your un-amended commit, use the --force-with-lease option of git push.

In TortoiseGit, you can do the same thing under "Push..." options "Force: May discard" and checking "known changes".

Force (May discard known changes) allows the remote repository to accept a safer non-fast-forward push. This can cause the remote repository to lose commits; use it with care. This can prevent from losing unknown changes from other people on the remote. It checks if the server branch points to the same commit as the remote-tracking branch (known changes). If yes, a force push will be performed. Otherwise it will be rejected. Since git does not have remote-tracking tags, tags cannot be overwritten using this option.

Named placeholders in string formatting

Another example of Apache Common StringSubstitutor for simple named placeholder.

String template = "Welcome to {theWorld}. My name is {myName}.";

Map<String, String> values = new HashMap<>();
values.put("theWorld", "Stackoverflow");
values.put("myName", "Thanos");

String message = StringSubstitutor.replace(template, values, "{", "}");

System.out.println(message);

// Welcome to Stackoverflow. My name is Thanos.

installing requests module in python 2.7 windows

If you want to install requests directly you can use the "-m" (module) option available to python.

python.exe -m pip install requests

You can do this directly in PowerShell, though you may need to use the full python path (eg. C:\Python27\python.exe) instead of just python.exe.

As mentioned in the comments, if you have added Python to your path you can simply do:

python -m pip install requests

How to change navbar/container width? Bootstrap 3

Container widths will drop down to 940 pixels for viewports less than 992 pixels. If you really don’t want containers larger than 940 pixels wide, then go to the Bootstrap customize page, and set @container-lg-desktop to either @container-desktop or hard-coded 940px.

How to automatically update your docker containers, if base-images are updated

I'm not going into the whole question of whether or not you want unattended updates in production (I think not). I'm just leaving this here for reference in case anybody finds it useful. Update all your docker images to the latest version with the following command in your terminal:

# docker images | awk '(NR>1) && ($2!~/none/) {print $1":"$2}' | xargs -L1 docker pull

How to replace values at specific indexes of a python list?

A little slower, but readable I think:

>>> s, l, m
([5, 4, 3, 2, 1, 0], [0, 1, 3, 5], [0, 0, 0, 0])
>>> d = dict(zip(l, m))
>>> d  #dict is better then using two list i think
{0: 0, 1: 0, 3: 0, 5: 0}
>>> [d.get(i, j) for i, j in enumerate(s)]
[0, 0, 3, 0, 1, 0]

Declaring variables in Excel Cells

I also just found out how to do this with the Excel Name Manager (Formulas > Defined Names Section > Name Manager).

You can define a variable that doesn't have to "live" within a cell and then you can use it in formulas.

Excel Name Manager

XPath to select multiple tags

One correct answer is:

/a/b/*[self::c or self::d or self::e]

Do note that this

a/b/*[local-name()='c' or local-name()='d' or local-name()='e']

is both too-long and incorrect. This XPath expression will select nodes like:

OhMy:c

NotWanted:d 

QuiteDifferent:e

How do I write a method to calculate total cost for all items in an array?

In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like

float total;
total += theItem.getUnits() * theItem.getPrice();

total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.

Remove rows not .isin('X')

You can use numpy.logical_not to invert the boolean array returned by isin:

In [63]: s = pd.Series(np.arange(10.0))

In [64]: x = range(4, 8)

In [65]: mask = np.logical_not(s.isin(x))

In [66]: s[mask]
Out[66]: 
0    0
1    1
2    2
3    3
8    8
9    9

As given in the comment by Wes McKinney you can also use

s[~s.isin(x)]

RSA encryption and decryption in Python

Watch out using Crypto!!! It is a wonderful library but it has an issue in python3.8 'cause from the library time was removed the attribute clock(). To fix it just modify the source in /usr/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.pyline 77 changing t = time.clock() int t = time.perf_counter()

Insert content into iFrame

This should do what you want:

$("#iframe").ready(function() {
    var body = $("#iframe").contents().find("body");
    body.append('Test');
});

Check this JSFiddle for working demo.

Edit: You can of course do it one line style:

$("#iframe").contents().find("body").append('Test');

What are the differences between stateless and stateful systems, and how do they impact parallelism?

A stateful server keeps state between connections. A stateless server does not.

So, when you send a request to a stateful server, it may create some kind of connection object that tracks what information you request. When you send another request, that request operates on the state from the previous request. So you can send a request to "open" something. And then you can send a request to "close" it later. In-between the two requests, that thing is "open" on the server.

When you send a request to a stateless server, it does not create any objects that track information regarding your requests. If you "open" something on the server, the server retains no information at all that you have something open. A "close" operation would make no sense, since there would be nothing to close.

HTTP and NFS are stateless protocols. Each request stands on its own.

Sometimes cookies are used to add some state to a stateless protocol. In HTTP (web pages), the server sends you a cookie and then the browser holds the state, only to send it back to the server on a subsequent request.

SMB is a stateful protocol. A client can open a file on the server, and the server may deny other clients access to that file until the client closes it.

Android: long click on a button -> perform actions

Change return false; to return true; in longClickListener

You long click the button, if it returns true then it does the work. If it returns false then it does it's work and also calls the short click and then the onClick also works.

Where can I get a virtual machine online?

koding.com has a free VM running Ubuntu. The specs are pretty good, 1 gig memory for example. They have a terminal online you can access through their website, or use SSH. The VM will go to sleep approximately 20 minutes after you log out. The reason is to discourage users from running live production code on the VM. The VM resides behind a proxy. Running web servers that only speak HTTP (port 80) should work just fine, but I think you'll get into a lot of trouble whenever you want to work directly with other ports. Many mind-like alternatives offer similar setups. Good luck!

I had the same idea as you but given all restrictions everybody keep imposing everywhere I feel that I must go out and pay for a VPS.

jQuery or JavaScript auto click

First i tried with this sample code:

$(document).ready(function(){ 
     $('#upload-file').click(); 
});

It didn't work for me. Then after, tried with this

$(document).ready(function(){ 
     $('#upload-file')[0].click(); 
});

No change. At last, tried with this

$(document).ready(function(){ 
     $('#upload-file')[0].click(function(){
     }); 
});

Solved my problem. Helpful for anyone.

SQL Server SELECT into existing table

select *
into existing table database..existingtable
from database..othertables....

If you have used select * into tablename from other tablenames already, next time, to append, you say select * into existing table tablename from other tablenames

How to pass optional parameters while omitting some other optional parameters?

As specified in the documentation, use undefined:

export interface INotificationService {
    error(message: string, title?: string, autoHideAfter? : number);
}

class X {
    error(message: string, title?: string, autoHideAfter?: number) {
        console.log(message, title, autoHideAfter);
    }
}

new X().error("hi there", undefined, 1000);

Playground link.

How to set default vim colorscheme

Copy downloaded color schemes to ~/.vim/colors/Your_Color_Scheme.

Then write

colo Your_Color_Scheme

or

colorscheme Your_Color_Scheme

into your ~/.vimrc.

See this link for holokai

Create a dictionary with list comprehension

In fact, you don't even need to iterate over the iterable if it already comprehends some kind of mapping, the dict constructor doing it graciously for you:

>>> ts = [(1, 2), (3, 4), (5, 6)]
>>> dict(ts)
{1: 2, 3: 4, 5: 6}
>>> gen = ((i, i+1) for i in range(1, 6, 2))
>>> gen
<generator object <genexpr> at 0xb7201c5c>
>>> dict(gen)
{1: 2, 3: 4, 5: 6}

git recover deleted file where no commit was made after the delete

Since you're doing a git checkout ., it looks like you are trying to restore your branch back to the last commit state.

You can achieve this with a git reset HEAD --hard

Warning

Doing this may remove all your latest modifications and unstage your modifications, e.g., you can lose work. It may be what you want, but check out the docs to make sure.

Equivalent of "continue" in Ruby

Use next, it will bypass that condition and rest of the code will work. Below i have provided the Full script and out put

class TestBreak
  puts " Enter the nmber"
  no= gets.to_i
  for i in 1..no
    if(i==5)
      next
    else 
      puts i
    end
  end
end

obj=TestBreak.new()

Output: Enter the nmber 10

1 2 3 4 6 7 8 9 10

Counting no of rows returned by a select query

The syntax error is just due to a missing alias for the subquery:

select COUNT(*) from
(
select m.Company_id
from Monitor as m
    inner join Monitor_Request as mr on mr.Company_ID=m.Company_id
    group by m.Company_id
    having COUNT(m.Monitor_id)>=5)  mySubQuery  /* Alias */

How to get "wc -l" to print just the number of lines without file name?

Comparison of Techniques

I had a similar issue attempting to get a character count without the leading whitespace provided by wc, which led me to this page. After trying out the answers here, the following are the results from my personal testing on Mac (BSD Bash). Again, this is for character count; for line count you'd do wc -l. echo -n omits the trailing line break.

FOO="bar"
echo -n "$FOO" | wc -c                          # "       3"    (x)
echo -n "$FOO" | wc -c | bc                     # "3"           (v)
echo -n "$FOO" | wc -c | tr -d ' '              # "3"           (v)
echo -n "$FOO" | wc -c | awk '{print $1}'       # "3"           (v)
echo -n "$FOO" | wc -c | cut -d ' ' -f1         # "" for -f < 8 (x)
echo -n "$FOO" | wc -c | cut -d ' ' -f8         # "3"           (v)
echo -n "$FOO" | wc -c | perl -pe 's/^\s+//'    # "3"           (v)
echo -n "$FOO" | wc -c | grep -ch '^'           # "1"           (x)
echo $( printf '%s' "$FOO" | wc -c )            # "3"           (v)

I wouldn't rely on the cut -f* method in general since it requires that you know the exact number of leading spaces that any given output may have. And the grep one works for counting lines, but not characters.

bc is the most concise, and awk and perl seem a bit overkill, but they should all be relatively fast and portable enough.

Also note that some of these can be adapted to trim surrounding whitespace from general strings, as well (along with echo `echo $FOO`, another neat trick).

Getting a list of all subdirectories in the current directory

If you need a recursive solution that will find all the subdirectories in the subdirectories, use walk as proposed before.

If you only need the current directory's child directories, combine os.listdir with os.path.isdir

Evaluate empty or null JSTL c tags

if you check only null or empty then you can use the with default option for this: <c:out default="var1 is empty or null." value="${var1}"/>

How to print float to n decimal places including trailing 0s?

The cleanest way in modern Python >=3.6, is to use an f-string with string formatting:

>>> var = 1.6
>>> f"{var:.15f}"
'1.600000000000000'

SSH to Vagrant box in Windows?

very simple, once you install Vagrant manager and virtual box, try installing cygwin on windows but while installing cygwin, make sure to select the SSH package, VIM package which will enable your system to login to your VM from cygwin after spinning up your machine through vagrant.

How to convert Blob to File in JavaScript

My modern variant:

function blob2file(blobData) {
  const fd = new FormData();
  fd.set('a', blobData);
  return fd.get('a');
}

How do I enable index downloads in Eclipse for Maven dependency search?

  1. In Eclipse, click on Windows > Preferences, and then choose Maven in the left side.
  2. Check the box "Download repository index updates on startup".
    • Optionally, check the boxes Download Artifact Sources and Download Artifact JavaDoc.
  3. Click OK. The warning won't appear anymore.
  4. Restart Eclipse.

http://i.imgur.com/IJ2T3vc.png

CSS: Hover one element, effect for multiple elements?

This is not difficult to achieve, but you need to use the javascript onmouseover function. Pseudoscript:

<div class="section ">

<div class="image"><img src="myImage.jpg" onmouseover=".layer {border: 1px solid black;} .image {border: 1px solid black;}" /></div>

<div class="layer">Lorem Ipsum</div>

</div>

Use your own colors. You can also reference javascript functions in the mouseover command.

Remove last commit from remote git repository

Be careful that this will create an "alternate reality" for people who have already fetch/pulled/cloned from the remote repository. But in fact, it's quite simple:

git reset HEAD^ # remove commit locally
git push origin +HEAD # force-push the new HEAD commit

If you want to still have it in your local repository and only remove it from the remote, then you can use:

git push origin +HEAD^:<name of your branch, most likely 'master'>

PHP check if file is an image

Using file extension and getimagesize function to detect if uploaded file has right format is just the entry level check and it can simply bypass by uploading a file with true extension and some byte of an image header but wrong content.

for being secure and safe you may make thumbnail/resize (even with original image sizes) the uploaded picture and save this version instead the uploaded one. Also its possible to get uploaded file content and search it for special character like <?php to find the file is image or not.

Setting std=c99 flag in GCC

How about alias gcc99= gcc -std=c99?

How to return result of a SELECT inside a function in PostgreSQL?

Use RETURN QUERY:

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt   text   -- also visible as OUT parameter inside function
               , cnt   bigint
               , ratio bigint) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt
        , count(*) AS cnt                 -- column alias only visible inside
        , (count(*) * 100) / _max_tokens  -- I added brackets
   FROM  (
      SELECT t.txt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      LIMIT  _max_tokens
      ) t
   GROUP  BY t.txt
   ORDER  BY cnt DESC;                    -- potential ambiguity 
END
$func$  LANGUAGE plpgsql;

Call:

SELECT * FROM word_frequency(123);

Explanation:

  • It is much more practical to explicitly define the return type than simply declaring it as record. This way you don't have to provide a column definition list with every function call. RETURNS TABLE is one way to do that. There are others. Data types of OUT parameters have to match exactly what is returned by the query.

  • Choose names for OUT parameters carefully. They are visible in the function body almost anywhere. Table-qualify columns of the same name to avoid conflicts or unexpected results. I did that for all columns in my example.

    But note the potential naming conflict between the OUT parameter cnt and the column alias of the same name. In this particular case (RETURN QUERY SELECT ...) Postgres uses the column alias over the OUT parameter either way. This can be ambiguous in other contexts, though. There are various ways to avoid any confusion:

    1. Use the ordinal position of the item in the SELECT list: ORDER BY 2 DESC. Example:
    2. Repeat the expression ORDER BY count(*).
    3. (Not applicable here.) Set the configuration parameter plpgsql.variable_conflict or use the special command #variable_conflict error | use_variable | use_column in the function. See:
  • Don't use "text" or "count" as column names. Both are legal to use in Postgres, but "count" is a reserved word in standard SQL and a basic function name and "text" is a basic data type. Can lead to confusing errors. I use txt and cnt in my examples.

  • Added a missing ; and corrected a syntax error in the header. (_max_tokens int), not (int maxTokens) - type after name.

  • While working with integer division, it's better to multiply first and divide later, to minimize the rounding error. Even better: work with numeric (or a floating point type). See below.

Alternative

This is what I think your query should actually look like (calculating a relative share per token):

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt            text
               , abs_cnt        bigint
               , relative_share numeric) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt, t.cnt
        , round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2)  -- AS relative_share
   FROM  (
      SELECT t.txt, count(*) AS cnt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      GROUP  BY t.txt
      ORDER  BY cnt DESC
      LIMIT  _max_tokens
      ) t
   ORDER  BY t.cnt DESC;
END
$func$  LANGUAGE plpgsql;

The expression sum(t.cnt) OVER () is a window function. You could use a CTE instead of the subquery - pretty, but a subquery is typically cheaper in simple cases like this one.

A final explicit RETURN statement is not required (but allowed) when working with OUT parameters or RETURNS TABLE (which makes implicit use of OUT parameters).

round() with two parameters only works for numeric types. count() in the subquery produces a bigint result and a sum() over this bigint produces a numeric result, thus we deal with a numeric number automatically and everything just falls into place.

SQL Server Creating a temp table for this query

Like this. Make sure you drop the temp table (at the end of the code block, after you're done with it) or it will error on subsequent runs.

SELECT  
    tblMEP_Sites.Name AS SiteName, 
    convert(varchar(10),BillingMonth ,101) AS BillingMonth, 
    SUM(Consumption) AS Consumption
INTO 
    #MyTempTable
FROM 
    tblMEP_Projects
    JOIN tblMEP_Sites
        ON tblMEP_Projects.ID = tblMEP_Sites.ProjectID
    JOIN tblMEP_Meters
        ON tblMEP_Meters.SiteID = tblMEP_Sites.ID
    JOIN tblMEP_MonthlyData
        ON tblMEP_MonthlyData.MeterID = tblMEP_Meters.ID
    JOIN tblMEP_CustomerAccounts
        ON tblMEP_CustomerAccounts.ID = tblMEP_Meters.CustomerAccountID
    JOIN tblMEP_UtilityCompanies
        ON tblMEP_UtilityCompanies.ID = tblMEP_CustomerAccounts.UtilityCompanyID
    JOIN tblMEP_MeterTypes
        ON tblMEP_UtilityCompanies.UtilityTypeID = tblMEP_MeterTypes.ID
WHERE 
    tblMEP_Projects.ID = @ProjectID
    AND tblMEP_MonthlyData.BillingMonth Between @StartDate AND @EndDate
    AND tbLMEP_MeterTypes.ID = @MeterTypeID
GROUP BY 
    BillingMonth, tblMEP_Sites.Name

DROP TABLE #MyTempTable

Difference between 'cls' and 'self' in Python classes?

Instead of accepting a self parameter, class methods take a cls parameter that points to the class—and not the object instance—when the method is called. Since the class method only has access to this cls argument, it can’t modify object instance state. That would require access to self . However, class methods can still modify class state that applies across all instances of the class.

-Python Tricks

Print values for multiple variables on the same line from within a for-loop

Try out cat and sprintf in your for loop.

eg.

cat(sprintf("\"%f\" \"%f\"\n", df$r, df$interest))

See here

Angular 2 router.navigate

_x000D_
_x000D_
import { ActivatedRoute } from '@angular/router';_x000D_
_x000D_
export class ClassName {_x000D_
  _x000D_
  private router = ActivatedRoute;_x000D_
_x000D_
    constructor(r: ActivatedRoute) {_x000D_
        this.router =r;_x000D_
    }_x000D_
_x000D_
onSuccess() {_x000D_
     this.router.navigate(['/user_invitation'],_x000D_
         {queryParams: {email: loginEmail, code: userCode}});_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
Get this values:_x000D_
---------------_x000D_
_x000D_
ngOnInit() {_x000D_
    this.route_x000D_
        .queryParams_x000D_
        .subscribe(params => {_x000D_
            let code = params['code'];_x000D_
            let userEmail = params['email'];_x000D_
        });_x000D_
}
_x000D_
_x000D_
_x000D_

Ref: https://angular.io/docs/ts/latest/api/router/index/NavigationExtras-interface.html

Transmitting newline character "\n"

Try to replace the \n with %0A just like you have spaces replaced with %20.