Programs & Examples On #Measure

How do I measure request and response times at once using cURL?

Here is the answer:

curl -X POST -d @file server:port -w %{time_connect}:%{time_starttransfer}:%{time_total}

All of the variables used with -w can be found in man curl.

How to measure elapsed time in Python?

If you want to be able to time functions conveniently, you can use a simple decorator:

def timing_decorator(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        original_return_val = func(*args, **kwargs)
        end = time.time()
        print("time elapsed in ", func.__name__, ": ", end - start, sep='')
        return original_return_val

    return wrapper

You can use it on a function that you want to time like this:

@timing_decorator
def function_to_time():
    time.sleep(1)

Then any time you call function_to_time, it will print how long it took and the name of the function being timed.

How to retrieve the dimensions of a view?

Use the View's post method like this

post(new Runnable() {   
    @Override
    public void run() {
        Log.d(TAG, "width " + MyView.this.getMeasuredWidth());
        }
    });

How to measure time taken between lines of code in python?

I always prefer to check time in hours, minutes and seconds (%H:%M:%S) format:

from datetime import datetime
start = datetime.now()
# your code
end = datetime.now()
time_taken = end - start
print('Time: ',time_taken) 

output:

Time:  0:00:00.000019

How to make responsive table

To make a responsive table, you can make the width of each td 100% and insert a related heading in the td on mobile browsers (that are less 768px width.)

Here is a website that demonstrates this technique: http://www.quizexpo.com/list-of-banks-in-india/

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

Personally, to deal with empty responses, I use in my Integration Tests the MockMvcResponse object like this :

MockMvcResponse response = RestAssuredMockMvc.given()
                .webAppContextSetup(webApplicationContext)
                .when()
                .get("/v1/ticket");

    assertThat(response.mockHttpServletResponse().getStatus()).isEqualTo(HttpStatus.NO_CONTENT.value());

and in my controller I return empty response in a specific case like this :

return ResponseEntity.noContent().build();

Windows service on Local Computer started and then stopped error

I have found it very handy to convert your existing windows service to a console by simply changing your program with the following. With this change you can run the program by debugging in visual studio or running the executable normally. But it will also work as a windows service. I also made a blog post about it

program.cs

class Program
{
    static void Main()
    {
        var program = new YOUR_PROGRAM();
        if (Environment.UserInteractive)
        {
            program.Start();
        }
        else
        {
            ServiceBase.Run(new ServiceBase[]
            {
                program
            });
        }
    }
}

YOUR_PROGRAM.cs

[RunInstallerAttribute(true)]
public class YOUR_PROGRAM : ServiceBase
{
    public YOUR_PROGRAM()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        Start();
    }

    protected override void OnStop()
    {
        //Stop Logic Here
    }

    public void Start()
    {
        //Start Logic here
    }
}

Why does ASP.NET webforms need the Runat="Server" attribute?

I usually don't like to guess, but I'm going to on this one...

If you remember Microsoft's .NET marketing hype back in the day (2001?), it was hard to tell what .NET even was. Was it a server? a programming platform? a language? something new entirely? Given the ads, it was ambiguously anything you wanted it to be - it just solved any problem you might have.

So, my guess is there was a hidden grand vision that ASP.NET code could run anywhere - server side OR client side, in a copy of Internet Explorer tied to the .NET runtime. runat="server" is just a vestigial remnant, left behind because it's client-side equivalent never made it to production.

Remember those weird ads?

Related: Article from The Register with some .NET history.

Replace new line/return with space using regex

Your regex is good altough I would replace it with the empty string

String resultString = subjectString.replaceAll("[\t\n\r]", "");

You expect a space between "text." and "And" right?

I get that space when I try the regex by copying your sample

"This is my text. "

So all is well here. Maybe if you just replace it with the empty string it will work. I don't know why you replace it with \s. And the alternation | is not necessary in a character class.

How to send json data in the Http request using NSURLRequest

Most of you already know this by now, but I am posting this, just incase, some of you are still struggling with JSON in iOS6+.

In iOS6 and later, we have the NSJSONSerialization Class that is fast and has no dependency on including "outside" libraries.

NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[resultStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]; 

This is the way iOS6 and later can now parse JSON efficiently.The use of SBJson is also pre-ARC implementation and brings with it those issues too if you are working in an ARC environment.

I hope this helps!

Convert a string to a double - is this possible?

Use doubleval(). But be very careful about using decimals in financial transactions, and validate that user input very carefully.

How do I create a MessageBox in C#?

Code summary:

using System.Windows.Forms;

...

MessageBox.Show( "hello world" );

Also (as per this other stack post): In Visual Studio expand the project in Solution Tree, right click on References, Add Reference, Select System.Windows.Forms on Framework tab. This will get the MessageBox working in conjunction with the using System.Windows.Forms reference from above.

Batch not-equal (inequality) operator

NEQ is usually used for numbers and == is typically used for string comparison.

I cannot find any documentation that mentions a specific and equivalent inequality operand for string comparison (in place of NEQ). The solution using IF NOT == seems the most sound approach. I can't immediately think of a circumstance in which the evaluation of operations in a batch file would cause an issue or unexpected behavior when applying the IF NOT == comparison method to strings.

I wish I could offer insight into how the two functions behave differently on a lower level - would disassembling separate batch files (that use NEQ and IF NOT ==) offer any clues in terms of which (unofficially documented) native API calls conhost.exe is utilizing?

Setting up Eclipse with JRE Path

Add the following to the eclipse.ini :

-vm


Java_Home_Variable\bin\javaw.exe

In my Case its

-vm

H:\usr\java\jdk1.6.0_16\bin\javaw.exe

How to install Ruby 2.1.4 on Ubuntu 14.04

Use RVM (Ruby Version Manager) to install and manage any versions of Ruby. You can have multiple versions of Ruby installed on the machine and you can easily select the one you want.

To install RVM type into terminal:

\curl -sSL https://get.rvm.io | bash -s stable

And let it work. After that you will have RVM along with Ruby installed.

Source: RVM Site

Efficient way of having a function only execute once in a loop

You can also use one of the standard library functools.lru_cache or functools.cache decorators in front of the function:

from functools import lru_cache

@lru_cache def expensive_function(): return None

https://docs.python.org/3/library/functools.html

Set element focus in angular way

I like to avoid DOM lookups, watches, and global emitters whenever possible, so I use a more direct approach. Use a directive to assign a simple function that focuses on the directive element. Then call that function wherever needed within the scope of the controller.

Here's a simplified approach for attaching it to scope. See the full snippet for handling controller-as syntax.

Directive:

app.directive('inputFocusFunction', function () {
    'use strict';
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            scope[attr.inputFocusFunction] = function () {
                element[0].focus();
            };
        }
    };
});

and in html:

<input input-focus-function="focusOnSaveInput" ng-model="saveName">
<button ng-click="focusOnSaveInput()">Focus</button>

or in the controller:

$scope.focusOnSaveInput();

_x000D_
_x000D_
angular.module('app', [])_x000D_
  .directive('inputFocusFunction', function() {_x000D_
    'use strict';_x000D_
    return {_x000D_
      restrict: 'A',_x000D_
      link: function(scope, element, attr) {_x000D_
        // Parse the attribute to accomodate assignment to an object_x000D_
        var parseObj = attr.inputFocusFunction.split('.');_x000D_
        var attachTo = scope;_x000D_
        for (var i = 0; i < parseObj.length - 1; i++) {_x000D_
          attachTo = attachTo[parseObj[i]];_x000D_
        }_x000D_
        // assign it to a function that focuses on the decorated element_x000D_
        attachTo[parseObj[parseObj.length - 1]] = function() {_x000D_
          element[0].focus();_x000D_
        };_x000D_
      }_x000D_
    };_x000D_
  })_x000D_
  .controller('main', function() {});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>_x000D_
_x000D_
<body ng-app="app" ng-controller="main as vm">_x000D_
  <input input-focus-function="vm.focusOnSaveInput" ng-model="saveName">_x000D_
  <button ng-click="vm.focusOnSaveInput()">Focus</button>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Edited to provide more explanation about the reason for this approach and to extend the code snippet for controller-as use.

Checkout remote branch using git svn

Standard Subversion layout

Create a git clone of that includes your Subversion trunk, tags, and branches with

git svn clone http://svn.example.com/project -T trunk -b branches -t tags

The --stdlayout option is a nice shortcut if your Subversion repository uses the typical structure:

git svn clone http://svn.example.com/project --stdlayout

Make your git repository ignore everything the subversion repo does:

git svn show-ignore >> .git/info/exclude

You should now be able to see all the Subversion branches on the git side:

git branch -r

Say the name of the branch in Subversion is waldo. On the git side, you'd run

git checkout -b waldo-svn remotes/waldo

The -svn suffix is to avoid warnings of the form

warning: refname 'waldo' is ambiguous.

To update the git branch waldo-svn, run

git checkout waldo-svn
git svn rebase

Starting from a trunk-only checkout

To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config to contain

[svn-remote "svn-mybranch"]
        url = http://svn.example.com/project/branches/mybranch
        fetch = :refs/remotes/mybranch

You'll need to develop the habit of running

git svn fetch --fetch-all

to update all of what git svn thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run

git checkout -b mybranch-svn remotes/mybranch

For the branches from which you intend to git svn dcommit, keep their histories linear!


Further information

You may also be interested in reading an answer to a related question.

How to customize message box

Here is the code needed to create your own message box:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyStuff
{
    public class MyLabel : Label
    {
        public static Label Set(string Text = "", Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
        {
            Label l = new Label();
            l.Text = Text;
            l.Font = (Font == null) ? new Font("Calibri", 12) : Font;
            l.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
            l.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
            l.AutoSize = true;
            return l;
        }
    }
    public class MyButton : Button
    {
        public static Button Set(string Text = "", int Width = 102, int Height = 30, Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
        {
            Button b = new Button();
            b.Text = Text;
            b.Width = Width;
            b.Height = Height;
            b.Font = (Font == null) ? new Font("Calibri", 12) : Font;
            b.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
            b.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
            b.UseVisualStyleBackColor = (b.BackColor == SystemColors.Control);
            return b;
        }
    }
    public class MyImage : PictureBox
    {
        public static PictureBox Set(string ImagePath = null, int Width = 60, int Height = 60)
        {
            PictureBox i = new PictureBox();
            if (ImagePath != null)
            {
                i.BackgroundImageLayout = ImageLayout.Zoom;
                i.Location = new Point(9, 9);
                i.Margin = new Padding(3, 3, 2, 3);
                i.Size = new Size(Width, Height);
                i.TabStop = false;
                i.Visible = true;
                i.BackgroundImage = Image.FromFile(ImagePath);
            }
            else
            {
                i.Visible = true;
                i.Size = new Size(0, 0);
            }
            return i;
        }
    }
    public partial class MyMessageBox : Form
    {
        private MyMessageBox()
        {
            this.panText = new FlowLayoutPanel();
            this.panButtons = new FlowLayoutPanel();
            this.SuspendLayout();
            // 
            // panText
            // 
            this.panText.Parent = this;
            this.panText.AutoScroll = true;
            this.panText.AutoSize = true;
            this.panText.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            //this.panText.Location = new Point(90, 90);
            this.panText.Margin = new Padding(0);
            this.panText.MaximumSize = new Size(500, 300);
            this.panText.MinimumSize = new Size(108, 50);
            this.panText.Size = new Size(108, 50);
            // 
            // panButtons
            // 
            this.panButtons.AutoSize = true;
            this.panButtons.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            this.panButtons.FlowDirection = FlowDirection.RightToLeft;
            this.panButtons.Location = new Point(89, 89);
            this.panButtons.Margin = new Padding(0);
            this.panButtons.MaximumSize = new Size(580, 150);
            this.panButtons.MinimumSize = new Size(108, 0);
            this.panButtons.Size = new Size(108, 35);
            // 
            // MyMessageBox
            // 
            this.AutoScaleDimensions = new SizeF(8F, 19F);
            this.AutoScaleMode = AutoScaleMode.Font;
            this.ClientSize = new Size(206, 133);
            this.Controls.Add(this.panButtons);
            this.Controls.Add(this.panText);
            this.Font = new Font("Calibri", 12F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.Margin = new Padding(4);
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.MinimumSize = new Size(168, 132);
            this.Name = "MyMessageBox";
            this.ShowIcon = false;
            this.ShowInTaskbar = false;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.ResumeLayout(false);
            this.PerformLayout();
        }
        public static string Show(Label Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
        {
            List<Label> Labels = new List<Label>();
            Labels.Add(Label);
            return Show(Labels, Title, Buttons, Image);
        }
        public static string Show(string Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
        {
            List<Label> Labels = new List<Label>();
            Labels.Add(MyLabel.Set(Label));
            return Show(Labels, Title, Buttons, Image);
        }
        public static string Show(List<Label> Labels = null, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
        {
            if (Labels == null) Labels = new List<Label>();
            if (Labels.Count == 0) Labels.Add(MyLabel.Set(""));
            if (Buttons == null) Buttons = new List<Button>();
            if (Buttons.Count == 0) Buttons.Add(MyButton.Set("OK"));
            List<Button> buttons = new List<Button>(Buttons);
            buttons.Reverse();

            int ImageWidth = 0;
            int ImageHeight = 0;
            int LabelWidth = 0;
            int LabelHeight = 0;
            int ButtonWidth = 0;
            int ButtonHeight = 0;
            int TotalWidth = 0;
            int TotalHeight = 0;

            MyMessageBox mb = new MyMessageBox();

            mb.Text = Title;

            //Image
            if (Image != null)
            {
                mb.Controls.Add(Image);
                Image.MaximumSize = new Size(150, 300);
                ImageWidth = Image.Width + Image.Margin.Horizontal;
                ImageHeight = Image.Height + Image.Margin.Vertical;
            }

            //Labels
            List<int> il = new List<int>();
            mb.panText.Location = new Point(9 + ImageWidth, 9);
            foreach (Label l in Labels)
            {
                mb.panText.Controls.Add(l);
                l.Location = new Point(200, 50);
                l.MaximumSize = new Size(480, 2000);
                il.Add(l.Width);
            }
            int mw = Labels.Max(x => x.Width);
            il.ToString();
            Labels.ForEach(l => l.MinimumSize = new Size(Labels.Max(x => x.Width), 1));
            mb.panText.Height = Labels.Sum(l => l.Height);
            mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
            mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
            LabelWidth = mb.panText.Width;
            LabelHeight = mb.panText.Height;

            //Buttons
            foreach (Button b in buttons)
            {
                mb.panButtons.Controls.Add(b);
                b.Location = new Point(3, 3);
                b.TabIndex = Buttons.FindIndex(i => i.Text == b.Text);
                b.Click += new EventHandler(mb.Button_Click);
            }
            ButtonWidth = mb.panButtons.Width;
            ButtonHeight = mb.panButtons.Height;

            //Set Widths
            if (ButtonWidth > ImageWidth + LabelWidth)
            {
                Labels.ForEach(l => l.MinimumSize = new Size(ButtonWidth - ImageWidth - mb.ScrollBarWidth(Labels), 1));
                mb.panText.Height = Labels.Sum(l => l.Height);
                mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
                mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
                LabelWidth = mb.panText.Width;
                LabelHeight = mb.panText.Height;
            }
            TotalWidth = ImageWidth + LabelWidth;

            //Set Height
            TotalHeight = LabelHeight + ButtonHeight;

            mb.panButtons.Location = new Point(TotalWidth - ButtonWidth + 9, mb.panText.Location.Y + mb.panText.Height);

            mb.Size = new Size(TotalWidth + 25, TotalHeight + 47);
            mb.ShowDialog();
            return mb.Result;
        }

        private FlowLayoutPanel panText;
        private FlowLayoutPanel panButtons;
        private int ScrollBarWidth(List<Label> Labels)
        {
            return (Labels.Sum(l => l.Height) > 300) ? 23 : 6;
        }

        private void Button_Click(object sender, EventArgs e)
        {
            Result = ((Button)sender).Text;
            Close();
        }

        private string Result = "";
    }
}   

PLS-00201 - identifier must be declared

you should give permission on your db

grant execute on (packageName or tableName) to user;

Replace substring with another substring C++

Generalizing on rotmax's answer, here is a full solution to search & replace all instances in a string. If both substrings are of different size, the substring is replaced using string::erase and string::insert., otherwise the faster string::replace is used.

void FindReplace(string& line, string& oldString, string& newString) {
  const size_t oldSize = oldString.length();

  // do nothing if line is shorter than the string to find
  if( oldSize > line.length() ) return;

  const size_t newSize = newString.length();
  for( size_t pos = 0; ; pos += newSize ) {
    // Locate the substring to replace
    pos = line.find( oldString, pos );
    if( pos == string::npos ) return;
    if( oldSize == newSize ) {
      // if they're same size, use std::string::replace
      line.replace( pos, oldSize, newString );
    } else {
      // if not same size, replace by erasing and inserting
      line.erase( pos, oldSize );
      line.insert( pos, newString );
    }
  }
}

How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?

If you don't have specific needs you can just do this:

if ($(window).width() < 768) {
    // do something for small screens
}
else if ($(window).width() >= 768 &&  $(window).width() <= 992) {
    // do something for medium screens
}
else if ($(window).width() > 992 &&  $(window).width() <= 1200) {
    // do something for big screens
}
else  {
    // do something for huge screens
}

Edit: I don't see why you should use another js library when you can do this just with jQuery already included in your Bootstrap project.

How can I see all the "special" characters permissible in a varchar or char field in SQL Server?

The specific characters that can be stored in a varchar or char column depend upon the column collation. See my answer here for a script that will show you these for the various different collations.

If you want to find all characters outside a particular ASCII range see my answer here.

What's the difference between an Angular component and module

A module in Angular 2 is something which is made from components, directives, services etc. One or many modules combine to make an Application. Modules breakup application into logical pieces of code. Each module performs a single task.

Components in Angular 2 are classes where you write your logic for the page you want to display. Components control the view (html). Components communicate with other components and services.

Python String and Integer concatenation

If we want output like 'string0123456789' then we can use map function and join method of string.

>>> 'string'+"".join(map(str,xrange(10)))
'string0123456789'

If we want List of string values then use list comprehension method.

>>> ['string'+i for i in map(str,xrange(10))]
['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9']

Note:

Use xrange() for Python 2.x

USe range() for Python 3.x

PHP - iterate on string characters

Hmm... There's no need to complicate things. The basics work great always.

    $string = 'abcdef';
    $len = strlen( $string );
    $x = 0;

Forward Direction:

while ( $len > $x ) echo $string[ $x++ ];

Outputs: abcdef

Reverse Direction:

while ( $len ) echo $string[ --$len ];

Outputs: fedcba

Getting the actual usedrange

Here's another one. It looks for the first and last non empty cell and builds are range from those. This also handles cases where your data is not rectangular and does not start in A1. Furthermore it handles merged cells as well, which .Find skips when executed from a macro, used on .Cells on a worksheet.

Function getUsedRange(ByRef sheet As Worksheet) As Range
' finds used range by looking for non empty cells
' works around bug in .Find that skips merged cells
' by starting at with the UsedRange (that may be too big)

' credit to https://contexturesblog.com/archives/2012/03/01/select-actual-used-range-in-excel-sheet/
' for the .Find commands

Dim excelsUsedRange As Range
Dim lastRow As Long
Dim lastCol As Long
Dim lastCell As Range
Dim firstRow As Long
Dim firstCol As Long
Dim firstCell As Range

Set excelsUsedRange = ActiveSheet.UsedRange

lastRow = excelsUsedRange.Find(What:="*", _
                               LookIn:=xlValues, SearchOrder:=xlRows, _
                               SearchDirection:=xlPrevious).Row
lastCol = excelsUsedRange.Find(What:="*", _
                               LookIn:=xlValues, SearchOrder:=xlByColumns, _
                               SearchDirection:=xlPrevious).Column
Set lastCell = sheet.Cells(lastRow, lastCol)

firstRow = excelsUsedRange.Find(What:="*", After:=lastCell, _
                                LookIn:=xlValues, SearchOrder:=xlRows, _
                                SearchDirection:=xlNext).Row
firstCol = excelsUsedRange.Find(What:="*", After:=lastCell, _
                                LookIn:=xlValues, SearchOrder:=xlByColumns, _
                                SearchDirection:=xlNext).Row
Set firstCell = sheet.Cells(firstRow, firstCol)
Set getUsedRange = sheet.Range(firstCell, lastCell)
End Function

How do I set a textbox's value using an anchor with jQuery?

Just to note that prefixing the tagName in a selector is slower than just using the id. In your case jQuery will get all the inputs rather than just using the getElementById. Just use $('#textbox')

Referring to a table in LaTeX

You must place the label after a caption in order to for label to store the table's number, not the chapter's number.

\begin{table}
\begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |}
  -- cut --
\end{tabular}
\caption{My table}
\label{table:kysymys}
\end{table}

Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...

How to redirect to previous page in Ruby On Rails?

In rails 5, as per the instructions in Rails Guides, you can use:

redirect_back(fallback_location: root_path)

The 'back' location is pulled from the HTTP_REFERER header which is not guaranteed to be set by the browser. Thats why you should provide a 'fallback_location'.

How to use ArrayList's get() method

Would this help?

final List<String> l = new ArrayList<String>();
for (int i = 0; i < 10; i++) l.add("Number " + i);
for (int i = 0; i < 10; i++) System.out.println(l.get(i));

How can I hide or encrypt JavaScript code?

While everyone will generally agree that Javascript encryption is a bad idea, there are a few small use cases where slowing down the attack is better than nothing. You can start with YUI Compressor (as @Ben Alpert) said, or JSMin, Uglify, or many more.

However, the main case in which I want to really 'hide stuff' is when I'm publishing an email address. Note, there is the problem of Chrome when you click on 'inspect element'. It will show your original code: every time. This is why obfuscation is generally regarded as being a better way to go.

On that note, I take a two pronged attack, purely to slow down spam bots. I Obfuscate/minify the js and then run it again through an encoder (again, this second step is completely pointless in chrome).

While not exactly a pure Javascript encoder, the best html encoder I have found is http://hivelogic.com/enkoder/. It will turn this:

<script type="text/javascript">
//<![CDATA[
<!--
var c=function(e) { var m="mail" + "to:webmaster";var a="somedomain"; e.href = m+"@"+a+".com";  
};
//-->
//]]>
</script>
<a href="#" onclick="return c(this);"><img src="images/email.png" /></a>

into this:

<script type="text/javascript">
//<![CDATA[
<!--
var x="function f(x){var i,o=\"\",ol=x.length,l=ol;while(x.charCodeAt(l/13)!" +
"=50){try{x+=x;l+=l;}catch(e){}}for(i=l-1;i>=0;i--){o+=x.charAt(i);}return o" +
".substr(0,ol);}f(\")87,\\\"meozp?410\\\\=220\\\\s-dvwggd130\\\\#-2o,V_PY420" +
"\\\\I\\\\\\\\_V[\\\\\\\\620\\\\o710\\\\RB\\\\\\\\610\\\\JAB620\\\\720\\\\n\\"+
"\\{530\\\\410\\\\WJJU010\\\\|>snnn|j5J(771\\\\p{}saa-.W)+T:``vk\\\"\\\\`<02" +
"0\\\\!610\\\\'Dr\\\\010\\\\630\\\\400\\\\620\\\\700\\\\\\\\\\\\N730\\\\,530" +
"\\\\2S16EF600\\\\;420\\\\9ZNONO1200\\\\/000\\\\`'7400\\\\%n\\\\!010\\\\hpr\\"+
"\\= -cn720\\\\a(ce230\\\\500\\\\f730\\\\i,`200\\\\630\\\\[YIR720\\\\]720\\\\"+
"r\\\\720\\\\h][P]@JHADY310\\\\t230\\\\G500\\\\VBT230\\\\200\\\\Clxhh{tzra/{" +
"g0M0$./Pgche%Z8i#p`v^600\\\\\\\\\\\\R730\\\\Q620\\\\030\\\\730\\\\100\\\\72" +
"0\\\\530\\\\700\\\\720\\\\M410\\\\N730\\\\r\\\\530\\\\400\\\\4420\\\\8OM771" +
"\\\\`4400\\\\$010\\\\t\\\\120\\\\230\\\\r\\\\610\\\\310\\\\530\\\\e~o120\\\\"+
"RfJjn\\\\020\\\\lZ\\\\\\\\CZEWCV771\\\\v5lnqf2R1ox771\\\\p\\\"\\\\tr\\\\220" +
"\\\\310\\\\420\\\\600\\\\OSG300\\\\700\\\\410\\\\320\\\\410\\\\120\\\\620\\" +
"\\q)5<: 0>+\\\"(f};o nruter};))++y(^)i(tAedoCrahc.x(edoCrahCmorf.gnirtS=+o;" +
"721=%y;++y)87<i(fi{)++i;l<i;0=i(rof;htgnel.x=l,\\\"\\\"=o,i rav{)y,x(f noit" +
"cnuf\")"                                                                     ;
while(x=eval(x));
//-->
//]]>
</script>

Maybe it's enough to slow down a few spam bots. I haven't had any spam come through using this (!yet).

How to process a file in PowerShell line-by-line as a stream

If you want to use straight PowerShell check out the below code.

$content = Get-Content C:\Users\You\Documents\test.txt
foreach ($line in $content)
{
    Write-Host $line
}

HTML button calling an MVC Controller and Action method

it's better use this example

_x000D_
_x000D_
<a href="@Url.Action("Register","Account", new {id=Item.id })"_x000D_
class="btn btn-primary btn-lg">Register</a>
_x000D_
_x000D_
_x000D_

Bootstrap close responsive menu "on click"

I think you are all over engineering..

    $('.navbar-collapse ul li a').click(function(){ 
            $('.navbar-toggle:visible').click();
    });

EDIT: To take care of sub menus, make sure their toggle anchor has the dropdown-toggle class on it.

    $(function () { 
            $('.navbar-collapse ul li a:not(.dropdown-toggle)').click(function () { 
                    $('.navbar-toggle:visible').click(); 
            }); 
    });

EDIT 2: Add support for phone touch.

    $(function () {
            $('.navbar-collapse ul li a:not(.dropdown-toggle)').bind('click touchstart', function () {
                    $('.navbar-toggle:visible').click();
            });
    });

Django datetime issues (default=datetime.now())

The datetime.now() is evaluated when the class is created, not when new record is being added to the database.

To achieve what you want define this field as:

date = models.DateTimeField(auto_now_add=True)

This way the date field will be set to current date for each new record.

What is the difference between precision and scale?

Maybe more clear:

Note that precision is the total number of digits, scale included

NUMBER(Precision,Scale)

Precision 8, scale 3 : 87654.321

Precision 5, scale 3 : 54.321

Precision 5, scale 1 : 5432.1

Precision 5, scale 0 : 54321

Precision 5, scale -1: 54320

Precision 5, scale -3: 54000

How to add an object to an array

  • JavaScript is case-sensitive. Calling new array() and new object() will throw a ReferenceError since they don't exist.
  • It's better to avoid new Array() due to its error-prone behavior.
    Instead, assign the new array with = [val1, val2, val_n]. For objects, use = {}.
  • There are many ways when it comes to extending an array (as shown in John's answer) but the safest way would be just to use concat instead of push. concat returns a new array, leaving the original array untouched. push mutates the calling array which should be avoided, especially if the array is globally defined.
  • It's also a good practice to freeze the object as well as the new array in order to avoid unintended mutations. A frozen object is neither mutable nor extensible (shallowly).

Applying those points and to answer your two questions, you could define a function like this:

function appendObjTo(thatArray, newObj) {
  const frozenObj = Object.freeze(newObj);
  return Object.freeze(thatArray.concat(frozenObj));
}

Usage:

// Given
const myArray = ["A", "B"];
// "save it to a variable"
const newArray = appendObjTo(myArray, {hello: "world!"});
// returns: ["A", "B", {hello: "world!"}]. myArray did not change.

JavaScript array to CSV

for a simple csv one map() and a join() are enough:

var csv = test_array.map(function(d){
    return d.join();
}).join('\n');

/* Results in 
name1,2,3
name2,4,5
name3,6,7
name4,8,9
name5,10,11

This method also allows you to specify column separator other than a comma in the inner join. for example a tab: d.join('\t')

On the other hand if you want to do it properly and enclose strings in quotes "", then you can use some JSON magic:

var csv = test_array.map(function(d){
   return JSON.stringify(d);
})
.join('\n') 
.replace(/(^\[)|(\]$)/mg, ''); // remove opening [ and closing ] brackets from each line 

/* would produce
"name1",2,3
"name2",4,5
"name3",6,7
"name4",8,9
"name5",10,11

if you have array of objects like :

var data = [
  {"title": "Book title 1", "author": "Name1 Surname1"},
  {"title": "Book title 2", "author": "Name2 Surname2"},
  {"title": "Book title 3", "author": "Name3 Surname3"},
  {"title": "Book title 4", "author": "Name4 Surname4"}
];

// use
var csv = data.map(function(d){
    return JSON.stringify(Object.values(d));
})
.join('\n') 
.replace(/(^\[)|(\]$)/mg, '');

jQuery: How can I create a simple overlay?

An overlay is, simply put, a div that stays fixed on the screen (no matter if you scroll) and has some sort of opacity.

This will be your CSS for cross browser opacity of 0.5:

#overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #000;
    filter:alpha(opacity=50);
    -moz-opacity:0.5;
    -khtml-opacity: 0.5;
    opacity: 0.5;
    z-index: 10000;
}

This will be your jQuery code (no UI needed). You're just going to create a new element with the ID #overlay. Creating and destroying the DIV should be all you need.

var overlay = jQuery('<div id="overlay"> </div>');
overlay.appendTo(document.body)

For performance reasons you might wanna have the DIV hidden and setting the display to block and none as you need it or not.

Hope it helps!

Edit: As @Vitaly so well put it, be sure to check your DocType. Read more on the comments on his findings..

Run an Ansible task only when the variable contains a specific string

From Ansible 2.5

when: variable1 is search("value")

Show history of a file?

You can use git log to display the diffs while searching:

git log -p -- path/to/file

In Java, how do I get the difference in seconds between 2 dates?

If you're using Joda (which may be coming as jsr 310 in JDK 7, separate open source api until then) then there is a Seconds class with a secondsBetween method.

Here's the javadoc link: http://joda-time.sourceforge.net/api-release/org/joda/time/Seconds.html#secondsBetween(org.joda.time.ReadableInstant,%20org.joda.time.ReadableInstant)

Curl command without using cache

I know this is an older question, but I wanted to post an answer for users with the same question:

curl -H 'Cache-Control: no-cache' http://www.example.com

This curl command servers in its header request to return non-cached data from the web server.

How do I append text to a file?

Other possible way is:

echo "text" | tee -a filename >/dev/null

The -a will append at the end of the file.

If needing sudo, use:

echo "text" | sudo tee -a filename >/dev/null

SELECT only rows that contain only alphanumeric characters in MySQL

Try this

select count(*) from table where cast(col as double) is null;

node and Error: EMFILE, too many open files

I had this issue, and i solved it by running npm update and it worked.

In some cases you may need to remove node_modules rm -rf node_modules/

What exactly are iterator, iterable, and iteration?

Iteration is a general term for taking each item of something, one after another. Any time you use a loop, explicit or implicit, to go over a group of items, that is iteration.

In Python, iterable and iterator have specific meanings.

An iterable is an object that has an __iter__ method which returns an iterator, or which defines a __getitem__ method that can take sequential indexes starting from zero (and raises an IndexError when the indexes are no longer valid). So an iterable is an object that you can get an iterator from.

An iterator is an object with a next (Python 2) or __next__ (Python 3) method.

Whenever you use a for loop, or map, or a list comprehension, etc. in Python, the next method is called automatically to get each item from the iterator, thus going through the process of iteration.

A good place to start learning would be the iterators section of the tutorial and the iterator types section of the standard types page. After you understand the basics, try the iterators section of the Functional Programming HOWTO.

Is log(n!) = T(n·log(n))?

enter image description here

Sorry, I don't know how to use LaTeX syntax on stackoverflow..

How do search engines deal with AngularJS applications?

Use PushState and Precomposition

The current (2015) way to do this is using the JavaScript pushState method.

PushState changes the URL in the top browser bar without reloading the page. Say you have a page containing tabs. The tabs hide and show content, and the content is inserted dynamically, either using AJAX or by simply setting display:none and display:block to hide and show the correct tab content.

When the tabs are clicked, use pushState to update the url in the address bar. When the page is rendered, use the value in the address bar to determine which tab to show. Angular routing will do this for you automatically.

Precomposition

There are two ways to hit a PushState Single Page App (SPA)

  1. Via PushState, where the user clicks a PushState link and the content is AJAXed in.
  2. By hitting the URL directly.

The initial hit on the site will involve hitting the URL directly. Subsequent hits will simply AJAX in content as the PushState updates the URL.

Crawlers harvest links from a page then add them to a queue for later processing. This means that for a crawler, every hit on the server is a direct hit, they don't navigate via Pushstate.

Precomposition bundles the initial payload into the first response from the server, possibly as a JSON object. This allows the Search Engine to render the page without executing the AJAX call.

There is some evidence to suggest that Google might not execute AJAX requests. More on this here:

https://web.archive.org/web/20160318211223/http://www.analog-ni.co/precomposing-a-spa-may-become-the-holy-grail-to-seo

Search Engines can read and execute JavaScript

Google has been able to parse JavaScript for some time now, it's why they originally developed Chrome, to act as a full featured headless browser for the Google spider. If a link has a valid href attribute, the new URL can be indexed. There's nothing more to do.

If clicking a link in addition triggers a pushState call, the site can be navigated by the user via PushState.

Search Engine Support for PushState URLs

PushState is currently supported by Google and Bing.

Google

Here's Matt Cutts responding to Paul Irish's question about PushState for SEO:

http://youtu.be/yiAF9VdvRPw

Here is Google announcing full JavaScript support for the spider:

http://googlewebmastercentral.blogspot.de/2014/05/understanding-web-pages-better.html

The upshot is that Google supports PushState and will index PushState URLs.

See also Google webmaster tools' fetch as Googlebot. You will see your JavaScript (including Angular) is executed.

Bing

Here is Bing's announcement of support for pretty PushState URLs dated March 2013:

http://blogs.bing.com/webmaster/2013/03/21/search-engine-optimization-best-practices-for-ajax-urls/

Don't use HashBangs #!

Hashbang urls were an ugly stopgap requiring the developer to provide a pre-rendered version of the site at a special location. They still work, but you don't need to use them.

Hashbang URLs look like this:

domain.com/#!path/to/resource

This would be paired with a metatag like this:

<meta name="fragment" content="!">

Google will not index them in this form, but will instead pull a static version of the site from the _escaped_fragments_ URL and index that.

Pushstate URLs look like any ordinary URL:

domain.com/path/to/resource

The difference is that Angular handles them for you by intercepting the change to document.location dealing with it in JavaScript.

If you want to use PushState URLs (and you probably do) take out all the old hash style URLs and metatags and simply enable HTML5 mode in your config block.

Testing your site

Google Webmaster tools now contains a tool which will allow you to fetch a URL as google, and render JavaScript as Google renders it.

https://www.google.com/webmasters/tools/googlebot-fetch

Generating PushState URLs in Angular

To generate real URLs in Angular, rather than # prefixed ones, set HTML5 mode on your $locationProvider object.

$locationProvider.html5Mode(true);

Server Side

Since you are using real URLs, you will need to ensure the same template (plus some precomposed content) gets shipped by your server for all valid URLs. How you do this will vary depending on your server architecture.

Sitemap

Your app may use unusual forms of navigation, for example hover or scroll. To ensure Google is able to drive your app, I would probably suggest creating a sitemap, a simple list of all the urls your app responds to. You can place this at the default location (/sitemap or /sitemap.xml), or tell Google about it using webmaster tools.

It's a good idea to have a sitemap anyway.

Browser support

Pushstate works in IE10. In older browsers, Angular will automatically fall back to hash style URLs

A demo page

The following content is rendered using a pushstate URL with precomposition:

http://html5.gingerhost.com/london

As can be verified, at this link, the content is indexed and is appearing in Google.

Serving 404 and 301 Header status codes

Because the search engine will always hit your server for every request, you can serve header status codes from your server and expect Google to see them.

How to pass multiple parameters from ajax to mvc controller?

  var data = JSON.stringify
            ({
            'StrContactDetails': Details,
            'IsPrimary': true
            })

Posting a File and Associated Data to a RESTful WebService preferably as JSON

You can send the file and data over in one request using the multipart/form-data content type:

In many applications, it is possible for a user to be presented with a form. The user will fill out the form, including information that is typed, generated by user input, or included from files that the user has selected. When the form is filled out, the data from the form is sent from the user to the receiving application.

The definition of MultiPart/Form-Data is derived from one of those applications...

From http://www.faqs.org/rfcs/rfc2388.html:

"multipart/form-data" contains a series of parts. Each part is expected to contain a content-disposition header [RFC 2183] where the disposition type is "form-data", and where the disposition contains an (additional) parameter of "name", where the value of that parameter is the original field name in the form. For example, a part might contain a header:

Content-Disposition: form-data; name="user"

with the value corresponding to the entry of the "user" field.

You can include file information or field information within each section between boundaries. I've successfully implemented a RESTful service that required the user to submit both data and a form, and multipart/form-data worked perfectly. The service was built using Java/Spring, and the client was using C#, so unfortunately I don't have any Grails examples to give you concerning how to set up the service. You don't need to use JSON in this case since each "form-data" section provides you a place to specify the name of the parameter and its value.

The good thing about using multipart/form-data is that you're using HTTP-defined headers, so you're sticking with the REST philosophy of using existing HTTP tools to create your service.

Clear Cache in Android Application programmatically

Kotlin has an one-liner

context.cacheDir.deleteRecursively()

how to pass parameters to query in SQL (Excel)

It depends on the database to which you're trying to connect, the method by which you created the connection, and the version of Excel that you're using. (Also, most probably, the version of the relevant ODBC driver on your computer.)

The following examples are using SQL Server 2008 and Excel 2007, both on my local machine.

When I used the Data Connection Wizard (on the Data tab of the ribbon, in the Get External Data section, under From Other Sources), I saw the same thing that you did: the Parameters button was disabled, and adding a parameter to the query, something like select field from table where field2 = ?, caused Excel to complain that the value for the parameter had not been specified, and the changes were not saved.

When I used Microsoft Query (same place as the Data Connection Wizard), I was able to create parameters, specify a display name for them, and enter values each time the query was run. Bringing up the Connection Properties for that connection, the Parameters... button is enabled, and the parameters can be modified and used as I think you want.

I was also able to do this with an Access database. It seems reasonable that Microsoft Query could be used to create parameterized queries hitting other types of databases, but I can't easily test that right now.

Best way to get identity of inserted row?

From MSDN

@@IDENTITY, SCOPE_IDENTITY, and IDENT_CURRENT are similar functions in that they return the last value inserted into the IDENTITY column of a table.

@@IDENTITY and SCOPE_IDENTITY will return the last identity value generated in any table in the current session. However, SCOPE_IDENTITY returns the value only within the current scope; @@IDENTITY is not limited to a specific scope.

IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope. For more information, see IDENT_CURRENT.

  • IDENT_CURRENT is a function which takes a table as a argument.
  • @@IDENTITY may return confusing result when you have an trigger on the table
  • SCOPE_IDENTITY is your hero most of the time.

How to put a delay on AngularJS instant search?

(See answer below for a Angular 1.3 solution.)

The issue here is that the search will execute every time the model changes, which is every keyup action on an input.

There would be cleaner ways to do this, but probably the easiest way would be to switch the binding so that you have a $scope property defined inside your Controller on which your filter operates. That way you can control how frequently that $scope variable is updated. Something like this:

JS:

var App = angular.module('App', []);

App.controller('DisplayController', function($scope, $http, $timeout) {
    $http.get('data.json').then(function(result){
        $scope.entries = result.data;
    });

    // This is what you will bind the filter to
    $scope.filterText = '';

    // Instantiate these variables outside the watch
    var tempFilterText = '',
        filterTextTimeout;
    $scope.$watch('searchText', function (val) {
        if (filterTextTimeout) $timeout.cancel(filterTextTimeout);

        tempFilterText = val;
        filterTextTimeout = $timeout(function() {
            $scope.filterText = tempFilterText;
        }, 250); // delay 250 ms
    })
});

HTML:

<input id="searchText" type="search" placeholder="live search..." ng-model="searchText" />
<div class="entry" ng-repeat="entry in entries | filter:filterText">
    <span>{{entry.content}}</span>
</div>

Is arr.__len__() the preferred way to get the length of an array in Python?

Python uses duck typing: it doesn't care about what an object is, as long as it has the appropriate interface for the situation at hand. When you call the built-in function len() on an object, you are actually calling its internal __len__ method. A custom object can implement this interface and len() will return the answer, even if the object is not conceptually a sequence.

For a complete list of interfaces, have a look here: http://docs.python.org/reference/datamodel.html#basic-customization

Is there a kind of Firebug or JavaScript console debug for Android?

Try js-mobile-console

MobileConsole can be embedded within any page for debugging. It will catch errors and behave exactly as the native JavaScript console in the browser. It also outputs all the logs you've written via an API of window.console.

Gradle store on local file system

I just stumbled onto this while searching for this answer. If you are using intellij, you can navigate to the file location, but opening the external lib folder in the project explorer, right clicking on the jar, and select Open Library Settings. enter image description here

MySQL: Error dropping database (errno 13; errno 17; errno 39)

Simply go to /opt/lampp/var/mysql

There You can find your database name. Open that folder. Remove if any files in it

Now come to phpmyadmin and drop that database

navbar color in Twitter Bootstrap

If you are using the LESS or SASS Version of the Bootstrap. The most efficient way is to change the variable name, in the LESS or SASS file.

$navbar-default-color:              #FFFFFF !default;
$navbar-default-bg:                 #36669d !default;
$navbar-default-border:             $navbar-default-bg !default;

This by far the most easiest and the most efficient way to change the Bootstraps Navbar. You need not write overrides, and the code remains clean.

PHP Parse error: syntax error, unexpected '?' in helpers.php 233

If I had to guess, I'd say you installed the PPA 7.1.8 as CLI only (php7-cli). You're getting your version info from that, but your libapache2-mod-php package is still 14.04 main which is 5.6. Check your phpinfo in your browser to confirm the version. You might also consider migrating to Ubuntu 16.04 to get PHP 7.0 in main.

Can't compile C program on a Mac after upgrade to Mojave

After trying every answer I could find here and online, I was still getting errors for some missing headers. When trying to compile pyRFR, I was getting errors about stdexcept not being found, which apparently was not installed in /usr/include with the other headers. However, I found where it was hiding in Mojave and added this to the end of my ~/.bash_profile file:

export CPATH=/Library/Developer/CommandLineTools/usr/include/c++/v1

Having done that, I can now compile pyRFR and other C/C++ programs. According to echo | gcc -E -Wp,-v -, gcc was looking in the old location for these headers (without the /c++/v1), but not the new location, so adding that to CFLAGS fixed it.

How do I determine the current operating system with Node.js

The variable to use would be process.platform

On Mac the variable returns darwin. On Windows, it returns win32 (even on 64 bit).

Current possible values are:

  • aix
  • darwin
  • freebsd
  • linux
  • openbsd
  • sunos
  • win32

I just set this at the top of my jakeFile:

var isWin = process.platform === "win32";

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

How about using a simple loop to count the occurrences of number of spaces!?

_x000D_
_x000D_
txt = "Just an example here move along" _x000D_
count = 1_x000D_
for i in txt:_x000D_
if i == " ":_x000D_
   count += 1_x000D_
print(count)
_x000D_
_x000D_
_x000D_

Read data from a text file using Java

If you want to read line-by-line, use a BufferedReader. It has a readLine() method which returns the line as a String, or null if the end of the file has been reached. So you can do something like:

BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = reader.readLine()) != null) {
 // Do something with line
}

(Note that this code doesn't handle exceptions or close the stream, etc)

Laravel 4 Eloquent Query Using WHERE with OR AND OR?

Incase you're looping the OR conditions, you don't need the the second $query->where from the other posts (actually I don't think you need in general, you can just use orWhere in the nested where if easier)

$attributes = ['first'=>'a','second'=>'b'];

$query->where(function ($query) use ($attributes) 
{
    foreach ($attributes as $key=>value)
    {
        //you can use orWhere the first time, doesn't need to be ->where
        $query->orWhere($key,$value);
    }
});

Angular - Can't make ng-repeat orderBy work

Here's a version of @Julian Mosquera's code that also supports a "fallback" field to use in case the primary field happens to be null or undefined:

yourApp.filter('orderObjectBy', function() {
  return function(items, field, fallback, reverse) {
    var filtered = [];
    angular.forEach(items, function(item) {
      filtered.push(item);
    });
    filtered.sort(function (a, b) {
      var af = a[field];
      if(af === undefined || af === null) { af = a[fallback]; }

      var bf = b[field];
      if(bf === undefined || bf === null) { bf = b[fallback]; }

      return (af > bf ? 1 : -1);
    });
    if(reverse) filtered.reverse();
    return filtered;
  };
});

IIS7 Settings File Locations

It sounds like you're looking for applicationHost.config, which is located in C:\Windows\System32\inetsrv\config.

Yes, it's an XML file, and yes, editing the file by hand will affect the IIS config after a restart. You can think of IIS Manager as a GUI front-end for editing applicationHost.config and web.config.

How do I write dispatch_after GCD in Swift 3, 4, and 5?

A somewhat different flavour of the Accepted Answer.

Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1 + .milliseconds(500) + 
.microseconds(500) + .nanoseconds(1000)) {
                print("Delayed by 0.1 second + 500 milliseconds + 500 microseconds + 
                      1000 nanoseconds)")
 }

How to redirect to another page in node.js

In another way you can use window.location.href="your URL"

e.g.:

res.send('<script>window.location.href="your URL";</script>');

or:

return res.redirect("your url");

Change link color of the current page with CSS

You do not need jQuery just to do this! All you need is a tiny and very light vanilla Javascript and a css class (as in all the answers above) :

  • First define a CSS class in your stylesheet called current.

  • Second add the following pure JavaScript either in your existing JavaScript file or in a separate js script file (but add script tage link to it in the head of the pages) or event just add it in a script tag just before the closing body tag, it will still work in all these cases.



    function highlightCurrent() {
         const curPage = document.URL;
         const links = document.getElementsByTagName('a');
         for (let link of links) {
           if (link.href == curPage) {
             link.classList.add("current");
           }
         }
       }


       document.onreadystatechange = () => {
         if (document.readyState === 'complete') {
           highlightCurrent()
         }
       };

The 'href' attribute of current link should be the absolute path as given by document.URL (console.log it to make sure it is the same)

Force browser to download image files on click

I managed to get this working in Chrome and Firefox too by appending a link to the to document.

var link = document.createElement('a');
link.href = 'images.jpg';
link.download = 'Download.jpg';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

Bootstrap Element 100% Width

The following answer is not exactly optimal by any measure, but I needed something that maintains its position within the container whilst it stretches the inner div fully.

https://jsfiddle.net/fah5axm5/

$(function() {
    $(window).on('load resize', ppaFullWidth);

    function ppaFullWidth() {
        var $elements = $('[data-ppa-full-width="true"]');
        $.each( $elements, function( key, item ) {
            var $el = $(this);
            var $container = $el.closest('.container');
            var margin = parseInt($container.css('margin-left'), 10);
            var padding = parseInt($container.css('padding-left'), 10)
            var offset = margin + padding;

            $el.css({
                position: "relative",
                left: -offset,
                "box-sizing": "border-box",
                width: $(window).width(),
                "padding-left": offset + "px",
                "padding-right": offset + "px"
            });
        });
    }
});

Python: pandas merge multiple dataframes

There are 2 solutions for this, but it return all columns separately:

import functools

dfs = [df1, df2, df3]

df_final = functools.reduce(lambda left,right: pd.merge(left,right,on='date'), dfs)
print (df_final)
          date     a_x   b_x       a_y      b_y   c_x         a        b   c_y
0  May 15,2017  900.00  0.2%  1,900.00  1000000  0.2%  2,900.00  2000000  0.2%

k = np.arange(len(dfs)).astype(str)
df = pd.concat([x.set_index('date') for x in dfs], axis=1, join='inner', keys=k)
df.columns = df.columns.map('_'.join)
print (df)
                0_a   0_b       1_a      1_b   1_c       2_a      2_b   2_c
date                                                                       
May 15,2017  900.00  0.2%  1,900.00  1000000  0.2%  2,900.00  2000000  0.2%

How can I change the language (to english) in Oracle SQL Developer?

Or use the menu: Tools->Preferences->Database->NLS and change language and territory. enter image description here

Shift column in pandas dataframe up by one?

df.gdp = df.gdp.shift(-1) ## shift up
df.gdp.drop(df.gdp.shape[0] - 1,inplace = True) ## removing the last row

How do I get the scroll position of a document?

If you are using Jquery 1.6 or above, use prop to access the value.

$(document).prop('scrollHeight')

Previous versions used to get the value from attr but not post 1.6.

Read contents of a local file into a variable in Rails

I think you should consider using IO.binread("/path/to/file") if you have a recent ruby interpreter (i.e. >= 1.9.2)

You could find IO class documentation here http://www.ruby-doc.org/core-2.1.2/IO.html

Making PHP var_dump() values display one line per value

Personally I like the replacement function provided by Symfony's var dumper component

Install with composer require symfony/var-dumper and just use dump($var)

It takes care of the rest. I believe there's also a bit of JS injected there to allow you to interact with the output a bit.

Return Boolean Value on SQL Select Statement

Use 'Exists' which returns either 0 or 1.

The query will be like:

SELECT EXISTS(SELECT * FROM USER WHERE UserID = 20070022)

How to convert Observable<any> to array[]

You will need to subscribe to your observables:

this.CountryService.GetCountries()
    .subscribe(countries => {
        this.myGridOptions.rowData = countries as CountryData[]
    })

And, in your html, wherever needed, you can pass the async pipe to it.

How to recover Git objects damaged by hard disk failure?

Try the following commands at first (re-run again if needed):

$ git fsck --full
$ git gc
$ git gc --prune=today
$ git fetch --all
$ git pull --rebase

And then you you still have the problems, try can:

  • remove all the corrupt objects, e.g.

    fatal: loose object 91c5...51e5 (stored in .git/objects/06/91c5...51e5) is corrupt
    $ rm -v .git/objects/06/91c5...51e5
    
  • remove all the empty objects, e.g.

    error: object file .git/objects/06/91c5...51e5 is empty
    $ find .git/objects/ -size 0 -exec rm -vf "{}" \;
    
  • check a "broken link" message by:

    git ls-tree 2d9263c6d23595e7cb2a21e5ebbb53655278dff8
    

    This will tells you what file the corrupt blob came from!

  • to recover file, you might be really lucky, and it may be the version that you already have checked out in your working tree:

    git hash-object -w my-magic-file
    

    again, and if it outputs the missing SHA1 (4b945..) you're now all done!

  • assuming that it was some older version that was broken, the easiest way to do it is to do:

    git log --raw --all --full-history -- subdirectory/my-magic-file
    

    and that will show you the whole log for that file (please realize that the tree you had may not be the top-level tree, so you need to figure out which subdirectory it was in on your own), then you can now recreate the missing object with hash-object again.

  • to get a list of all refs with missing commits, trees or blobs:

    $ git for-each-ref --format='%(refname)' | while read ref; do git rev-list --objects $ref >/dev/null || echo "in $ref"; done
    

    It may not be possible to remove some of those refs using the regular branch -d or tag -d commands, since they will die if git notices the corruption. So use the plumbing command git update-ref -d $ref instead. Note that in case of local branches, this command may leave stale branch configuration behind in .git/config. It can be deleted manually (look for the [branch "$ref"] section).

  • After all refs are clean, there may still be broken commits in the reflog. You can clear all reflogs using git reflog expire --expire=now --all. If you do not want to lose all of your reflogs, you can search the individual refs for broken reflogs:

    $ (echo HEAD; git for-each-ref --format='%(refname)') | while read ref; do git rev-list -g --objects $ref >/dev/null || echo "in $ref"; done
    

    (Note the added -g option to git rev-list.) Then, use git reflog expire --expire=now $ref on each of those. When all broken refs and reflogs are gone, run git fsck --full in order to check that the repository is clean. Dangling objects are Ok.


Below you can find advanced usage of commands which potentially can cause lost of your data in your git repository if not used wisely, so make a backup before you accidentally do further damages to your git. Try on your own risk if you know what you're doing.


To pull the current branch on top of the upstream branch after fetching:

$ git pull --rebase

You also may try to checkout new branch and delete the old one:

$ git checkout -b new_master origin/master

To find the corrupted object in git for removal, try the following command:

while [ true ]; do f=`git fsck --full 2>&1|awk '{print $3}'|sed -r 's/(^..)(.*)/objects\/\1\/\2/'`; if [ ! -f "$f" ]; then break; fi; echo delete $f; rm -f "$f"; done

For OSX, use sed -E instead of sed -r.


Other idea is to unpack all objects from pack files to regenerate all objects inside .git/objects, so try to run the following commands within your repository:

$ cp -fr .git/objects/pack .git/objects/pack.bak
$ for i in .git/objects/pack.bak/*.pack; do git unpack-objects -r < $i; done
$ rm -frv .git/objects/pack.bak

If above doesn't help, you may try to rsync or copy the git objects from another repo, e.g.

$ rsync -varu git_server:/path/to/git/.git local_git_repo/
$ rsync -varu /local/path/to/other-working/git/.git local_git_repo/
$ cp -frv ../other_repo/.git/objects .git/objects

To fix the broken branch when trying to checkout as follows:

$ git checkout -f master
fatal: unable to read tree 5ace24d474a9535ddd5e6a6c6a1ef480aecf2625

Try to remove it and checkout from upstream again:

$ git branch -D master
$ git checkout -b master github/master

In case if git get you into detached state, checkout the master and merge into it the detached branch.


Another idea is to rebase the existing master recursively:

$ git reset HEAD --hard
$ git rebase -s recursive -X theirs origin/master

See also:

Use Excel pivot table as data source for another Pivot Table

  • Make your first pivot table.

  • Select the first top left cell.

  • Create a range name using offset:

    OFFSET(Sheet1!$A$3,0,0,COUNTA(Sheet1!$A:$A)-1,COUNTA(Sheet1!$3:$3))

  • Make your second pivot with your range name as source of data using F3.

If you change number of rows or columns from your first pivot, your second pivot will be update after refreshing pivot

GFGDT

reading HttpwebResponse json response, C#

First you need an object

public class MyObject {
  public string Id {get;set;}
  public string Text {get;set;}
  ...
}

Then in here

    using (var twitpicResponse = (HttpWebResponse)request.GetResponse()) {

        using (var reader = new StreamReader(twitpicResponse.GetResponseStream())) {
            JavaScriptSerializer js = new JavaScriptSerializer();
            var objText = reader.ReadToEnd();
            MyObject myojb = (MyObject)js.Deserialize(objText,typeof(MyObject));
        }

    }

I haven't tested with the hierarchical object you have, but this should give you access to the properties you want.

JavaScriptSerializer System.Web.Script.Serialization

Lists: Count vs Count()

Count() is an extension method introduced by LINQ while the Count property is part of the List itself (derived from ICollection). Internally though, LINQ checks if your IEnumerable implements ICollection and if it does it uses the Count property. So at the end of the day, there's no difference which one you use for a List.

To prove my point further, here's the code from Reflector for Enumerable.Count()

public static int Count<TSource>(this IEnumerable<TSource> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    ICollection<TSource> is2 = source as ICollection<TSource>;
    if (is2 != null)
    {
        return is2.Count;
    }
    int num = 0;
    using (IEnumerator<TSource> enumerator = source.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            num++;
        }
    }
    return num;
}

Maven: add a dependency to a jar by relative path

we switched to gradle and this works much better in gradle ;). we just specify a folder we can drop jars into for temporary situations like that. We still have most of our jars defined i the typicaly dependency management section(ie. the same as maven). This is just one more dependency we define.

so basically now we can just drop any jar we want into our lib dir for temporary testing if it is not a in maven repository somewhere.

How to include a sub-view in Blade templates?

You can use the blade template engine:

@include('view.name') 

'view.name' would live in your main views folder:

// for laravel 4.X
app/views/view/name.blade.php  

// for laravel 5.X
resources/views/view/name.blade.php

Another example

@include('hello.world');

would display the following view

// for laravel 4.X
app/views/hello/world.blade.php

// for laravel 5.X
resources/views/hello/world.blade.php

Another example

@include('some.directory.structure.foo');

would display the following view

// for Laravel 4.X
app/views/some/directory/structure/foo.blade.php

// for Laravel 5.X
resources/views/some/directory/structure/foo.blade.php

So basically the dot notation defines the directory hierarchy that your view is in, followed by the view name, relative to app/views folder for laravel 4.x or your resources/views folder in laravel 5.x

ADDITIONAL

If you want to pass parameters: @include('view.name', array('paramName' => 'value'))

You can then use the value in your views like so <p>{{$paramName}}</p>

how to find all indexes and their columns for tables, views and synonyms in oracle

SELECT * FROM user_cons_columns WHERE table_name = 'table_name';

smtp configuration for php mail

php's email() function hands the email over to a underlying mail transfer agent which is usually postfix on linux systems

so the preferred method on linux is to configure your postfix to use a relayhost, which is done by a line of

relayhost = smtp.example.com

in /etc/postfix/main.cf

however in the OP's scenario I somehow suspect that it's a job that his hosting team should have done

Convert string to datetime in vb.net

You can try with ParseExact method

Sample

Dim format As String  
format = "d" 
Dim provider As CultureInfo = CultureInfo.InvariantCulture
result = Date.ParseExact(DateString, format, provider)

What is the difference between canonical name, simple name and class name in Java Class?

If you're unsure about something, try writing a test first.

I did this:

class ClassNameTest {
    public static void main(final String... arguments) {
        printNamesForClass(
            int.class,
            "int.class (primitive)");
        printNamesForClass(
            String.class,
            "String.class (ordinary class)");
        printNamesForClass(
            java.util.HashMap.SimpleEntry.class,
            "java.util.HashMap.SimpleEntry.class (nested class)");
        printNamesForClass(
            new java.io.Serializable(){}.getClass(),
            "new java.io.Serializable(){}.getClass() (anonymous inner class)");
    }

    private static void printNamesForClass(final Class<?> clazz, final String label) {
        System.out.println(label + ":");
        System.out.println("    getName():          " + clazz.getName());
        System.out.println("    getCanonicalName(): " + clazz.getCanonicalName());
        System.out.println("    getSimpleName():    " + clazz.getSimpleName());
        System.out.println("    getTypeName():      " + clazz.getTypeName()); // added in Java 8
        System.out.println();
    }
}

Prints:

int.class (primitive):
    getName():          int
    getCanonicalName(): int
    getSimpleName():    int
    getTypeName():      int

String.class (ordinary class):
    getName():          java.lang.String
    getCanonicalName(): java.lang.String
    getSimpleName():    String
    getTypeName():      java.lang.String

java.util.HashMap.SimpleEntry.class (nested class):
    getName():          java.util.AbstractMap$SimpleEntry
    getCanonicalName(): java.util.AbstractMap.SimpleEntry
    getSimpleName():    SimpleEntry
    getTypeName():      java.util.AbstractMap$SimpleEntry

new java.io.Serializable(){}.getClass() (anonymous inner class):
    getName():          ClassNameTest$1
    getCanonicalName(): null
    getSimpleName():    
    getTypeName():      ClassNameTest$1

There's an empty entry in the last block where getSimpleName returns an empty string.

The upshot looking at this is:

  • the name is the name that you'd use to dynamically load the class with, for example, a call to Class.forName with the default ClassLoader. Within the scope of a certain ClassLoader, all classes have unique names.
  • the canonical name is the name that would be used in an import statement. It might be useful during toString or logging operations. When the javac compiler has complete view of a classpath, it enforces uniqueness of canonical names within it by clashing fully qualified class and package names at compile time. However JVMs must accept such name clashes, and thus canonical names do not uniquely identify classes within a ClassLoader. (In hindsight, a better name for this getter would have been getJavaName; but this method dates from a time when the JVM was used solely to run Java programs.)
  • the simple name loosely identifies the class, again might be useful during toString or logging operations but is not guaranteed to be unique.
  • the type name returns "an informative string for the name of this type", "It's like toString: it's purely informative and has no contract value". (as written by sir4ur0n)

How to install easy_install in Python 2.7.1 on Windows 7

Look for the official 2.7 setuptools installer (which contains easy_install). You only need to install from sources for windows 64 bits.

How to initialize weights in PyTorch?

If you see a deprecation warning (@Fábio Perez)...

def init_weights(m):
    if type(m) == nn.Linear:
        torch.nn.init.xavier_uniform_(m.weight)
        m.bias.data.fill_(0.01)

net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
net.apply(init_weights)

Selecting specific rows and columns from NumPy array

As Toan suggests, a simple hack would be to just select the rows first, and then select the columns over that.

>>> a[[0,1,3], :]            # Returns the rows you want
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [12, 13, 14, 15]])
>>> a[[0,1,3], :][:, [0,2]]  # Selects the columns you want as well
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

[Edit] The built-in method: np.ix_

I recently discovered that numpy gives you an in-built one-liner to doing exactly what @Jaime suggested, but without having to use broadcasting syntax (which suffers from lack of readability). From the docs:

Using ix_ one can quickly construct index arrays that will index the cross product. a[np.ix_([1,3],[2,5])] returns the array [[a[1,2] a[1,5]], [a[3,2] a[3,5]]].

So you use it like this:

>>> a = np.arange(20).reshape((5,4))
>>> a[np.ix_([0,1,3], [0,2])]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

And the way it works is that it takes care of aligning arrays the way Jaime suggested, so that broadcasting happens properly:

>>> np.ix_([0,1,3], [0,2])
(array([[0],
        [1],
        [3]]), array([[0, 2]]))

Also, as MikeC says in a comment, np.ix_ has the advantage of returning a view, which my first (pre-edit) answer did not. This means you can now assign to the indexed array:

>>> a[np.ix_([0,1,3], [0,2])] = -1
>>> a    
array([[-1,  1, -1,  3],
       [-1,  5, -1,  7],
       [ 8,  9, 10, 11],
       [-1, 13, -1, 15],
       [16, 17, 18, 19]])

Most efficient way to find mode in numpy array

Expanding on this method, applied to finding the mode of the data where you may need the index of the actual array to see how far away the value is from the center of the distribution.

(_, idx, counts) = np.unique(a, return_index=True, return_counts=True)
index = idx[np.argmax(counts)]
mode = a[index]

Remember to discard the mode when len(np.argmax(counts)) > 1, also to validate if it is actually representative of the central distribution of your data you may check whether it falls inside your standard deviation interval.

Should I use 'has_key()' or 'in' on Python dicts?

There is one example where in actually kills your performance.

If you use in on a O(1) container that only implements __getitem__ and has_key() but not __contains__ you will turn an O(1) search into an O(N) search (as in falls back to a linear search via __getitem__).

Fix is obviously trivial:

def __contains__(self, x):
    return self.has_key(x)

How to force view controller orientation in iOS 8?

Use this to lock view controller orientation, tested on IOS 9:

// Lock orientation to landscape right

-(UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscapeRight;
}

-(NSUInteger)navigationControllerSupportedInterfaceOrientations:(UINavigationController *)navigationController {
    return UIInterfaceOrientationMaskLandscapeRight;
}

How to override trait function and call it from the overridden function?

Another variation: Define two functions in the trait, a protected one that performs the actual task, and a public one which in turn calls the protected one.

This just saves classes from having to mess with the 'use' statement if they want to override the function, since they can still call the protected function internally.

trait A {
    protected function traitcalc($v) {
        return $v+1;
    }

    function calc($v) {
        return $this->traitcalc($v);
    }
}

class MyClass {
    use A;

    function calc($v) {
        $v++;
        return $this->traitcalc($v);
    }
}

class MyOtherClass {
    use A;
}


print (new MyClass())->calc(2); // will print 4

print (new MyOtherClass())->calc(2); // will print 3

new Date() is working in Chrome but not Firefox

This should work for you:

var date1 = new Date(year, month, day, hour, minute, seconds);

I had to create date form a string so I have done it like this:

var d = '2013-07-20 16:57:27';
var date1 = new Date(d.substr(0, 4), d.substr(5, 2), d.substr(8, 2), d.substr(11, 2), d.substr(14, 2), d.substr(17, 2));

Remember that the months in javascript are from 0 to 11, so you should reduce the month value by 1, like this:

var d = '2013-07-20 16:57:27';
var date1 = new Date(d.substr(0, 4), d.substr(5, 2) - 1, d.substr(8, 2), d.substr(11, 2), d.substr(14, 2), d.substr(17, 2));

Correct file permissions for WordPress

For those who have their wordpress root folder under their home folder:

** Ubuntu/apache

  1. Add your user to www-data group:

CREDIT Granting write permissions to www-data group

You want to call usermod on your user. So that would be:

sudo usermod -aG www-data yourUserName

** Assuming www-data group exists

  1. Check your user is in www-data group:

    groups yourUserName

You should get something like:

youUserName : youUserGroupName www-data

** youUserGroupName is usually similar to you user name

  1. Recursively change group ownership of the wp-content folder keeping your user ownership

    chown yourUserName:www-data -R youWebSiteFolder/wp-content/*

  2. Change directory to youWebSiteFolder/wp-content/

    cd youWebSiteFolder/wp-content

  3. Recursively change group permissions of the folders and sub-folders to enable write permissions:

    find . -type d -exec chmod -R 775 {} \;

** mode of `/home/yourUserName/youWebSiteFolder/wp-content/' changed from 0755 (rwxr-xr-x) to 0775 (rwxrwxr-x)

  1. Recursively change group permissions of the files and sub-files to enable write permissions:

    find . -type f -exec chmod -R 664 {} \;

The result should look something like:

WAS:
-rw-r--r--  1 yourUserName www-data  7192 Oct  4 00:03 filename.html
CHANGED TO:
-rw-rw-r--  1 yourUserName www-data  7192 Oct  4 00:03 filename.html

Equivalent to:

chmod -R ug+rw foldername

Permissions will be like 664 for files or 775 for directories.

P.s. if anyone encounters error 'could not create directory' when updating a plugin, do:
server@user:~/domainame.com$ sudo chown username:www-data -R wp-content
when you are at the root of your domain.
Assuming: wp-config.php has
FTP credentials on LocalHost
define('FS_METHOD','direct');

Java equivalent to C# extension methods

We can simulate the implementation of C# extension methods in Java by using the default method implementation available since Java 8. We start by defining an interface that will allow us to access the support object via a base() method, like so:

public interface Extension<T> {

    default T base() {
        return null;
    }
}

We return null since interfaces cannot have state, but this has to be fixed later via a proxy.

The developer of extensions would have to extend this interface by a new interface containing extension methods. Let's say we want to add a forEach consumer on List interface:

public interface ListExtension<T> extends Extension<List<T>> {

    default void foreach(Consumer<T> consumer) {
        for (T item : base()) {
            consumer.accept(item);
        }
    }

}

Because we extend the Extension interface, we can call base() method inside our extension method to access the support object we attach to.

The Extension interface must have a factory method which will create an extension of a given support object:

public interface Extension<T> {

    ...

    static <E extends Extension<T>, T> E create(Class<E> type, T instance) {
        if (type.isInterface()) {
            ExtensionHandler<T> handler = new ExtensionHandler<T>(instance);
            List<Class<?>> interfaces = new ArrayList<Class<?>>();
            interfaces.add(type);
            Class<?> baseType = type.getSuperclass();
            while (baseType != null && baseType.isInterface()) {
                interfaces.add(baseType);
                baseType = baseType.getSuperclass();
            }
            Object proxy = Proxy.newProxyInstance(
                    Extension.class.getClassLoader(),
                    interfaces.toArray(new Class<?>[interfaces.size()]),
                    handler);
            return type.cast(proxy);
        } else {
            return null;
        }
    }
}

We create a proxy that implements the extension interface and all the interface implemented by the type of the support object. The invocation handler given to the proxy would dispatch all the calls to the support object, except for the "base" method, which must return the support object, otherwise its default implementation is returning null:

public class ExtensionHandler<T> implements InvocationHandler {

    private T instance;

    private ExtensionHandler(T instance) {
        this.instance = instance;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        if ("base".equals(method.getName())
                && method.getParameterCount() == 0) {
            return instance;
        } else {
            Class<?> type = method.getDeclaringClass();
            MethodHandles.Lookup lookup = MethodHandles.lookup()
                .in(type);
            Field allowedModesField = lookup.getClass().getDeclaredField("allowedModes");
            makeFieldModifiable(allowedModesField);
            allowedModesField.set(lookup, -1);
            return lookup
                .unreflectSpecial(method, type)
                .bindTo(proxy)
                .invokeWithArguments(args);
        }
    }

    private static void makeFieldModifiable(Field field) throws Exception {
        field.setAccessible(true);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField
                .setInt(field, field.getModifiers() & ~Modifier.FINAL);
    }

}

Then, we can use the Extension.create() method to attach the interface containing the extension method to the support object. The result is an object which can be casted to the extension interface by which we can still access the support object calling the base() method. Having the reference casted to the extension interface, we now can safely call the extension methods that can have access to the support object, so that now we can attach new methods to the existing object, but not to its defining type:

public class Program {

    public static void main(String[] args) {
        List<String> list = Arrays.asList("a", "b", "c");
        ListExtension<String> listExtension = Extension.create(ListExtension.class, list);
        listExtension.foreach(System.out::println);
    }

}

So, this is a way we can simulate the ability to extend objects in Java by adding new contracts to them, which allow us to call additional methods on the given objects.

Below you may find the code of the Extension interface:

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

public interface Extension<T> {

    public class ExtensionHandler<T> implements InvocationHandler {

        private T instance;

        private ExtensionHandler(T instance) {
            this.instance = instance;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable {
            if ("base".equals(method.getName())
                    && method.getParameterCount() == 0) {
                return instance;
            } else {
                Class<?> type = method.getDeclaringClass();
                MethodHandles.Lookup lookup = MethodHandles.lookup()
                    .in(type);
                Field allowedModesField = lookup.getClass().getDeclaredField("allowedModes");
                makeFieldModifiable(allowedModesField);
                allowedModesField.set(lookup, -1);
                return lookup
                    .unreflectSpecial(method, type)
                    .bindTo(proxy)
                    .invokeWithArguments(args);
            }
        }

        private static void makeFieldModifiable(Field field) throws Exception {
            field.setAccessible(true);
            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        }

    }

    default T base() {
        return null;
    }

    static <E extends Extension<T>, T> E create(Class<E> type, T instance) {
        if (type.isInterface()) {
            ExtensionHandler<T> handler = new ExtensionHandler<T>(instance);
            List<Class<?>> interfaces = new ArrayList<Class<?>>();
            interfaces.add(type);
            Class<?> baseType = type.getSuperclass();
            while (baseType != null && baseType.isInterface()) {
                interfaces.add(baseType);
                baseType = baseType.getSuperclass();
            }
            Object proxy = Proxy.newProxyInstance(
                    Extension.class.getClassLoader(),
                    interfaces.toArray(new Class<?>[interfaces.size()]),
                    handler);
            return type.cast(proxy);
        } else {
            return null;
        }
    }

}

How do you list volumes in docker containers?

With docker 1.10, you now have new commands for data-volume containers.
(for regular containers, see the next section, for docker 1.8+):


With docker 1.8.1 (August 2015), a docker inspect -f '{{ .Volumes }}' containerid would be empty!

You now need to check Mounts, which is a list of mounted paths like:

   "Mounts": [
       {
           "Name": "7ced22ebb63b78823f71cf33f9a7e1915abe4595fcd4f067084f7c4e8cc1afa2",
           "Source": "/mnt/sda1/var/lib/docker/volumes/7ced22ebb63b78823f71cf33f9a7e1915abe4595fcd4f067084f7c4e8cc1afa2/_data",
           "Destination": "/home/git/repositories",
           "Driver": "local",
           "Mode": "",
           "RW": true
       }
   ],

If you want the path of the first mount (for instance), that would be (using index 0):

docker inspect -f '{{ (index .Mounts 0).Source }}' containerid

As Mike Mitterer comments below:

Pretty print the whole thing:

 docker inspect -f '{{ json .Mounts }}' containerid | python -m json.tool 

Or, as commented by Mitja, use the jq command.

docker inspect -f '{{ json .Mounts }}' containerid | jq 

How to insert a new line in strings in Android

I use <br> in a CDATA tag. As an example, my strings.xml file contains an item like this:

<item><![CDATA[<b>My name is John</b><br>Nice to meet you]]></item>

and prints

My name is John
Nice to meet you

How do I display images from Google Drive on a website?

Google Drive Hosting is now deprecated. It stopped working from August 31, 2016.

hosting on Google Drive - deprecation schedule

I have removed the explanation of how to previously host an image on Google Drive.

Git checkout: updating paths is incompatible with switching branches

none of the above worked for me. My situation is slightly different, my remote branch is not at origin. but in a different repository.

git remote add remoterepo GIT_URL.git
git fetch remoterepo
git checkout -b branchname remoterepo/branchname

tip: if you don't see the remote branch in the following output git branch -v -a there is no way to check it out.

Confirmed working on 1.7.5.4

Detect when browser receives file download

If you don't want to generate and store the file on the server, are you willing to store the status, e.g. file-in-progress, file-complete? Your "waiting" page could poll the server to know when the file generation is complete. You wouldn't know for sure that the browser started the download but you'd have some confidence.

How to make div's percentage width relative to parent div and not viewport

Use position: relative on the parent element.

Also note that had you not added any position attributes to any of the divs you wouldn't have seen this behavior. Juan explains further.

Regex match digits, comma and semicolon?

You almost have it, you just left out 0 and forgot the quantifier.

word.matches("^[0-9,;]+$")

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

Forcing label to flow inline with input that they label

<style>
.nowrap {
    white-space: nowrap;
}
</style>

...

<label for="id1" class="nowrap">label1:
    <input type="text" id="id1"/>
</label>

Wrap your inputs within the label tag

Update a table using JOIN in SQL Server?

Aaron's approach above worked perfectly for me. My update statement was slightly different because I needed to join based on two fields concatenated in one table to match a field in another table.

 --update clients table cell field from custom table containing mobile numbers

update clients
set cell = m.Phone
from clients as c
inner join [dbo].[COSStaffMobileNumbers] as m 
on c.Last_Name + c.First_Name = m.Name

What is the main purpose of setTag() getTag() methods of View?

Unlike IDs, tags are not used to identify views. Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure.

Reference: http://developer.android.com/reference/android/view/View.html

How to read and write to a text file in C++?

Default c++ mechanism for file IO is called streams. Streams can be of three flavors: input, output and inputoutput. Input streams act like sources of data. To read data from an input stream you use >> operator:

istream >> my_variable; //This code will read a value from stream into your variable.

Operator >> acts different for different types. If in the example above my_variable was an int, then a number will be read from the strem, if my_variable was a string, then a word would be read, etc. You can read more then one value from the stream by writing istream >> a >> b >> c; where a, b and c would be your variables.

Output streams act like sink to which you can write your data. To write your data to a stream, use << operator.

ostream << my_variable; //This code will write a value from your variable into stream.

As with input streams, you can write several values to the stream by writing something like this:

ostream << a << b << c;

Obviously inputoutput streams can act as both.

In your code sample you use cout and cin stream objects. cout stands for console-output and cin for console-input. Those are predefined streams for interacting with default console.

To interact with files, you need to use ifstream and ofstream types. Similar to cin and cout, ifstream stands for input-file-stream and ofstream stands for output-file-stream.

Your code might look like this:

#include <iostream>
#include <fstream>

using namespace std;

int start()
{
    cout << "Welcome...";

    // do fancy stuff

    return 0;
}

int main ()
{
    string usreq, usr, yn, usrenter;

    cout << "Is this your first time using TEST" << endl;
    cin >> yn;
    if (yn == "y")
    {
        ifstream iusrfile;
        ofstream ousrfile;
        iusrfile.open("usrfile.txt");
        iusrfile >> usr;
        cout << iusrfile; // I'm not sure what are you trying to do here, perhaps print iusrfile contents?
        iusrfile.close();
        cout << "Please type your Username. \n";
        cin >> usrenter;
        if (usrenter == usr)
        {
            start ();
        }
    }
    else
    {
        cout << "THAT IS NOT A REGISTERED USERNAME.";
    }

    return 0;
}

For further reading you might want to look at c++ I/O reference

On a CSS hover event, can I change another div's styling?

This can not be done purely with css. This is a behaviour, which affects the styling of the page.

With jquery you can quickly implement the behavior from your question:

$(function() {
  $('#a').hover(function() {
    $('#b').css('background-color', 'yellow');
  }, function() {
    // on mouseout, reset the background colour
    $('#b').css('background-color', '');
  });
});

PowerShell: Run command from script's directory

Well I was looking for solution for this for a while, without any scripts just from CLI. This is how I do it xD:

  • Navigate to folder from which you want to run script (important thing is that you have tab completions)

    ..\..\dir

  • Now surround location with double quotes, and inside them add cd, so we could invoke another instance of powershell.

    "cd ..\..\dir"

  • Add another command to run script separated by ;, with is a command separator in powershell

    "cd ..\..\dir\; script.ps1"

  • Finally Run it with another instance of powershell

    start powershell "cd..\..\dir\; script.ps1"

This will open new powershell window, go to ..\..\dir, run script.ps1 and close window.


Note that ";" just separates commands, like you typed them one by one, if first fails second will run and next after, and next after... If you wanna keep new powershell window open you add -noexit in passed command . Note that I first navigate to desired folder so I could use tab completions (you couldn't in double quotes).

start powershell "-noexit cd..\..\dir\; script.ps1"

Use double quotes "" so you could pass directories with spaces in names e.g.,

start powershell "-noexit cd '..\..\my dir'; script.ps1"

Angular2 dynamic change CSS property

Just use standard CSS variables:

Your global css (eg: styles.css)

body {
  --my-var: #000
}

In your component's css or whatever it is:

span {
  color: var(--my-var)
}

Then you can change the value of the variable directly with TS/JS by setting inline style to html element:

document.querySelector("body").style.cssText = "--my-var: #000";

Otherwise you can use jQuery for it:

$("body").css("--my-var", "#fff");

Capture Image from Camera and Display in Activity

Capture photo + Choose from Gallery:

        a = (ImageButton)findViewById(R.id.imageButton1);

        a.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                selectImage();

            }

        });
    }
    private File savebitmap(Bitmap bmp) {
      String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
      OutputStream outStream = null;
     // String temp = null;
        File file = new File(extStorageDirectory, "temp.png");
      if (file.exists()) {
       file.delete();
       file = new File(extStorageDirectory, "temp.png");

      }

      try {
       outStream = new FileOutputStream(file);
       bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
       outStream.flush();
       outStream.close();

      } catch (Exception e) {
       e.printStackTrace();
       return null;
      }
      return file;
     }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
     private void selectImage() {



            final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };



            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

            builder.setTitle("Add Photo!");

            builder.setItems(options, new DialogInterface.OnClickListener() {

                @Override

                public void onClick(DialogInterface dialog, int item) {

                    if (options[item].equals("Take Photo"))

                    {

                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                        File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");

                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                        //pic = f;

                        startActivityForResult(intent, 1);


                    }

                    else if (options[item].equals("Choose from Gallery"))

                    {

                        Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                        startActivityForResult(intent, 2);



                    }

                    else if (options[item].equals("Cancel")) {

                        dialog.dismiss();

                    }

                }

            });

            builder.show();

        }



        @Override

        protected void onActivityResult(int requestCode, int resultCode, Intent data) {

            super.onActivityResult(requestCode, resultCode, data);

            if (resultCode == RESULT_OK) {

                if (requestCode == 1) {
                    //h=0;
                    File f = new File(Environment.getExternalStorageDirectory().toString());

                    for (File temp : f.listFiles()) {

                        if (temp.getName().equals("temp.jpg")) {

                            f = temp;
                            File photo = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
                           //pic = photo;
                            break;

                        }

                    }

                    try {

                        Bitmap bitmap;

                        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();



                        bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),

                                bitmapOptions); 



                        a.setImageBitmap(bitmap);




                        String path = android.os.Environment

                                .getExternalStorageDirectory()

                                + File.separator

                                + "Phoenix" + File.separator + "default";
                        //p = path;

                        f.delete();

                        OutputStream outFile = null;

                        File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");

                        try {

                            outFile = new FileOutputStream(file);

                            bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
    //pic=file;
                            outFile.flush();

                            outFile.close();


                        } catch (FileNotFoundException e) {

                            e.printStackTrace();

                        } catch (IOException e) {

                            e.printStackTrace();

                        } catch (Exception e) {

                            e.printStackTrace();

                        }

                    } catch (Exception e) {

                        e.printStackTrace();

                    }

                } else if (requestCode == 2) {



                    Uri selectedImage = data.getData();
                   // h=1;
    //imgui = selectedImage;
                    String[] filePath = { MediaStore.Images.Media.DATA };

                    Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);

                    c.moveToFirst();

                    int columnIndex = c.getColumnIndex(filePath[0]);

                    String picturePath = c.getString(columnIndex);

                    c.close();

                    Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));


                    Log.w("path of image from gallery......******************.........", picturePath+"");


                    a.setImageBitmap(thumbnail);

                }

            }

What are the differences between char literals '\n' and '\r' in Java?

The above answers provided are perfect. The LF(\n), CR(\r) and CRLF(\r\n) characters are platform dependent. However, the interpretation for these characters is not only defined by the platforms but also the console that you are using. In Intellij console (Windows), this \r character in this statement System.out.print("Happ\ry"); produces the output y. But, if you use the terminal (Windows), you will get yapp as the output.

Python: Tuples/dictionaries as keys, select, sort

This type of data is efficiently pulled from a Trie-like data structure. It also allows for fast sorting. The memory efficiency might not be that great though.

A traditional trie stores each letter of a word as a node in the tree. But in your case your "alphabet" is different. You are storing strings instead of characters.

it might look something like this:

root:                Root
                     /|\
                    / | \
                   /  |  \     
fruit:       Banana Apple Strawberry
              / |      |     \
             /  |      |      \
color:     Blue Yellow Green  Blue
            /   |       |       \
           /    |       |        \
end:      24   100      12        0

see this link: trie in python

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

You just need to keep Program Files in double quote & rest of the command don't need any quote.

C:\"Program Files"\IAR Systems\Embedded Workbench 7.0\430\bin\icc430.exe F:\CP00 .....

Insert text into textarea with jQuery

Here is a quick solution that works in jQuery 1.9+:

a) Get caret position:

function getCaret(el) {
        if (el.prop("selectionStart")) {
            return el.prop("selectionStart");
        } else if (document.selection) {
            el.focus();

            var r = document.selection.createRange();
            if (r == null) {
                return 0;
            }

            var re = el.createTextRange(),
                    rc = re.duplicate();
            re.moveToBookmark(r.getBookmark());
            rc.setEndPoint('EndToStart', re);

            return rc.text.length;
        }
        return 0;
    };

b) Append text at caret position:

function appendAtCaret($target, caret, $value) {
        var value = $target.val();
        if (caret != value.length) {
            var startPos = $target.prop("selectionStart");
            var scrollTop = $target.scrollTop;
            $target.val(value.substring(0, caret) + ' ' + $value + ' ' + value.substring(caret, value.length));
            $target.prop("selectionStart", startPos + $value.length);
            $target.prop("selectionEnd", startPos + $value.length);
            $target.scrollTop = scrollTop;
        } else if (caret == 0)
        {
            $target.val($value + ' ' + value);
        } else {
            $target.val(value + ' ' + $value);
        }
    };

c) Example

$('textarea').each(function() {
  var $this = $(this);
  $this.click(function() {
    //get caret position
    var caret = getCaret($this);

    //append some text
    appendAtCaret($this, caret, 'Some text');
  });
});

How to Correctly Check if a Process is running and Stop it

Thanks @Joey. It's what I am looking for.

I just bring some improvements:

  • to take into account multiple processes
  • to avoid reaching the timeout when all processes have terminated
  • to package the whole in a function

function Stop-Processes {
    param(
        [parameter(Mandatory=$true)] $processName,
                                     $timeout = 5
    )
    $processList = Get-Process $processName -ErrorAction SilentlyContinue
    if ($processList) {
        # Try gracefully first
        $processList.CloseMainWindow() | Out-Null

        # Wait until all processes have terminated or until timeout
        for ($i = 0 ; $i -le $timeout; $i ++){
            $AllHaveExited = $True
            $processList | % {
                $process = $_
                If (!$process.HasExited){
                    $AllHaveExited = $False
                }                    
            }
            If ($AllHaveExited){
                Return
            }
            sleep 1
        }
        # Else: kill
        $processList | Stop-Process -Force        
    }
}

Efficient way to return a std::vector in c++

In C++11, this is the preferred way:

std::vector<X> f();

That is, return by value.

With C++11, std::vector has move-semantics, which means the local vector declared in your function will be moved on return and in some cases even the move can be elided by the compiler.

'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

I wrestled with this problem and implemented the URL concatenation solution contributed by @Kushan in the accepted answer above. It worked in my local MySql instance. But when I deployed my Play/Scala app to Heroku it no longer would work. Heroku also concatenates several args to the DB URL that they provide users, and this solution, because of Heroku's use concatenation of "?" before their own set of args, will not work. However I found a different solution which seems to work equally well.

SET sql_mode = 'NO_ZERO_DATE';

I put this in my table descriptions and it solved the problem of '0000-00-00 00:00:00' can not be represented as java.sql.Timestamp

$lookup on ObjectId's in an array

use $unwind you will get the first object instead of array of objects

query:

db.getCollection('vehicles').aggregate([
  {
    $match: {
      status: "AVAILABLE",
      vehicleTypeId: {
        $in: Array.from(newSet(d.vehicleTypeIds))
      }
    }
  },
  {
    $lookup: {
      from: "servicelocations",
      localField: "locationId",
      foreignField: "serviceLocationId",
      as: "locations"
    }
  },
  {
    $unwind: "$locations"
  }
]);

result:

{
    "_id" : ObjectId("59c3983a647101ec58ddcf90"),
    "vehicleId" : "45680",
    "regionId" : 1.0,
    "vehicleTypeId" : "10TONBOX",
    "locationId" : "100",
    "description" : "Isuzu/2003-10 Ton/Box",
    "deviceId" : "",
    "earliestStart" : 36000.0,
    "latestArrival" : 54000.0,
    "status" : "AVAILABLE",
    "accountId" : 1.0,
    "locations" : {
        "_id" : ObjectId("59c3afeab7799c90ebb3291f"),
        "serviceLocationId" : "100",
        "regionId" : 1.0,
        "zoneId" : "DXBZONE1",
        "description" : "Masafi Park Al Quoz",
        "locationPriority" : 1.0,
        "accountTypeId" : 0.0,
        "locationType" : "DEPOT",
        "location" : {
            "makani" : "",
            "lat" : 25.123091,
            "lng" : 55.21082
        },
        "deliveryDays" : "MTWRFSU",
        "timeWindow" : {
            "timeWindowTypeId" : "1"
        },
        "address1" : "",
        "address2" : "",
        "phone" : "",
        "city" : "",
        "county" : "",
        "state" : "",
        "country" : "",
        "zipcode" : "",
        "imageUrl" : "",
        "contact" : {
            "name" : "",
            "email" : ""
        },
        "status" : "",
        "createdBy" : "",
        "updatedBy" : "",
        "updateDate" : "",
        "accountId" : 1.0,
        "serviceTimeTypeId" : "1"
    }
}


{
    "_id" : ObjectId("59c3983a647101ec58ddcf91"),
    "vehicleId" : "81765",
    "regionId" : 1.0,
    "vehicleTypeId" : "10TONBOX",
    "locationId" : "100",
    "description" : "Hino/2004-10 Ton/Box",
    "deviceId" : "",
    "earliestStart" : 36000.0,
    "latestArrival" : 54000.0,
    "status" : "AVAILABLE",
    "accountId" : 1.0,
    "locations" : {
        "_id" : ObjectId("59c3afeab7799c90ebb3291f"),
        "serviceLocationId" : "100",
        "regionId" : 1.0,
        "zoneId" : "DXBZONE1",
        "description" : "Masafi Park Al Quoz",
        "locationPriority" : 1.0,
        "accountTypeId" : 0.0,
        "locationType" : "DEPOT",
        "location" : {
            "makani" : "",
            "lat" : 25.123091,
            "lng" : 55.21082
        },
        "deliveryDays" : "MTWRFSU",
        "timeWindow" : {
            "timeWindowTypeId" : "1"
        },
        "address1" : "",
        "address2" : "",
        "phone" : "",
        "city" : "",
        "county" : "",
        "state" : "",
        "country" : "",
        "zipcode" : "",
        "imageUrl" : "",
        "contact" : {
            "name" : "",
            "email" : ""
        },
        "status" : "",
        "createdBy" : "",
        "updatedBy" : "",
        "updateDate" : "",
        "accountId" : 1.0,
        "serviceTimeTypeId" : "1"
    }
}

Maintain image aspect ratio when changing height

I have been playing around flexbox lately and i came to solution for this through experimentation and the following reasoning. However, in reality I'm not sure if this is exactly what happens.

If real width is affected by flex system. So after width of elements hit max width of parent they extra width set in css is ignored. Then it's safe to set width to 100%.

Since height of img tag is derived from image itself then setting height to 0% could do something. (this is where i am unclear as to what...but it made sense to me that it should fix it)

DEMO

(remember saw it here first!)

.slider {
    display: flex;
}
.slider img {
    height: 0%;
    width: 100%;
    margin: 0 5px;
}

Works only in chrome yet

How to read a CSV file into a .NET Datatable

Can't resist adding my own spin to this. This is so much better and more compact than what I've used in the past.

This solution:

  • Does not depend on a database driver or 3rd party library.
  • Will not fail on duplicate column names
  • Handles commas in the data
  • Handles any delimiter, not just commas (although that is the default)

Here's what I came up with:

  Public Function ToDataTable(FileName As String, Optional Delimiter As String = ",") As DataTable
    ToDataTable = New DataTable
    Using TextFieldParser As New Microsoft.VisualBasic.FileIO.TextFieldParser(FileName) With
      {.HasFieldsEnclosedInQuotes = True, .TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited, .TrimWhiteSpace = True}
      With TextFieldParser
        .SetDelimiters({Delimiter})
        .ReadFields.ToList.Unique.ForEach(Sub(x) ToDataTable.Columns.Add(x))
        ToDataTable.Columns.Cast(Of DataColumn).ToList.ForEach(Sub(x) x.AllowDBNull = True)
        Do Until .EndOfData
          ToDataTable.Rows.Add(.ReadFields.Select(Function(x) Text.BlankToNothing(x)).ToArray)
        Loop
      End With
    End Using
  End Function

It depends on an extension method (Unique) to handle duplicate column names to be found as my answer in How to append unique numbers to a list of strings

And here's the BlankToNothing helper function:

  Public Function BlankToNothing(ByVal Value As String) As Object 
    If String.IsNullOrEmpty(Value) Then Return Nothing
    Return Value
  End Function

Sort list in C# with LINQ

Like this?

In LINQ:

var sortedList = originalList.OrderBy(foo => !foo.AVC)
                             .ToList();

Or in-place:

originalList.Sort((foo1, foo2) => foo2.AVC.CompareTo(foo1.AVC));

As Jon Skeet says, the trick here is knowing that false is considered to be 'smaller' than true.

If you find that you are doing these ordering operations in lots of different places in your code, you might want to get your type Foo to implement the IComparable<Foo> and IComparable interfaces.

What is /var/www/html?

/var/www/html is just the default root folder of the web server. You can change that to be whatever folder you want by editing your apache.conf file (usually located in /etc/apache/conf) and changing the DocumentRoot attribute (see http://httpd.apache.org/docs/current/mod/core.html#documentroot for info on that)

Many hosts don't let you change these things yourself, so your mileage may vary. Some let you change them, but only with the built in admin tools (cPanel, for example) instead of via a command line or editing the raw config files.

Can a table have two foreign keys?

CREATE TABLE User (
user_id INT NOT NULL AUTO_INCREMENT,
userName VARCHAR(100) NOT NULL,
password VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
userImage  LONGBLOB NOT NULL, 
Favorite VARCHAR(255) NOT NULL,
PRIMARY KEY (user_id)
);

and

CREATE TABLE Event (
    EventID INT NOT NULL AUTO_INCREMENT, 
    PRIMARY KEY (EventID),
    EventName VARCHAR(100) NOT NULL,
    EventLocation VARCHAR(100) NOT NULL,
    EventPriceRange VARCHAR(100) NOT NULL,
    EventDate Date NOT NULL,
    EventTime Time NOT NULL,
    EventDescription VARCHAR(255) NOT NULL,
    EventCategory VARCHAR(255) NOT NULL,
    EventImage  LONGBLOB NOT NULL,     
    index(EventID),
    FOREIGN KEY (EventID) REFERENCES User(user_id)
);

How to print colored text to the terminal?

I ended up doing this, and I felt it was cleanest:

formatters = {
    'RED': '\033[91m',
    'GREEN': '\033[92m',
    'END': '\033[0m',
}

print 'Master is currently {RED}red{END}!'.format(**formatters)
print 'Help make master {GREEN}green{END} again!'.format(**formatters)

initialize a vector to zeros C++/C++11

You don't need initialization lists for that:

std::vector<int> vector1(length, 0);
std::vector<double> vector2(length, 0.0);

Upload files with HTTPWebrequest (multipart/form-data)

Check out the MyToolkit library:

var request = new HttpPostRequest("http://www.server.com");
request.Data.Add("name", "value"); // POST data
request.Files.Add(new HttpPostFile("name", "file.jpg", "path/to/file.jpg")); 

await Http.PostAsync(request, OnRequestFinished);

http://mytoolkit.codeplex.com/wikipage?title=Http

PHP is_numeric or preg_match 0-9 validation

Not exactly the same.

From the PHP docs of is_numeric:

'42' is numeric
'1337' is numeric
'1e4' is numeric
'not numeric' is NOT numeric
'Array' is NOT numeric
'9.1' is numeric

With your regex you only check for 'basic' numeric values.

Also is_numeric() should be faster.

What's the u prefix in a Python string?

All strings meant for humans should use u"".

I found that the following mindset helps a lot when dealing with Python strings: All Python manifest strings should use the u"" syntax. The "" syntax is for byte arrays, only.

Before the bashing begins, let me explain. Most Python programs start out with using "" for strings. But then they need to support documentation off the Internet, so they start using "".decode and all of a sudden they are getting exceptions everywhere about decoding this and that - all because of the use of "" for strings. In this case, Unicode does act like a virus and will wreak havoc.

But, if you follow my rule, you won't have this infection (because you will already be infected).

How to send and retrieve parameters using $state.go toParams and $stateParams?

I was trying to Navigate from Page 1 to 2, and I had to pass some data as well.

In my router.js, I added params name and age :

.state('page2', {
          url: '/vehicle/:source',
          params: {name: null, age: null},
.................

In Page1, onClick of next button :

$state.go("page2", {name: 'Ron', age: '20'});

In Page2, I could access those params :

$stateParams.name
$stateParams.age

One time page refresh after first page load

Use rel="external" like below is the example

<li><a href="index.html" rel="external" data-theme="c">Home</a></li>

How to specify font attributes for all elements on an html web page?

If you're using IE, chances are it will revert to the browser defaults for certain elements, like tables. You can counter that with something like the following CSS:

html, body, form, fieldset, table, tr, td, img {
    margin: 0;
    padding: 0;
    font: 100%/150% calibri,helvetica,sans-serif;
}

input, button, select, textarea, optgroup, option {
    font-family: inherit;
    font-size: inherit;
    font-style: inherit;
    font-weight: inherit;
}

/* rest of your styles; like: */
body {
    font-size: 0.875em;
}

Edit: you may want to read up on CSS resets; see threads like this one

Error - replacement has [x] rows, data has [y]

You could use cut

 df$valueBin <- cut(df$value, c(-Inf, 250, 500, 1000, 2000, Inf), 
    labels=c('<=250', '250-500', '500-1,000', '1,000-2,000', '>2,000'))

data

 set.seed(24)
 df <- data.frame(value= sample(0:2500, 100, replace=TRUE))

Permanently adding a file path to sys.path in Python

This way worked for me:

adding the path that you like:

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

checking: you can run 'export' cmd and check the output or you can check it using this cmd:

python -c "import sys; print(sys.path)"

How to install all required PHP extensions for Laravel?

Laravel Server Requirements mention that BCMath, Ctype, JSON, Mbstring, OpenSSL, PDO, Tokenizer, and XML extensions are required. Most of the extensions are installed and enabled by default.

You can run the following command in Ubuntu to make sure the extensions are installed.

sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip

PHP version specific installation (if PHP 7.4 installed)

sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring

You may need other PHP extensions for your composer packages. Find from links below.

PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)

PHP extensions for Ubuntu 18.04 LTS (Bionic)

PHP extensions for Ubuntu 16.04 LTS (Xenial)

How to install the Sun Java JDK on Ubuntu 10.10 (Maverick Meerkat)?

Installation:

for 10.10:

sudo add-apt-repository "deb http://archive.canonical.com/ maverick partner"

for 11.04

sudo add-apt-repository "deb http://archive.canonical.com/ natty partner"

Continue with:

sudo apt-get update
sudo apt-get install sun-java6-jre sun-java6-plugin

Use as default:

sudo update-alternatives --config java

Installing JDK:

sudo apt-get install sun-java6-jdk

Source code (to be used in development):

sudo apt-get install sun-java6-source

Source of these instructions: https://help.ubuntu.com/community/Java

How to check if IEnumerable is null or empty?

Here's the code from Marc Gravell's answer, along with an example of using it.

using System;
using System.Collections.Generic;
using System.Linq;

public static class Utils
{
    public static bool IsAny<T>(this IEnumerable<T> data)
    {
        return data != null && data.Any();
    }
}

class Program
{
    static void Main(string[] args)
    {
        IEnumerable<string> items;
        //items = null;
        //items = new String[0];
        items = new String[] { "foo", "bar", "baz" };

        /*** Example Starts Here ***/
        if (items.IsAny())
        {
            foreach (var item in items)
            {
                Console.WriteLine(item);
            }
        }
        else
        {
            Console.WriteLine("No items.");
        }
    }
}

As he says, not all sequences are repeatable, so that code may sometimes cause problems, because IsAny() starts stepping through the sequence. I suspect what Robert Harvey's answer meant was that you often don't need to check for null and empty. Often, you can just check for null and then use foreach.

To avoid starting the sequence twice and take advantage of foreach, I just wrote some code like this:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        IEnumerable<string> items;
        //items = null;
        //items = new String[0];
        items = new String[] { "foo", "bar", "baz" };

        /*** Example Starts Here ***/
        bool isEmpty = true;
        if (items != null)
        {
            foreach (var item in items)
            {
                isEmpty = false;
                Console.WriteLine(item);
            }
        }
        if (isEmpty)
        {
            Console.WriteLine("No items.");
        }
    }
}

I guess the extension method saves you a couple of lines of typing, but this code seems clearer to me. I suspect that some developers wouldn't immediately realize that IsAny(items) will actually start stepping through the sequence. (Of course if you're using a lot of sequences, you quickly learn to think about what steps through them.)

How to check if a Unix .tar.gz file is a valid file without uncompressing?

These are all very sub-optimal solutions. From the GZIP spec

ID2 (IDentification 2)
These have the fixed values ID1 = 31 (0x1f, \037), ID2 = 139 (0x8b, \213), to identify the file as being in gzip format.

Has to be coded into whatever language you're using.

Linux Process States

Assuming your process is a single thread, and that you're using blocking I/O, your process will block waiting for the I/O to complete. The kernel will pick another process to run in the meantime based on niceness, priority, last run time, etc. If there are no other runnable processes, the kernel won't run any; instead, it'll tell the hardware the machine is idle (which will result in lower power consumption).

Processes that are waiting for I/O to complete typically show up in state D in, e.g., ps and top.

When do you use varargs in Java?

Varargs can be used when we are unsure about the number of arguments to be passed in a method. It creates an array of parameters of unspecified length in the background and such a parameter can be treated as an array in runtime.

If we have a method which is overloaded to accept different number of parameters, then instead of overloading the method different times, we can simply use varargs concept.

Also when the parameters' type is going to vary then using "Object...test" will simplify the code a lot.

For example:

public int calculate(int...list) {
    int sum = 0;
    for (int item : list) {
        sum += item;
    }
    return sum;
}

Here indirectly an array of int type (list) is passed as parameter and is treated as an array in the code.

For a better understanding follow this link(it helped me a lot in understanding this concept clearly): http://www.javadb.com/using-varargs-in-java

P.S: Even I was afraid of using varargs when I didn't knw abt it. But now I am used to it. As it is said: "We cling to the known, afraid of the unknown", so just use it as much as you can and you too will start liking it :)

Problems installing the devtools package

I hit this issue with Ubuntu 18.04 and none of the previous answers solved it. Eventually I succeeded by installing devtools with the package manager itself:

sudo apt install r-cran-devtools

Set a cookie to HttpOnly via Javascript

An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly.

Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly by just XSS and still have access to the cookie via JS and thus make the HttpOnly on your cookie completely useless.

Getting value GET OR POST variable using JavaScript?

You can only get the URI arguments with JavaScript.

// get query arguments
var $_GET = {},
    args = location.search.substr(1).split(/&/);
for (var i=0; i<args.length; ++i) {
    var tmp = args[i].split(/=/);
    if (tmp[0] != "") {
        $_GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp.slice(1).join("").replace("+", " "));
    }
}

Open file in a relative location in Python

This code works fine:

import os


def readFile(filename):
    filehandle = open(filename)
    print filehandle.read()
    filehandle.close()



fileDir = os.path.dirname(os.path.realpath('__file__'))
print fileDir

#For accessing the file in the same folder
filename = "same.txt"
readFile(filename)

#For accessing the file in a folder contained in the current folder
filename = os.path.join(fileDir, 'Folder1.1/same.txt')
readFile(filename)

#For accessing the file in the parent folder of the current folder
filename = os.path.join(fileDir, '../same.txt')
readFile(filename)

#For accessing the file inside a sibling folder.
filename = os.path.join(fileDir, '../Folder2/same.txt')
filename = os.path.abspath(os.path.realpath(filename))
print filename
readFile(filename)

How to add external fonts to android application

I recommend this approach it very nice with adding name of custom font in typeface to styles.xml and putting your set of fonts into assets folder.

Why is __init__() always called after __new__()?

Use __new__ when you need to control the creation of a new instance.

Use __init__ when you need to control initialization of a new instance.

__new__ is the first step of instance creation. It's called first, and is responsible for returning a new instance of your class.

In contrast, __init__ doesn't return anything; it's only responsible for initializing the instance after it's been created.

In general, you shouldn't need to override __new__ unless you're subclassing an immutable type like str, int, unicode or tuple.

From April 2008 post: When to use __new__ vs. __init__? on mail.python.org.

You should consider that what you are trying to do is usually done with a Factory and that's the best way to do it. Using __new__ is not a good clean solution so please consider the usage of a factory. Here you have a good factory example.

MySQL - sum column value(s) based on row from the same table

SUM CASE using example:

    SELECT 
  DISTINCT(p.`ProductID`) AS ProductID,
  SUM(IF(p.`PaymentMethod`='Cash',Amount,0)) AS Cash_,
  SUM(IF(p.`PaymentMethod`='Check',Amount,0)) AS Check_,
  SUM(IF(p.`PaymentMethod`='Credit Card',Amount,0)) AS Credit_Card_,
  SUM( CASE PaymentMethod 
      WHEN 'Cash' THEN Amount
      WHEN 'Check' THEN Amount
      WHEN 'Credit Card' THEN Amount
     END) AS Total
FROM
  `payments` AS p 
GROUP BY p.`ProductID`;

SQL FIDDLE: http://www.sqlfiddle.com/#!9/23d07d/18

Result and Table view

What does it mean to "program to an interface"?

Imagine you have a product called 'Zebra' that can be extended by plugins. It finds the plugins by searching for DLLs in some directory. It loads all those DLLs and uses reflection to find any classes that implement IZebraPlugin, and then calls the methods of that interface to communicate with the plugins.

This makes it completely independent of any specific plugin class - it doesn't care what the classes are. It only cares that they fulfill the interface specification.

Interfaces are a way of defining points of extensibility like this. Code that talks to an interface is more loosely coupled - in fact it is not coupled at all to any other specific code. It can inter-operate with plugins written years later by people who have never met the original developer.

You could instead use a base class with virtual functions - all plugins would be derived from the base class. But this is much more limiting because a class can only have one base class, whereas it can implement any number of interfaces.

JavaScriptSerializer.Deserialize - how to change field names

By creating a custom JavaScriptConverter you can map any name to any property. But it does require hand coding the map, which is less than ideal.

public class DataObjectJavaScriptConverter : JavaScriptConverter
{
    private static readonly Type[] _supportedTypes = new[]
    {
        typeof( DataObject )
    };

    public override IEnumerable<Type> SupportedTypes 
    { 
        get { return _supportedTypes; } 
    }

    public override object Deserialize( IDictionary<string, object> dictionary, 
                                        Type type, 
                                        JavaScriptSerializer serializer )
    {
        if( type == typeof( DataObject ) )
        {
            var obj = new DataObject();
            if( dictionary.ContainsKey( "user_id" ) )
                obj.UserId = serializer.ConvertToType<int>( 
                                           dictionary["user_id"] );
            if( dictionary.ContainsKey( "detail_level" ) )
                obj.DetailLevel = serializer.ConvertToType<DetailLevel>(
                                           dictionary["detail_level"] );

            return obj;
        }

        return null;
    }

    public override IDictionary<string, object> Serialize( 
            object obj, 
            JavaScriptSerializer serializer )
    {
        var dataObj = obj as DataObject;
        if( dataObj != null )
        {
            return new Dictionary<string,object>
            {
                {"user_id", dataObj.UserId },
                {"detail_level", dataObj.DetailLevel }
            }
        }
        return new Dictionary<string, object>();
    }
}

Then you can deserialize like so:

var serializer = new JavaScriptSerializer();
serialzer.RegisterConverters( new[]{ new DataObjectJavaScriptConverter() } );
var dataObj = serializer.Deserialize<DataObject>( json );

Display image at 50% of its "native" size

The zoom property sounds as though it's perfect for Adam Ernst as it suits his target device. However, for those who need a solution to this and have to support as many devices as possible you can do the following:

<img src="..." onload="this.width/=2;this.onload=null;" />

The reason for the this.onload=null addition is to avoid older browsers that sometimes trigger the load event twice (which means you can end up with quater-sized images). If you aren't worried about that though you could write:

<img src="..." onload="this.width/=2;" />

Which is quite succinct.

What is the path that Django uses for locating and loading templates?

Contrary to some answers posted in this thread, adding 'DIRS': ['templates'] has no effect(it's redundant) since templates is the default path where Django looks for templates.

If you are attempting to reference an app's template, ensure that your app is in the list of INSTALLED_APPS in the main project settings.py.

INSTALLED_APPS': [
   # ...
   'my_app',
]

Quoting Django's Templates documentation:

class DjangoTemplates¶

Set BACKEND to 'django.template.backends.django.DjangoTemplates' to configure a Django template engine.

When APP_DIRS is True, DjangoTemplates engines look for templates in the templates subdirectory of installed applications. This generic name was kept for backwards-compatibility.

When you create an application to your project, there's no templates directory inside the application directory. Since that you can have an application without using templates, Django doesn't create such directory. That is, you have to create it and storing your templates in there.

Here's another paragraph from Django Tutorial documentation, which is even clearer:

Your project’s TEMPLATES setting describes how Django will load and render templates. The default settings file configures a DjangoTemplates backend whose APP_DIRS option is set to True. By convention DjangoTemplates looks for a “templates” subdirectory in each of the INSTALLED_APPS.

How can I insert multiple rows into oracle with a sequence value?

This works:

insert into TABLE_NAME (COL1,COL2)
select my_seq.nextval, a
from
(SELECT 'SOME VALUE' as a FROM DUAL
 UNION ALL
 SELECT 'ANOTHER VALUE' FROM DUAL)

ECMAScript 6 arrow function that returns an object

Issue:

When you do are doing:

p => {foo: "bar"}

JavaScript interpreter thinks you are opening a multi-statement code block, and in that block, you have to explicitly mention a return statement.

Solution:

If your arrow function expression has a single statement, then you can use the following syntax:

p => ({foo: "bar", attr2: "some value", "attr3": "syntax choices"})

But if you want to have multiple statements then you can use the following syntax:

p => {return {foo: "bar", attr2: "some value", "attr3": "syntax choices"}}

In above example, first set of curly braces opens a multi-statement code block, and the second set of curly braces is for dynamic objects. In multi-statement code block of arrow function, you have to explicitly use return statements

For more details, check Mozilla Docs for JS Arrow Function Expressions

hidden field in php

You absolutely can, I use this approach a lot w/ both JavaScript and PHP.

Field definition:

<input type="hidden" name="foo" value="<?php echo $var;?>" />

Access w/ PHP:

$_GET['foo'] or $_POST['foo']

Also: Don't forget to sanitize your inputs if they are going into a database. Feel free to use my routine: https://github.com/niczak/PHP-Sanitize-Post/blob/master/sanitize.php

Cheers!

URL Encode a string in jQuery for an AJAX request

encodeURIComponent works fine for me. we can give the url like this in ajax call.The code shown below:

  $.ajax({
    cache: false,
    type: "POST",
    url: "http://atandra.mivamerchantdev.com//mm5/json.mvc?Store_Code=ATA&Function=Module&Module_Code=thub_connector&Module_Function=THUB_Request",
    data: "strChannelName=" + $('#txtupdstorename').val() + "&ServiceUrl=" + encodeURIComponent($('#txtupdserviceurl').val()),
    dataType: "HTML",
    success: function (data) {
    },
    error: function (xhr, ajaxOptions, thrownError) {
    }
  });

javascript regex for special characters

this is the actual regex only match:

/[-!$%^&*()_+|~=`{}[:;<>?,.@#\]]/g

String.Format not work in TypeScript

String Interpolation

Note: As of TypeScript 1.4, string interpolation is available in TypeScript:

var a = "Hello";
var b = "World";

var text = `${a} ${b}`

This will compile to:

var a = "Hello";
var b = "World";
var text = a + " " + b;

String Format

The JavaScript String object doesn't have a format function. TypeScript doesn't add to the native objects, so it also doesn't have a String.format function.

For TypeScript, you need to extend the String interface and then you need to supply an implementation:

interface String {
    format(...replacements: string[]): string;
}

if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}

You can then use the feature:

var myStr = 'This is an {0} for {0} purposes: {1}';

alert(myStr.format('example', 'end'));

You could also consider string interpolation (a feature of Template Strings), which is an ECMAScript 6 feature - although to use it for the String.format use case, you would still need to wrap it in a function in order to supply a raw string containing the format and then positional arguments. It is more typically used inline with the variables that are being interpolated, so you'd need to map using arguments to make it work for this use case.

For example, format strings are normally defined to be used later... which doesn't work:

// Works
var myFormatString = 'This is an {0} for {0} purposes: {1}';

// Compiler warnings (a and b not yet defines)
var myTemplateString = `This is an ${a} for ${a} purposes: ${b}`;

So to use string interpolation, rather than a format string, you would need to use:

function myTemplate(a: string, b: string) {
    var myTemplateString = `This is an ${a} for ${a} purposes: ${b}`;
}

alert(myTemplate('example', 'end'));

The other common use case for format strings is that they are used as a resource that is shared. I haven't yet discovered a way to load a template string from a data source without using eval.

Does a VPN Hide my Location on Android?

Your question can be conveniently divided into several parts:

Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.

How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.

You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):

  1. Download and install a trusted VPN.

  2. Install the VPN on your Android device.

  3. Open the application and connect to a server in a different country.

  4. Your Android location will now be successfully changed!

Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.

Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.

Load arrayList data into JTable

"The problem is that i cant find a way to set a fixed number of rows"

You don't need to set the number of rows. Use a TableModel. A DefaultTableModel in particular.

String col[] = {"Pos","Team","P", "W", "L", "D", "MP", "GF", "GA", "GD"};

DefaultTableModel tableModel = new DefaultTableModel(col, 0);
                                            // The 0 argument is number rows.

JTable table = new JTable(tableModel);

Then you can add rows to the tableModel with an Object[]

Object[] objs = {1, "Arsenal", 35, 11, 2, 2, 15, 30, 11, 19};

tableModel.addRow(objs);

You can loop to add your Object[] arrays.

Note: JTable does not currently allow instantiation with the input data as an ArrayList. It must be a Vector or an array.

See JTable and DefaultTableModel. Also, How to Use JTable tutorial

"I created an arrayList from it and I somehow can't find a way to store this information into a JTable."

You can do something like this to add the data

ArrayList<FootballClub> originalLeagueList = new ArrayList<FootballClub>();

originalLeagueList.add(new FootballClub(1, "Arsenal", 35, 11, 2, 2, 15, 30, 11, 19));
originalLeagueList.add(new FootballClub(2, "Liverpool", 30, 9, 3, 3, 15, 34, 18, 16));
originalLeagueList.add(new FootballClub(3, "Chelsea", 30, 9, 2, 2, 15, 30, 11, 19));
originalLeagueList.add(new FootballClub(4, "Man City", 29, 9, 2, 4, 15, 41, 15, 26));
originalLeagueList.add(new FootballClub(5, "Everton", 28, 7, 1, 7, 15, 23, 14, 9));
originalLeagueList.add(new FootballClub(6, "Tottenham", 27, 8, 4, 3, 15, 15, 16, -1));
originalLeagueList.add(new FootballClub(7, "Newcastle", 26, 8, 5, 2, 15, 20, 21, -1));
originalLeagueList.add(new FootballClub(8, "Southampton", 23, 6, 4, 5, 15, 19, 14, 5));

for (int i = 0; i < originalLeagueList.size(); i++){
   int position = originalLeagueList.get(i).getPosition();
   String name = originalLeagueList.get(i).getName();
   int points = originalLeagueList.get(i).getPoinst();
   int wins = originalLeagueList.get(i).getWins();
   int defeats = originalLeagueList.get(i).getDefeats();
   int draws = originalLeagueList.get(i).getDraws();
   int totalMatches = originalLeagueList.get(i).getTotalMathces();
   int goalF = originalLeagueList.get(i).getGoalF();
   int goalA = originalLeagueList.get(i).getGoalA();
   in ttgoalD = originalLeagueList.get(i).getTtgoalD();

   Object[] data = {position, name, points, wins, defeats, draws, 
                               totalMatches, goalF, goalA, ttgoalD};

   tableModel.add(data);

}

Escaping Double Quotes in Batch Script

As an addition to mklement0's excellent answer:

Almost all executables accept \" as an escaped ". Safe usage in cmd however is almost only possible using DELAYEDEXPANSION.
To explicitely send a literal " to some process, assign \" to an environment variable, and then use that variable, whenever you need to pass a quote. Example:

SETLOCAL ENABLEDELAYEDEXPANSION
set q=\"
child "malicious argument!q!&whoami"

Note SETLOCAL ENABLEDELAYEDEXPANSION seems to work only within batch files. To get DELAYEDEXPANSION in an interactive session, start cmd /V:ON.

If your batchfile does't work with DELAYEDEXPANSION, you can enable it temporarily:

::region without DELAYEDEXPANSION

SETLOCAL ENABLEDELAYEDEXPANSION
::region with DELAYEDEXPANSION
set q=\"
echoarg.exe "ab !q! & echo danger"
ENDLOCAL

::region without DELAYEDEXPANSION

If you want to pass dynamic content from a variable that contains quotes that are escaped as "" you can replace "" with \" on expansion:

SETLOCAL ENABLEDELAYEDEXPANSION
foo.exe "danger & bar=region with !dynamic_content:""=\"! & danger"
ENDLOCAL

This replacement is not safe with %...% style expansion!

In case of OP bash -c "g++-linux-4.1 !v_params:"=\"!" is the safe version.


If for some reason even temporarily enabling DELAYEDEXPANSION is not an option, read on:

Using \" from within cmd is a little bit safer if one always needs to escape special characters, instead of just sometimes. (It's less likely to forget a caret, if it's consistent...)

To achieve this, one precedes any quote with a caret (^"), quotes that should reach the child process as literals must additionally be escaped with a backlash (\^"). ALL shell meta characters must be escaped with ^ as well, e.g. & => ^&; | => ^|; > => ^>; etc.

Example:

child ^"malicious argument\^"^&whoami^"

Source: Everyone quotes command line arguments the wrong way, see "A better method of quoting"


To pass dynamic content, one needs to ensure the following:
The part of the command that contains the variable must be considered "quoted" by cmd.exe (This is impossible if the variable can contain quotes - don't write %var:""=\"%). To achieve this, the last " before the variable and the first " after the variable are not ^-escaped. cmd-metacharacters between those two " must not be escaped. Example:

foo.exe ^"danger ^& bar=\"region with %dynamic_content% & danger\"^"

This isn't safe, if %dynamic_content% can contain unmatched quotes.

How to get the screen width and height in iOS?

It's very, very easy to get your device size as well as take into account the orientation:

// grab the window frame and adjust it for orientation
UIView *rootView = [[[UIApplication sharedApplication] keyWindow] 
                                   rootViewController].view;
CGRect originalFrame = [[UIScreen mainScreen] bounds];
CGRect adjustedFrame = [rootView convertRect:originalFrame fromView:nil];

Convert string to Time

string Time = "16:23:01";
DateTime date = DateTime.Parse(Time, System.Globalization.CultureInfo.CurrentCulture);

string t = date.ToString("HH:mm:ss tt");

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided does not match the recipient window's origin ('null')

In My Case, Im trying to pass messages from Salesforce Marketing Cloud Custom Activity(Domain 1) to Heroku(Domain 2) on load.

The Error Appeared in console, when I loaded my original html page from where message is being passed.

Issue I noticed after reading many blogs is that, the receiver page is not loaded yet. i.e

I need to debug from my receiver page not from sender page.

Simple but glad if it helps anyone.

Creating SVG elements dynamically with javascript inside HTML

Add this to html:

<svg id="mySVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"/>

Try this function and adapt for you program:

var svgNS = "http://www.w3.org/2000/svg";  

function createCircle()
{
    var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle. for rectangle use "rectangle"
    myCircle.setAttributeNS(null,"id","mycircle");
    myCircle.setAttributeNS(null,"cx",100);
    myCircle.setAttributeNS(null,"cy",100);
    myCircle.setAttributeNS(null,"r",50);
    myCircle.setAttributeNS(null,"fill","black");
    myCircle.setAttributeNS(null,"stroke","none");

    document.getElementById("mySVG").appendChild(myCircle);
}     

X close button only using css

Here's some variety for you with several sizes and hover animations.. demo(link)

enter image description here

<ul>
  <li>Large</li>
  <li>Medium</li>
  <li>Small</li>
  <li>Switch</li>
</ul>

<ul>
  <li class="ele">
    <div class="x large"><b></b><b></b><b></b><b></b></div>
    <div class="x spin large"><b></b><b></b><b></b><b></b></div>
    <div class="x spin large slow"><b></b><b></b><b></b><b></b></div>
    <div class="x flop large"><b></b><b></b><b></b><b></b></div>
    <div class="x t large"><b></b><b></b><b></b><b></b></div>
    <div class="x shift large"><b></b><b></b><b></b><b></b></div>
  </li>
  <li class="ele">
    <div class="x medium"><b></b><b></b><b></b><b></b></div>
    <div class="x spin medium"><b></b><b></b><b></b><b></b></div>
    <div class="x spin medium slow"><b></b><b></b><b></b><b></b></div>
    <div class="x flop medium"><b></b><b></b><b></b><b></b></div>
    <div class="x t medium"><b></b><b></b><b></b><b></b></div>
    <div class="x shift medium"><b></b><b></b><b></b><b></b></div>

  </li>
  <li class="ele">
    <div class="x small"><b></b><b></b><b></b><b></b></div>
    <div class="x spin small"><b></b><b></b><b></b><b></b></div>
    <div class="x spin small slow"><b></b><b></b><b></b><b></b></div>
    <div class="x flop small"><b></b><b></b><b></b><b></b></div>
    <div class="x t small"><b></b><b></b><b></b><b></b></div>
    <div class="x shift small"><b></b><b></b><b></b><b></b></div>
    <div class="x small grow"><b></b><b></b><b></b><b></b></div>

  </li>
  <li class="ele">
    <div class="x switch"><b></b><b></b><b></b><b></b></div>
  </li>
</ul>

css

.ele div.x {
-webkit-transition-duration:0.5s;
  transition-duration:0.5s;
}

.ele div.x.slow {
-webkit-transition-duration:1s;
  transition-duration:1s;
}

ul { list-style:none;float:left;display:block;width:100%; }
li { display:inline;width:25%;float:left; }
.ele { width:25%;display:inline; }
.x {
  float:left;
  position:relative;
  margin:0;
  padding:0;
  overflow:hidden;
  background:#CCC;
  border-radius:2px;
  border:solid 2px #FFF;
  transition: all .3s ease-out;
  cursor:pointer;
}
.x.large { 
  width:30px;
  height:30px;
}

.x.medium {
  width:20px;
  height:20px;
}

.x.small {
  width:10px;
  height:10px;
}

.x.switch {
  width:15px;
  height:15px;
}
.x.grow {

}

.x.spin:hover{
  background:#BB3333;
  transform: rotate(180deg);
}
.x.flop:hover{
  background:#BB3333;
  transform: rotate(90deg);
}
.x.t:hover{
  background:#BB3333;
  transform: rotate(45deg);
}
.x.shift:hover{
  background:#BB3333;
}

.x b{
  display:block;
  position:absolute;
  height:0;
  width:0;
  padding:0;
  margin:0;
}
.x.small b {
  border:solid 5px rgba(255,255,255,0);
}
.x.medium b {
  border:solid 10px rgba(255,255,255,0);
}
.x.large b {
  border:solid 15px rgba(255,255,255,0);
}
.x.switch b {
  border:solid 10px rgba(255,255,255,0);
}

.x b:nth-child(1){
  border-top-color:#FFF;
  top:-2px;
}
.x b:nth-child(2){
  border-left-color:#FFF;
  left:-2px;
}
.x b:nth-child(3){
  border-bottom-color:#FFF;
  bottom:-2px;
}
.x b:nth-child(4){
  border-right-color:#FFF;
  right:-2px;
}

MSSQL Regular expression

Thank you all for your help.

This is what I have used in the end:

SELECT *, 
  CASE WHEN [url] NOT LIKE '%[^-A-Za-z0-9/.+$]%' 
    THEN 'Valid' 
    ELSE 'No valid' 
  END [Validate]
FROM 
  *table*
  ORDER BY [Validate]

Accessing constructor of an anonymous class

Yes , It is right that you can not define construct in an Anonymous class but it doesn't mean that anonymous class don't have constructor. Confuse... Actually you can not define construct in an Anonymous class but compiler generates an constructor for it with the same signature as its parent constructor called. If the parent has more than one constructor, the anonymous will have one and only one constructor

How to get the query string by javascript?

// Assuming "?post=1234&action=edit"

var urlParams = new URLSearchParams(window.location.search);

console.log(urlParams.has('post')); // true

console.log(urlParams.get('action')); // "edit"

console.log(urlParams.getAll('action')); // ["edit"]

console.log(urlParams.toString()); // "?post=1234&action=edit"

console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"

What values can I pass to the event attribute of the f:ajax tag?

The event attribute of <f:ajax> can hold at least all supported DOM events of the HTML element which is been generated by the JSF component in question. An easy way to find them all out is to check all on* attribues of the JSF input component of interest in the JSF tag library documentation and then remove the "on" prefix. For example, the <h:inputText> component which renders <input type="text"> lists the following on* attributes (of which I've already removed the "on" prefix so that it ultimately becomes the DOM event type name):

  • blur
  • change
  • click
  • dblclick
  • focus
  • keydown
  • keypress
  • keyup
  • mousedown
  • mousemove
  • mouseout
  • mouseover
  • mouseup
  • select

Additionally, JSF has two more special event names for EditableValueHolder and ActionSource components, the real HTML DOM event being rendered depends on the component type:

  • valueChange (will render as change on text/select inputs and as click on radio/checkbox inputs)
  • action (will render as click on command links/buttons)

The above two are the default events for the components in question.

Some JSF component libraries have additional customized event names which are generally more specialized kinds of valueChange or action events, such as PrimeFaces <p:ajax> which supports among others tabChange, itemSelect, itemUnselect, dateSelect, page, sort, filter, close, etc depending on the parent <p:xxx> component. You can find them all in the "Ajax Behavior Events" subsection of each component's chapter in PrimeFaces Users Guide.

How to check if DST (Daylight Saving Time) is in effect, and if so, the offset?

Create two dates: one in June, one in January. Compare their getTimezoneOffset() values.

  • if January offset > June offset, client is in northern hemisphere
  • if January offset < June offset, client is in southern hemisphere
  • if no difference, client timezone does not observe DST

Now check getTimezoneOffset() of the current date.

  • if equal to June, northern hemisphere, then current time zone is DST (+1 hour)
  • if equal to January, southern hemisphere, then current time zone is DST (+1 hour)

What are OLTP and OLAP. What is the difference between them?

The difference is quite simple:

OLTP (Online Transaction Processing)

OLTP is a class of information systems that facilitate and manage transaction-oriented applications. OLTP has also been used to refer to processing in which the system responds immediately to user requests. Online transaction processing applications are high throughput and insert or update-intensive in database management. Some examples of OLTP systems include order entry, retail sales, and financial transaction systems.

OLAP (Online Analytical Processing)

OLAP is part of the broader category of business intelligence, which also encompasses relational database, report writing and data mining. Typical applications of OLAP include business reporting for sales, marketing, management reporting, business process management (BPM), budgeting and forecasting, financial reporting and similar areas.

See more details OLTP and OLAP

C++ Passing Pointer to Function (Howto) + C++ Pointer Manipulation

To pass a pointer to an int it should be void Fun(int* pointer).

Passing a reference to an int would look like this...

void Fun(int& ref) {
   ref = 10;
}

int main() {
   int test = 5;
   cout << test << endl;  // prints 5

   Fun(test);
   cout << test << endl;  // prints 10 because Fun modified the value

   return 1;
}

Are Git forks actually Git clones?

Apart from the fact that cloning is from server to your machine and forking is making a copy on the server itself, an important difference is that when we clone, we actually get all the branches, labels, etc.

But when we fork, we actually only get the current files in the master branch, nothing other than that. This means we don't get the other branches, etc.

Hence if you have to merge something back to the original repository, it is a inter-repository merge and will definitely need higher privileges.

Fork is not a command in Git; it is just a concept which GitHub implements. Remember Git was designed to work in peer-to-peer environment without the need to synchronize stuff with any master copy. The server is just another peer, but we look at it as a master copy.

Switch statement multiple cases in JavaScript

In Javascript to assign multiple cases in a switch, we have to define different case without break inbetween like given below:

   <script>
      function checkHere(varName){
        switch (varName)
           {
           case "saeed":
           case "larry":
           case "afshin":
                alert('Hey');
                break;
          case "ss":
               alert('ss');
               break;
         default:
               alert('Default case');
               break;
       }
      }
     </script>

Please see example click on link

Log4j: How to configure simplest possible file logging?

Here is a log4j.properties file that I've used with great success.

logDir=/var/log/myapp

log4j.rootLogger=INFO, stdout
#log4j.rootLogger=DEBUG, stdout

log4j.appender.stdout=org.apache.log4j.DailyRollingFileAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{MM/dd/yyyy hh:mm:ss a}|%-5p|%-30c{1}| %m%n
log4j.appender.stdout.DatePattern='.'yyyy-MM-dd
log4j.appender.stdout.File=${logDir}/myapp.log
log4j.appender.stdout.append=true

The DailyRollingFileAppender will create new files each day with file names that look like this:

myapp.log.2017-01-27
myapp.log.2017-01-28
myapp.log.2017-01-29
myapp.log  <-- today's log

Each entry in the log file will will have this format:

01/30/2017 12:59:47 AM|INFO |Component1   | calling foobar(): userId=123, returning totalSent=1
01/30/2017 12:59:47 AM|INFO |Component2   | count=1 > 0, calling fooBar()

Set the location of the above file by using -Dlog4j.configuration, as mentioned in this posting:

java -Dlog4j.configuration=file:/home/myapp/config/log4j.properties com.foobar.myapp

In your Java code, be sure to set the name of each software component when you instantiate your logger object. I also like to log to both the log file and standard output, so I wrote this small function.

private static final Logger LOGGER = Logger.getLogger("Component1");

public static void log(org.apache.log4j.Logger logger, String message) {

    logger.info(message);
    System.out.printf("%s\n", message);
}

public static String stackTraceToString(Exception ex) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    ex.printStackTrace(pw);
    return sw.toString();
}

And then call it like so:

LOGGER.info(String.format("Exception occurred: %s", stackTraceToString(ex)));

Access a JavaScript variable from PHP

If showing data to the user, do a redirect:

<script language="JavaScript">
    var tester = "foobar";
    document.location="http://www.host.org/myphp.php?test=" + tester;
</script>

or an iframe:

<script language="JavaScript">
    var tester = "foobar";
    document.write("<iframe src=\"http://www.host.org/myphp.php?test=" + tester + "\"></iframe>");
</script>

If you don't need user output, create an iframe with width=0 and height=0.

change Oracle user account status from EXPIRE(GRACE) to OPEN

In case you know the password of that user, or you would like to guess it, do the following:

  • connect user/password

If this command connects successufully, you will see the message "connected", otherwise you'd see an error message. If you are then successufull logging, that means that you know the password. In that case, just do:

  • alter user NAME_OF_THE_USER identified by OLD_PASSWORD;

and this will reset the password to the same password as before and also reset the account_status for that user.

How do I programmatically "restart" an Android app?

You can restart your current activity like this:

Fragment :

activity?.recreate()

Activity :

recreate()

Converting from longitude\latitude to Cartesian coordinates

Theory for convert GPS(WGS84) to Cartesian coordinates https://en.wikipedia.org/wiki/Geographic_coordinate_conversion#From_geodetic_to_ECEF_coordinates

The following is what I am using:

  • Longitude in GPS(WGS84) and Cartesian coordinates are the same.
  • Latitude need be converted by WGS 84 ellipsoid parameters semi-major axis is 6378137 m, and
  • Reciprocal of flattening is 298.257223563.

I attached a VB code I wrote:

Imports System.Math

'Input GPSLatitude is WGS84 Latitude,h is altitude above the WGS 84 ellipsoid

Public Function GetSphericalLatitude(ByVal GPSLatitude As Double, ByVal h As Double) As Double

        Dim A As Double = 6378137 'semi-major axis 
        Dim f As Double = 1 / 298.257223563  '1/f Reciprocal of flattening
        Dim e2 As Double = f * (2 - f)
        Dim Rc As Double = A / (Sqrt(1 - e2 * (Sin(GPSLatitude * PI / 180) ^ 2)))
        Dim p As Double = (Rc + h) * Cos(GPSLatitude * PI / 180)
        Dim z As Double = (Rc * (1 - e2) + h) * Sin(GPSLatitude * PI / 180)
        Dim r As Double = Sqrt(p ^ 2 + z ^ 2)
        Dim SphericalLatitude As Double =  Asin(z / r) * 180 / PI
        Return SphericalLatitude
End Function

Please notice that the h is altitude above the WGS 84 ellipsoid.

Usually GPS will give us H of above MSL height. The MSL height has to be converted to height h above the WGS 84 ellipsoid by using the geopotential model EGM96 (Lemoine et al, 1998).
This is done by interpolating a grid of the geoid height file with a spatial resolution of 15 arc-minutes.

Or if you have some level professional GPS has Altitude H (msl,heigh above mean sea level) and UNDULATION,the relationship between the geoid and the ellipsoid (m) of the chosen datum output from internal table. you can get h = H(msl) + undulation

To XYZ by Cartesian coordinates:

x = R * cos(lat) * cos(lon)

y = R * cos(lat) * sin(lon)

z = R *sin(lat)

textarea's rows, and cols attribute in CSS

I just wanted to post a demo using calc() for setting rows/height, since no one did.

_x000D_
_x000D_
body {_x000D_
  /* page default */_x000D_
  font-size: 15px;_x000D_
  line-height: 1.5;_x000D_
}_x000D_
_x000D_
textarea {_x000D_
  /* demo related */_x000D_
  width: 300px;_x000D_
  margin-bottom: 1em;_x000D_
  display: block;_x000D_
  _x000D_
  /* rows related */_x000D_
  font-size: inherit;_x000D_
  line-height: inherit;_x000D_
  padding: 3px;_x000D_
}_x000D_
_x000D_
textarea.border-box {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
textarea.rows-5 {_x000D_
  /* height: calc(font-size * line-height * rows); */_x000D_
  height: calc(1em * 1.5 * 5);_x000D_
}_x000D_
_x000D_
textarea.border-box.rows-5 {_x000D_
  /* height: calc(font-size * line-height * rows + padding-top + padding-bottom + border-top-width + border-bottom-width); */_x000D_
  height: calc(1em * 1.5 * 5 + 3px + 3px + 1px + 1px);_x000D_
}
_x000D_
<p>height is 2 rows by default</p>_x000D_
_x000D_
<textarea>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
_x000D_
<p>height is 5 now</p>_x000D_
_x000D_
<textarea class="rows-5">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
_x000D_
<p>border-box height is 5 now</p>_x000D_
_x000D_
<textarea class="border-box rows-5">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>
_x000D_
_x000D_
_x000D_

If you use large values for the paddings (e.g. greater than 0.5em), you'll start to see the text that overflows the content(-box) area, and that might lead you to think that the height is not exactly x rows (that you set), but it is. To understand what's going on, you might want to check out The box model and box-sizing pages.

How to unpack pkl file?

Generally

Your pkl file is, in fact, a serialized pickle file, which means it has been dumped using Python's pickle module.

To un-pickle the data you can:

import pickle


with open('serialized.pkl', 'rb') as f:
    data = pickle.load(f)

For the MNIST data set

Note gzip is only needed if the file is compressed:

import gzip
import pickle


with gzip.open('mnist.pkl.gz', 'rb') as f:
    train_set, valid_set, test_set = pickle.load(f)

Where each set can be further divided (i.e. for the training set):

train_x, train_y = train_set

Those would be the inputs (digits) and outputs (labels) of your sets.

If you want to display the digits:

import matplotlib.cm as cm
import matplotlib.pyplot as plt


plt.imshow(train_x[0].reshape((28, 28)), cmap=cm.Greys_r)
plt.show()

mnist_digit

The other alternative would be to look at the original data:

http://yann.lecun.com/exdb/mnist/

But that will be harder, as you'll need to create a program to read the binary data in those files. So I recommend you to use Python, and load the data with pickle. As you've seen, it's very easy. ;-)

Hosting a Maven repository on github

Another alternative is to use any web hosting with webdav support. You will need some space for this somewhere of course but it is straightforward to set up and a good alternative to running a full blown nexus server.

add this to your build section

     <extensions>
        <extension>
        <artifactId>wagon-webdav-jackrabbit</artifactId>
        <groupId>org.apache.maven.wagon</groupId>
        <version>2.2</version>
        </extension>
    </extensions>

Add something like this to your distributionManagement section

<repository>
    <id>release.repo</id>
    <url>dav:http://repo.jillesvangurp.com/releases/</url>
</repository>

Finally make sure to setup the repository access in your settings.xml

add this to your servers section

    <server>
        <id>release.repo</id>
        <username>xxxx</username>
        <password>xxxx</password>
    </server>

and a definition to your repositories section

            <repository>
                <id>release.repo</id>
                <url>http://repo.jillesvangurp.com/releases</url>
                <releases>
                    <enabled>true</enabled>
                </releases>
                <snapshots>
                    <enabled>false</enabled>
                </snapshots>
            </repository>

Finally, if you have any standard php hosting, you can use something like sabredav to add webdav capabilities.

Advantages: you have your own maven repository Downsides: you don't have any of the management capabilities in nexus; you need some webdav setup somewhere

Correct way to write loops for promise.

Here's another method (ES6 w/std Promise). Uses lodash/underscore type exit criteria (return === false). Note that you could easily add an exitIf() method in options to run in doOne().

const whilePromise = (fnReturningPromise,options = {}) => { 
    // loop until fnReturningPromise() === false
    // options.delay - setTimeout ms (set to 0 for 1 tick to make non-blocking)
    return new Promise((resolve,reject) => {
        const doOne = () => {
            fnReturningPromise()
            .then((...args) => {
                if (args.length && args[0] === false) {
                    resolve(...args);
                } else {
                    iterate();
                }
            })
        };
        const iterate = () => {
            if (options.delay !== undefined) {
                setTimeout(doOne,options.delay);
            } else {
                doOne();
            }
        }
        Promise.resolve()
        .then(iterate)
        .catch(reject)
    })
};

Convert string to List<string> in one line?

The List<T> has a constructor that accepts an IEnumerable<T>:

List<string> listOfNames = new List<string>(names.Split(','));

What is the Angular equivalent to an AngularJS $watch?

You can use getter function or get accessor to act as watch on angular 2.

See demo here.

import {Component} from 'angular2/core';

@Component({
  // Declare the tag name in index.html to where the component attaches
  selector: 'hello-world',

  // Location of the template for this component
  template: `
  <button (click)="OnPushArray1()">Push 1</button>
  <div>
    I'm array 1 {{ array1 | json }}
  </div>
  <button (click)="OnPushArray2()">Push 2</button>
  <div>
    I'm array 2 {{ array2 | json }}
  </div>
  I'm concatenated {{ concatenatedArray | json }}
  <div>
    I'm length of two arrays {{ arrayLength | json }}
  </div>`
})
export class HelloWorld {
    array1: any[] = [];
    array2: any[] = [];

    get concatenatedArray(): any[] {
      return this.array1.concat(this.array2);
    }

    get arrayLength(): number {
      return this.concatenatedArray.length;
    }

    OnPushArray1() {
        this.array1.push(this.array1.length);
    }

    OnPushArray2() {
        this.array2.push(this.array2.length);
    }
}

Why can't I have abstract static methods in C#?

Here is a situation where there is definitely a need for inheritance for static fields and methods:

abstract class Animal
{
  protected static string[] legs;

  static Animal() {
    legs=new string[0];
  }

  public static void printLegs()
  {
    foreach (string leg in legs) {
      print(leg);
    }
  }
}


class Human: Animal
{
  static Human() {
    legs=new string[] {"left leg", "right leg"};
  }
}


class Dog: Animal
{
  static Dog() {
    legs=new string[] {"left foreleg", "right foreleg", "left hindleg", "right hindleg"};
  }
}


public static void main() {
  Dog.printLegs();
  Human.printLegs();
}


//what is the output?
//does each subclass get its own copy of the array "legs"?

How do I copy the contents of a String to the clipboard in C#?

WPF: System.Windows.Clipboard (PresentationCore.dll)

Winforms: System.Windows.Forms.Clipboard

Both have a static SetText method.

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

As others have said, it's a new syntax to create functions.

However, this kind of functions differ from normal ones:

  • They bind the this value. As explained by the spec,

    An ArrowFunction does not define local bindings for arguments, super, this, or new.target. Any reference to arguments, super, this, or new.target within an ArrowFunction must resolve to a binding in a lexically enclosing environment. Typically this will be the Function Environment of an immediately enclosing function.

    Even though an ArrowFunction may contain references to super, the function object created in step 4 is not made into a method by performing MakeMethod. An ArrowFunction that references super is always contained within a non-ArrowFunction and the necessary state to implement super is accessible via the scope that is captured by the function object of the ArrowFunction.

  • They are non-constructors.

    That means they have no [[Construct]] internal method, and thus can't be instantiated, e.g.

    var f = a => a;
    f(123);  // 123
    new f(); // TypeError: f is not a constructor
    

Should I use Java's String.format() if performance is important?

In your example, performance probalby isn't too different but there are other issues to consider: namely memory fragmentation. Even concatenate operation is creating a new string, even if its temporary (it takes time to GC it and it's more work). String.format() is just more readable and it involves less fragmentation.

Also, if you're using a particular format a lot, don't forget you can use the Formatter() class directly (all String.format() does is instantiate a one use Formatter instance).

Also, something else you should be aware of: be careful of using substring(). For example:

String getSmallString() {
  String largeString = // load from file; say 2M in size
  return largeString.substring(100, 300);
}

That large string is still in memory because that's just how Java substrings work. A better version is:

  return new String(largeString.substring(100, 300));

or

  return String.format("%s", largeString.substring(100, 300));

The second form is probably more useful if you're doing other stuff at the same time.

Updating a JSON object using Javascript

I took Michael Berkowski's answer a step (or two) farther and created a more flexible function allowing any lookup field and any target field. For fun I threw splat (*) capability in there incase someone might want to do a replace all. jQuery is NOT needed. checkAllRows allows the option to break from the search on found for performance or the previously mentioned replace all.

function setVal(update) {
    /* Included to show an option if you care to use jQuery  
    var defaults = { jsonRS: null, lookupField: null, lookupKey: null,
        targetField: null, targetData: null, checkAllRows: false }; 
    //update = $.extend({}, defaults, update); */

    for (var i = 0; i < update.jsonRS.length; i++) {
        if (update.jsonRS[i][update.lookupField] === update.lookupKey || update.lookupKey === '*') {
            update.jsonRS[i][update.targetField] = update.targetData;
            if (!update.checkAllRows) { return; }
        }
    }
}


var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},  
           {'Id':'2','Username':'Steve','FatherName':'Johnson'},
           {'Id':'3','Username':'Albert','FatherName':'Einstein'}]

With your data you would use like:

var update = {
    jsonRS: jsonObj,
    lookupField: "Id",
    lookupKey: 2, 
    targetField: "Username",
    targetData: "Thomas", 
    checkAllRows: false
    };

setVal(update);

And Bob's your Uncle. :) [Works great]