Programs & Examples On #Oxite

Open source, web standards compliant, blog engine built on ASP.NET MVC.

How to get first N number of elements from an array

The following worked for me.

array.slice( where_to_start_deleting, array.length )

Here is an example

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.slice(2, fruits.length);
//Banana,Orange  ->These first two we get as resultant

How to add a recyclerView inside another recyclerView

I ran into similar problem a while back and what was happening in my case was the outer recycler view was working perfectly fine but the the adapter of inner/second recycler view had minor issues all the methods like constructor got initiated and even getCount() method was being called, although the final methods responsible to generate view ie..

1. onBindViewHolder() methods never got called. --> Problem 1.

2. When it got called finally it never show the list items/rows of recycler view. --> Problem 2.

Reason why this happened :: When you put a recycler view inside another recycler view, then height of the first/outer recycler view is not auto adjusted. It is defined when the first/outer view is created and then it remains fixed. At that point your second/inner recycler view has not yet loaded its items and thus its height is set as zero and never changes even when it gets data. Then when onBindViewHolder() in your second/inner recycler view is called, it gets items but it doesn't have the space to show them because its height is still zero. So the items in the second recycler view are never shown even when the onBindViewHolder() has added them to it.

Solution :: you have to create your custom LinearLayoutManager for the second recycler view and that is it. To create your own LinearLayoutManager: Create a Java class with the name CustomLinearLayoutManager and paste the code below into it. NO CHANGES REQUIRED

public class CustomLinearLayoutManager extends LinearLayoutManager {

    private static final String TAG = CustomLinearLayoutManager.class.getSimpleName();

    public CustomLinearLayoutManager(Context context) {
        super(context);

    }

    public CustomLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    private int[] mMeasuredDimension = new int[2];

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {

        final int widthMode = View.MeasureSpec.getMode(widthSpec);
        final int heightMode = View.MeasureSpec.getMode(heightSpec);
        final int widthSize = View.MeasureSpec.getSize(widthSpec);
        final int heightSize = View.MeasureSpec.getSize(heightSpec);

        int width = 0;
        int height = 0;
        for (int i = 0; i < getItemCount(); i++) {
            measureScrapChild(recycler, i, View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    mMeasuredDimension);


            if (getOrientation() == HORIZONTAL) {
                width = width + mMeasuredDimension[0];
                if (i == 0) {
                    height = mMeasuredDimension[1];
                }
            } else {
                height = height + mMeasuredDimension[1];
                if (i == 0) {
                    width = mMeasuredDimension[0];
                }
            }
        }
        switch (widthMode) {
            case View.MeasureSpec.EXACTLY:
                width = widthSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        switch (heightMode) {
            case View.MeasureSpec.EXACTLY:
                height = heightSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        setMeasuredDimension(width, height);
    }

    private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                                   int heightSpec, int[] measuredDimension) {
        try {
            View view = recycler.getViewForPosition(position);

            if (view != null) {
                RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();

                int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                        getPaddingLeft() + getPaddingRight(), p.width);

                int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                        getPaddingTop() + getPaddingBottom(), p.height);

                view.measure(childWidthSpec, childHeightSpec);
                measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
                measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
                recycler.recycleView(view);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Use C# HttpWebRequest to send json to web service

First of all you missed ScriptService attribute to add in webservice.

[ScriptService]

After then try following method to call webservice via JSON.

        var webAddr = "http://Domain/VBRService.asmx/callJson";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";            

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"x\":\"true\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }

How to make all controls resize accordingly proportionally when window is maximized?

Well, it's fairly simple to do.

On the window resize event handler, calculate how much the window has grown/shrunk, and use that fraction to adjust 1) Height, 2) Width, 3) Canvas.Top, 4) Canvas.Left properties of all the child controls inside the canvas.

Here's the code:

private void window1_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            myCanvas.Width = e.NewSize.Width;
            myCanvas.Height = e.NewSize.Height;

            double xChange = 1, yChange = 1;

            if (e.PreviousSize.Width != 0)
            xChange = (e.NewSize.Width/e.PreviousSize.Width);

            if (e.PreviousSize.Height != 0)
            yChange = (e.NewSize.Height / e.PreviousSize.Height);

            foreach (FrameworkElement fe in myCanvas.Children )
            {   
                /*because I didn't want to resize the grid I'm having inside the canvas in this particular instance. (doing that from xaml) */            
                if (fe is Grid == false)
                {
                    fe.Height = fe.ActualHeight * yChange;
                    fe.Width = fe.ActualWidth * xChange;

                    Canvas.SetTop(fe, Canvas.GetTop(fe) * yChange);
                    Canvas.SetLeft(fe, Canvas.GetLeft(fe) * xChange);

                }
            }
        }

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

try this:

ComboBox cbx = new ComboBox();
cbx.DisplayMember = "Text";
cbx.ValueMember = "Value";

EDIT (a little explanation, sory, I also didn't notice your combobox wasn't bound, I blame the lack of caffeine):

The difference between SelectedValue and SelectedItem are explained pretty well here: ComboBox SelectedItem vs SelectedValue

So, if your combobox is not bound to datasource, DisplayMember and ValueMember doesn't do anything, and SelectedValue will always be null, SelectedValueChanged won't be called. So either bind your combobox:

            comboBox1.DisplayMember = "Text";
            comboBox1.ValueMember = "Value";

            List<ComboboxItem> list = new List<ComboboxItem>();

            ComboboxItem item = new ComboboxItem();
            item.Text = "choose a server...";
            item.Value = "-1";
            list.Add(item);

            item = new ComboboxItem();
            item.Text = "S1";
            item.Value = "1";
            list.Add(item);

            item = new ComboboxItem();
            item.Text = "S2";
            item.Value = "2";
            list.Add(item);

            cbx.DataSource = list; // bind combobox to a datasource

or use SelectedItem property:

if (cbx.SelectedItem != null)
             Console.WriteLine("ITEM: "+comboBox1.SelectedItem.ToString());

how to remove empty strings from list, then remove duplicate values from a list

Amiram's answer is correct, but Distinct() as implemented is an N2 operation; for each item in the list, the algorithm compares it to all the already processed elements, and returns it if it's unique or ignores it if not. We can do better.

A sorted list can be deduped in linear time; if the current element equals the previous element, ignore it, otherwise return it. Sorting is NlogN, so even having to sort the collection, we get some benefit:

public static IEnumerable<T> SortAndDedupe<T>(this IEnumerable<T> input)
{
   var toDedupe = input.OrderBy(x=>x);

   T prev;
   foreach(var element in toDedupe)
   {
      if(element == prev) continue;

      yield return element;
      prev = element;      
   }
}

//Usage
dtList  = dtList.Where(s => !string.IsNullOrWhitespace(s)).SortAndDedupe().ToList();

This returns the same elements; they're just sorted.

Value does not fall within the expected range

This might be due to the fact that you are trying to add a ListBoxItem with a same name to the page.

If you want to refresh the content of the listbox with the newly retrieved values you will have to first manually remove the content of the listbox other wise your loop will try to create lb_1 again and add it to the same list.

Look at here for a similar problem that occured Silverlight: Value does not fall within the expected range exception

Cheers,

Getting selected value of a combobox

You have to cast the selected item to your custom class (ComboboxItem) Try this:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
            int selectedIndex = cmb.SelectedIndex;
            string selectedText = this.comboBox1.Text;
            string selectedValue = ((ComboboxItem)cmb.SelectedItem).Value.ToString();

ComboboxItem selectedCar = (ComboboxItem)cmb.SelectedItem;
MessageBox.Show(String.Format("Index: [{0}] CarName={1}; Value={2}", selectedIndex, selectedCar.Text, selecteVal));        

}

The result of a query cannot be enumerated more than once

Try replacing this

var query = context.Search(id, searchText);

with

var query = context.Search(id, searchText).tolist();

and everything will work well.

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

I'm sure this is a duplicate, but I can't find a question with the same answer.

Add HorizontalContentAlignment="Stretch" to your ListBox. That should do the trick. Just be careful with auto-complete because it is so easy to get HorizontalAlignment by mistake.

C# difference between == and Equals()

When we create any object there are two parts to the object one is the content and the other is reference to that content. == compares both content and reference; equals() compares only content

http://www.codeproject.com/Articles/584128/What-is-the-difference-between-equalsequals-and-Eq

How to draw a line in android

This one draws 2 lines which form a cross on the top left of the screen:

DrawView.java

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

public class DrawView extends View {
    Paint paint = new Paint();

    private void init() {
        paint.setColor(Color.BLACK);
    }

    public DrawView(Context context) {
        super(context);
        init();
    }

    public DrawView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public DrawView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    @Override
    public void onDraw(Canvas canvas) {
            canvas.drawLine(0, 0, 20, 20, paint);
            canvas.drawLine(20, 0, 0, 20, paint);
    }

}

The activity to start it:

StartDraw.java

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;

public class StartDraw extends Activity {
    DrawView drawView;

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

        drawView = new DrawView(this);
        drawView.setBackgroundColor(Color.WHITE);
        setContentView(drawView);

    }
}

Modify property value of the objects in list using Java 8 streams

You can use just forEach. No stream at all:

fruits.forEach(fruit -> fruit.setName(fruit.getName() + "s"));

Add element to a list In Scala

Since you want to append elements to existing list, you can use var List[Int] and then keep on adding elements to the same list. Note -> You have to make sure that you insert an element into existing list as follows:-

var l: List[int] = List() // creates an empty list

l = 3 :: l // adds 3 to the head of the list

l = 4 :: l // makes int 4 as the head of the list

// Now when you will print l, you will see two elements in the list ( 4, 3)

What is the alternative for ~ (user's home directory) on Windows command prompt?

You can also do cd ......\ as many times as there are folders that takes you to home directory. For example, if you are in cd:\windows\syatem32, then cd ....\ takes you to the home, that is c:\

What is more efficient? Using pow to square or just multiply it with itself?

That's the wrong kind of question. The right question would be: "Which one is easier to understand for human readers of my code?"

If speed matters (later), don't ask, but measure. (And before that, measure whether optimizing this actually will make any noticeable difference.) Until then, write the code so that it is easiest to read.

Edit
Just to make this clear (although it already should have been): Breakthrough speedups usually come from things like using better algorithms, improving locality of data, reducing the use of dynamic memory, pre-computing results, etc. They rarely ever come from micro-optimizing single function calls, and where they do, they do so in very few places, which would only be found by careful (and time-consuming) profiling, more often than never they can be sped up by doing very non-intuitive things (like inserting noop statements), and what's an optimization for one platform is sometimes a pessimization for another (which is why you need to measure, instead of asking, because we don't fully know/have your environment).

Let me underline this again: Even in the few applications where such things matter, they don't matter in most places they're used, and it is very unlikely that you will find the places where they matter by looking at the code. You really do need to identify the hot spots first, because otherwise optimizing code is just a waste of time.

Even if a single operation (like computing the square of some value) takes up 10% of the application's execution time (which IME is quite rare), and even if optimizing it saves 50% of the time necessary for that operation (which IME is even much, much rarer), you still made the application take only 5% less time.
Your users will need a stopwatch to even notice that. (I guess in most cases anything under 20% speedup goes unnoticed for most users. And that is four such spots you need to find.)

Android: How to turn screen on and off programmatically?

If your app is a system app,you can use PowerManager.goToSleep() to turn screen off,you requires a special permission

before you use goToSleep(), you need use reflection just like:

public static void goToSleep(Context context) {
    PowerManager powerManager= (PowerManager)context.getSystemService(Context.POWER_SERVICE);
    try {
        powerManager.getClass().getMethod("goToSleep", new Class[]{long.class}).invoke(powerManager, SystemClock.uptimeMillis());
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
}

Now,you can use goToSleep() to turn screen off.

This is what happens when the power key is pressed to turn off the screen.

combining two data frames of different lengths

It's not clear to me at all what the OP is actually after, given the follow-up comments. It's possible they are actually looking for a way to write the data to file.

But let's assume that we're really after a way to cbind multiple data frames of differing lengths.

cbind will eventually call data.frame, whose help files says:

Objects passed to data.frame should have the same number of rows, but atomic vectors, factors and character vectors protected by I will be recycled a whole number of times if necessary (including as from R 2.9.0, elements of list arguments).

so in the OP's actual example, there shouldn't be an error, as R ought to recycle the shorter vectors to be of length 50. Indeed, when I run the following:

set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(10),e = runif(10))
cbind(dat1,dat2)

I get no errors and the shorter data frame is recycled as expected. However, when I run this:

set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(9), e = runif(9))
cbind(dat1,dat2)

I get the following error:

Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 50, 9

But the wonderful thing about R is that you can make it do almost anything you want, even if you shouldn't. For example, here's a simple function that will cbind data frames of uneven length and automatically pad the shorter ones with NAs:

cbindPad <- function(...){
args <- list(...)
n <- sapply(args,nrow)
mx <- max(n)
pad <- function(x, mx){
    if (nrow(x) < mx){
        nms <- colnames(x)
        padTemp <- matrix(NA, mx - nrow(x), ncol(x))
        colnames(padTemp) <- nms
        if (ncol(x)==0) {
          return(padTemp)
        } else {
        return(rbind(x,padTemp))
          }
    }
    else{
        return(x)
    }
}
rs <- lapply(args,pad,mx)
return(do.call(cbind,rs))
}

which can be used like this:

set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(10),e = runif(10))
dat3 <- data.frame(d = runif(9), e = runif(9))
cbindPad(dat1,dat2,dat3)

I make no guarantees that this function works in all cases; it is meant as an example only.

EDIT

If the primary goal is to create a csv or text file, all you need to do it alter the function to pad using "" rather than NA and then do something like this:

dat <- cbindPad(dat1,dat2,dat3)
rs <- as.data.frame(apply(dat,1,function(x){paste(as.character(x),collapse=",")}))

and then use write.table on rs.

Hide div if screen is smaller than a certain width

I have the almost the same situation as yours; that if the screen width is less than the my specified width it should hide the div. This is the jquery code I used that worked for me.

$(window).resize(function() {

  if ($(this).width() < 1024) {

    $('.divIWantedToHide').hide();

  } else {

    $('.divIWantedToHide').show();

    }

});

Is there a download function in jsFiddle?

I found an article under the above topic.There by I could take the full code .I will mention it.

Here are steps mentioned in the article:

  1. Add embedded/result/ at the end of the JSFiddle URL you wanna grab.

  2. Show the frame or the frame’s source code: right-click anywhere in the page and view the frame in a new tab or the source right-away (requires Firefox).

  3. Finally, save the page in your preferred format (MHT, HTML, TXT, etc.) and voilà!

also you can find it : https://sirusdark.wordpress.com/2014/04/10/how-to-save-and-download-jsfiddle-code/

Connect Android to WiFi Enterprise network EAP(PEAP)

Thanks for enlightening us Cypawer.

I also tried this app https://play.google.com/store/apps/details?id=com.oneguyinabasement.leapwifi

and it worked flawlessly.

Leap Wifi Connector

How to clean node_modules folder of packages that are not in package.json?

Remove/Edit the packages that are not needed in package-lock.json (package names will be written under dependencies & devDependencies) and then

npm install

Selenium C# WebDriver: Wait until element is present

WebDriverWait won't take effect.

var driver = new FirefoxDriver(
    new FirefoxOptions().PageLoadStrategy = PageLoadStrategy.Eager
);
driver.Navigate().GoToUrl("xxx");
new WebDriverWait(driver, TimeSpan.FromSeconds(60))
    .Until(d => d.FindElement(By.Id("xxx"))); // A tag that close to the end

This would immediately throw an exception once the page was "interactive". I don't know why, but the timeout acts as if it does not exist.

Perhaps SeleniumExtras.WaitHelpers works, but I didn't try. It's official, but it was split out into another NuGet package. You can refer to C# Selenium 'ExpectedConditions is obsolete'.

I use FindElements and check Count == 0. If true, use await Task.Delay. It's really not quite efficient.

Overlay normal curve to histogram in R

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

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

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

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

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

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

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

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

Quick example:

hist(g)

enter image description here

For dates it's bit different. For reference:

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

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

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

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

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

How to fix ReferenceError: primordials is not defined in node

What worked for me was to use python2 during npm installation.

> npm install --python=~/venv/bin/python

Display unescaped HTML in Vue.js

Starting with Vue2, the triple braces were deprecated, you are to use v-html.

<div v-html="task.html_content"> </div>

It is unclear from the documentation link as to what we are supposed to place inside v-html, your variables goes inside v-html.

Also, v-html works only with <div> or <span> but not with <template>.

If you want to see this live in an app, click here.

Efficient way to Handle ResultSet in Java

I just cleaned up RHT's answer to eliminate some warnings and thought I would share. Eclipse did most of the work:

public List<HashMap<String,Object>> convertResultSetToList(ResultSet rs) throws SQLException {
    ResultSetMetaData md = rs.getMetaData();
    int columns = md.getColumnCount();
    List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();

    while (rs.next()) {
        HashMap<String,Object> row = new HashMap<String, Object>(columns);
        for(int i=1; i<=columns; ++i) {
            row.put(md.getColumnName(i),rs.getObject(i));
        }
        list.add(row);
    }

    return list;
}

In Python, what happens when you import inside of a function?

The very first time you import goo from anywhere (inside or outside a function), goo.py (or other importable form) is loaded and sys.modules['goo'] is set to the module object thus built. Any future import within the same run of the program (again, whether inside or outside a function) just look up sys.modules['goo'] and bind it to barename goo in the appropriate scope. The dict lookup and name binding are very fast operations.

Assuming the very first import gets totally amortized over the program's run anyway, having the "appropriate scope" be module-level means each use of goo.this, goo.that, etc, is two dict lookups -- one for goo and one for the attribute name. Having it be "function level" pays one extra local-variable setting per run of the function (even faster than the dictionary lookup part!) but saves one dict lookup (exchanging it for a local-variable lookup, blazingly fast) for each goo.this (etc) access, basically halving the time such lookups take.

We're talking about a few nanoseconds one way or another, so it's hardly a worthwhile optimization. The one potentially substantial advantage of having the import within a function is when that function may well not be needed at all in a given run of the program, e.g., that function deals with errors, anomalies, and rare situations in general; if that's the case, any run that does not need the functionality will not even perform the import (and that's a saving of microseconds, not just nanoseconds), only runs that do need the functionality will pay the (modest but measurable) price.

It's still an optimization that's only worthwhile in pretty extreme situations, and there are many others I would consider before trying to squeeze out microseconds in this way.

How to find out which package version is loaded in R?

GUI solution:

If you are using RStudio then you can check the package version in the Packages pane.

enter image description here

Daemon Threads Explanation

Quoting Chris: "... when your program quits, any daemon threads are killed automatically.". I think that sums it up. You should be careful when you use them as they abruptly terminate when main program executes to completion.

Using Jasmine to spy on a function without an object

My answer differs slightly to @FlavorScape in that I had a single (default export) function in the imported module, I did the following:

import * as functionToTest from 'whatever-lib';

const fooSpy = spyOn(functionToTest, 'default');

CardView not showing Shadow in Android L

Add android:hardwareAccelerated="true" in your manifests file like below it works for me

 <activity
        android:name=".activity.MyCardViewActivity"
        android:hardwareAccelerated="true"></activity>

how to display data values on Chart.js

From my experience, once you include the chartjs-plugin-datalabels plugin (make sure to place the <script> tag after the chart.js tag on your page), your charts begin to display values.

If you then choose you can customize it to fit your needs. The customization is clearly documented here but basically, the format is like this hypothetical example:

var myBarChart = new Chart(ctx, {
    type: 'bar',
    data: yourDataObject,
    options: {
        // other options
        plugins: {
            datalabels: {
                anchor :'end',
                align :'top',
                // and if you need to format how the value is displayed...
                formatter: function(value, context) {
                    return GetValueFormatted(value);
                }
            }
        }
    }
});

Regular cast vs. static_cast vs. dynamic_cast

Static cast

The static cast performs conversions between compatible types. It is similar to the C-style cast, but is more restrictive. For example, the C-style cast would allow an integer pointer to point to a char.
char c = 10;       // 1 byte
int *p = (int*)&c; // 4 bytes

Since this results in a 4-byte pointer pointing to 1 byte of allocated memory, writing to this pointer will either cause a run-time error or will overwrite some adjacent memory.

*p = 5; // run-time error: stack corruption

In contrast to the C-style cast, the static cast will allow the compiler to check that the pointer and pointee data types are compatible, which allows the programmer to catch this incorrect pointer assignment during compilation.

int *q = static_cast<int*>(&c); // compile-time error

Reinterpret cast

To force the pointer conversion, in the same way as the C-style cast does in the background, the reinterpret cast would be used instead.

int *r = reinterpret_cast<int*>(&c); // forced conversion

This cast handles conversions between certain unrelated types, such as from one pointer type to another incompatible pointer type. It will simply perform a binary copy of the data without altering the underlying bit pattern. Note that the result of such a low-level operation is system-specific and therefore not portable. It should be used with caution if it cannot be avoided altogether.

Dynamic cast

This one is only used to convert object pointers and object references into other pointer or reference types in the inheritance hierarchy. It is the only cast that makes sure that the object pointed to can be converted, by performing a run-time check that the pointer refers to a complete object of the destination type. For this run-time check to be possible the object must be polymorphic. That is, the class must define or inherit at least one virtual function. This is because the compiler will only generate the needed run-time type information for such objects.

Dynamic cast examples

In the example below, a MyChild pointer is converted into a MyBase pointer using a dynamic cast. This derived-to-base conversion succeeds, because the Child object includes a complete Base object.

class MyBase 
{ 
  public:
  virtual void test() {}
};
class MyChild : public MyBase {};



int main()
{
  MyChild *child = new MyChild();
  MyBase  *base = dynamic_cast<MyBase*>(child); // ok
}

The next example attempts to convert a MyBase pointer to a MyChild pointer. Since the Base object does not contain a complete Child object this pointer conversion will fail. To indicate this, the dynamic cast returns a null pointer. This gives a convenient way to check whether or not a conversion has succeeded during run-time.

MyBase  *base = new MyBase();
MyChild *child = dynamic_cast<MyChild*>(base);

 
if (child == 0) 
std::cout << "Null pointer returned";

If a reference is converted instead of a pointer, the dynamic cast will then fail by throwing a bad_cast exception. This needs to be handled using a try-catch statement.

#include <exception>
// …  
try
{ 
  MyChild &child = dynamic_cast<MyChild&>(*base);
}
catch(std::bad_cast &e) 
{ 
  std::cout << e.what(); // bad dynamic_cast
}

Dynamic or static cast

The advantage of using a dynamic cast is that it allows the programmer to check whether or not a conversion has succeeded during run-time. The disadvantage is that there is a performance overhead associated with doing this check. For this reason using a static cast would have been preferable in the first example, because a derived-to-base conversion will never fail.

MyBase *base = static_cast<MyBase*>(child); // ok

However, in the second example the conversion may either succeed or fail. It will fail if the MyBase object contains a MyBase instance and it will succeed if it contains a MyChild instance. In some situations this may not be known until run-time. When this is the case dynamic cast is a better choice than static cast.

// Succeeds for a MyChild object
MyChild *child = dynamic_cast<MyChild*>(base);

If the base-to-derived conversion had been performed using a static cast instead of a dynamic cast the conversion would not have failed. It would have returned a pointer that referred to an incomplete object. Dereferencing such a pointer can lead to run-time errors.

// Allowed, but invalid
MyChild *child = static_cast<MyChild*>(base);
 
// Incomplete MyChild object dereferenced
(*child);

Const cast

This one is primarily used to add or remove the const modifier of a variable.

const int myConst = 5;
int *nonConst = const_cast<int*>(&myConst); // removes const

Although const cast allows the value of a constant to be changed, doing so is still invalid code that may cause a run-time error. This could occur for example if the constant was located in a section of read-only memory.

*nonConst = 10; // potential run-time error

Const cast is instead used mainly when there is a function that takes a non-constant pointer argument, even though it does not modify the pointee.

void print(int *p) 
{
   std::cout << *p;
}

The function can then be passed a constant variable by using a const cast.

print(&myConst); // error: cannot convert 
                 // const int* to int*
 
print(nonConst); // allowed

Source and More Explanations

What is Android keystore file, and what is it used for?

The answer I would provide is that a keystore file is to authenticate yourself to anyone who is asking. It isn't restricted to just signing .apk files, you can use it to store personal certificates, sign data to be transmitted and a whole variety of authentication.

In terms of what you do with it for Android and probably what you're looking for since you mention signing apk's, it is your certificate. You are branding your application with your credentials. You can brand multiple applications with the same key, in fact, it is recommended that you use one certificate to brand multiple applications that you write. It easier to keep track of what applications belong to you.

I'm not sure what you mean by implications. I suppose it means that no one but the holder of your certificate can update your application. That means that if you release it into the wild, lose the cert you used to sign the application, then you cannot release updates so keep that cert safe and backed up if need be.

But apart from signing apks to release into the wild, you can use it to authenticate your device to a server over SSL if you so desire, (also Android related) among other functions.

Webdriver Screenshot

You can use below function for relative path as absolute path is not a good idea to add in script

Import

import sys, os

Use code as below :

ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
screenshotpath = os.path.join(os.path.sep, ROOT_DIR,'Screenshots'+ os.sep)
driver.get_screenshot_as_file(screenshotpath+"testPngFunction.png")

make sure you create the folder where the .py file is present.

os.path.join also prevent you to run your script in cross-platform like: UNIX and windows. It will generate path separator as per OS at runtime. os.sep is similar like File.separtor in java

What is the purpose of the vshost.exe file?

It seems to be a long-running framework process for debugging (to decrease load times?). I discovered that when you start your application twice from the debugger often the same vshost.exe process will be used. It just unloads all user-loaded DLLs first. This does odd things if you are fooling around with API hooks from managed processes.

ARG or ENV, which one to use in this case?

From Dockerfile reference:

  • The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag.

  • The ENV instruction sets the environment variable <key> to the value <value>.
    The environment variables set using ENV will persist when a container is run from the resulting image.

So if you need build-time customization, ARG is your best choice.
If you need run-time customization (to run the same image with different settings), ENV is well-suited.

If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable

Given the number of combinations involved, using ENV to set those features at runtime is best here.

But you can combine both by:

  • building an image with a specific ARG
  • using that ARG as an ENV

That is, with a Dockerfile including:

ARG var
ENV var=${var}

You can then either build an image with a specific var value at build-time (docker build --build-arg var=xxx), or run a container with a specific runtime value (docker run -e var=yyy)

How to define a default value for "input type=text" without using attribute 'value'?

The value is there. The source is not updated as the values on the form change. The source is from when the page initially loaded.

Split comma separated column data into additional columns

split_part() does what you want in one step:

SELECT split_part(col, ',', 1) AS col1
     , split_part(col, ',', 2) AS col2
     , split_part(col, ',', 3) AS col3
     , split_part(col, ',', 4) AS col4
FROM   tbl;

Add as many lines as you have items in col (the possible maximum). Columns exceeding data items will be empty strings ('').

Question mark and colon in statement. What does it mean?

It's a ternary operator, or the short form for if..else.

condition ? value if true : value if false

See Microsoft Docs | ?: operator (C# reference).

Implement Stack using Two Queues

#include <bits/stdc++.h>
using namespace std;
queue<int>Q;
stack<int>Stk;
void PRINT(stack<int>ss , queue<int>qq) {
    while( ss.size() ) {
        cout << ss.top() << " " ;
        ss.pop();
    }
    puts("");
    while( qq.size() ) {
        cout << qq.front() << " " ;
        qq.pop();
    }
    puts("\n----------------------------------");
}
void POP() {
    queue<int>Tmp ;
    while( Q.size() > 1 ) {
        Tmp.push( Q.front()  );
        Q.pop();
    }
    cout << Q.front() << " " << Stk.top() << endl;
    Q.pop() , Stk.pop() ;
    Q = Tmp ;
}
void PUSH(int x ) {
    Q.push(x);
    Stk.push(x);
}
int main() {
    while( true ) {
        string typ ;
        cin >> typ ;
        if( typ == "push" ) {
            int x ;
            cin >> x;
            PUSH(x);
        } else POP();
        PRINT(Stk,Q);
    }
}

Change / Add syntax highlighting for a language in Sublime 2/3

I finally found a way to customize the given Themes.

Go to C:\Program Files\Sublime Text 3\Packages and copy + rename Color Scheme - Default.sublime-package to Color Scheme - Default.zip. Afterwards unzip it and copy the Theme, you want to change to %APPDATA%\Sublime Text 3\Packages\User. (In my case, All Hallow's Eve.tmTheme).

Then you can open it with any Text Editor and change / add something, for example for changing this in JavaScript:

<dict>
    <key>name</key>
    <string>Lang Variable</string>
    <key>scope</key>
    <string>variable.language</string>
    <key>settings</key>
    <dict>
        <key>foreground</key>
        <string>#FF0000</string>
    </dict>
</dict>

This will mark this in JavaScript Files red. You can select your Theme under Preferences -> Color Scheme -> User -> <Your Name>.

How to make Twitter bootstrap modal full screen

My variation of the solution: (scss)

  .modal {
        .modal-dialog.modal-fs {
            width: 100%;
            margin: 0;
            box-shadow: none;
            height: 100%;
            .modal-content {
                border: none;
                border-radius: 0;
                box-shadow: none;
                box-shadow: none;
                height: 100%;
            }
        }
    }

(css)

.modal .modal-dialog.modal-fs {
  width: 100%;
  margin: 0;
  box-shadow: none;
  height: 100%;
}
.modal .modal-dialog.modal-fs .modal-content {
  border: none;
  border-radius: 0;
  box-shadow: none;
  box-shadow: none;
  height: 100%;
}

HTML 5 video or audio playlist

You should take a look at Popcorn.js - a javascript framework for interacting with Html5 : http://popcornjs.org/documentation

How to initialize a nested struct?

You also could allocate using new and initialize all fields by hand

package main

type Configuration struct {
    Val   string
    Proxy struct {
        Address string
        Port    string
    }
}

func main() {
    c := new(Configuration)
    c.Val = "test"
    c.Proxy.Address = "addr"
    c.Proxy.Port = "80"
}

See in playground: https://play.golang.org/p/sFH_-HawO_M

Is it better to use NOT or <> when comparing values?

Because "not ... =" is two operations and "<>" is only one, it is faster to use "<>".

Here is a quick experiment to prove it:

StartTime = Timer
For x = 1 to 100000000
   If 4 <> 3 Then
   End if
Next
WScript.echo Timer-StartTime

StartTime = Timer
For x = 1 to 100000000
   If Not (4 = 3) Then
   End if
Next
WScript.echo Timer-StartTime

The results I get on my machine:

4.783203
5.552734

How to convert CharSequence to String?

You can directly use String.valueOf()

String.valueOf(charSequence)

Though this is same as toString() it does a null check on the charSequence before actually calling toString.

This is useful when a method can return either a charSequence or null value.

Maximum execution time in phpMyadmin

Your change should work. However, there are potentially few php.ini configuration files with the 'xampp' stack. Try to identify whether or not there's an 'apache' specific php.ini. One potential location is:

C:\xampp\apache\bin\php.ini

check if a string matches an IP address pattern in python?

Your regular expression doesn't check for the end of the string, so it would match:

123.45.67.89abc123boogabooga

To fix this, use:

'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$'

(note the $ at the end).

Finally, in Python the usual style is to use is not None instead of != None.

Angular 2: 404 error occur when I refresh through the browser

For people (like me) who really want PathLocationStrategy (i.e. html5Mode) instead of HashLocationStrategy, see How to: Configure your server to work with html5Mode from a third-party wiki:

When you have html5Mode enabled, the # character will no longer be used in your URLs. The # symbol is useful because it requires no server side configuration. Without #, the URL looks much nicer, but it also requires server side rewrites.

Here I only copy three examples from the wiki, in case the Wiki get lost. Other examples can be found by searching keyword "URL rewrite" (e.g. this answer for Firebase).

Apache

<VirtualHost *:80>
    ServerName my-app

    DocumentRoot /path/to/app

    <Directory /path/to/app>
        RewriteEngine on

        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]

        # Rewrite everything else to index.html to allow HTML5 state links
        RewriteRule ^ index.html [L]
    </Directory>
</VirtualHost>

Documentation for rewrite module

nginx

server {
    server_name my-app;

    root /path/to/app;

    location / {
        try_files $uri $uri/ /index.html;
    }
}

Documentation for try_files

IIS

<system.webServer>
  <rewrite>
    <rules> 
      <rule name="Main Rule" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

How to check version of a CocoaPods framework

The Podfile.lock keeps track of the resolved versions of each Pod installed. If you want to double check that FlurrySDK is using 4.2.3, check that file.

Note: You should not edit this file. It is auto-generated when you run pod install or pod update

Twitter - share button, but with image

I used this code to solve this problem.

<a href="https://twitter.com/intent/tweet?url=myUrl&text=myTitle" target="_blank"><img src="path_to_my_image"/></a>

You can check the tweet-button documentation here tweet-button

What's the best way to store co-ordinates (longitude/latitude, from Google Maps) in SQL Server?

If you are using Entity Framework 5 < you can use DbGeography. Example from MSDN:

public class University  
{ 
    public int UniversityID { get; set; } 
    public string Name { get; set; } 
    public DbGeography Location { get; set; } 
}

public partial class UniversityContext : DbContext 
{ 
    public DbSet<University> Universities { get; set; } 
}

using (var context = new UniversityContext ()) 
{ 
    context.Universities.Add(new University() 
        { 
            Name = "Graphic Design Institute", 
            Location = DbGeography.FromText("POINT(-122.336106 47.605049)"), 
        }); 

    context. Universities.Add(new University() 
        { 
            Name = "School of Fine Art", 
            Location = DbGeography.FromText("POINT(-122.335197 47.646711)"), 
        }); 

    context.SaveChanges(); 

    var myLocation = DbGeography.FromText("POINT(-122.296623 47.640405)"); 

    var university = (from u in context.Universities 
                        orderby u.Location.Distance(myLocation) 
                        select u).FirstOrDefault(); 

    Console.WriteLine( 
        "The closest University to you is: {0}.", 
        university.Name); 
}

https://msdn.microsoft.com/en-us/library/hh859721(v=vs.113).aspx

Something I struggled with then I started using DbGeography was the coordinateSystemId. See the answer below for an excellent explanation and source for the code below.

public class GeoHelper
{
    public const int SridGoogleMaps = 4326;
    public const int SridCustomMap = 3857;

    public static DbGeography FromLatLng(double lat, double lng)
    {
        return DbGeography.PointFromText(
            "POINT("
            + lng.ToString() + " "
            + lat.ToString() + ")",
            SridGoogleMaps);
    }
}

https://stackoverflow.com/a/25563269/3850405

Retrieve the commit log for a specific line in a file?

Here is a solution that defines a git alias, so you will be able use it like that :

git rblame -M -n -L '/REGEX/,+1' FILE

Output example :

00000000 18 (Not Committed Yet 2013-08-19 13:04:52 +0000 728) fooREGEXbar
15227b97 18 (User1 2013-07-11 18:51:26 +0000 728) fooREGEX
1748695d 23 (User2 2013-03-19 21:09:09 +0000 741) REGEXbar

You can define the alias in your .gitconfig or simply run the following command

git config alias.rblame !sh -c 'while line=$(git blame "$@" $commit 2>/dev/null); do commit=${line:0:8}^; [ 00000000^ == $commit ] && commit=$(git rev-parse HEAD); echo $line; done' dumb_param

This is an ugly one-liner, so here is a de-obfuscated equivalent bash function :

git-rblame () {
    local commit line
    while line=$(git blame "$@" $commit 2>/dev/null); do
        commit="${line:0:8}^"
        if [ "00000000^" == "$commit" ]; then
            commit=$(git rev-parse HEAD)
        fi
        echo $line
    done
}

The pickaxe solution ( git log --pickaxe-regex -S'REGEX' ) will only give you line additions/deletions, not the other alterations of the line containing the regular expression.

A limitation of this solution is that git blame only returns the 1st REGEX match, so if multiple matches exist the recursion may "jump" to follow another line. Be sure to check the full history output to spot those "jumps" and then fix your REGEX to ignore the parasite lines.

Finally, here is an alternate version that run git show on each commit to get the full diff :

git config alias.rblameshow !sh -c 'while line=$(git blame "$@" $commit 2>/dev/null); do commit=${line:0:8}^; [ 00000000^ == $commit ] && commit=$(git rev-parse HEAD); git show $commit; done' dumb_param

Resizing an Image without losing any quality

You can't resize an image without losing some quality, simply because you are reducing the number of pixels.

Don't reduce the size client side, because browsers don't do a good job of resizing images.

What you can do is programatically change the size before you render it, or as a user uploads it.

Here is an article that explains one way to do this in c#: http://www.codeproject.com/KB/GDI-plus/imageresize.aspx

Get a pixel from HTML Canvas?

If you want to extract a particular color of pixel by passing the coordinates of pixel into the function, this will come in handy:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
function detectColor(x, y){
  data=ctx.getImageData(x, y, 1, 1).data;
  col={
    r:data[0],
    g:data[1],
    b:data[2]
  };
  return col;
}

x, y is the coordinate you want to filter out color.

var color = detectColor(x, y)

The color is the object, you will get the RGB value by color.r, color.g, color.b.

How to split an integer into an array of digits?

Splitting a single number to it's digits (as answered by all):

>>> [int(i) for i in str(12345)]
[1, 2, 3, 4, 5]

But, to get digits from a list of numbers:

>>> [int(d) for d in ''.join(str(x) for x in [12, 34, 5])]
[1, 2, 3, 4, 5]

So like to know, if we can do the above, more efficiently.

How to execute a java .class from the command line

With Java 11 you won't have to go through this rigmarole anymore!

Instead, you can do this:

> java MyApp.java

You don't have to compile beforehand, as it's all done in one step.

You can get the Java 11 JDK here: JDK 11 GA Release

git ignore all files of a certain type, except those in a specific subfolder

An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

http://schacon.github.com/git/gitignore.html

*.json
!spec/*.json

VBA: Convert Text to Number

Use the below function (changing [E:E] to the appropriate range for your needs) to circumvent this issue (or change to any other format such as "mm/dd/yyyy"):

[E:E].Select
With Selection
    .NumberFormat = "General"
    .Value = .Value
End With

P.S. In my experience, this VBA solution works SIGNIFICANTLY faster on large data sets and is less likely to crash Excel than using the 'warning box' method.

Issue pushing new code in Github

I use the Branches options, and then right click on the "remote/origin" folder and then click on "delete branches from remote", see the image below:

the image

How to check if an object is a certain type

In VB.NET, you need to use the GetType method to retrieve the type of an instance of an object, and the GetType() operator to retrieve the type of another known type.

Once you have the two types, you can simply compare them using the Is operator.

So your code should actually be written like this:

Sub FillCategories(ByVal Obj As Object)
    Dim cmd As New SqlCommand("sp_Resources_Categories", Conn)
    cmd.CommandType = CommandType.StoredProcedure
    Obj.DataSource = cmd.ExecuteReader
    If Obj.GetType() Is GetType(System.Web.UI.WebControls.DropDownList) Then

    End If
    Obj.DataBind()
End Sub

You can also use the TypeOf operator instead of the GetType method. Note that this tests if your object is compatible with the given type, not that it is the same type. That would look like this:

If TypeOf Obj Is System.Web.UI.WebControls.DropDownList Then

End If

Totally trivial, irrelevant nitpick: Traditionally, the names of parameters are camelCased (which means they always start with a lower-case letter) when writing .NET code (either VB.NET or C#). This makes them easy to distinguish at a glance from classes, types, methods, etc.

Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

another alternative, just in case you want to have a shell script which creates the database if it does not exist and otherwise just keeps it as it is:

psql -U postgres -tc "SELECT 1 FROM pg_database WHERE datname = 'my_db'" | grep -q 1 || psql -U postgres -c "CREATE DATABASE my_db"

I found this to be helpful in devops provisioning scripts, which you might want to run multiple times over the same instance.

For those of you who would like an explanation:

-c = run command in database session, command is given in string
-t = skip header and footer
-q = silent mode for grep 
|| = logical OR, if grep fails to find match run the subsequent command

Convert to/from DateTime and Time in Ruby

require 'time'
require 'date'

t = Time.now
d = DateTime.now

dd = DateTime.parse(t.to_s)
tt = Time.parse(d.to_s)

How to add a button dynamically in Android?

I've used this (or very similar) code to add several TextViews to a LinearLayout:

// Quick & dirty pre-made list of text labels...
String names[] = {"alpha", "beta", "gamma", "delta", "epsilon"};
int namesLength = 5;

// Create a LayoutParams...
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT, 
    LinearLayout.LayoutParams.FILL_PARENT);

// Get existing UI containers...
LinearLayout nameButtons = (LinearLayout) view.findViewById(R.id.name_buttons);
TextView label = (TextView) view.findViewById(R.id.master_label);

TextView tv;

for (int i = 0; i < namesLength; i++) {
    // Grab the name for this "button"
    final String name = names[i];

    tv = new TextView(context);
    tv.setText(name);

    // TextViews CAN have OnClickListeners
    tv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            label.setText("Clicked button for " + name); 
        }
    });

    nameButtons.addView(tv, params);
}

The main difference between this and dicklaw795's code is it doesn't set() and re-get() the ID for each TextView--I found it unnecessary, although I may need it to later identify each button in a common handler routine (e.g. one called by onClick() for each TextView).

Scanner is never closed

According to the Javadoc of Scanner, it closes the stream when you call it's close method. Generally speaking, the code that creates a resource is also responsible for closing it. System.in was not instantiated by by your code, but by the VM. So in this case it's safe to not close the Scanner, ignore the warning and add a comment why you ignore it. The VM will take care of closing it if needed.

(Offtopic: instead of "amount", the word "number" would be more appropriate to use for a number of players. English is not my native language (I'm Dutch) and I used to make exactly the same mistake.)

C# An established connection was aborted by the software in your host machine

An established connection was aborted by the software in your host machine

That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.

The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.

You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.

How to define custom exception class in Java, the easiest way?

package customExceptions;

public class MyException extends Exception{

    public MyException(String exc)
    {
        super(exc);
    }
    public String getMessage()
    {
        return super.getMessage();
    }
}

import customExceptions.MyException;

public class UseCustomException {

    MyException newExc=new MyException("This is a custom exception");

    public UseCustomException() throws MyException
    {
        System.out.println("Hello Back Again with custom exception");
        throw newExc;       
}

    public static void main(String args[])
    {
        try
        {
            UseCustomException use=new UseCustomException();
        }
        catch(MyException myEx)
        {
            System.out.println("This is my custom exception:" + myEx.getMessage());
        }
    }
}

How to remove any URL within a string in Python

In order to remove any URL within a string in Python, you can use this RegEx function :

import re

def remove_URL(text):
    """Remove URLs from a text string"""
    return re.sub(r"http\S+", "", text)

self referential struct definition?

I know this post is old, however, to get the effect you are looking for, you may want to try the following:

#define TAKE_ADVANTAGE

/* Forward declaration of "struct Cell" as type Cell. */
typedef struct Cell Cell;

#ifdef TAKE_ADVANTAGE
/*
   Define Cell structure taking advantage of forward declaration.
*/
struct Cell
{
   int isParent;
   Cell *child;
};

#else

/*
   Or...you could define it as other posters have mentioned without taking
   advantage of the forward declaration.
*/
struct Cell
{
   int isParent;
   struct Cell *child;
};

#endif

/*
    Some code here...
*/

/* Use the Cell type. */
Cell newCell;

In either of the two cases mentioned in the code fragment above, you MUST declare your child Cell structure as a pointer. If you do not, then you will get the "field 'child' has incomplete type" error. The reason is that "struct Cell" must be defined in order for the compiler to know how much space to allocate when it is used.

If you attempt to use "struct Cell" inside the definition of "struct Cell", then the compiler cannot yet know how much space "struct Cell" is supposed to take. However, the compiler already knows how much space a pointer takes, and (with the forward declaration) it knows that "Cell" is a type of "struct Cell" (although it doesn't yet know how big a "struct Cell" is). So, the compiler can define a "Cell *" within the struct that is being defined.

C Programming: How to read the whole file contents into a buffer

Portability between Linux and Windows is a big headache, since Linux is a POSIX-conformant system with - generally - a proper, high quality toolchain for C, whereas Windows doesn't even provide a lot of functions in the C standard library.

However, if you want to stick to the standard, you can write something like this:

#include <stdio.h>
#include <stdlib.h>

FILE *f = fopen("textfile.txt", "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);  /* same as rewind(f); */

char *string = malloc(fsize + 1);
fread(string, 1, fsize, f);
fclose(f);

string[fsize] = 0;

Here string will contain the contents of the text file as a properly 0-terminated C string. This code is just standard C, it's not POSIX-specific (although that it doesn't guarantee it will work/compile on Windows...)

How to convert AAR to JAR

As many other people have pointed out, just extracting the .jar from the .aar file doesn't quite cut it as resources may be missing.

Here are the steps that worked for me (context of Android, your mileage may vary if you have other purposes):

  1. Rename the .aar file to .zip and extract.
  2. The extracted folder is an ADT project that you can import in Eclipse with some minor modifications (see below)!
  3. In the extracted folder rename the contained file classes.jar to whatever you like (in this example myProjectLib.jar) and move it to the lib folder within the extracted folder.
  4. Now in order for Eclipse to accept it you need to put two files into the extracted folder root:
    • .project
    • .classpath
  5. To do that, create a new Android dummy project in Eclipse and copy over the files, or copy over from an existing Android project.
  6. Open the .project file and look for the XML name tag and replace the contents of it with myProjectLib (or whatever you called your jar file above) and save.
  7. Now in Eclipse you can File -> New -> Project -> Android Project from existing source.. and point to the extracted folder content.
  8. After import right click on the newly created project, select Properties -> Android, and check Is Library.
  9. In your main project that you want to use the library for, also go to Properties -> Android and add the newly added myProjectLib to the list of dependencies.

How to remove elements/nodes from angular.js array

Here is filter with Underscore library might help you, we remove item with name "ted"

$scope.items = _.filter($scope.items, function(item) {
    return !(item.name == 'ted');
 });

How to make modal dialog in WPF?

Given a Window object myWindow, myWindow.Show() will open it modelessly and myWindow.ShowDialog() will open it modally. However, even the latter doesn't block, from what I remember.

How to convert a string to a date in sybase

Use the convert function, for example:

select * from data 
where dateVal < convert(datetime, '01/01/2008', 103)

Where the convert style (103) determines the date format to use.

How to split a dos path into its components in Python

Adapted the solution of @Mike Robins avoiding empty path elements at the beginning:

def parts(path):
    p,f = os.path.split(os.path.normpath(path))
    return parts(p) + [f] if f and p else [p] if p else []

os.path.normpath() is actually required only once and could be done in a separate entry function to the recursion.

How do you build a Singleton in Dart?

Thanks to Dart's factory constructors, it's easy to build a singleton:

class Singleton {
  static final Singleton _singleton = Singleton._internal();

  factory Singleton() {
    return _singleton;
  }

  Singleton._internal();
}

You can construct it like this

main() {
  var s1 = Singleton();
  var s2 = Singleton();
  print(identical(s1, s2));  // true
  print(s1 == s2);           // true
}

How to increment a letter N times per iteration and store in an array?

ord() will not work because your end string is two characters long.

Returns the ASCII value of the first character of string.

Watch it break.

From my testing, you need to check that the end string doesn't get "stepped over". The perl-style character incrementation is a cool method, but it is a single-stepping method. For this reason, an inner loop helps it along when necessary. This is actually not a bother, in fact, it is useful because we need to check if the loop(s) should be broken on each single step.

Code: (Demo)

function excelCols($letter,$end,$step=1){  // function doesn't check that $end is "later" than $letter
    if($step==0)return [];  // prevent infinite loop
    do{
        $letters[]=$letter;  // store letter
        for($x=0; $x<$step; ++$x){  // increment in accordance with $step declaration
            if($letter===$end)break(2);  // break if end is "stepped on"
            ++$letter;
        }
    }while(true);
    return $letters;    
}
echo implode(' ',excelCols('A','JJ',4));
echo "\n --- \n";
echo implode(' ',excelCols('A','BB',3));
echo "\n --- \n";
echo implode(' ',excelCols('A','ZZ',1));
echo "\n --- \n";
echo implode(' ',excelCols('A','ZZ',3));

Output:

A E I M Q U Y AC AG AK AO AS AW BA BE BI BM BQ BU BY CC CG CK CO CS CW DA DE DI DM DQ DU DY EC EG EK EO ES EW FA FE FI FM FQ FU FY GC GG GK GO GS GW HA HE HI HM HQ HU HY IC IG IK IO IS IW JA JE JI
 --- 
A D G J M P S V Y AB AE AH AK AN AQ AT AW AZ
 --- 
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z AA AB AC AD AE AF AG AH AI AJ AK AL AM AN AO AP AQ AR AS AT AU AV AW AX AY AZ BA BB BC BD BE BF BG BH BI BJ BK BL BM BN BO BP BQ BR BS BT BU BV BW BX BY BZ CA CB CC CD CE CF CG CH CI CJ CK CL CM CN CO CP CQ CR CS CT CU CV CW CX CY CZ DA DB DC DD DE DF DG DH DI DJ DK DL DM DN DO DP DQ DR DS DT DU DV DW DX DY DZ EA EB EC ED EE EF EG EH EI EJ EK EL EM EN EO EP EQ ER ES ET EU EV EW EX EY EZ FA FB FC FD FE FF FG FH FI FJ FK FL FM FN FO FP FQ FR FS FT FU FV FW FX FY FZ GA GB GC GD GE GF GG GH GI GJ GK GL GM GN GO GP GQ GR GS GT GU GV GW GX GY GZ HA HB HC HD HE HF HG HH HI HJ HK HL HM HN HO HP HQ HR HS HT HU HV HW HX HY HZ IA IB IC ID IE IF IG IH II IJ IK IL IM IN IO IP IQ IR IS IT IU IV IW IX IY IZ JA JB JC JD JE JF JG JH JI JJ JK JL JM JN JO JP JQ JR JS JT JU JV JW JX JY JZ KA KB KC KD KE KF KG KH KI KJ KK KL KM KN KO KP KQ KR KS KT KU KV KW KX KY KZ LA LB LC LD LE LF LG LH LI LJ LK LL LM LN LO LP LQ LR LS LT LU LV LW LX LY LZ MA MB MC MD ME MF MG MH MI MJ MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NB NC ND NE NF NG NH NI NJ NK NL NM NN NO NP NQ NR NS NT NU NV NW NX NY NZ OA OB OC OD OE OF OG OH OI OJ OK OL OM ON OO OP OQ OR OS OT OU OV OW OX OY OZ PA PB PC PD PE PF PG PH PI PJ PK PL PM PN PO PP PQ PR PS PT PU PV PW PX PY PZ QA QB QC QD QE QF QG QH QI QJ QK QL QM QN QO QP QQ QR QS QT QU QV QW QX QY QZ RA RB RC RD RE RF RG RH RI RJ RK RL RM RN RO RP RQ RR RS RT RU RV RW RX RY RZ SA SB SC SD SE SF SG SH SI SJ SK SL SM SN SO SP SQ SR SS ST SU SV SW SX SY SZ TA TB TC TD TE TF TG TH TI TJ TK TL TM TN TO TP TQ TR TS TT TU TV TW TX TY TZ UA UB UC UD UE UF UG UH UI UJ UK UL UM UN UO UP UQ UR US UT UU UV UW UX UY UZ VA VB VC VD VE VF VG VH VI VJ VK VL VM VN VO VP VQ VR VS VT VU VV VW VX VY VZ WA WB WC WD WE WF WG WH WI WJ WK WL WM WN WO WP WQ WR WS WT WU WV WW WX WY WZ XA XB XC XD XE XF XG XH XI XJ XK XL XM XN XO XP XQ XR XS XT XU XV XW XX XY XZ YA YB YC YD YE YF YG YH YI YJ YK YL YM YN YO YP YQ YR YS YT YU YV YW YX YY YZ ZA ZB ZC ZD ZE ZF ZG ZH ZI ZJ ZK ZL ZM ZN ZO ZP ZQ ZR ZS ZT ZU ZV ZW ZX ZY ZZ
 --- 
A D G J M P S V Y AB AE AH AK AN AQ AT AW AZ BC BF BI BL BO BR BU BX CA CD CG CJ CM CP CS CV CY DB DE DH DK DN DQ DT DW DZ EC EF EI EL EO ER EU EX FA FD FG FJ FM FP FS FV FY GB GE GH GK GN GQ GT GW GZ HC HF HI HL HO HR HU HX IA ID IG IJ IM IP IS IV IY JB JE JH JK JN JQ JT JW JZ KC KF KI KL KO KR KU KX LA LD LG LJ LM LP LS LV LY MB ME MH MK MN MQ MT MW MZ NC NF NI NL NO NR NU NX OA OD OG OJ OM OP OS OV OY PB PE PH PK PN PQ PT PW PZ QC QF QI QL QO QR QU QX RA RD RG RJ RM RP RS RV RY SB SE SH SK SN SQ ST SW SZ TC TF TI TL TO TR TU TX UA UD UG UJ UM UP US UV UY VB VE VH VK VN VQ VT VW VZ WC WF WI WL WO WR WU WX XA XD XG XJ XM XP XS XV XY YB YE YH YK YN YQ YT YW YZ ZC ZF ZI ZL ZO ZR ZU ZX

Here is an array-functions approach:

Code: (Demo)

$start='C';
$end='DD';
$step=4;

// generate and store more than we need (this is an obvious method disadvantage)
$result=$array=range('A','Z',1);  // store A - Z as $array and $result
foreach($array as $a){
    foreach($array as $b){
        $result[]="$a$b";  // store double letter combinations
        if(in_array($end,$result)){break(2);}  // stop asap
    }
}
//echo implode(' ',$result),"\n\n";

// slice away from the front of the array
$result=array_slice($result,array_search($start,$result));  // reindex keys
//echo implode(' ',$result),"\n\n";

 // punch out elements that are not "stepped on"
$result=array_filter($result,function($k)use($step){return $k%$step==0;},ARRAY_FILTER_USE_KEY); // use modulo

// result is ready
echo implode(' ',$result);

Output:

C G K O S W AA AE AI AM AQ AU AY BC BG BK BO BS BW CA CE CI CM CQ CU CY DC

C++ sorting and keeping track of indexes

Are the items in the vector unique? If so, copy the vector, sort one of the copies with STL Sort then you can find which index each item had in the original vector.

If the vector is supposed to handle duplicate items, I think youre better of implementing your own sort routine.

How to set cornerRadius for only top-left and top-right corner of a UIView?

In Swift 4.1 and Xcode 9.4.1

In iOS 11 this single line is enough:

detailsSubView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]//Set your view here

See the complete code:

//In viewDidLoad
if #available(iOS 11.0, *) {
        detailsSubView.clipsToBounds = false
        detailsSubView.layer.cornerRadius = 10
        detailsSubView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
} else {
      //For lower versions
}

But for lower versions

let rectShape = CAShapeLayer()
    rectShape.bounds = detailsSubView.frame
    rectShape.position = detailsSubView.center
    rectShape.path = UIBezierPath(roundedRect: detailsSubView.bounds,    byRoundingCorners: [.topLeft , .topRight], cornerRadii: CGSize(width: 20, height: 20)).cgPath
    detailsSubView.layer.mask = rectShape

Complete code is.

if #available(iOS 11.0, *) {
    detailsSubView.clipsToBounds = false
    detailsSubView.layer.cornerRadius = 10
    detailsSubView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
} else {
    let rectShape = CAShapeLayer()
    rectShape.bounds = detailsSubView.frame
    rectShape.position = detailsSubView.center
    rectShape.path = UIBezierPath(roundedRect: detailsSubView.bounds,    byRoundingCorners: [.topLeft , .topRight], cornerRadii: CGSize(width: 20, height: 20)).cgPath
    detailsSubView.layer.mask = rectShape
}

If you are using AutoResizing in storyboard write this code in viewDidLayoutSubviews().

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if #available(iOS 11.0, *) {
        detailsSubView.clipsToBounds = false
        detailsSubView.layer.cornerRadius = 10
        detailsSubView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
    } else {
        let rectShape = CAShapeLayer()
        rectShape.bounds = detailsSubView.frame
        rectShape.position = detailsSubView.center
        rectShape.path = UIBezierPath(roundedRect: detailsSubView.bounds,    byRoundingCorners: [.topLeft , .topRight], cornerRadii: CGSize(width: 20, height: 20)).cgPath
        detailsSubView.layer.mask = rectShape
    }
}

Usage of MySQL's "IF EXISTS"

You cannot use IF control block OUTSIDE of functions. So that affects both of your queries.

Turn the EXISTS clause into a subquery instead within an IF function

SELECT IF( EXISTS(
             SELECT *
             FROM gdata_calendars
             WHERE `group` =  ? AND id = ?), 1, 0)

In fact, booleans are returned as 1 or 0

SELECT EXISTS(
         SELECT *
         FROM gdata_calendars
         WHERE `group` =  ? AND id = ?)

to remove first and last element in array

fruits.shift();  // Removes the first element from an array and returns only that element.
fruits.pop();    // Removes the last element from an array and returns only that element. 

See all methods for an Array.

Limit Decimal Places in Android EditText

A very late response: We can do it simply like this:

etv.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.toString().length() > 3 && s.toString().contains(".")) {
                if (s.toString().length() - s.toString().indexOf(".") > 3) {
                    etv.setText(s.toString().substring(0, s.length() - 1));
                    etv.setSelection(edtSendMoney.getText().length());
                }
            }
        }

        @Override
        public void afterTextChanged(Editable arg0) {
        }
}

How to use youtube-dl from a python program?

For simple code, may be i think

import os
os.system('youtube-dl [OPTIONS] URL [URL...]')

Above is just running command line inside python.

Other is mentioned in the documentation Using youtube-dl on python Here is the way

from __future__ import unicode_literals
import youtube_dl

ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['https://www.youtube.com/watch?v=BaW_jenozKc'])

WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

During the download of wamp server from wampserver website you get a warning..

WARNING : Vous devez avoir installé Visual Studio 2012 : VC 11 vcredist_x64/86.exe Visual Studio 2012 VC 11 vcredist_x64/86.exe : http://www.microsoft.com/en-us/download/details.aspx?id=30679

So if you install the vcredist_xxx.exe it will be ok

Remove ListView items in Android

You will want to remove() the item from your adapter object and then just run the notifyDatasetChanged() on the Adapter, any ListViews will (should) recycle and update on it's own.

Here's a brief activity example with AlertDialogs:

adapter = new MyListAdapter(this);
    lv = (ListView) findViewById(android.R.id.list);
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> a, View v, int position, long id) {
        AlertDialog.Builder adb=new AlertDialog.Builder(MyActivity.this);
        adb.setTitle("Delete?");
        adb.setMessage("Are you sure you want to delete " + position);
        final int positionToRemove = position;
        adb.setNegativeButton("Cancel", null);
        adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                MyDataObject.remove(positionToRemove);
                adapter.notifyDataSetChanged();
            }});
        adb.show();
        }
    });

How to get a date in YYYY-MM-DD format from a TSQL datetime field?

If your source date format is all messed up, try something along the lines of:

select
convert(nvarchar(50),year(a.messedupDate))+'-'+
(case when len(convert(nvarchar(50),month(a.messedupDate)))=1 
    then '0'+ convert(nvarchar(50),month(a.messedupDate))+'-' 
    else convert(nvarchar(50),month(a.messedupDate)) end)+
(case when len(convert(nvarchar(50),day(a.messedupDate)))=1 
    then '0'+ convert(nvarchar(50),day(a.messedupDate))+'-'
    else convert(nvarchar(50),day(a.messedupDate)) end) 
from messytable a

IP to Location using Javascript

A rather inexpensive option would be to use the ipdata.co API, it's free upto 1500 requests a day.

This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.

_x000D_
_x000D_
$.get("https://api.ipdata.co?api-key=test", function (response) {_x000D_
    $("#ip").html("IP: " + response.ip);_x000D_
    $("#city").html(response.city + ", " + response.region);_x000D_
    $("#response").html(JSON.stringify(response, null, 4));_x000D_
}, "jsonp");
_x000D_
<h1><a href="https://ipdata.co">ipdata.co</a> - IP geolocation API</h1>_x000D_
_x000D_
<div id="ip"></div>_x000D_
<div id="city"></div>_x000D_
<pre id="response"></pre>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

View the Fiddle at https://jsfiddle.net/ipdata/6wtf0q4g/922/

PHP session handling errors

I'm using php-5.4.45 and I got the same problem.

If you are a php-fpm user, try edit php-fpm.conf and change listen.owner and listen.group to the right one. My nginx user is apache, so here I change these to params to apache, then it works well for me.

For apache user, I guess you should edit your fast-cgi params refer the two params I mention above.

jQueryUI modal dialog does not show close button (x)

Using the principle of the idea user2620505 got result with implementation of addClass:

...
open: function(){
    $('.ui-dialog-titlebar-close').addClass('ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only');
    $('.ui-dialog-titlebar-close').append('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
}, 
...

If English is bad forgive me, I am using Google Translate.

Cannot find pkg-config error

Try

Difference between require, include, require_once and include_once?

Include / Require you can include the same file more than once also:

require() is identical to include() except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.

require_once / include_once

is identical to include/require except PHP will check if the file has already been included, and if so, not include (require) it again.

How do I view cookies in Internet Explorer 11 using Developer Tools

Update 2018 for Microsoft Edge Developer Tools

The Dev Tools in Edge finally added support for managing and browsing cookies.

Note: Even if you are testing and supporting IE targets, you mine as well do the heavy lifting of your browser compatibility testing by leveraging the new tooling in Edge, and defer checking in IE 11 (etc) for the last leg.

Debugger Panel > Cookies Manager

Debugger Tab

Network Panel > Request Details > Cookies

Network Tab

The benefit, of course, to the debugger tab is you don't have to hunt and peck for individual cookies across multiple different and historical requests.

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

This is fixed by:

a) adding schemas: [ CUSTOM_ELEMENTS_SCHEMA ] to every component or

b) adding

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

and

schemas: [
  CUSTOM_ELEMENTS_SCHEMA
],

to your module.

How can I enable auto complete support in Notepad++?

Open Notepad++ and Settings -> Preferences -> Auto-Completion -> Check the Auto-insert options you want. this link will help alot: http://docs.notepad-plus-plus.org/index.php/Auto_Completion

Converting unix timestamp string to readable date

>>> import time
>>> time.ctime(int("1284101485"))
'Fri Sep 10 16:51:25 2010'
>>> time.strftime("%D %H:%M", time.localtime(int("1284101485")))
'09/10/10 16:51'

Regular expression to match balanced parentheses

This do not fully address the OP question but I though it may be useful to some coming here to search for nested structure regexp:

Parse parmeters from function string (with nested structures) in javascript

Match structures like:
Parse parmeters from function string

  • matches brackets, square brackets, parentheses, single and double quotes

Here you can see generated regexp in action

/**
 * get param content of function string.
 * only params string should be provided without parentheses
 * WORK even if some/all params are not set
 * @return [param1, param2, param3]
 */
exports.getParamsSAFE = (str, nbParams = 3) => {
    const nextParamReg = /^\s*((?:(?:['"([{](?:[^'"()[\]{}]*?|['"([{](?:[^'"()[\]{}]*?|['"([{][^'"()[\]{}]*?['")}\]])*?['")}\]])*?['")}\]])|[^,])*?)\s*(?:,|$)/;
    const params = [];
    while (str.length) { // this is to avoid a BIG performance issue in javascript regexp engine
        str = str.replace(nextParamReg, (full, p1) => {
            params.push(p1);
            return '';
        });
    }
    return params;
};

Changing SVG image color with javascript

Your SVG must be inline in your document in order to be styled with CSS. This can be done by writing the SVG markup directly into your HTML code, or by using SVG injection, which replaces the img element with the content from and SVG file with Javascript.

There is an open source library called SVGInject that does this for you. All you have to do is to add the attribute onload="SVGInject(this)" to you <img> tag.

A simple example using SVGInject looks like this:

<html>
  <head>
    <script src="svg-inject.min.js"></script>
  </head>
  <body>
    <img src="image.svg" onload="SVGInject(this)" />
  </body>
</html>

After the image is loaded the onload="SVGInject(this) will trigger the injection and the <img> element will be replaced by the contents of the SVG file provided in the src attribute.

align textbox and text/labels in html?

I have found better option,

<style type="text/css">
    .form {
        margin: 0 auto;
        width: 210px;
    }
    .form label{
        display: inline-block;
        text-align: right;
        float: left;
    }
    .form input{
        display: inline-block;
        text-align: left;
        float: right;
    }
</style>

Demo here: https://jsfiddle.net/durtpwvx/

Angular 2 - Redirect to an external URL and open in a new tab

To solve this issue more globally, here is another way using a directive:

import { Directive, HostListener, ElementRef } from "@angular/core";

@Directive({
  selector: "[hrefExternalUrl]"
})
export class HrefExternalUrlDirective {
  constructor(elementRef: ElementRef) {}

  @HostListener("click", ["$event"])
  onClick(event: MouseEvent) {
    event.preventDefault();

    let url: string = (<any>event.currentTarget).getAttribute("href");

    if (url && url.indexOf("http") === -1) {
      url = `//${url}`;
    }

    window.open(url, "_blank");
  }
}

then it's as simple as using it like this:

<a [href]="url" hrefExternalUrl> Link </a>

and don't forget to declare the directive in your module.

Row count on the Filtered data

Simply put this in your code:

Application.WorksheetFunction.Subtotal(3, Range("A2:A500000"))

Make sure you apply the correct range, but just keep it to ONE column

HowTo Generate List of SQL Server Jobs and their owners

A colleague told me about this stored procedure...

USE msdb

EXEC dbo.sp_help_job

One DbContext per web request... why?

Another issue to watch out for with Entity Framework specifically is when using a combination of creating new entities, lazy loading, and then using those new entities (from the same context). If you don't use IDbSet.Create (vs just new), Lazy loading on that entity doesn't work when its retrieved out of the context it was created in. Example:

 public class Foo {
     public string Id {get; set; }
     public string BarId {get; set; }
     // lazy loaded relationship to bar
     public virtual Bar Bar { get; set;}
 }
 var foo = new Foo {
     Id = "foo id"
     BarId = "some existing bar id"
 };
 dbContext.Set<Foo>().Add(foo);
 dbContext.SaveChanges();

 // some other code, using the same context
 var foo = dbContext.Set<Foo>().Find("foo id");
 var barProp = foo.Bar.SomeBarProp; // fails with null reference even though we have BarId set.

Simulate low network connectivity for Android

I have one strategy to settle your problem. You can use the application of proxy to modify or monitor your net status. e.g, Charles.

You ought to change the default config of the Charles like the following picture I posted.

Open Your Throttle Setting

Setting Your Throttle Setting

And finally, you will discover the net status has been shaped into lower pace.

Before

Setting After

Which one is the best PDF-API for PHP?

Personally I prefer to use dompdf for simple PDF pages as it is very quick. you simply feed it an HTML source and it will generate the required page.

however for more complex designs i prefer the more classic pdflib which is available as a pecl for PHP. it has greater control over designs and allows you do do more complex designs like pixel-perfect forms.

Get Hours and Minutes (HH:MM) from date

You can cast datetime to time

select CAST(GETDATE() as time)

If you want a hh:mm format

select cast(CAST(GETDATE() as time) as varchar(5))

Get current cursor position in a textbox

It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.

_x000D_
_x000D_
function textbox()_x000D_
{_x000D_
        var ctl = document.getElementById('Javascript_example');_x000D_
        var startPos = ctl.selectionStart;_x000D_
        var endPos = ctl.selectionEnd;_x000D_
        alert(startPos + ", " + endPos);_x000D_
}
_x000D_
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">
_x000D_
_x000D_
_x000D_

Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart and selectionEnd.

How to view/delete local storage in Firefox?

I could not use localStorage directly in the Firefox (v27) console. I got the error:

[Exception... "Component is not available" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: debugger eval code :: :: line 1" data: no]

What worked was:

window.content.localStorage

Is it possible to format an HTML tooltip (title attribute)?

No. But there are other options out there like Overlib, and jQuery that allow you this freedom.

Personally, I would suggest jQuery as the route to take. It's typically very unobtrusive, and requires no additional setup in the markup of your site (with the exception of adding the jquery script tag in your <head>).

min and max value of data type in C

The header file limits.h defines macros that expand to various limits and parameters of the standard integer types.

beyond top level package error in relative import

Edit: 2020-05-08: Is seems the website I quoted is no longer controlled by the person who wrote the advice, so I'm removing the link to the site. Thanks for letting me know baxx.


If someone's still struggling a bit after the great answers already provided, I found advice on a website that no longer is available.

Essential quote from the site I mentioned:

"The same can be specified programmatically in this way:

import sys

sys.path.append('..')

Of course the code above must be written before the other import statement.

It's pretty obvious that it has to be this way, thinking on it after the fact. I was trying to use the sys.path.append('..') in my tests, but ran into the issue posted by OP. By adding the import and sys.path defintion before my other imports, I was able to solve the problem.

Issue with background color and Google Chrome

Oddly enough it doesn't actually happen on every page and it doesn't seem to always work even when refreshed.

My solutions was to add {height: 100%;} as well.

difference between throw and throw new Exception()

None of the answers here show the difference, which could be helpful for folks struggling to understand the difference. Consider this sample code:

using System;
using System.Collections.Generic;

namespace ExceptionDemo
{
   class Program
   {
      static void Main(string[] args)
      {
         void fail()
         {
            (null as string).Trim();
         }

         void bareThrow()
         {
            try
            {
               fail();
            }
            catch (Exception e)
            {
               throw;
            }
         }

         void rethrow()
         {
            try
            {
               fail();
            }
            catch (Exception e)
            {
               throw e;
            }
         }

         void innerThrow()
         {
            try
            {
               fail();
            }
            catch (Exception e)
            {
               throw new Exception("outer", e);
            }
         }

         var cases = new Dictionary<string, Action>()
         {
            { "Bare Throw:", bareThrow },
            { "Rethrow", rethrow },
            { "Inner Throw", innerThrow }
         };

         foreach (var c in cases)
         {
            Console.WriteLine(c.Key);
            Console.WriteLine(new string('-', 40));
            try
            {
               c.Value();
            } catch (Exception e)
            {
               Console.WriteLine(e.ToString());
            }
         }
      }
   }
}

Which generates the following output:

Bare Throw:
----------------------------------------
System.NullReferenceException: Object reference not set to an instance of an object.
   at ExceptionDemo.Program.<Main>g__fail|0_0() in C:\...\ExceptionDemo\Program.cs:line 12
   at ExceptionDemo.Program.<>c.<Main>g__bareThrow|0_1() in C:\...\ExceptionDemo\Program.cs:line 19
   at ExceptionDemo.Program.Main(String[] args) in C:\...\ExceptionDemo\Program.cs:line 64

Rethrow
----------------------------------------
System.NullReferenceException: Object reference not set to an instance of an object.
   at ExceptionDemo.Program.<>c.<Main>g__rethrow|0_2() in C:\...\ExceptionDemo\Program.cs:line 35
   at ExceptionDemo.Program.Main(String[] args) in C:\...\ExceptionDemo\Program.cs:line 64

Inner Throw
----------------------------------------
System.Exception: outer ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at ExceptionDemo.Program.<Main>g__fail|0_0() in C:\...\ExceptionDemo\Program.cs:line 12
   at ExceptionDemo.Program.<>c.<Main>g__innerThrow|0_3() in C:\...\ExceptionDemo\Program.cs:line 43
   --- End of inner exception stack trace ---
   at ExceptionDemo.Program.<>c.<Main>g__innerThrow|0_3() in C:\...\ExceptionDemo\Program.cs:line 47
   at ExceptionDemo.Program.Main(String[] args) in C:\...\ExceptionDemo\Program.cs:line 64

The bare throw, as indicated in the previous answers, clearly shows both the original line of code that failed (line 12) as well as the two other points active in the call stack when the exception occurred (lines 19 and 64).

The output of the re-throw case shows why it's a problem. When the exception is rethrown like this the exception won't include the original stack information. Note that only the throw e (line 35) and outermost call stack point (line 64) are included. It would be difficult to track down the fail() method as the source of the problem if you throw exceptions this way.

The last case (innerThrow) is most elaborate and includes more information than either of the above. Since we're instantiating a new exception we get the chance to add contextual information (the "outer" message, here but we can also add to the .Data dictionary on the new exception) as well as preserving all of the information in the original exception (including help links, data dictionary, etc.).

Oracle 10g: Extract data (select) from XML (CLOB Type)

Try this instead:

select xmltype(t.xml).extract('//fax/text()').getStringVal() from mytab t

MatPlotLib: Multiple datasets on the same scatter plot

You can also do this easily in Pandas, if your data is represented in a Dataframe, as described here:

http://pandas.pydata.org/pandas-docs/version/0.15.0/visualization.html#scatter-plot

How to use Greek symbols in ggplot2?

Here is a link to an excellent wiki that explains how to put greek symbols in ggplot2. In summary, here is what you do to obtain greek symbols

  1. Text Labels: Use parse = T inside geom_text or annotate.
  2. Axis Labels: Use expression(alpha) to get greek alpha.
  3. Facet Labels: Use labeller = label_parsed inside facet.
  4. Legend Labels: Use bquote(alpha == .(value)) in legend label.

You can see detailed usage of these options in the link

EDIT. The objective of using greek symbols along the tick marks can be achieved as follows

require(ggplot2);
data(tips);
p0 = qplot(sex, data = tips, geom = 'bar');
p1 = p0 + scale_x_discrete(labels = c('Female' = expression(alpha),
                                      'Male'   = expression(beta)));
print(p1);

For complete documentation on the various symbols that are available when doing this and how to use them, see ?plotmath.

Blank HTML SELECT without blank item in dropdown list

You can try this snippet

$("#your-id")[0].selectedIndex = -1

It worked for me.

Python: One Try Multiple Except

Yes, it is possible.

try:
   ...
except FirstException:
   handle_first_one()

except SecondException:
   handle_second_one()

except (ThirdException, FourthException, FifthException) as e:
   handle_either_of_3rd_4th_or_5th()

except Exception:
   handle_all_other_exceptions()

See: http://docs.python.org/tutorial/errors.html

The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)

All shards failed

It is possible on your restart some shards were not recovered, causing the cluster to stay red.
If you hit:
http://<yourhost>:9200/_cluster/health/?level=shards you can look for red shards.

I have had issues on restart where shards end up in a non recoverable state. My solution was to simply delete that index completely. That is not an ideal solution for everyone.

It is also nice to visualize issues like this with a plugin like:
Elasticsearch Head

Repeat String - Javascript

Fiddle: http://jsfiddle.net/3Y9v2/

function repeat(s, n){
    return ((new Array(n+1)).join(s));
}
alert(repeat('R', 10));

How to rebuild docker container in docker-compose.yml?

Only:

$ docker-compose restart [yml_service_name]

How to show Bootstrap table with sort icon

Use this icons with bootstrap (glyphicon):

<span class="glyphicon glyphicon-triangle-bottom"></span>
<span class="glyphicon glyphicon-triangle-top"></span>

http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h

http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h

Build Maven Project Without Running Unit Tests

Run following command:

mvn clean install -DskipTests=true

Pass in an array of Deferreds to $.when()

I had a case very similar where I was posting in an each loop and then setting the html markup in some fields from numbers received from the ajax. I then needed to do a sum of the (now-updated) values of these fields and place in a total field.

Thus the problem was that I was trying to do a sum on all of the numbers but no data had arrived back yet from the async ajax calls. I needed to complete this functionality in a few functions to be able to reuse the code. My outer function awaits the data before I then go and do some stuff with the fully updated DOM.

    // 1st
    function Outer() {
        var deferreds = GetAllData();

        $.when.apply($, deferreds).done(function () {
            // now you can do whatever you want with the updated page
        });
    }

    // 2nd
    function GetAllData() {
        var deferreds = [];
        $('.calculatedField').each(function (data) {
            deferreds.push(GetIndividualData($(this)));
        });
        return deferreds;
    }

    // 3rd
    function GetIndividualData(item) {
        var def = new $.Deferred();
        $.post('@Url.Action("GetData")', function (data) {
            item.html(data.valueFromAjax);
            def.resolve(data);
        });
        return def;
    }

"No such file or directory" but it exists

I faced this error when I was trying to build Selenium source on Ubuntu. The simple shell script with correct shebang was not able to run even after I had all pre-requisites covered.

file file-name # helped me in understanding that CRLF ending were present in the file.

I opened the file in Vim and I could see that just because I once edited this file on a Windows machine, it was in DOS format. I converted the file to Unix format with below command:

dos2unix filename # actually helped me and things were fine.

I hope that we should take care whenever we edit files across platforms we should take care for the file formats as well.

How to use the CancellationToken property?

@BrainSlugs83

You shouldn't blindly trust everything posted on stackoverflow. The comment in Jens code is incorrect, the parameter doesn't control whether exceptions are thrown or not.

MSDN is very clear what that parameter controls, have you read it? http://msdn.microsoft.com/en-us/library/dd321703(v=vs.110).aspx

If throwOnFirstException is true, an exception will immediately propagate out of the call to Cancel, preventing the remaining callbacks and cancelable operations from being processed. If throwOnFirstException is false, this overload will aggregate any exceptions thrown into an AggregateException, such that one callback throwing an exception will not prevent other registered callbacks from being executed.

The variable name is also wrong because Cancel is called on CancellationTokenSource not the token itself and the source changes state of each token it manages.

How do you rotate a two dimensional array?

All the current solutions have O(n^2) overhead as scratch space (this excludes those filthy OOP cheaters!). Here's a solution with O(1) memory usage, rotating the matrix in-place 90 degress right. Screw extensibility, this sucker runs fast!

#include <algorithm>
#include <cstddef>

// Rotates an NxN matrix of type T 90 degrees to the right.
template <typename T, size_t N>
void rotate_matrix(T (&matrix)[N][N])
{
    for(size_t i = 0; i < N; ++i)
        for(size_t j = 0; j <= (N-i); ++j)
            std::swap(matrix[i][j], matrix[j][i]);
}

DISCLAIMER: I didn't actually test this. Let's play whack-a-bug!

Get Image Height and Width as integer values?

list($width, $height) = getimagesize($filename)

Or,

$data = getimagesize($filename);
$width = $data[0];
$height = $data[1];

Using sed to mass rename files

The easiest way would be:

for i in F00001*; do mv "$i" "${i/F00001/F0001}"; done

or, portably,

for i in F00001*; do mv "$i" "F0001${i#F00001}"; done

This replaces the F00001 prefix in the filenames with F0001. credits to mahesh here: http://www.debian-administration.org/articles/150

SqlException: DB2 SQL error: SQLCODE: -302, SQLSTATE: 22001, SQLERRMC: null

To get the definition of the SQL codes, the easiest way is to use db2 cli!

at the unix or dos command prompt, just type

db2 "? SQL302"

this will give you the required explanation of the particular SQL code that you normally see in the java exception or your db2 sql output :)

hope this helped.

How do I remove a specific element from a JSONArray?

You can use reflection

A Chinese website provides a relevant solution: http://blog.csdn.net/peihang1354092549/article/details/41957369
If you don't understand Chinese, please try to read it with the translation software.

He provides this code for the old version:

public void JSONArray_remove(int index, JSONArray JSONArrayObject) throws Exception{
    if(index < 0)
        return;
    Field valuesField=JSONArray.class.getDeclaredField("values");
    valuesField.setAccessible(true);
    List<Object> values=(List<Object>)valuesField.get(JSONArrayObject);
    if(index >= values.size())
        return;
    values.remove(index);
}

Can iterators be reset in Python?

No. Python's iterator protocol is very simple, and only provides one single method (.next() or __next__()), and no method to reset an iterator in general.

The common pattern is to instead create a new iterator using the same procedure again.

If you want to "save off" an iterator so that you can go back to its beginning, you may also fork the iterator by using itertools.tee

How to parse XML using shellscript?

This really is beyond the capabilities of shell script. Shell script and the standard Unix tools are okay at parsing line oriented files, but things change when you talk about XML. Even simple tags can present a problem:

<MYTAG>Data</MYTAG>

<MYTAG>
     Data
</MYTAG>

<MYTAG param="value">Data</MYTAG>

<MYTAG><ANOTHER_TAG>Data
</ANOTHER_TAG><MYTAG>

Imagine trying to write a shell script that can read the data enclosed in . The three very, very simply XML examples all show different ways this can be an issue. The first two examples are the exact same syntax in XML. The third simply has an attribute attached to it. The fourth contains the data in another tag. Simple sed, awk, and grep commands cannot catch all possibilities.

You need to use a full blown scripting language like Perl, Python, or Ruby. Each of these have modules that can parse XML data and make the underlying structure easier to access. I've use XML::Simple in Perl. It took me a few tries to understand it, but it did what I needed, and made my programming much easier.

Changing Shell Text Color (Windows)

This is extremely simple! Rather than importing odd modules for python or trying long commands you can take advantage of windows OS commands.

In windows, commands exist to change the command prompt text color. You can use this in python by starting with a: import os

Next you need to have a line changing the text color, place it were you want in your code. os.system('color 4')

You can figure out the other colors by starting cmd.exe and typing color help.

The good part? Thats all their is to it, to simple lines of code. -Day

On localhost, how do I pick a free port number?

In my experience, just pick a relatively high number (between 1024-65535) that you think is unlikely to be used by anything else. For example, port # 8080 and # 5555 are ones that I routinely use. Just pick a port number like this as opposed to just making the code randomly select it and then having to find the port number later is much easier for me.

For example, in my current ChatBot project:

port = 8080

Sun JSTL taglib declaration fails with "Can not find the tag library descriptor"

I just want to share my experience. I have same problem about jstl using maven. I resolved it by adding two dependency.

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

Drop rows with all zeros in pandas data frame

You can use a quick lambda function to check if all the values in a given row are 0. Then you can use the result of applying that lambda as a way to choose only the rows that match or don't match that condition:

import pandas as pd
import numpy as np

np.random.seed(0)

df = pd.DataFrame(np.random.randn(5,3), 
                  index=['one', 'two', 'three', 'four', 'five'],
                  columns=list('abc'))

df.loc[['one', 'three']] = 0

print df
print df.loc[~df.apply(lambda row: (row==0).all(), axis=1)]

Yields:

              a         b         c
one    0.000000  0.000000  0.000000
two    2.240893  1.867558 -0.977278
three  0.000000  0.000000  0.000000
four   0.410599  0.144044  1.454274
five   0.761038  0.121675  0.443863

[5 rows x 3 columns]
             a         b         c
two   2.240893  1.867558 -0.977278
four  0.410599  0.144044  1.454274
five  0.761038  0.121675  0.443863

[3 rows x 3 columns]

Class has no member named

Maybe I am 6.5 years late. But I'm answering because others maybe searching still now. I faced the same problem and was searching everywhere. But then I realized I had written my code in an empty file. If you create a project and write your code in there, there won't be this error.

Where do I download JDBC drivers for DB2 that are compatible with JDK 1.5?

I know its late but i recently ran into this situation. After wasting entire day I finally found the solution. I am suprised that I got this info on oracle's website whereas this seems nowhere to be found on IBM's website.

If you want to use JDBC drivers for DB2 that are compatible with JDK 1.5 or 1.4 , you need to use the jar db2jcc.jar, which is available in SQLLIB/java/ folder of your db2 installation.

How do you execute SQL from within a bash script?

As Bash doesn't have built in sql database connectivity... you will need to use some sort of third party tool.

How to fix corrupted git repository?

Quick way if you have change on your current project and don't want to lose it , move your current project some where , clone the project from github to this folder and make some change an try to commit again. Or just delete the repo and clone it again , it worked form me .

importing pyspark in python shell

Here is a simple method (If you don't bother about how it works!!!)

Use findspark

  1. Go to your python shell

    pip install findspark
    
    import findspark
    findspark.init()
    
  2. import the necessary modules

    from pyspark import SparkContext
    from pyspark import SparkConf
    
  3. Done!!!

How to parse a JSON file in swift?

Codable

In Swift 4+ is strongly recommended to use Codable instead of JSONSerialization.

This Codable includes two protocols: Decodable and Encodable. This Decodable protocol allows you to decode Data in JSON format to custom struct/class conforming to this protocol.

For example imagine situation that we have this simple Data (array of two objects)

let data = Data("""
[
    {"name":"Steve","age":56}, 
    {"name":"iPhone","age":11}
]
""".utf8)

then have following struct and implement protocol Decodable

struct Person: Decodable {
    let name: String
    let age: Int
}

now you can decode your Data to your array of Person using JSONDecoder where first parameter is type conforming to Decodable and to this type should Data be decoded

do {
    let people = try JSONDecoder().decode([Person].self, from: data)
} catch { print(error) }

... note that decoding has to be marked with try keyword since you could for example make some mistake with naming and then your model can't be decoded correctly ... so you should put it inside do-try-catch block


Cases that key in json is different from name of property:

  • If key is in named using snake_case, you can set decoder's keyDecodingStrategy to convertFromSnakeCase which changes key from property_name to camelCase propertyName

    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let people = try decoder.decode([Person].self, from: data)
    
  • If you need unique name you can use coding keys inside struct/class where you declare name of key

    let data = Data(""" 
    { "userName":"Codable", "age": 1 } 
    """.utf8)
    
    struct Person: Decodable {
    
        let name: String
        let age: Int
    
        enum CodingKeys: String, CodingKey {
            case name = "userName"
            case age
        }
    }
    

JFrame Exit on close Java

I spent quite a bit of time spelunking through the internet for an elegant solution to this. As is usually the case, I found a lot of conflicting information.

I finally ended with:

  1. Do not use EXIT_ON_CLOSE as this can leave resources behind;
  2. Do use something like the following in the JFrame initialization:

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    
  3. The real discovery was how to actually dispatch a window message to the JFrame. As an example, as part of your JMenuItem for exiting the application, use the following, where the function getFrame() returns a reference to the JFrame:

    public class AppMenuFileExit extends JMenuItem implements ActionListener
    {
        // do your normal menu item code here
    
          @Override
          public void actionPerformed(ActionEvent e)
          {
            WindowEvent we;
            we = new WindowEvent((Window) App.getFrame(), WindowEvent.WINDOW_CLOSING);
    
            App.getFrame().dispatchEvent(we);
          }
    }
    

    JFrame is a subclass of Window so may be cast to Window for this purpose.

  4. And, have the following in your JFrame class to handle Window messages:

    public class AppFrame extends JFrame implements WindowListener
    {
      // Do all the things you need to for the class
    
      @Override
      public void windowOpened(WindowEvent e)
      {}
      @Override
      public void windowClosing(WindowEvent e)
      {/* can do cleanup here if necessary */}
    
      @Override
      public void windowClosed(WindowEvent e)
      {
        dispose();
        System.exit(0);
      }
      @Override
      public void windowActivated(WindowEvent e)
      {}
      @Override
      public void windowDeactivated(WindowEvent e)
      {}    
      @Override
      public void windowDeiconified(WindowEvent e)
      {}
      @Override
      public void windowIconified(WindowEvent e)
      {}
    }
    

Creating stored procedure with declare and set variables

You should try this syntax - assuming you want to have @OrderID as a parameter for your stored procedure:

CREATE PROCEDURE dbo.YourStoredProcNameHere
   @OrderID INT
AS
BEGIN
 DECLARE @OrderItemID AS INT
 DECLARE @AppointmentID AS INT
 DECLARE @PurchaseOrderID AS INT
 DECLARE @PurchaseOrderItemID AS INT
 DECLARE @SalesOrderID AS INT
 DECLARE @SalesOrderItemID AS INT

 SELECT @OrderItemID = OrderItemID 
 FROM [OrderItem] 
 WHERE OrderID = @OrderID

 SELECT @AppointmentID = AppoinmentID 
 FROM [Appointment] 
 WHERE OrderID = @OrderID

 SELECT @PurchaseOrderID = PurchaseOrderID 
 FROM [PurchaseOrder] 
 WHERE OrderID = @OrderID

END

OF course, that only works if you're returning exactly one value (not multiple values!)

AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?

Try using No Wrap - In Head or No wrap - in body in your fiddle:

Working fiddle: http://jsfiddle.net/Q5hd6/

Explanation:

Angular begins compiling the DOM when the DOM is fully loaded. You register your code to run onLoad (onload option in fiddle) => it's too late to register your myApp module because angular begins compiling the DOM and angular sees that there is no module named myApp and throws an exception.

By using No Wrap - In Head, your code looks like this:

<head>

    <script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js'></script>

    <script type='text/javascript'>
      //Your script.
    </script>

</head>

Your script has a chance to run before angular begins compiling the DOM and myApp module is already created when angular starts compiling the DOM.

ANTLR: Is there a simple example?

ANTLR mega tutorial by Gabriele Tomassetti is very helpful

It has grammar examples, examples of visitors in different languages (Java, JavaScript, C# and Python) and many other things. Highly recommended.

EDIT: other useful articles by Gabriele Tomassetti on ANTLR

C++ Array of pointers: delete or delete []?

To simplify the answare let's look on the following code:

#include "stdafx.h"
#include <iostream>
using namespace std;

class A
{
private:
    int m_id;
    static int count;
public:
    A() {count++; m_id = count;}
    A(int id) { m_id = id; }
    ~A() {cout<< "Destructor A "   <<m_id<<endl; }
};

int A::count = 0;

void f1()
{   
    A* arr = new A[10];
    //delete operate only one constructor, and crash!
    delete arr;
    //delete[] arr;
}

int main()
{
    f1();
    system("PAUSE");
    return 0;
}

The output is: Destructor A 1 and then it's crashing (Expression: _BLOCK_TYPE_IS_VALID(phead- nBlockUse)).

We need to use: delete[] arr; becuse it's delete the whole array and not just one cell!

try to use delete[] arr; the output is: Destructor A 10 Destructor A 9 Destructor A 8 Destructor A 7 Destructor A 6 Destructor A 5 Destructor A 4 Destructor A 3 Destructor A 2 Destructor A 1

The same principle is for an array of pointers:

void f2()
{
    A** arr = new A*[10];
    for(int i = 0; i < 10; i++)
    {
        arr[i] = new A(i);
    }
    for(int i = 0; i < 10; i++)
    {
        delete arr[i];//delete the A object allocations.
    }

    delete[] arr;//delete the array of pointers
}

if we'll use delete arr instead of delete[] arr. it will not delete the whole pointers in the array => memory leak of pointer objects!

Where to find Java JDK Source Code?

Here the official link for jdk source. http://www.oracle.com/technetwork/java/javase/downloads/index.html (you may need to scroll to the bottom of the page)

How to change default language for SQL Server?

Please try below:

DECLARE @Today DATETIME;  
SET @Today = '12/5/2007';  

SET LANGUAGE Italian;  
SELECT DATENAME(month, @Today) AS 'Month Name';  

SET LANGUAGE us_english;  
SELECT DATENAME(month, @Today) AS 'Month Name' ;  
GO  

Reference:

https://docs.microsoft.com/en-us/sql/t-sql/statements/set-language-transact-sql

Using Excel VBA to run SQL query

Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):

References required for SQL

Sub Module for Connecting to MS SQL with Remote Host & Username/Password

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

How to write a multiline Jinja statement

According to the documentation: https://jinja.palletsprojects.com/en/2.10.x/templates/#line-statements you may use multi-line statements as long as the code has parens/brackets around it. Example:

{% if ( (foo == 'foo' or bar == 'bar') and 
        (fooo == 'fooo' or baar == 'baar') ) %}
    <li>some text</li>
{% endif %}

Edit: Using line_statement_prefix = '#'* the code would look like this:

# if ( (foo == 'foo' or bar == 'bar') and 
       (fooo == 'fooo' or baar == 'baar') )
    <li>some text</li>
# endif

*Here's an example of how you'd specify the line_statement_prefix in the Environment:

from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
    loader=PackageLoader('yourapplication', 'templates'),
    autoescape=select_autoescape(['html', 'xml']),
    line_statement_prefix='#'
)

Or using Flask:

from flask import Flask
app = Flask(__name__, instance_relative_config=True, static_folder='static')
app.jinja_env.filters['zip'] = zip
app.jinja_env.line_statement_prefix = '#'

Quick way to clear all selections on a multiselect enabled <select> with jQuery?

This is the best way to clear a multi-select or list box:

 $("#drp_assign_list option[value]").remove();

"Multiple definition", "first defined here" errors

Maybe you included the .c file in makefile multiple times.

Disable button in WPF?

This should do it:

<StackPanel>
    <TextBox x:Name="TheTextBox" />
    <Button Content="Click Me">
        <Button.Style>
            <Style TargetType="Button">
                <Setter Property="IsEnabled" Value="True" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Text, ElementName=TheTextBox}" Value="">
                        <Setter Property="IsEnabled" Value="False" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>
</StackPanel>

How to break out or exit a method in Java?

How to break out in java??

Ans: Best way: System.exit(0);

Java language provides three jump statemnts that allow you to interrupt the normal flow of program.

These include break , continue ,return ,labelled break statement for e.g

import java.util.Scanner;
class demo
{   
    public static void main(String args[])
    {
            outerLoop://Label
            for(int i=1;i<=10;i++)
            {
                    for(int j=1;j<=i;j++)
                    {   
                        for(int k=1;k<=j;k++)
                        {
                            System.out.print(k+"\t");
                            break outerLoop;
                        }
                     System.out.println();                  
                    }
             System.out.println();
            }
    }   
}

Output: 1

Now Note below Program:

import java.util.Scanner;
class demo
{   
    public static void main(String args[])
    {
            for(int i=1;i<=10;i++)
            {
                    for(int j=1;j<=i;j++)
                    {   
                        for(int k=1;k<=j;k++)
                        {
                            System.out.print(k+"\t");
                            break ;
                        }                   
                    }
             System.out.println();
            }
    }   
}

output:

1
11
111
1111

and so on upto

1111111111

Similarly you can use continue statement just replace break with continue in above example.

Things to Remember :

A case label cannot contain a runtime expressions involving variable or method calls

outerLoop:
Scanner s1=new Scanner(System.in);
int ans=s1.nextInt();
// Error s1 cannot be resolved

How to properly add cross-site request forgery (CSRF) token using PHP

CSRF protection

TYPES OF CSRF USAGE

IN FORM

<form>
   @csrf
</form>

or

<input type="hidden" name="token" value="{{ form_token() }}" />

META TAG

<meta name="csrf-token" content="{{ csrf_token() }}">

AJAX

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

SESSION

use Illuminate\Http\Request;

Route::get('/token', function (Request $request) {
    $token = $request->session()->token();

    $token = csrf_token();

    // ...
});

MIDDLEWARE

 App\Providers\RouteServiceProvider

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'stripe/*',
        'http://example.com/foo/bar',
        'http://example.com/foo/*',
    ];
}

Why must wait() always be in synchronized block

When you call notify() from an object t, java notifies a particular t.wait() method. But, how does java search and notify a particular wait method.

java only looks into the synchronized block of code which was locked by object t. java cannot search the whole code to notify a particular t.wait().

NSString with \n or line break

\n is the preferred way to break a line. \r will work too. \n\r or \r\n are overkill and may cause you issues later. Cocoa, has specific paragraph and line break characters for specific uses NSParagraphSeparatorCharacter, NSLineSeparatorCharacter. Here is my source for all the above.

Current user in Magento?

This way:

$email = Mage::getSingleton('customer/session')->getCustomer()->getEmail();
echo $email;

How to submit form on change of dropdown list?

To those in the answer above. It's definitely JavaScript. It's just inline.

BTW the jQuery equivalent if you want to apply to all selects:

$('form select').on('change', function(){
    $(this).closest('form').submit();
});

Common sources of unterminated string literal

Scan the code that comes before the line# mentioned by error message. Whatever is unterminated has resulted in something downstream, (the blamed line#), to be flagged.

How to avoid java.util.ConcurrentModificationException when iterating through and removing elements from an ArrayList

"Should I clone the list first?"

That will be the easiest solution, remove from the clone, and copy the clone back after removal.

An example from my rummikub game:

SuppressWarnings("unchecked")
public void removeStones() {
  ArrayList<Stone> clone = (ArrayList<Stone>) stones.clone();
  // remove the stones moved to the table
  for (Stone stone : stones) {
      if (stone.isOnTable()) {
         clone.remove(stone);
      }
  }
  stones = (ArrayList<Stone>) clone.clone();
  sortStones();
}

How to secure MongoDB with username and password

Some of the answers are sending mixed signals between using --auth command line flag or setting config file property.

security:
  authorization: enabled

I would like to clarify that aspect. First of all, authentication credentials (ie user/password) in both cases has to be created by executing db.createUser query on the default admin database. Once credentials are obtained, there are two ways to enable authentication:

  1. Without a custom config file: This is when the former auth flag is applicable. Start mongod like: usr/bin/mongod --auth
  2. With a custom config file: This is when the latter configs has to be present in the custom config file.Start mongod like: usr/bin/mongod --config <config file path>

To connect to the mongo shell with authentication: mongo -u <user> -p <password> --authenticationDatabase admin

--authenticationDatabase here is the database name where the user was created. All other mongo commands like mongorestore, mongodump accept the additional options ie -u <user> -p <password> --authenticationDatabase admin

Refer to https://docs.mongodb.com/manual/tutorial/enable-authentication/ for details.

How to add screenshot to READMEs in github repository?

Method 1->Markdown way

![Alt Text](https://raw.github.com/{USERNAME}/{REPOSITORY}/{BRANCH}/{PATH})

Method 2->HTML way

<img src="https://link(format same as above)" width="100" height="100"/>

or

<img src="https://link" style=" width:100px ; height:100px " />

Note-> If you don't want to style your image i.e resize remove the style part

Finding even or odd ID values

ID % 2 is checking what the remainder is if you divide ID by 2. If you divide an even number by 2 it will always have a remainder of 0. Any other number (odd) will result in a non-zero value. Which is what is checking for.

How to get child element by class name?

June 2018 update to ES6

    const doc = document.getElementById('test');
    let notes = null;
    for (const value of doc) {
        if (value.className === '4') {
            notes = value;
            break;
        }    
    }

Granting Rights on Stored Procedure to another user of Oracle

SQL> grant create any procedure to testdb;

This is a command when we want to give create privilege to "testdb" user.

How to use an existing database with an Android application

If you already have a database, keep it in your asset folder and copy it in your application. For more detail, see Android database basics.

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

If you have the latest browsers window.orientation might not work. In that case use following code for getting angle -

var orientation = window.screen.orientation.angle;

This is still an experimental technology, you can check the browser compatibility here

How to add Active Directory user group as login in SQL Server

Go to the SQL Server Management Studio, navigate to Security, go to Logins and right click it. A Menu will come up with a button saying "New Login". There you will be able to add users and/or groups from Active Directory to your SQL Server "permissions". Hope this helps

How to open remote files in sublime text 3

Base on this.

Step by step:

  • On your local workstation: On Sublime Text 3, open Package Manager (Ctrl-Shift-P on Linux/Win, Cmd-Shift-P on Mac, Install Package), and search for rsub
  • On your local workstation: Add RemoteForward 52698 127.0.0.1:52698 to your .ssh/config file, or -R 52698:localhost:52698 if you prefer command line
  • On your remote server:

    sudo wget -O /usr/local/bin/rsub https://raw.github.com/aurora/rmate/master/rmate
    sudo chmod a+x /usr/local/bin/rsub
    

Just keep your ST3 editor open, and you can easily edit remote files with

rsub myfile.txt

EDIT: if you get "no such file or directory", it's because your /usr/local/bin is not in your PATH. Just add the directory to your path:

echo "export PATH=\"$PATH:/usr/local/bin\"" >> $HOME/.bashrc

Now just log off, log back in, and you'll be all set.

What is the difference between application server and web server?

  • web server: for every URL, it returns a file. That's all it does. The file is static content, meaning, it is stored somewhere in the server, before you make your request. Most popular web servers are apache http and nginx.
  • application server: for every URL, it runs some code, written in some language, generates a response, and returns it. The response doesn't exist in advance, it is generated for your particular request, that is, it is dynamic content. Application servers are different for each language. Some popular examples are tomcat/jetty for java, uwsgi/gunicorn for python.

Almost every page you visit uses both. The static content (eg, images, videos) is served by the web server, and the rest (the parts that are different between you and other users) are generated by the application server.

Two arrays in foreach loop

foreach( $codes as $code and $names as $name ) { }

That is not valid.

You probably want something like this...

foreach( $codes as $index => $code ) {
   echo '<option value="' . $code . '">' . $names[$index] . '</option>';
}

Alternatively, it'd be much easier to make the codes the key of your $names array...

$names = array(
   'tn' => 'Tunisia',
   'us' => 'United States',
   ...
);

YAML: Do I need quotes for strings in YAML?

After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:

  • In general, you don't need quotes.
  • Use quotes to force a string, e.g. if your key or value is 10 but you want it to return a String and not a Fixnum, write '10' or "10".
  • Use quotes if your value includes special characters, (e.g. :, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, \).
  • Single quotes let you put almost any character in your string, and won't try to parse escape codes. '\n' would be returned as the string \n.
  • Double quotes parse escape codes. "\n" would be returned as a line feed character.
  • The exclamation mark introduces a method, e.g. !ruby/sym to return a Ruby symbol.

Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.

Update

"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:

en:
  yesno:
    'yes': 'Yes'
    'no': 'No'

CSS selector - element with a given child

Update 2019

The :has() pseudo-selector is propsed in the CSS Selectors 4 spec, and will address this use case once implemented.

To use it, we will write something like:

.foo > .bar:has(> .baz) { /* style here */ }

In a structure like:

<div class="foo">
  <div class="bar">
    <div class="baz">Baz!</div>
  </div>
</div>

This CSS will target the .bar div - because it both has a parent .foo and from its position in the DOM, > .baz resolves to a valid element target.


Original Answer (left for historical purposes) - this portion is no longer accurate

For completeness, I wanted to point out that in the Selectors 4 specification (currently in proposal), this will become possible. Specifically, we will gain Subject Selectors, which will be used in the following format:

!div > span { /* style here */

The ! before the div selector indicates that it is the element to be styled, rather than the span. Unfortunately, no modern browsers (as of the time of this posting) have implemented this as part of their CSS support. There is, however, support via a JavaScript library called Sel, if you want to go down the path of exploration further.

How to disable the ability to select in a DataGridView?

This worked for me like a charm:

row.DataGridView.Enabled = false;

row.DefaultCellStyle.BackColor = Color.LightGray;

row.DefaultCellStyle.ForeColor = Color.DarkGray;

(where row = DataGridView.NewRow(appropriate overloads);)

Case Statement Equivalent in R

As of data.table v1.13.0 you can use the function fcase() (fast-case) to do SQL-like CASE operations (also similar to dplyr::case_when()):

require(data.table)

dt <- data.table(name = c('cow','pig','eagle','pigeon','cow','eagle'))
dt[ , category := fcase(name %in% c('cow', 'pig'), 'mammal',
                        name %in% c('eagle', 'pigeon'), 'bird') ]

Javamail Could not convert socket to TLS GMail

If your context is android application , then make sure your android device time is set to current date and time. The underlying exception is "The SSL certificates was not getting authenticated."

How to get the text node of an element?

Another native JS solution that can be useful for "complex" or deeply nested elements is to use NodeIterator. Put NodeFilter.SHOW_TEXT as the second argument ("whatToShow"), and iterate over just the text node children of the element.

_x000D_
_x000D_
var root = document.querySelector('p'),_x000D_
    iter = document.createNodeIterator(root, NodeFilter.SHOW_TEXT),_x000D_
    textnode;_x000D_
_x000D_
// print all text nodes_x000D_
while (textnode = iter.nextNode()) {_x000D_
  console.log(textnode.textContent)_x000D_
}
_x000D_
<p>_x000D_
<br>some text<br>123_x000D_
</p>
_x000D_
_x000D_
_x000D_

You can also use TreeWalker. The difference between the two is that NodeIterator is a simple linear iterator, while TreeWalker allows you to navigate via siblings and ancestors as well.

How to determine whether code is running in DEBUG / RELEASE build?

Apple already includes a DEBUG flag in debug builds, so you don't need to define your own.

You might also want to consider just redefining NSLog to a null operation when not in DEBUG mode, that way your code will be more portable and you can just use regular NSLog statements:

//put this in prefix.pch

#ifndef DEBUG
#undef NSLog
#define NSLog(args, ...)
#endif

Remove last character from string. Swift language

Use the function advance(startIndex, endIndex):

var str = "45+22"
str = str.substringToIndex(advance(str.startIndex, countElements(str) - 1))

Groovy method with optional parameters

You can use arguments with default values.

def someMethod(def mandatory,def optional=null){}

if argument "optional" not exist, it turns to "null".

No function matches the given name and argument types

That error means that a function call is only matched by an existing function if all its arguments are of the same type and passed in same order. So if the next f() function

create function f() returns integer as $$ 
    select 1;
$$ language sql;

is called as

select f(1);

It will error out with

ERROR:  function f(integer) does not exist
LINE 1: select f(1);
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

because there is no f() function that takes an integer as argument.

So you need to carefully compare what you are passing to the function to what it is expecting. That long list of table columns looks like bad design.

Show an image preview before upload

_x000D_
_x000D_
function handleFileSelect(evt) {_x000D_
    var files = evt.target.files;_x000D_
_x000D_
    // Loop through the FileList and render image files as thumbnails._x000D_
    for (var i = 0, f; f = files[i]; i++) {_x000D_
_x000D_
      // Only process image files._x000D_
      if (!f.type.match('image.*')) {_x000D_
        continue;_x000D_
      }_x000D_
_x000D_
      var reader = new FileReader();_x000D_
_x000D_
      // Closure to capture the file information._x000D_
      reader.onload = (function(theFile) {_x000D_
        return function(e) {_x000D_
          // Render thumbnail._x000D_
          var span = document.createElement('span');_x000D_
          span.innerHTML = _x000D_
          [_x000D_
            '<img style="height: 75px; border: 1px solid #000; margin: 5px" src="', _x000D_
            e.target.result,_x000D_
            '" title="', escape(theFile.name), _x000D_
            '"/>'_x000D_
          ].join('');_x000D_
          _x000D_
          document.getElementById('list').insertBefore(span, null);_x000D_
        };_x000D_
      })(f);_x000D_
_x000D_
      // Read in the image file as a data URL._x000D_
      reader.readAsDataURL(f);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  document.getElementById('files').addEventListener('change', handleFileSelect, false);
_x000D_
<input type="file" id="files" multiple />_x000D_
<output id="list"></output>
_x000D_
_x000D_
_x000D_

Easiest way to convert a List to a Set in Java

With Java 10, you could now use Set#copyOf to easily convert a List<E> to an unmodifiable Set<E>:

Example:

var set = Set.copyOf(list);

Keep in mind that this is an unordered operation, and null elements are not permitted, as it will throw a NullPointerException.

If you wish for it to be modifiable, then simply pass it into the constructor a Set implementation.

Logcat not displaying my log calls

Using the SDK 4.0.3 you have to explicitly select it on debug configurations > project > target or else it will never show using Eclipse Indigo (3.7). Of course an eclipse restart ensues.

Command to get time in milliseconds

The other answers are probably sufficient in most cases but I thought I'd add my two cents as I ran into a problem on a BusyBox system.

The system in question did not support the %N format option and doesn't have no Python or Perl interpreter.

After much head scratching, we (thanks Dave!) came up with this:

adjtimex | awk '/(time.tv_sec|time.tv_usec):/ { printf("%06d", $2) }'

It extracts the seconds and microseconds from the output of adjtimex (normally used to set options for the system clock) and prints them without new lines (so they get glued together). Note that the microseconds field has to be pre-padded with zeros, but this doesn't affect the seconds field which is longer than six digits anyway. From this it should be trivial to convert microseconds to milliseconds.

If you need a trailing new line (maybe because it looks better) then try

adjtimex | awk '/(time.tv_sec|time.tv_usec):/ { printf("%06d", $2) }' && printf "\n"

Also note that this requires adjtimex and awk to be available. If not then with BusyBox you can point to them locally with:

ln -s /bin/busybox ./adjtimex
ln -s /bin/busybox ./awk

And then call the above as

./adjtimex | ./awk '/(time.tv_sec|time.tv_usec):/ { printf("%06d", $2) }'

Or of course you could put them in your PATH

EDIT:

The above worked on my BusyBox device. On Ubuntu I tried the same thing and realised that adjtimex has different versions. On Ubuntu this worked to output the time in seconds with decimal places to microseconds (including a trailing new line)

sudo apt-get install adjtimex
adjtimex -p | awk '/raw time:/ { print $6 }'

I wouldn't do this on Ubuntu though. I would use date +%s%N

Java recursive Fibonacci sequence

Here is O(1) solution :

 private static long fibonacci(int n) {
    double pha = pow(1 + sqrt(5), n);
    double phb = pow(1 - sqrt(5), n);
    double div = pow(2, n) * sqrt(5);

    return (long) ((pha - phb) / div);
}

Binet's Fibonacci number formula used for above implementation. For large inputs long can be replaced with BigDecimal.

Set windows environment variables with a batch file

@ECHO OFF

:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/


:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"

:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m

:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m

PAUSE

How to close a window using jQuery

$(element).click(function(){
    window.close();
});

Note: you can not close any window that you didn't opened with window.open. Directly invoking window.close() will ask user with a dialogue box.

Turning error reporting off php

Tried this yet?

error_reporting(0);
@ini_set('display_errors', 0);

pip issue installing almost any library

Solution - Install any package by marking below hosts trusted

  • pypi.python.org
  • pypi.org
  • files.pythonhosted.org

Temporary solution

pip install --trusted-host pypi.python.org --trusted-host pypi.org --trusted-host files.pythonhosted.org {package name}

Permanent solution - Update your PIP(problem with version 9.0.1) to latest.

pip install --trusted-host pypi.python.org --trusted-host pypi.org --trusted-host files.pythonhosted.org pytest-xdist

python -m pip install --trusted-host pypi.python.org --trusted-host pypi.org --trusted-host files.pythonhosted.org --upgrade pip

make a header full screen (width) css

Live Demo

You can achieve the effect using a container element, then just set the containing elements margin to 0 auto and it will be centered.

Markup

<div id="header">
    <div id="headerContent">
        Header text
    </div>
</div>

CSS

#header{
    width:100%; 
    background: url(yourimage);
}
#headerContent{
    margin: 0 auto; width: 960px;
}

Check if a string matches a regex in Bash script

You can use the test construct, [[ ]], along with the regular expression match operator, =~, to check if a string matches a regex pattern.

For your specific case, you can write:

[[ $date =~ ^[0-9]{8}$ ]] && echo "yes"

Or more a accurate test:

[[ $date =~ ^[0-9]{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])$ ]] && echo "yes"
#           |^^^^^^^^ ^^^^^^ ^^^^^^  ^^^^^^ ^^^^^^^^^^ ^^^^^^ |
#           |   |     ^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^^^^^^^ |
#           |   |          |                   |              |
#           |   |           \                  |              |
#           | --year--   --month--           --day--          |
#           |          either 01...09      either 01..09     end of line
# start of line            or 10,11,12         or 10..29
#                                              or 30, 31

That is, you can define a regex in Bash matching the format you want. This way you can do:

[[ $date =~ ^regex$ ]] && echo "matched" || echo "did not match"

where commands after && are executed if the test is successful, and commands after || are executed if the test is unsuccessful.

Note this is based on the solution by Aleks-Daniel Jakimenko in User input date format verification in bash.


In other shells you can use grep. If your shell is POSIX compliant, do

(echo "$date" | grep -Eq  ^regex$) && echo "matched" || echo "did not match"

In fish, which is not POSIX-compliant, you can do

echo "$date" | grep -Eq "^regex\$"; and echo "matched"; or echo "did not match"

Checking the equality of two slices

And for now, here is https://github.com/google/go-cmp which

is intended to be a more powerful and safer alternative to reflect.DeepEqual for comparing whether two values are semantically equal.

package main

import (
    "fmt"

    "github.com/google/go-cmp/cmp"
)

func main() {
    a := []byte{1, 2, 3}
    b := []byte{1, 2, 3}

    fmt.Println(cmp.Equal(a, b)) // true
}

How to chain scope queries with OR instead of AND?

Rails 4

scope :combined_scope, -> { where("name = ? or name = ?", 'a', 'b') }

Create a dictionary with list comprehension

This code will create dictionary using list comprehension for multiple lists with different values that can be used for pd.DataFrame()

#Multiple lists 
model=['A', 'B', 'C', 'D']
launched=[1983,1984,1984,1984]
discontinued=[1986, 1985, 1984, 1986]

#Dictionary with list comprehension
keys=['model','launched','discontinued']
vals=[model, launched,discontinued]
data = {key:vals[n] for n, key in enumerate(keys)}

enumerate will pass n to vals to match each key with its list

How to read input with multiple lines in Java

The easilest way is

import java.util.*;

public class Stdio4 {

public static void main(String[] args) {
    int a=0;
    int arr[] = new int[3];
    Scanner scan = new Scanner(System.in);
    for(int i=0;i<3;i++)
    { 
         a = scan.nextInt();  //Takes input from separate lines
         arr[i]=a;


    }
    for(int i=0;i<3;i++)
    { 
         System.out.println(arr[i]);   //outputs in separate lines also
    }

}

}

Android ACTION_IMAGE_CAPTURE Intent

The file needs be writable by the camera, as Praveen pointed out.

In my usage I wanted to store the file in internal storage. I did this with:

Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (i.resolveActivity(getPackageManager()!=null)){
    try{
        cacheFile = createTempFile("img",".jpg",getCacheDir());
        cacheFile.setWritavle(true,false);
    }catch(IOException e){}
    if(cacheFile != null){
        i.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(cacheFile));
        startActivityForResult(i,REQUEST_IMAGE_CAPTURE);
    }
}

Here cacheFile is a global file used to refer to the file which is written. Then in the result method the returned intent is null. Then the method for processing the intent looks like:

protected void onActivityResult(int requestCode,int resultCode,Intent data){
    if(requestCode != RESULT_OK){
        return;
    }
    if(requestCode == REQUEST_IMAGE_CAPTURE){
        try{
            File output = getImageFile();
            if(output != null && cacheFile != null){
                copyFile(cacheFile,output);

                //Process image file stored at output

                cacheFile.delete();
                cacheFile=null;
            }
        }catch(IOException e){}
    }
}

Here getImageFile() is a utility method to name and create the file in which the image should be stored, and copyFile() is a method to copy a file.

When do you use the "this" keyword?

[C++]

this is used in the assignment operator where most of the time you have to check and prevent strange (unintentional, dangerous, or just a waste of time for the program) things like:

A a;
a = a;

Your assignment operator will be written:

A& A::operator=(const A& a) {
    if (this == &a) return *this;

    // we know both sides of the = operator are different, do something...

    return *this;
}

Why isn't my Pandas 'apply' function referencing multiple columns working?

All of the suggestions above work, but if you want your computations to by more efficient, you should take advantage of numpy vector operations (as pointed out here).

import pandas as pd
import numpy as np


df = pd.DataFrame ({'a' : np.random.randn(6),
             'b' : ['foo', 'bar'] * 3,
             'c' : np.random.randn(6)})

Example 1: looping with pandas.apply():

%%timeit
def my_test2(row):
    return row['a'] % row['c']

df['Value'] = df.apply(my_test2, axis=1)

The slowest run took 7.49 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 481 µs per loop

Example 2: vectorize using pandas.apply():

%%timeit
df['a'] % df['c']

The slowest run took 458.85 times longer than the fastest. This could mean that an intermediate result is being cached. 10000 loops, best of 3: 70.9 µs per loop

Example 3: vectorize using numpy arrays:

%%timeit
df['a'].values % df['c'].values

The slowest run took 7.98 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 6.39 µs per loop

So vectorizing using numpy arrays improved the speed by almost two orders of magnitude.

How to upload a project to Github

Probably the most useful thing you could do is to peruse the online book [http://git-scm.com/book/en/]. It's really a pretty decent read and gives you the conceptual context with which to execute things properly.

Remove unwanted parts from strings in a column

I often use list comprehensions for these types of tasks because they're often faster.

There can be big differences in performance between the various methods for doing things like this (i.e. modifying every element of a series within a DataFrame). Often a list comprehension can be fastest - see code race below for this task:

import pandas as pd
#Map
data = pd.DataFrame({'time':['09:00','10:00','11:00','12:00','13:00'], 'result':['+52A','+62B','+44a','+30b','-110a']})
%timeit data['result'] = data['result'].map(lambda x: x.lstrip('+-').rstrip('aAbBcC'))
10000 loops, best of 3: 187 µs per loop
#List comprehension
data = pd.DataFrame({'time':['09:00','10:00','11:00','12:00','13:00'], 'result':['+52A','+62B','+44a','+30b','-110a']})
%timeit data['result'] = [x.lstrip('+-').rstrip('aAbBcC') for x in data['result']]
10000 loops, best of 3: 117 µs per loop
#.str
data = pd.DataFrame({'time':['09:00','10:00','11:00','12:00','13:00'], 'result':['+52A','+62B','+44a','+30b','-110a']})
%timeit data['result'] = data['result'].str.lstrip('+-').str.rstrip('aAbBcC')
1000 loops, best of 3: 336 µs per loop

AJAX Mailchimp signup form integration

You don't need an API key, all you have to do is plop the standard mailchimp generated form into your code ( customize the look as needed ) and in the forms "action" attribute change post?u= to post-json?u= and then at the end of the forms action append &c=? to get around any cross domain issue. Also it's important to note that when you submit the form you must use GET rather than POST.

Your form tag will look something like this by default:

<form action="http://xxxxx.us#.list-manage1.com/subscribe/post?u=xxxxx&id=xxxx" method="post" ... >

change it to look something like this

<form action="http://xxxxx.us#.list-manage1.com/subscribe/post-json?u=xxxxx&id=xxxx&c=?" method="get" ... >

Mail Chimp will return a json object containing 2 values: 'result' - this will indicate if the request was successful or not ( I've only ever seen 2 values, "error" and "success" ) and 'msg' - a message describing the result.

I submit my forms with this bit of jQuery:

$(document).ready( function () {
    // I only have one form on the page but you can be more specific if need be.
    var $form = $('form');

    if ( $form.length > 0 ) {
        $('form input[type="submit"]').bind('click', function ( event ) {
            if ( event ) event.preventDefault();
            // validate_input() is a validation function I wrote, you'll have to substitute this with your own.
            if ( validate_input($form) ) { register($form); }
        });
    }
});

function register($form) {
    $.ajax({
        type: $form.attr('method'),
        url: $form.attr('action'),
        data: $form.serialize(),
        cache       : false,
        dataType    : 'json',
        contentType: "application/json; charset=utf-8",
        error       : function(err) { alert("Could not connect to the registration server. Please try again later."); },
        success     : function(data) {
            if (data.result != "success") {
                // Something went wrong, do something to notify the user. maybe alert(data.msg);
            } else {
                // It worked, carry on...
            }
        }
    });
}

How to multiply duration by integer?

It's nice that Go has a Duration type -- having explicitly defined units can prevent real-world problems.

And because of Go's strict type rules, you can't multiply a Duration by an integer -- you must use a cast in order to multiply common types.

/*
MultiplyDuration Hide semantically invalid duration math behind a function
*/
func MultiplyDuration(factor int64, d time.Duration) time.Duration {
    return time.Duration(factor) * d        // method 1 -- multiply in 'Duration'
 // return time.Duration(factor * int64(d)) // method 2 -- multiply in 'int64'
}

The official documentation demonstrates using method #1:

To convert an integer number of units to a Duration, multiply:

seconds := 10
fmt.Print(time.Duration(seconds)*time.Second) // prints 10s

But, of course, multiplying a duration by a duration should not produce a duration -- that's nonsensical on the face of it. Case in point, 5 milliseconds times 5 milliseconds produces 6h56m40s. Attempting to square 5 seconds results in an overflow (and won't even compile if done with constants).

By the way, the int64 representation of Duration in nanoseconds "limits the largest representable duration to approximately 290 years", and this indicates that Duration, like int64, is treated as a signed value: (1<<(64-1))/(1e9*60*60*24*365.25) ~= 292, and that's exactly how it is implemented:

// A Duration represents the elapsed time between two instants
// as an int64 nanosecond count. The representation limits the
// largest representable duration to approximately 290 years.
type Duration int64

So, because we know that the underlying representation of Duration is an int64, performing the cast between int64 and Duration is a sensible NO-OP -- required only to satisfy language rules about mixing types, and it has no effect on the subsequent multiplication operation.

If you don't like the the casting for reasons of purity, bury it in a function call as I have shown above.

<xsl:variable> Print out value of XSL variable using <xsl:value-of>

In XSLT the same <xsl:variable> can be declared only once and can be given a value only at its declaration. If more than one variables are declared at the same time, they are in fact different variables and have different scope.

Therefore, the way to achieve the wanted conditional setting of the variable and producing its value is the following:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>

    <xsl:template match="class">
    <xsl:variable name="subexists">
            <xsl:choose>
                <xsl:when test="joined-subclass">true</xsl:when>
                <xsl:otherwise>false</xsl:otherwise>
            </xsl:choose>
        </xsl:variable>
        subexists:  <xsl:text/>    
        <xsl:value-of select="$subexists" />
    </xsl:template>
</xsl:stylesheet>

When the above transformation is applied on the following XML document:

<class>
 <joined-subclass/>
</class>

the wanted result is produced:

    subexists:  true