Programs & Examples On #Xpath 2.0

Use this tag for questions specific to XML Path Language (XPath) version 2.0

What is the best way to conditionally apply attributes in AngularJS?

You can prefix attributes with ng-attr to eval an Angular expression. When the result of the expressions undefined this removes the value from the attribute.

<a ng-attr-href="{{value || undefined}}">Hello World</a>

Will produce (when value is false)

<a ng-attr-href="{{value || undefined}}" href>Hello World</a>

So don't use false because that will produce the word "false" as the value.

<a ng-attr-href="{{value || false}}" href="false">Hello World</a>

When using this trick in a directive. The attributes for the directive will be false if they are missing a value.

For example, the above would be false.

function post($scope, $el, $attr) {
      var url = $attr['href'] || false;
      alert(url === false);
}

Read file line by line using ifstream in C++

Since your coordinates belong together as pairs, why not write a struct for them?

struct CoordinatePair
{
    int x;
    int y;
};

Then you can write an overloaded extraction operator for istreams:

std::istream& operator>>(std::istream& is, CoordinatePair& coordinates)
{
    is >> coordinates.x >> coordinates.y;

    return is;
}

And then you can read a file of coordinates straight into a vector like this:

#include <fstream>
#include <iterator>
#include <vector>

int main()
{
    char filename[] = "coordinates.txt";
    std::vector<CoordinatePair> v;
    std::ifstream ifs(filename);
    if (ifs) {
        std::copy(std::istream_iterator<CoordinatePair>(ifs), 
                std::istream_iterator<CoordinatePair>(),
                std::back_inserter(v));
    }
    else {
        std::cerr << "Couldn't open " << filename << " for reading\n";
    }
    // Now you can work with the contents of v
}

How to show an empty view with a RecyclerView?

Here is my class for show empty view, retry view (when load api failed) and loading progress for RecyclerView

public class RecyclerViewEmptyRetryGroup extends RelativeLayout {
    private RecyclerView mRecyclerView;
    private LinearLayout mEmptyView;
    private LinearLayout mRetryView;
    private ProgressBar mProgressBar;
    private OnRetryClick mOnRetryClick;

    public RecyclerViewEmptyRetryGroup(Context context) {
        this(context, null);
    }

    public RecyclerViewEmptyRetryGroup(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RecyclerViewEmptyRetryGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void onViewAdded(View child) {
        super.onViewAdded(child);
        if (child.getId() == R.id.recyclerView) {
            mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
            return;
        }
        if (child.getId() == R.id.layout_empty) {
            mEmptyView = (LinearLayout) findViewById(R.id.layout_empty);
            return;
        }
        if (child.getId() == R.id.layout_retry) {
            mRetryView = (LinearLayout) findViewById(R.id.layout_retry);
            mRetryView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mRetryView.setVisibility(View.GONE);
                    mOnRetryClick.onRetry();
                }
            });
            return;
        }
        if (child.getId() == R.id.progress_bar) {
            mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
        }
    }

    public void loading() {
        mRetryView.setVisibility(View.GONE);
        mEmptyView.setVisibility(View.GONE);
        mProgressBar.setVisibility(View.VISIBLE);
    }

    public void empty() {
        mEmptyView.setVisibility(View.VISIBLE);
        mRetryView.setVisibility(View.GONE);
        mProgressBar.setVisibility(View.GONE);
    }

    public void retry() {
        mRetryView.setVisibility(View.VISIBLE);
        mEmptyView.setVisibility(View.GONE);
        mProgressBar.setVisibility(View.GONE);
    }

    public void success() {
        mRetryView.setVisibility(View.GONE);
        mEmptyView.setVisibility(View.GONE);
        mProgressBar.setVisibility(View.GONE);
    }

    public RecyclerView getRecyclerView() {
        return mRecyclerView;
    }

    public void setOnRetryClick(OnRetryClick onRetryClick) {
        mOnRetryClick = onRetryClick;
    }

    public interface OnRetryClick {
        void onRetry();
    }
}

activity_xml

<...RecyclerViewEmptyRetryGroup
        android:id="@+id/recyclerViewEmptyRetryGroup">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"/>

        <LinearLayout
            android:id="@+id/layout_empty">
            ...
        </LinearLayout>

        <LinearLayout
            android:id="@+id/layout_retry">
            ...
        </LinearLayout>

        <ProgressBar
            android:id="@+id/progress_bar"/>

</...RecyclerViewEmptyRetryGroup>

enter image description here

The source is here https://github.com/PhanVanLinh/AndroidRecyclerViewWithLoadingEmptyAndRetry

Java Generate Random Number Between Two Given Values

Assuming the upper is the upper bound and lower is the lower bound, then you can make a random number, r, between the two bounds with:

int r = (int) (Math.random() * (upper - lower)) + lower;

Print array elements on separate lines in Bash?

I've discovered that you can use eval to avoid using a subshell. Thus:

IFS=$'\n' eval 'echo "${my_array[*]}"'

Catch multiple exceptions in one line (except block)

From Python Documentation:

An except clause may name multiple exceptions as a parenthesized tuple, for example

except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass

Or, for Python 2 only:

except (IDontLikeYouException, YouAreBeingMeanException), e:
    pass

Separating the exception from the variable with a comma will still work in Python 2.6 and 2.7, but is now deprecated and does not work in Python 3; now you should be using as.

Reference an Element in a List of Tuples

The code

my_list = [(1, 2), (3, 4), (5, 6)]
for t in my_list:
    print t

prints

(1, 2)
(3, 4)
(5, 6)

The loop iterates over my_list, and assigns the elements of my_list to t one after the other. The elements of my_list happen to be tuples, so t will always be a tuple. To access the first element of the tuple t, use t[0]:

for t in my_list:
    print t[0]

To access the first element of the tuple at the given index i in the list, you can use

print my_list[i][0]

How do we count rows using older versions of Hibernate (~2009)?

You could try count(*)

Integer count = (Integer) session.createQuery("select count(*) from Books").uniqueResult();

Where Books is the name off the class - not the table in the database.

Unzipping files

I wrote "Binary Tools for JavaScript", an open source project that includes the ability to unzip, unrar and untar: https://github.com/codedread/bitjs

Used in my comic book reader: https://github.com/codedread/kthoom (also open source).

HTH!

Check if a value is within a range of numbers

If you're already using lodash, you could use the inRange() function: https://lodash.com/docs/4.17.15#inRange

_.inRange(3, 2, 4);
// => true

_.inRange(4, 8);
// => true

_.inRange(4, 2);
// => false

_.inRange(2, 2);
// => false

_.inRange(1.2, 2);
// => true

_.inRange(5.2, 4);
// => false

_.inRange(-3, -2, -6);
// => true

Difference between break and continue statement

The break statement breaks out of the loop (the next statement to be executed is the first one after the closing brace), while continue starts the loop over at the next iteration.

how to run mysql in ubuntu through terminal

If you want to run your scripts, then

mysql -u root -p < yourscript.sql

Playing .mp3 and .wav in Java?

You need to install JMF first (download using this link)

File f = new File("D:/Songs/preview.mp3");
MediaLocator ml = new MediaLocator(f.toURL());
Player p = Manager.createPlayer(ml);
p.start();

don't forget to add JMF jar files

How to pass extra variables in URL with WordPress

One issue you might run into is is_home() returns true when a registered query_var is present in the home URL. For example, if http://example.com displays a static page instead of the blog, http://example.com/?c=123 will return the blog.

See https://core.trac.wordpress.org/ticket/25143 and https://wordpress.org/support/topic/adding-query-var-makes-front-page-missing/ for more info on this.

What you can do (if you're not attempting to affect the query) is use add_rewrite_endpoint(). It should be run during the init action as it affects the rewrite rules. Eg.

add_action( 'init', 'add_custom_setcookie_rewrite_endpoints' );

function add_custom_setcookie_rewrite_endpoints() {
    //add ?c=123 endpoint with
    //EP_ALL so endpoint is present across all places
    //no effect on the query vars
    add_rewrite_endpoint( 'c', EP_ALL, $query_vars = false );
}

This should give you access to $_GET['c'] when the url contains more information like www.example.com/news?c=123.

Remember to flush your rewrite rules after adding/modifying this.

cell format round and display 2 decimal places

Input: 0 0.1 1000

=FIXED(E5,2)

Output: 0.00 0.10 1,000.00

=TEXT(E5,"0.00")

Output: 0.00 0.10 1000.00

Note: As you can see FIXED add a coma after a thousand, where TEXT does not.

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
  }
}

Copy mysql database from remote server to local computer

Assuming the following command works successfully:

mysql -u username -p -h remote.site.com

The syntax for mysqldump is identical, and outputs the database dump to stdout. Redirect the output to a local file on the computer:

mysqldump -u username -p -h remote.site.com DBNAME > backup.sql

Replace DBNAME with the name of the database you'd like to download to your computer.

slideToggle JQuery right to left

You can try this:

$('.show_hide').click(function () {
    $(".slidingDiv").toggle("'slide', {direction: 'right' }, 1000");
});

javascript: optional first argument in function

Like this:

my_function (null, options) // for options only
my_function (content) // for content only
my_function (content, options) // for both

Creating a mock HttpServletRequest out of a url string?

You would generally test these sorts of things in an integration test, which actually connects to a service. To do a unit test, you should test the objects used by your servlet's doGet/doPost methods.

In general you don't want to have much code in your servlet methods, you would want to create a bean class to handle operations and pass your own objects to it and not servlet API objects.

<div style display="none" > inside a table not working

simply change <div> to <tbody>

<table id="authenticationSetting" style="display: none">
  <tbody id="authenticationOuterIdentityBlock" style="display: none;">
    <tr>
      <td class="orionSummaryHeader">
        <orion:message key="policy.wifi.enterprise.authentication.outeridentitity" />:</td>
      <td class="orionSummaryColumn">
        <orion:textbox id="authenticationOuterIdentity" size="30" />
      </td>
    </tr>
  </tbody>
</table>

html text input onchange event

onChange doesn't fire until you lose focus later. If you want to be really strict with instantaneous changes of all sorts, use:

<input
   type       = "text" 
   onchange   = "myHandler();"
   onkeypress = "this.onchange();"
   onpaste    = "this.onchange();"
   oninput    = "this.onchange();"
/>

symfony2 : failed to write cache directory

If you face this error when you start Symfony project with docker (my Symfony version 5.1). Or errors like these:

Uncaught Exception: Failed to write file "/var/www/html/mysite.com.local/var/cache/dev/App_KernelDevDebugContainer.xml"" while reading upstream

Uncaught Warning: file_put_contents(/var/www/html/mysite.com.local/var/cache/dev/App_KernelDevDebugContainerDeprecations.log): failed to open stream: Permission denied" while reading upstream

Fix below helped me.

In Dockerfile for nginx container add line:

RUN usermod -u 1000 www-data

In Dockerfile for php-fpm container add line:

RUN usermod -u 1000 www-data

Then remove everything in directories "/var/cache", "/var/log" and rebuild docker's containers.

Modify SVG fill color when being served as Background-Image

Now you can achieve this on the client side like this:

var green = '3CB54A';
var red = 'ED1F24';
var svg = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"  width="320px" height="100px" viewBox="0 0 320 100" enable-background="new 0 0 320 100" xml:space="preserve"> <polygon class="mystar" fill="#'+green+'" points="134.973,14.204 143.295,31.066 161.903,33.77 148.438,46.896 151.617,65.43 134.973,56.679 118.329,65.43 121.507,46.896 108.042,33.77 126.65,31.066 "/><circle class="mycircle" fill="#'+red+'" cx="202.028" cy="58.342" r="12.26"/></svg>';      
var encoded = window.btoa(svg);
document.body.style.background = "url(data:image/svg+xml;base64,"+encoded+")";

Fiddle here!

Input widths on Bootstrap 3

I do not know why everyone has seem to overlook the site.css file in the Content folder. Look at line 22 in this file and you will see the settings for input to be controlled. It would appear that your site is not referencing this style sheet.

I added this:

input, select, textarea { max-width: 280px;}

to your fiddle and it works just fine.

You should never ever update bootstrap.css or bootstrap.min.css. Doing so will set you up to fail when bootstrap gets updated. That is why the site.css file is included. This is where you can make changes to site that will still give you the responsive design you are looking for.

Here is the fiddle with it working

How can I add shadow to the widget in flutter?

Use BoxDecoration with BoxShadow.

Here is a visual demo manipulating the following options:

  • opacity
  • x offset
  • y offset
  • blur radius
  • spread radius

The animated gif doesn't do so well with colors. You can try it yourself on a device.

enter image description here

Here is the full code for that demo:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: ShadowDemo(),
      ),
    );
  }
}

class ShadowDemo extends StatefulWidget {
  @override
  _ShadowDemoState createState() => _ShadowDemoState();
}

class _ShadowDemoState extends State<ShadowDemo> {
  var _image = NetworkImage('https://placebear.com/300/300');

  var _opacity = 1.0;
  var _xOffset = 0.0;
  var _yOffset = 0.0;
  var _blurRadius = 0.0;
  var _spreadRadius = 0.0;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Center(
          child:
          Container(
            decoration: BoxDecoration(
              color: Color(0xFF0099EE),
              boxShadow: [
                BoxShadow(
                  color: Color.fromRGBO(0, 0, 0, _opacity),
                  offset: Offset(_xOffset, _yOffset),
                  blurRadius: _blurRadius,
                  spreadRadius: _spreadRadius,
                )
              ],
            ),
            child: Image(image:_image, width: 100, height: 100,),
          ),
        ),
        Align(
          alignment: Alignment.bottomCenter,
          child: Padding(
            padding: const EdgeInsets.only(bottom: 80.0),
            child: Column(
              children: <Widget>[
                Spacer(),
                Slider(
                  value: _opacity,
                  min: 0.0,
                  max: 1.0,
                  onChanged: (newValue) =>
                  {
                    setState(() => _opacity = newValue)
                  },
                ),
                Slider(
                  value: _xOffset,
                  min: -100,
                  max: 100,
                  onChanged: (newValue) =>
                  {
                    setState(() => _xOffset = newValue)
                  },
                ),
                Slider(
                  value: _yOffset,
                  min: -100,
                  max: 100,
                  onChanged: (newValue) =>
                  {
                    setState(() => _yOffset = newValue)
                  },
                ),
                Slider(
                  value: _blurRadius,
                  min: 0,
                  max: 100,
                  onChanged: (newValue) =>
                  {
                    setState(() => _blurRadius = newValue)
                  },
                ),
                Slider(
                  value: _spreadRadius,
                  min: 0,
                  max: 100,
                  onChanged: (newValue) =>
                  {
                    setState(() => _spreadRadius = newValue)
                  },
                ),
              ],
            ),
          ),
        )
      ],
    );
  }
}

Vim delete blank lines

The following can be used to remove only multi blank lines (reduce them to a single blank line) and leaving single blank lines intact:

:g/^\_$\n\_^$/d

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

Maybe a little late to reply. I happen to run into the same problem today. I find that on Windows you can change the console encoder to utf-8 or other encoder that can represent your data. Then you can print it to sys.stdout.

First, run following code in the console:

chcp 65001
set PYTHONIOENCODING=utf-8

Then, start python do anything you want.

How to make script execution wait until jquery is loaded

the easiest and safest way is to use something like this:

var waitForJQuery = setInterval(function () {
    if (typeof $ != 'undefined') {

        // place your code here.

        clearInterval(waitForJQuery);
    }
}, 10);

AngularJS : Clear $watch

Ideally, every custom watch should be removed when you leave the scope.

It helps in better memory management and better app performance.

// call to $watch will return a de-register function
var listener = $scope.$watch(someVariableToWatch, function(....));

$scope.$on('$destroy', function() {
    listener(); // call the de-register function on scope destroy
});

What does %~dp0 mean, and how does it work?

Another tip that would help a lot is that to set the current directory to a different drive one would have to use %~d0 first, then cd %~dp0. This will change the directory to the batch file's drive, then change to its folder.

Alternatively, for #oneLinerLovers, as @Omni pointed out in the comments cd /d %~dp0 will change both the drive and directory :)

Hope this helps someone.

Structure of a PDF file?

I found the GNU Introduction to PDF to be helpful in understanding the structure. It includes an easily readable example PDF file that they describe in complete detail.

Other helpful links:

Window.open and pass parameters by post method

The default submit Action is Ext.form.action.Submit, which uses an Ajax request to submit the form's values to a configured URL. To enable normal browser submission of an Ext form, use the standardSubmit config option.

Link: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.form.Basic-cfg-standardSubmit

solution: put standardSubmit :true in your config. Hope that this will help you :)

How to center an unordered list?

To center align an unordered list, you need to use the CSS text align property. In addition to this, you also need to put the unordered list inside the div element.

Now, add the style to the div class and use the text-align property with center as its value.

See the below example.

<style>
.myDivElement{
    text-align:center;
}
.myDivElement ul li{
   display:inline;

 }
</style>
<div class="myDivElement">
<ul>
    <li>Home</li>
    <li>About</li>
    <li>Gallery</li>
    <li>Contact</li>
</ul>
</div>

Here is the reference website Center Align Unordered List

How to concatenate properties from multiple JavaScript objects

Why should the function be restricted to 3 arguments? Also, check for hasOwnProperty.

function Collect() {
    var o={};
    for(var i=0;i<arguments.length;i++) {
      var arg=arguments[i];
      if(typeof arg != "object") continue;
      for(var p in arg) {
        if(arg.hasOwnProperty(p)) o[p] = arg[p];
      }
    }
    return o;
}

Is calling destructor manually always a sign of bad design?

I have another situation where I think it is perfectly reasonable to call the destructor.

When writing a "Reset" type of method to restore an object to its initial state, it is perfectly reasonable to call the Destructor to delete the old data that is being reset.

class Widget
{
private: 
    char* pDataText { NULL  }; 
    int   idNumber  { 0     };

public:
    void Setup() { pDataText = new char[100]; }
    ~Widget()    { delete pDataText;          }

    void Reset()
    {
        Widget blankWidget;
        this->~Widget();     // Manually delete the current object using the dtor
        *this = blankObject; // Copy a blank object to the this-object.
    }
};

Configuring diff tool with .gitconfig

Adding one of the blocks below works for me to use KDiff3 for my Windows and Linux development environments. It makes for a nice consistent cross-platform diff and merge tool.

Linux

[difftool "kdiff3"]
    path = /usr/bin/kdiff3
    trustExitCode = false
[difftool]
    prompt = false
[diff]
    tool = kdiff3
[mergetool "kdiff3"]
    path = /usr/bin/kdiff3
    trustExitCode = false
[mergetool]
    keepBackup = false
[merge]
    tool = kdiff3

Windows

[difftool "kdiff3"]
    path = C:/Progra~1/KDiff3/kdiff3.exe
    trustExitCode = false
[difftool]
    prompt = false
[diff]
    tool = kdiff3
[mergetool "kdiff3"]
    path = C:/Progra~1/KDiff3/kdiff3.exe
    trustExitCode = false
[mergetool]
    keepBackup = false
[merge]
    tool = kdiff3

How find out which process is using a file in Linux?

@jim's answer is correct -- fuser is what you want.

Additionally (or alternately), you can use lsof to get more information including the username, in case you need permission (without having to run an additional command) to kill the process. (THough of course, if killing the process is what you want, fuser can do that with its -k option. You can have fuser use other signals with the -s option -- check the man page for details.)

For example, with a tail -F /etc/passwd running in one window:

ghoti@pc:~$ lsof | grep passwd
tail      12470    ghoti    3r      REG  251,0     2037 51515911 /etc/passwd

Note that you can also use lsof to find out what processes are using particular sockets. An excellent tool to have in your arsenal.

What are the obj and bin folders (created by Visual Studio) used for?

The obj directory is for intermediate object files and other transient data files that are generated by the compiler or build system during a build. The bin directory is the directory that final output binaries (and any dependencies or other deployable files) will be written to.

You can change the actual directories used for both purposes within the project settings, if you like.

Custom fonts and XML layouts (Android)

I might have a simple answer for the question without extending the TextView and implementing a long code.

Code :

 TextView tv = (TextView) findViewById(R.id.textview1);
    tv.setTypeface(Typeface.createFromAsset(getAssets(), "font.ttf"));

Place the custom font file in assets folder as usual and try this. It works for me. I just dont understand why peter has given such a huge code for this simple thing or he has given his answer in old version.

What's the difference between .bashrc, .bash_profile, and .environment?

That's simple. It's explained in man bash:

/bin/bash
       The bash executable
/etc/profile
       The systemwide initialization file, executed for login shells
~/.bash_profile
       The personal initialization file, executed for login shells
~/.bashrc
       The individual per-interactive-shell startup file
~/.bash_logout
       The individual login shell cleanup file, executed when a login shell exits
~/.inputrc
       Individual readline initialization file

Login shells are the ones that are read one you login (so, they are not executed when merely starting up xterm, for example). There are other ways to login. For example using an X display manager. Those have other ways to read and export environment variables at login time.

Also read the INVOCATION chapter in the manual. It says "The following paragraphs describe how bash executes its startup files.", i think that's a spot-on :) It explains what an "interactive" shell is too.

Bash does not know about .environment. I suspect that's a file of your distribution, to set environment variables independent of the shell that you drive.

What does the "assert" keyword do?

assert is a debugging tool that will cause the program to throw an AssertionFailed exception if the condition is not true. In this case, the program will throw an exception if either of the two conditions following it evaluate to false. Generally speaking, assert should not be used in production code

JavaScript data grid for millions of rows

https://github.com/mleibman/SlickGrid/wiki

"SlickGrid utilizes virtual rendering to enable you to easily work with hundreds of thousands of items without any drop in performance. In fact, there is no difference in performance between working with a grid with 10 rows versus a 100’000 rows."

Some highlights:

  • Adaptive virtual scrolling (handle hundreds of thousands of rows)
  • Extremely fast rendering speed
  • Background post-rendering for richer cells
  • Configurable & customizable
  • Full keyboard navigation
  • Column resize/reorder/show/hide
  • Column autosizing & force-fit
  • Pluggable cell formatters & editors
  • Support for editing and creating new rows." by mleibman

It's free (MIT license). It uses jQuery.

How to read file from res/raw by name

With the help of the given links I was able to solve the problem myself. The correct way is to get the resource ID with

getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
                             "raw", getPackageName());

To get it as a InputStream

InputStream ins = getResources().openRawResource(
            getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
            "raw", getPackageName()));

Why do we need to install gulp globally and locally?

The question "Why do we need to install gulp globally and locally?" can be broken down into the following two questions:

  1. Why do I need to install gulp locally if I've already installed it globally?

  2. Why do I need to install gulp globally if I've already installed it locally?

Several others have provided excellent answers to theses questions in isolation, but I thought it would be beneficial to consolidate the information in a unified answer.

Why do I need to install gulp locally if I've already installed it globally?

The rationale for installing gulp locally is comprised of several reasons:

  1. Including the dependencies of your project locally ensures the version of gulp (or other dependencies) used is the originally intended version.
  2. Node doesn't consider global modules by default when using require() (which you need to include gulp within your script). Ultimately, this is because the path to the global modules isn't added to NODE_PATH by default.
  3. According to the Node development team, local modules load faster. I can't say why this is, but this would seem to be more relevant to node's use in production (i.e. run-time dependencies) than in development (i.e. dev dependencies). I suppose this is a legitimate reason as some may care about whatever minor speed advantage is gained loading local vs. global modules, but feel free to raise your eyebrow at this reason.

Why do I need to install gulp globally if I've already installed it locally?

  1. The rationale for installing gulp globally is really just the convenience of having the gulp executable automatically found within your system path.

To avoid installing locally you can use npm link [package], but the link command as well as the install --global command doesn't seem to support the --save-dev option which means there doesn't appear to be an easy way to install gulp globally and then easily add whatever version that is to your local package.json file.

Ultimately, I believe it makes more sense to have the option of using global modules to avoid having to duplicate the installation of common tools across all your projects, especially in the case of development tools such as grunt, gulp, jshint, etc. Unfortunately it seems you end up fighting the tools a bit when you go against the grain.

How to remove illegal characters from path and filenames?

You can remove illegal chars using Linq like this:

var invalidChars = Path.GetInvalidFileNameChars();

var invalidCharsRemoved = stringWithInvalidChars
.Where(x => !invalidChars.Contains(x))
.ToArray();

EDIT
This is how it looks with the required edit mentioned in the comments:

var invalidChars = Path.GetInvalidFileNameChars();

string invalidCharsRemoved = new string(stringWithInvalidChars
  .Where(x => !invalidChars.Contains(x))
  .ToArray());

How to send custom headers with requests in Swagger UI?

I ended up here because I was trying to conditionally add header parameters in Swagger UI, based on my own [Authentication] attribute I added to my API method. Following the hint that @Corcus listed in a comment, I was able to derive my solution, and hopefully it will help others.

Using Reflection, it's checking if the method nested down in apiDescription has the desired attribute (MyApiKeyAuthenticationAttribute, in my case). If it does, I can append my desired header parameters.

public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) {
    if (operation.parameters == null)
        operation.parameters = new List<Parameter>();


    var attributes = ((System.Web.Http.Controllers.ReflectedHttpActionDescriptor)
        ((apiDescription.ActionDescriptor).ActionBinding.ActionDescriptor)).MethodInfo
        .GetCustomAttributes(false);
    if(attributes != null && attributes.Any()) {
        if(attributes.Where(x => x.GetType() 
            == typeof(MyApiKeyAuthenticationAttribute)).Any()) {

            operation.parameters.Add(new Parameter {
                name = "MyApiKey",
                @in = "header",
                type = "string",
                description = "My API Key",
                required = true
            });
            operation.parameters.Add(new Parameter {
                name = "EID",
                @in = "header",
                type = "string",
                description = "Employee ID",
                required = true
            });
        }
    }


}

How do I add a library (android-support-v7-appcompat) in IntelliJ IDEA

Another yet simple solution is to paste these line into the build.gradle file

dependencies {

    //import of gridlayout
    compile 'com.android.support:gridlayout-v7:19.0.0'
    compile 'com.android.support:appcompat-v7:+'
}

Comparing two java.util.Dates to see if they are in the same day

Java 8

If you are using Java 8 in your project and comparing java.sql.Timestamp, you could use the LocalDate class:

sameDate = date1.toLocalDateTime().toLocalDate().equals(date2.toLocalDateTime().toLocalDate());

If you are using java.util.Date, have a look at Istvan answer which is less ambiguous.

XML Error: Extra content at the end of the document

You need a root node

<?xml version="1.0" encoding="ISO-8859-1"?>    
<documents>
    <document>
        <name>Sample Document</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;wordcount3=0</url>
    </document>

    <document>
        <name>Sample</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;</url>
    </document>
</documents>

Intellij IDEA Java classes not auto compiling on save

I ended up recording a Macro to save and compile in one step, and keymap Ctrl+s to it.

What techniques can be used to define a class in JavaScript, and what are their trade-offs?

If you're going for simple, you can avoid the "new" keyword entirely and just use factory methods. I prefer this, sometimes, because I like using JSON to create objects.

function getSomeObj(var1, var2){
  var obj = {
     instancevar1: var1,
     instancevar2: var2,
     someMethod: function(param)
     {  
          //stuff; 
     }
  };
  return obj;
}

var myobj = getSomeObj("var1", "var2");
myobj.someMethod("bla");

I'm not sure what the performance hit is for large objects, though.

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

This works:

Iterator<Integer> iter = l.iterator();
while (iter.hasNext()) {
    if (iter.next() == 5) {
        iter.remove();
    }
}

I assumed that since a foreach loop is syntactic sugar for iterating, using an iterator wouldn't help... but it gives you this .remove() functionality.

What is key=lambda

Lambda can be any function. So if you had a function

def compare_person(a):
         return a.age

You could sort a list of Person (each of which having an age attribute) like this:

sorted(personArray, key=compare_person)

This way, the list would be sorted by age in ascending order.

The parameter is called lambda because python has a nifty lambda keywords for defining such functions on the fly. Instead of defining a function compare_person and passing that to sorted, you can also write:

sorted(personArray, key=lambda a: a.age)

which does the same thing.

More elegant way of declaring multiple variables at the same time

This is an elaboration on @Jeff M's and my comments.

When you do this:

a, b = c, d

It works with tuple packing and unpacking. You can separate the packing and unpacking steps:

_ = c, d
a, b = _

The first line creates a tuple called _ which has two elements, the first with the value of c and the second with the value of d. The second line unpacks the _ tuple into the variables a and b. This breaks down your one huge line:

a, b, c, d, e, f, g, h, i, j = True, True, True, True, True, False, True, True, True, True

Into two smaller lines:

_ = True, True, True, True, True, False, True, True, True, True
a, b, c, d, e, f, g, h, i, j = _

It will give you the exact same result as the first line (including the same exception if you add values or variables to one part but forget to update the other). However, in this specific case, yan's answer is perhaps the best.

If you have a list of values, you can still unpack them. You just have to convert it to a tuple first. For example, the following will assign a value between 0 and 9 to each of a through j, respectively:

a, b, c, d, e, f, g, h, i, j = tuple(range(10))

EDIT: Neat trick to assign all of them as true except element 5 (variable f):

a, b, c, d, e, f, g, h, i, j = tuple(x != 5 for x in range(10))

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

I totally agree with the solution provided, but I think a little clarification is important I think, might be necessary.

For each process (read also: vshost.exe, yourWinformApplication.exe.svchost, or the name of your application.exe) that will need to add a DWORD with the value provided, in my case I leave 9000 (in decimal) in application name and running smoothly and error-free script.

the most common mistake is to believe that it is necessary to add "contoso.exe" AS IS and think it all work!

Convert Iterable to Stream using Java 8 JDK

Another way to do it, with Java 8 and without external libs:

Stream.concat(collectionA.stream(), collectionB.stream())
      .collect(Collectors.toList())

jQuery ajax error function

you're using a function

error(error) 

but jquery is actually looking for a function with three parameters:

error(jqXHR, textStatus, errorThrown)

you'll need to add two more parameters.

ALSO: please have a look at all the comments above that mention 'deprecated' :)

$.ajax("www.stackoverflow.com/api/whatever", {
    dataType:"JSON"
    data: { id=1, name='example' }
}).succes(function (result) {
    // use result
}).error(function (jqXHR, textStatus, errorThrown) {
    // handle error
});

Python name 'os' is not defined

Just add:

import os

in the beginning, before:

from settings import PROJECT_ROOT

This will import the python's module os, which apparently is used later in the code of your module without being imported.

What is the best way to prevent session hijacking?

Have you considered reading a book on PHP security? Highly recommended.

I have had much success with the following method for non SSL certified sites.

  1. Dis-allow multiple sessions under the same account, making sure you aren't checking this solely by IP address. Rather check by token generated upon login which is stored with the users session in the database, as well as IP address, HTTP_USER_AGENT and so forth

  2. Using Relation based hyperlinks Generates a link ( eg. http://example.com/secure.php?token=2349df98sdf98a9asdf8fas98df8 ) The link is appended with a x-BYTE ( preferred size ) random salted MD5 string, upon page redirection the randomly generated token corresponds to a requested page.

    • Upon reload, several checks are done.
    • Originating IP Address
    • HTTP_USER_AGENT
    • Session Token
    • you get the point.
  3. Short Life-span session authentication cookie. as posted above, a cookie containing a secure string, which is one of the direct references to the sessions validity is a good idea. Make it expire every x Minutes, reissuing that token, and re-syncing the session with the new Data. If any mis-matches in the data, either log the user out, or having them re-authenticate their session.

I am in no means an expert on the subject, I'v had a bit of experience in this particular topic, hope some of this helps anyone out there.

Java - Check if input is a positive integer, negative integer, natural number and so on.

What about using the following:

int number = input.nextInt();
if (number < 0) {
    // negative
} else {
   // it's a positive
}

How to position a Bootstrap popover?

I had to make the following changes for the popover to position below with some overlap and to show the arrow correctly.

js

case 'bottom-right':  
    tp = {top: pos.top + pos.height + 10, left: pos.left + pos.width - 40}  
    break  

css

    .popover.bottom-right .arrow {  
      left: 20px; /* MODIFIED */  
      margin-left: -11px;  
      border-top-width: 0;  
      border-bottom-color: #999;  
      border-bottom-color: rgba(0, 0, 0, 0.25);  
      top: -11px;  
    }  
    .popover.bottom-right .arrow:after {  
      top: 1px;  
      margin-left: -10px;  
      border-top-width: 0;  
      border-bottom-color: #ffffff;  
    }  

This can be extended for arrow locations elsewhere .. enjoy!

How to use onResume()?

The best way to understand would be to have all the LifeCycle methods overridden in your activity and placing a breakpoint(if checking in emulator) or a Log in each one of them. You'll get to know which one gets called when.

Just as an spoiler, onCreate() gets called first, then if you paused the activity by either going to home screen or by launching another activity, onPause() gets called. If the OS destroys the activity in the meantime, onDestroy() gets called. If you resume the app and the app already got destroyed, onCreate() will get called, or else onResume() will get called.

Edit: I forgot about onStop(), it gets called before onDestroy().

Do the exercise I mentioned and you'll be having a better understanding.

Convert INT to FLOAT in SQL

In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):

select myintfield + 0.0 as myfloatfield from mytable

While @Heximal's answer works, I don't personally recommend it.

This is because it uses implicit casting. Although you didn't type CAST, either the SUM() or the 0.0 need to be cast to be the same data-types, before the + can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +. But SUM(aFloatField) + 0 does not yield an INT, because the 0 is being implicitly cast to a FLOAT.

I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.

If you want to be explicit, I would use the following.

CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT  requires 8.0

I won't discuss whether NUMERIC or FLOAT *(fixed point, instead of floating point)* is more appropriate, when it comes to rounding errors, etc. I'll just let you google that if you need to, but FLOAT is so massively misused that there is a lot to read about the subject already out there.

You can try the following to see what happens...

CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))

DataGridView - Focus a specific cell

Set the Current Cell like:

DataGridView1.CurrentCell = DataGridView1.Rows[rowindex].Cells[columnindex]

or

DataGridView1.CurrentCell = DataGridView1.Item("ColumnName", 5)

and you can directly focus with Editing by:

dataGridView1.BeginEdit(true)

Sort dataGridView columns in C# ? (Windows Form)

This one is simplier :)

dataview dataview1; 
this.dataview1= dataset.tables[0].defaultview;
this.dataview1.sort = "[ColumnName] ASC, [ColumnName] DESC";
this.datagridview.datasource = dataview1;

How to use RANK() in SQL Server

Change:

RANK() OVER (PARTITION BY ContenderNum ORDER BY totals ASC) AS xRank

to:

RANK() OVER (ORDER BY totals DESC) AS xRank

Have a look at this example:

SQL Fiddle DEMO

You might also want to have a look at the difference between RANK (Transact-SQL) and DENSE_RANK (Transact-SQL):

RANK (Transact-SQL)

If two or more rows tie for a rank, each tied rows receives the same rank. For example, if the two top salespeople have the same SalesYTD value, they are both ranked one. The salesperson with the next highest SalesYTD is ranked number three, because there are two rows that are ranked higher. Therefore, the RANK function does not always return consecutive integers.

DENSE_RANK (Transact-SQL)

Returns the rank of rows within the partition of a result set, without any gaps in the ranking. The rank of a row is one plus the number of distinct ranks that come before the row in question.

Is there a way to call a stored procedure with Dapper?

Here is code for getting value return from Store procedure

Stored procedure:

alter proc [dbo].[UserlogincheckMVC]    
@username nvarchar(max),    
@password nvarchar(max)
as    
begin    
    if exists(select Username from Adminlogin where Username =@username and Password=@password)    
        begin        
            return 1  
        end    
    else    
        begin     
            return 0  
        end    
end 

Code:

var parameters = new DynamicParameters();
string pass = EncrytDecry.Encrypt(objUL.Password);
conx.Open();
parameters.Add("@username", objUL.Username);
parameters.Add("@password", pass);
parameters.Add("@RESULT", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
var RS = conx.Execute("UserlogincheckMVC", parameters, null, null, commandType: CommandType.StoredProcedure);
int result = parameters.Get<int>("@RESULT");

Bootstrap full responsive navbar with logo or brand name text

If you want to achieve this (you can resize the window to see how it will look for mobile version), all you have to do is to have 2 logo images (1 for desktop and one for mobile) and display them depending of the enviroment using visible-xs and hidden-xs classes.

So i used something like this:

<img class="hidden-xs" src="http://placehold.it/150x50&text=Logo" alt="">
<img class="visible-xs" src="http://placehold.it/120x40&text=Logo" alt=""> 

And ofcourse, i styled the mobile logo using:

@media (max-width: 767px) { 
    .navbar-brand {
        padding: 0;        
    }

    .navbar-brand img {
        margin-top: 5px;
        margin-left: 5px;
    }
}

You can see all the code here. In case you need a text on mobile version insted of the logo, it's not a big deal. Just replace the logo with a <h1 class="visible-xs">AppName</h3> and change the style inside the media query like this:

@media (max-width: 767px) { 
    .navbar-brand {
        padding: 0;        
    }

    .navbar-brand h1{
        //here add your style depending of the position you want the text to be placed
    }
} 

EDIT:

You need this conditions to make it work:

.navbar-toggle {
   margin: 23px 0; 
}

.navbar-nav, .navbar-nav li, .navbar-nav li a {
  height: 80px;
  line-height: 80px;
}

.navbar-nav li a {
  padding-top: 0;
  padding-bottom:0;
}

How to tell if a <script> tag failed to load

This can be done safely using promises

    function loadScript(src) {
      return new Promise(function(resolve, reject) {
        let script = document.createElement('script');
        script.src = src;
    
        script.onload = () => resolve(script);
        script.onerror = () => reject(new Error("Script load error: " + src));
    
        document.head.append(script);
      });
    }

and use like this

    let promise = loadScript("https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js");
    
    promise.then(
      script => alert(`${script.src} is loaded!`),
      error => alert(`Error: ${error.message}`)
    );

Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction

If you really need to do it in separate transaction you need to use REQUIRES_NEW and live with the performance overhead. Watch out for dead locks.

I'd rather do it the other way:

  • Validate data on Java side.
  • Run everyting in one transaction.
  • If anything goes wrong on DB side -> it's a major error of DB or validation design. Rollback everything and throw critical top level error.
  • Write good unit tests.

&& (AND) and || (OR) in IF statements

Java has 5 different boolean compare operators: &, &&, |, ||, ^

& and && are "and" operators, | and || "or" operators, ^ is "xor"

The single ones will check every parameter, regardless of the values, before checking the values of the parameters. The double ones will first check the left parameter and its value and if true (||) or false (&&) leave the second one untouched. Sound compilcated? An easy example should make it clear:

Given for all examples:

 String aString = null;

AND:

 if (aString != null & aString.equals("lala"))

Both parameters are checked before the evaluation is done and a NullPointerException will be thrown for the second parameter.

 if (aString != null && aString.equals("lala"))

The first parameter is checked and it returns false, so the second paramter won't be checked, because the result is false anyway.

The same for OR:

 if (aString == null | !aString.equals("lala"))

Will raise NullPointerException, too.

 if (aString == null || !aString.equals("lala"))

The first parameter is checked and it returns true, so the second paramter won't be checked, because the result is true anyway.

XOR can't be optimized, because it depends on both parameters.

How to style a checkbox using CSS

My solution

_x000D_
_x000D_
input[type="checkbox"] {_x000D_
  cursor: pointer;_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
  appearance: none;_x000D_
  outline: 0;_x000D_
  background: lightgray;_x000D_
  height: 16px;_x000D_
  width: 16px;_x000D_
  border: 1px solid white;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:checked {_x000D_
  background: #2aa1c0;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:hover {_x000D_
  filter: brightness(90%);_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:disabled {_x000D_
  background: #e6e6e6;_x000D_
  opacity: 0.6;_x000D_
  pointer-events: none;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:after {_x000D_
  content: '';_x000D_
  position: relative;_x000D_
  left: 40%;_x000D_
  top: 20%;_x000D_
  width: 15%;_x000D_
  height: 40%;_x000D_
  border: solid #fff;_x000D_
  border-width: 0 2px 2px 0;_x000D_
  transform: rotate(45deg);_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:checked:after {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:disabled:after {_x000D_
  border-color: #7b7b7b;_x000D_
}
_x000D_
<input type="checkbox"><br>_x000D_
<input type="checkbox" checked><br>_x000D_
<input type="checkbox" disabled><br>_x000D_
<input type="checkbox" disabled checked><br>
_x000D_
_x000D_
_x000D_

Can I get image from canvas element and use it in img src tag?

Corrected the Fiddle - updated shows the Image duplicated into the Canvas...

And right click can be saved as a .PNG

http://jsfiddle.net/gfyWK/67/

<div style="text-align:center">
<img src="http://imgon.net/di-M7Z9.jpg" id="picture" style="display:none;" />
<br />
<div id="for_jcrop">here the image should apear</div>
<canvas id="rotate" style="border:5px double black; margin-top:5px; "></canvas>
</div>

Plus the JS on the fiddle page...

Cheers Si

Currently looking at saving this to File on the server --- ASP.net C# (.aspx web form page) Any advice would be cool....

Minimum Hardware requirements for Android development

I did the following experiment at home:

let's compare how 2 computers compile the same android application in eclipse. Here are the competitors:

"the monster" - pentinum i7 - 16 gig RAM - solid state hard drive

"peabody" - pentinum i3 - 4 gig RAM

The results: when I compiled the same application in eclipse, the monster and peabody took exactly the same amount of time to bring up the emulator to the point where you have to slide the button to run the app: 1 minute 12 seconds.

After that point, the monster executed the app 30-40 seconds faster than peabody.

The monster costs about $500 more than the peabody. So the question is, is it really worth it? In my opinion, No. I can wait the extra 30-40 seconds

Is it possible to use the instanceof operator in a switch statement?

If you want to avoid the verbosity of if(){} else if{}, you may consider switching this single file to kotlin and use the switch-like when expression in combination with is operator.

In any case Kotlin and java files can co-exist in a project.

when (this) { //switch-like statement in kotlin supporting class-pattern-matching and smart casts via `is` operator.
    is A -> doA()
    is B -> doB()
    is C -> doC()
}

What is jQuery Unobtrusive Validation?

jQuery Validation Unobtrusive Native is a collection of ASP.Net MVC HTML helper extensions. These make use of jQuery Validation's native support for validation driven by HTML 5 data attributes. Microsoft shipped jquery.validate.unobtrusive.js back with MVC 3. It provided a way to apply data model validations to the client side using a combination of jQuery Validation and HTML 5 data attributes (that's the "unobtrusive" part).

Temporary table in SQL server causing ' There is already an object named' error

You are dropping it, then creating it, then trying to create it again by using SELECT INTO. Change to:

DROP TABLE #TMPGUARDIAN
CREATE TABLE #TMPGUARDIAN(
LAST_NAME NVARCHAR(30),
FRST_NAME NVARCHAR(30))  

INSERT INTO #TMPGUARDIAN 
SELECT LAST_NAME,FRST_NAME  
FROM TBL_PEOPLE

In MS SQL Server you can create a table without a CREATE TABLE statement by using SELECT INTO

How to update attributes without validation

USE update_attribute instead of update_attributes

Updates a single attribute and saves the record without going through the normal validation procedure.

if a.update_attribute('state', a.state)

Note:- 'update_attribute' update only one attribute at a time from the code given in question i think it will work for you.

CURLOPT_RETURNTRANSFER set to true doesnt work on hosting server

Just try this line:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

after:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

Installing tkinter on ubuntu 14.04

If you're using Python 3 then you must install as follows:

sudo apt-get update
sudo apt-get install python3-tk

Tkinter for Python 2 (python-tk) is different from Python 3's (python3-tk).

How to get Real IP from Visitor?

If the Proxy is which you trust, you can try: (Assume the Proxy IP is 151.101.2.10)

<?php

$trustProxyIPs = ['151.101.2.10'];

$clientIP  = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : NULL;

if (in_array($clientIP, $trustProxyIPs)) {

    $headers = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR'];

    foreach ($headers as $key => $header) {

        if (isset($_SERVER[$header]) && filter_var($_SERVER[$header], FILTER_VALIDATE_IP)) {

            $clientIP = $_SERVER[$header];

            break;
        }
    }
}

echo $clientIP;

This will prevent forged forward header by direct requested clients, and get real IP via trusted Proxies.

How to browse localhost on Android device?

I use testproxy to do this.

npm install testproxy

testproxy http://10.0.2.2

You then get the url (and QR code) you can access on your mobile device. It even works with virtual machines you can't reach by just entering the IP of your dev machine.

java doesn't run if structure inside of onclick listener

both your conditions are the same:

if(s < f) {     calc = f - s;     n = s; }else if(f > s){     calc =  s - f;     n = f;  } 

so

if(s < f)   

and

}else if(f > s){ 

are the same

change to

}else if(f < s){ 

What exactly is node.js used for?

The Developers Survey from Stack Overflow is a good source of information for you to start this research.

2017: https://insights.stackoverflow.com/survey/2017#most-popular-technologies

2016: https://insights.stackoverflow.com/survey/2016#technology-most-popular-technologies

Why the Hell Would You Use Node.js

https://medium.com/the-node-js-collection/why-the-hell-would-you-use-node-js-4b053b94ab8e

Where Node.js really shines is in building fast, scalable network applications, as it’s capable of handling a huge number of simultaneous connections with high throughput, which equates to high scalability. How it works under-the-hood is pretty interesting. Compared to traditional web-serving techniques where each connection (request) spawns a new thread, taking up system RAM and eventually maxing-out at the amount of RAM available, Node.js operates on a single-thread, using non-blocking I/O calls, allowing it to support tens of thousands of concurrent connections (held in the event loop).

How to use underscore.js as a template engine?

with express it's so easy. all what you need is to use the consolidate module on node so you need to install it :

npm install consolidate --save

then you should change the default engine to html template by this:

app.set('view engine', 'html');

register the underscore template engine for the html extension:

app.engine('html', require('consolidate').underscore);

it's done !

Now for load for example an template called 'index.html':

res.render('index', { title : 'my first page'});

maybe you will need to install the underscore module.

npm install underscore --save

I hope this helped you!

How do I check for vowels in JavaScript?

benchmark

I think you can safely say a for loop is faster.

I do admit that a regexp looks cleaner in terms of code. If it's a real bottleneck then use a for loop, otherwise stick with the regular expression for reasons of "elegance"

If you want to go for simplicity then just use

function isVowel(c) {
    return ['a', 'e', 'i', 'o', 'u'].indexOf(c.toLowerCase()) !== -1
}

How can a windows service programmatically restart itself?

I don't think it can. When a service is "stopped", it gets totally unloaded.

Well, OK, there's always a way I suppose. For instance, you could create a detached process to stop the service, then restart it, then exit.

Android textview usage as label and value

You should implement a Custom List View, such that you define a Layout once and draw it for every row in the list view.

Python equivalent for HashMap

You need a dict:

my_dict = {'cheese': 'cake'}

Example code (from the docs):

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

You can read more about dictionaries here.

Strings in C, how to get subString

char largeSrt[] = "123456789-123";  // original string

char * substr;
substr = strchr(largeSrt, '-');     // we save the new string "-123"
int substringLength = strlen(largeSrt) - strlen(substr); // 13-4=9 (bigger string size) - (new string size) 

char *newStr = malloc(sizeof(char) * substringLength + 1);// keep memory free to new string
strcpy(newStr, largeSrt, substringLength);  // copy only 9 characters 
newStr[substringLength] = '\0'; // close the new string with final character

printf("newStr=%s\n", newStr);

free(newStr);   // you free the memory 

Calling jQuery method from onClick attribute in HTML

Don't do this!

Stay away from putting the events inline with the elements! If you don't, you're missing the point of JQuery (or one of the biggest ones at least).

The reason why it's easy to define click() handlers one way and not the other is that the other way is simply not desirable. Since you're just learning JQuery, stick to the convention. Now is not the time in your learning curve for JQuery to decide that everyone else is doing it wrong and you have a better way!

Prevent flicker on webkit-transition of webkit-transform

The solution is mentioned here: iPhone WebKit CSS animations cause flicker.

For your element, you need to set

-webkit-backface-visibility: hidden;

How to use @Nullable and @Nonnull annotations more effectively?

I agree that the annotations "don't propagate very far". However, I see the mistake on the programmer's side.

I understand the Nonnull annotation as documentation. The following method expresses that is requires (as a precondition) a non-null argument x.

    public void directPathToA(@Nonnull Integer x){
        x.toString(); // do stuff to x        
    }

The following code snippet then contains a bug. The method calls directPathToA() without enforcing that y is non-null (that is, it does not guarantee the precondition of the called method). One possibility is to add a Nonnull annotation as well to indirectPathToA() (propagating the precondition). Possibility two is to check for the nullity of y in indirectPathToA() and avoid the call to directPathToA() when y is null.

    public void indirectPathToA(Integer y){
        directPathToA(y);
    }

Reading Email using Pop3 in C#

call me old fashion but why use a 3rd party library for a simple protocol. I've implemented POP3 readers in web based ASP.NET application with System.Net.Sockets.TCPClient and System.Net.Security.SslStream for the encryption and authentication. As far as protocols go, once you open up communication with the POP3 server, there are only a handful of commands that you have to deal with. It is a very easy protocol to work with.

Issue with Task Scheduler launching a task

Thanks all, I had the same issue. I have a task that runs via a generic user account not linked to a particular person. This user as somehow logged off the VM, when I was trying to fix it I was logged in as me and not that user.

Logging back in with that user fixed the issue!

What is the difference between range and xrange functions in Python 2.X?

range() in Python 2.x

This function is essentially the old range() function that was available in Python 2.x and returns an instance of a list object that contains the elements in the specified range.

However, this implementation is too inefficient when it comes to initialise a list with a range of numbers. For example, for i in range(1000000) would be a very expensive command to execute, both in terms of memory and time usage as it requires the storage of this list into the memory.


range() in Python 3.x and xrange() in Python 2.x

Python 3.x introduced a newer implementation of range() (while the newer implementation was already available in Python 2.x through the xrange() function).

The range() exploits a strategy known as lazy evaluation. Instead of creating a huge list of elements in range, the newer implementation introduces the class range, a lightweight object that represents the required elements in the given range, without storing them explicitly in memory (this might sound like generators but the concept of lazy evaluation is different).


As an example, consider the following:

# Python 2.x
>>> a = range(10)
>>> type(a)
<type 'list'>
>>> b = xrange(10)
>>> type(b)
<type 'xrange'>

and

# Python 3.x
>>> a = range(10)
>>> type(a)
<class 'range'>

Configuring Git over SSH to login once

Try this from the box you are pushing from

    ssh [email protected]

You should then get a welcome response from github and will be fine to then push.

How do I reference a cell within excel named range?

Add a column to the left so that B10 to B20 is your named range Age.

Set A10 to A20 so that A10 = 1, A11= 2,... A20 = 11 and give the range A10 to A20 a name e.g. AgeIndex.

The 5th element can be then found by using an array formula:

=sum( Age * (1 * (AgeIndex = 5) )

As it's an array formula you'll need to press Ctrl + Shift + Return to make it work and not just return. Doing that, the formula will be turned into an array formula:

{=sum( Age * (1 * (AgeIndex = 5) )}

Pretty git branch graphs

I have this git log alias in ~/.gitconfig to view the graph history:

[alias]
l = log --all --graph --pretty=format:'%C(auto)%h%C(auto)%d %s %C(dim white)(%aN, %ar)'

With this in place, git l will output something like:

enter image description here

In Git 2.12+ you can even customize the line colors of the graph using the log.graphColors configuration option.

As for the logs' format, it's similar to --oneline, with the addition of the author name (respecting .mailmap) and the relative author date. Note that the %C(auto) syntax, which tells Git to use the default colors for commit hash, etc. is supported in Git >= 1.8.3.

How to resize an image to fit in the browser window?

Use this code in your style tag

<style>
html {
  background: url(imagename) no-repeat center center fixed;
  background-size: cover;
  height: 100%;
  overflow: hidden;
}
</style>

How to change font size on part of the page in LaTeX?

\begingroup
    \fontsize{10pt}{12pt}\selectfont
    \begin{verbatim}  
        % how to set font size here to 10 px ?  
    \end{verbatim}  
\endgroup

Is it possible to specify condition in Count()?

If you can't just limit the query itself with a where clause, you can use the fact that the count aggregate only counts the non-null values:

select count(case Position when 'Manager' then 1 else null end)
from ...

You can also use the sum aggregate in a similar way:

select sum(case Position when 'Manager' then 1 else 0 end)
from ...

Get text of the selected option with jQuery

$(document).ready(function() {
    $('select#select_2').change(function() {
        var selectedText = $(this).find('option:selected').text();
        alert(selectedText);
    });
});

Fiddle

Center an item with position: relative

If you have a relatively- (or otherwise-) positioned div you can center something inside it with margin:auto

Vertical centering is a bit tricker, but possible.

PHP display current server path

echo $_SERVER["DOCUMENT_ROOT"];

'DOCUMENT_ROOT' The document root directory under which the current script is executing, as defined in the server's configuration file.

http://php.net/manual/en/reserved.variables.server.php

How to make the division of 2 ints produce a float instead of another int?

JLS Standard

JLS 7 15.17.2. Division Operator / says:

Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d · q| = |n|. Moreover, q is positive when |n| = |d| and n and d have the same sign, but q is negative when |n| = |d| and n and d have opposite signs.

This is why 1/2 does not give a float.

Converting just either one to float as in (float)1/2 suffices because 15.17. Multiplicative Operators says:

Binary numeric promotion is performed on the operands

and 5.6.2. Binary Numeric Promotion says:

  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to float

What is the difference between exit(0) and exit(1) in C?

exit in the C language takes an integer representing an exit status.

Exit Success

Typically, an exit status of 0 is considered a success, or an intentional exit caused by the program's successful execution.

Exit Failure

An exit status of 1 is considered a failure, and most commonly means that the program had to exit for some reason, and was not able to successfully complete everything in the normal program flow.

Here's a GNU Resource talking about Exit Status.


As @Als has stated, two constants should be used in place of 0 and 1.

EXIT_SUCCESS is defined by the standard to be zero.

EXIT_FAILURE is not restricted by the standard to be one, but many systems do implement it as one.

StringIO in Python3

Thank you OP for your question, and Roman for your answer. I had to search a bit to find this; I hope the following helps others.

Python 2.7

See: https://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html

import numpy as np
from StringIO import StringIO

data = "1, abc , 2\n 3, xxx, 4"

print type(data)
"""
<type 'str'>
"""

print '\n', np.genfromtxt(StringIO(data), delimiter=",", dtype="|S3", autostrip=True)
"""
[['1' 'abc' '2']
 ['3' 'xxx' '4']]
"""

print '\n', type(data)
"""
<type 'str'>
"""

print '\n', np.genfromtxt(StringIO(data), delimiter=",", autostrip=True)
"""
[[  1.  nan   2.]
 [  3.  nan   4.]]
"""

Python 3.5:

import numpy as np
from io import StringIO
import io

data = "1, abc , 2\n 3, xxx, 4"
#print(data)
"""
1, abc , 2
 3, xxx, 4
"""

#print(type(data))
"""
<class 'str'>
"""

#np.genfromtxt(StringIO(data), delimiter=",", autostrip=True)
# TypeError: Can't convert 'bytes' object to str implicitly

print('\n')
print(np.genfromtxt(io.BytesIO(data.encode()), delimiter=",", dtype="|S3", autostrip=True))
"""
[[b'1' b'abc' b'2']
 [b'3' b'xxx' b'4']]
"""

print('\n')
print(np.genfromtxt(io.BytesIO(data.encode()), delimiter=",", autostrip=True))
"""
[[  1.  nan   2.]
 [  3.  nan   4.]]
"""

Aside:

dtype="|Sx", where x = any of { 1, 2, 3, ...}:

dtypes. Difference between S1 and S2 in Python

"The |S1 and |S2 strings are data type descriptors; the first means the array holds strings of length 1, the second of length 2. ..."

PHP function to make slug (URL string)

What about using something that is already implemented in Core?

//Clean non UTF-8 characters    
Mage::getHelper('core/string')->cleanString($str)

Or one of the core url/ url rewrite methods..

Freeze the top row for an html table only (Fixed Table Header Scrolling)

It is possible using position:fixed on <th> (<th> being the top row).

Here's an example

rsync: how can I configure it to create target directory on server?

from rsync manual (man rsync)

--mkpath create the destination's path component

Naming Conventions: What to name a boolean variable?

A simple semantic name would be last. This would allow code always positive code like:

if (item.last)
    ...

do {
   ...
} until (item.last);

How to input a regex in string.replace?

import os, sys, re, glob

pattern = re.compile(r"\<\[\d\>")
replacementStringMatchesPattern = "<[1>"

for infile in glob.glob(os.path.join(os.getcwd(), '*.txt')):
   for line in reader: 
      retline =  pattern.sub(replacementStringMatchesPattern, "", line)         
      sys.stdout.write(retline)
      print (retline)

PHP Warning: Unknown: failed to open stream

It happened to me today with /home/user/public_html/index.php and the solution was to do chmod o+x /home/user as this directory has to have the X as otherwise the apache server can't list files (i.e. do ls)

Insert new item in array on any position in PHP

function insert(&$arr, $value, $index){       
    $lengh = count($arr);
    if($index<0||$index>$lengh)
        return;

    for($i=$lengh; $i>$index; $i--){
        $arr[$i] = $arr[$i-1];
    }

    $arr[$index] = $value;
}

How to fast-forward a branch to head?

git checkout master
git pull

should do the job.

You will get the "Your branch is behind" message every time when you work on a branch different than master, someone does changes to master and you git pull.

(branch) $ //hack hack hack, while someone push the changes to origin/master
(branch) $ git pull   

now the origin/master reference is pulled, but your master is not merged with it

(branch) $ git checkout master
(master) $ 

now master is behind origin/master and can be fast forwarded

this will pull and merge (so merge also newer commits to origin/master)
(master) $ git pull 

this will just merge what you have already pulled
(master) $ git merge origin/master

now your master and origin/master are in sync

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

For some databases, you can just explicitly insert a NULL into the auto_increment column:

INSERT INTO table_name VALUES (NULL, 'my name', 'my group')

How can I change the text color with jQuery?

Or you may do the following

$(this).animate({color:'black'},1000);

But you need to download the color plugin from here.

Embedding Windows Media Player for all browsers

The following works for me in Firefox and Internet Explorer:

<object id="mediaplayer" classid="clsid:22d6f312-b0f6-11d0-94ab-0080c74c7e95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#version=5,1,52,701" standby="loading microsoft windows media player components..." type="application/x-oleobject" width="320" height="310">
<param name="filename" value="./test.wmv">
     <param name="animationatstart" value="true">
     <param name="transparentatstart" value="true">
     <param name="autostart" value="true">
     <param name="showcontrols" value="true">
     <param name="ShowStatusBar" value="true">
     <param name="windowlessvideo" value="true">
     <embed src="./test.wmv" autostart="true" showcontrols="true" showstatusbar="1" bgcolor="white" width="320" height="310">
</object>

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

According to this SO thread, the solution is to use the non-primitive wrapper types; e.g., Integer instead of int.

Gradle - Could not find or load main class

Struggled with the same problem for some time. But after creating the directory structure src/main/java and putting the source(from the top of the package), it worked as expected.

The tutorial I tried with. After you execute gradle build, you will have to be able to find classes under build directory.

Differences between C++ string == and compare()?

This is what the standard has to say about operator==

21.4.8.2 operator==

template<class charT, class traits, class Allocator>
bool operator==(const basic_string<charT,traits,Allocator>& lhs,
                const basic_string<charT,traits,Allocator>& rhs) noexcept;

Returns: lhs.compare(rhs) == 0.

Seems like there isn't much of a difference!

ImportError: No module named PyQt4

If you're using Anaconda to manage Python on your system, you can install it with:

$ conda install pyqt=4

Omit the =4 to install the most current version.

Answer from How to install PyQt4 in anaconda?

Gem Command not found

FWIW, the equivalent package for RHEL/Fedora/CentOS/etc and SuSE/OpenSuSE appears to be called 'rubygems'.

What does "select count(1) from table_name" on any database tables mean?

Here is a link that will help answer your questions. In short:

count(*) is the correct way to write it and count(1) is OPTIMIZED TO BE count(*) internally -- since

a) count the rows where 1 is not null is less efficient than
b) count the rows

How to calculate UILabel width based on text length?

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font 
                        constrainedToSize:maximumLabelSize 
                        lineBreakMode:yourLabel.lineBreakMode]; 

What is -[NSString sizeWithFont:forWidth:lineBreakMode:] good for?

this question might have your answer, it worked for me.


For 2014, I edited in this new version, based on the ultra-handy comment by Norbert below! This does everything. Cheers

// yourLabel is your UILabel.

float widthIs = 
 [self.yourLabel.text
  boundingRectWithSize:self.yourLabel.frame.size                                           
  options:NSStringDrawingUsesLineFragmentOrigin
  attributes:@{ NSFontAttributeName:self.yourLabel.font }
  context:nil]
   .size.width;

NSLog(@"the width of yourLabel is %f", widthIs);

How to change color of Toolbar back button in Android?

To style the Toolbar on Android 21+ it's a bit different.

<style name="DarkTheme.v21" parent="DarkTheme.v19">
        <!-- toolbar background color -->
        <item name="android:navigationBarColor">@color/color_primary_blue_dark</item>
        <!-- toolbar back button color -->
        <item name="toolbarNavigationButtonStyle">@style/Toolbar.Button.Navigation.Tinted</item>
    </style>

    <style name="Toolbar.Button.Navigation.Tinted" parent="Widget.AppCompat.Toolbar.Button.Navigation">
        <item name="tint">@color/color_white</item>
    </style>

Is returning out of a switch statement considered a better practice than using break?

Neither, because both are quite verbose for a very simple task. You can just do:

let result = ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[opt] ?? 'Default'    // opt can be 1, 2, 3 or anything (default)

This, of course, also works with strings, a mix of both or without a default case:

let result = ({
  'first': 'One',
  'second': 'Two',
  3: 'Three'
})[opt]                // opt can be 'first', 'second' or 3

Explanation:

It works by creating an object where the options/cases are the keys and the results are the values. By putting the option into the brackets you access the value of the key that matches the expression via the bracket notation.

This returns undefined if the expression inside the brackets is not a valid key. We can detect this undefined-case by using the nullish coalescing operator ?? and return a default value.

Example:

_x000D_
_x000D_
console.log('Using a valid case:', ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[1] ?? 'Default')

console.log('Using an invalid case/defaulting:', ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[7] ?? 'Default')
_x000D_
.as-console-wrapper {max-height: 100% !important;top: 0;}
_x000D_
_x000D_
_x000D_

Overwriting my local branch with remote branch

Your local branch likely has modifications to it you want to discard. To do this, you'll need to use git reset to reset the branch head to the last spot that you diverged from the upstream repo's branch. Use git branch -v to find the sha1 id of the upstream branch, and reset your branch it it using git reset SHA1ID. Then you should be able to do a git checkout to discard the changes it left in your directory.

Note: always do this on a backed-up repo. That way you can assure you're self it worked right. Or if it didn't, you have a backup to revert to.

Jquery get form field value

_x000D_
_x000D_
$("form").submit(function(event) {_x000D_
    _x000D_
      var firstfield_value  = event.currentTarget[0].value;_x000D_
     _x000D_
      var secondfield_value = event.currentTarget[1].value; _x000D_
     _x000D_
      alert(firstfield_value);_x000D_
      alert(secondfield_value);_x000D_
      event.preventDefault(); _x000D_
     });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form action="" method="post" >_x000D_
<input type="text" name="field1" value="value1">_x000D_
<input type="text" name="field2" value="value2">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Get environment value in controller

In config/app.php file make a instance of env variable like 'name' => env('APP_NAME', 'Laravel') & In your controller call it like config('app.name')

Run following commands php artisan config:cache php artisan cache:clear if it is not working.

Angular2 - Focusing a textbox on component load

Also, it can be done dynamically like so...

<input [id]="input.id" [type]="input.type" [autofocus]="input.autofocus" />

Where input is

const input = {
  id: "my-input",
  type: "text",
  autofocus: true
};

How to skip over an element in .map()?

To extrapolate on Felix Kling's comment, you can use .filter() like this:

var sources = images.map(function (img) {
  if(img.src.split('.').pop() === "json") { // if extension is .json
    return null; // skip
  } else {
    return img.src;
  }
}).filter(Boolean);

That will remove falsey values from the array that is returned by .map()

You could simplify it further like this:

var sources = images.map(function (img) {
  if(img.src.split('.').pop() !== "json") { // if extension is .json
    return img.src;
  }
}).filter(Boolean);

Or even as a one-liner using an arrow function, object destructuring and the && operator:

var sources = images.map(({ src }) => src.split('.').pop() !== "json" && src).filter(Boolean);

Use Async/Await with Axios in React.js

In my experience over the past few months, I've realized that the best way to achieve this is:

class App extends React.Component{
  constructor(){
   super();
   this.state = {
    serverResponse: ''
   }
  }
  componentDidMount(){
     this.getData();
  }
  async getData(){
   const res = await axios.get('url-to-get-the-data');
   const { data } = await res;
   this.setState({serverResponse: data})
 }
 render(){
  return(
     <div>
       {this.state.serverResponse}
     </div>
  );
 }
}

If you are trying to make post request on events such as click, then call getData() function on the event and replace the content of it like so:

async getData(username, password){
 const res = await axios.post('url-to-post-the-data', {
   username,
   password
 });
 ...
}

Furthermore, if you are making any request when the component is about to load then simply replace async getData() with async componentDidMount() and change the render function like so:

render(){
 return (
  <div>{this.state.serverResponse}</div>
 )
}

Regular Expression to match string starting with a specific word

Try this:

/^stop.*$/

Explanation:

  • / charachters delimit the regular expression (i.e. they are not part of the Regex per se)
  • ^ means match at the beginning of the line
  • . followed by * means match any character (.), any number of times (*)
  • $ means to the end of the line

If you would like to enforce that stop be followed by a whitespace, you could modify the RegEx like so:

/^stop\s+.*$/
  • \s means any whitespace character
  • + following the \s means there has to be at least one whitespace character following after the stop word

Note: Also keep in mind that the RegEx above requires that the stop word be followed by a space! So it wouldn't match a line that only contains: stop

Where does Chrome store cookies?

The answer is due to the fact that Google Chrome uses an SQLite file to save cookies. It resides under:

C:\Users\<your_username>\AppData\Local\Google\Chrome\User Data\Default\

inside Cookies file. (which is an SQLite database file)

So it's not a file stored on hard drive but a row in an SQLite database file which can be read by a third party program such as: SQLite Database Browser

EDIT: Thanks to @Chexpir, it is also good to know that the values are stored encrypted.

How do I use brew installed Python as the default Python?

No idea what you mean with default Python. I consider it bad practice to replace the system Python interpreter with a different version. System functionality may depend in some way on the system Python and specific modules or a specific Python version. Instead install your custom Python installations in a safe different place and adjust your $PATH as needed in order to call you Python through a path lookup instead of looking for the default Python.

Hiding elements in responsive layout?

Bootstrap 4.x answer

hidden-* classes are removed from Bootstrap 4 beta onward.

If you want to show on medium and up use the d-* classes, e.g.:

<div class="d-none d-md-block">This will show in medium and up</div>

If you want to show only in small and below use this:

<div class="d-block d-md-none"> This will show only in below medium form factors</div>

Screen size and class chart

| Screen Size        | Class                          |
|--------------------|--------------------------------|
| Hidden on all      | .d-none                        |
| Hidden only on xs  | .d-none .d-sm-block            |
| Hidden only on sm  | .d-sm-none .d-md-block         |
| Hidden only on md  | .d-md-none .d-lg-block         |
| Hidden only on lg  | .d-lg-none .d-xl-block         |
| Hidden only on xl  | .d-xl-none                     |
| Visible on all     | .d-block                       |
| Visible only on xs | .d-block .d-sm-none            |
| Visible only on sm | .d-none .d-sm-block .d-md-none |
| Visible only on md | .d-none .d-md-block .d-lg-none |
| Visible only on lg | .d-none .d-lg-block .d-xl-none |
| Visible only on xl | .d-none .d-xl-block            |

Rather than using explicit .visible-* classes, you make an element visible by simply not hiding it at that screen size. You can combine one .d-*-none class with one .d-*-block class to show an element only on a given interval of screen sizes (e.g. .d-none.d-md-block.d-xl-none shows the element only on medium and large devices).

Documentation

How to use su command over adb shell?

for my use case, i wanted to grab the SHA1 hash from the magisk config file. the below worked for me.

adb shell "su -c "cat /sbin/.magisk/config | grep SHA | awk -F= '{ print $2 }'""

Returning multiple values from a C++ function

std::pair<int, int> divide(int dividend, int divisor)
{
   // :
   return std::make_pair(quotient, remainder);
}

std::pair<int, int> answer = divide(5,2);
 // answer.first == quotient
 // answer.second == remainder

std::pair is essentially your struct solution, but already defined for you, and ready to adapt to any two data types.

Initializing C# auto-properties

In the default constructor (and any non-default ones if you have any too of course):

public foo() {
    Bar = "bar";
}

This is no less performant that your original code I believe, since this is what happens behind the scenes anyway.

Can I set enum start value in Java?

Java enums are not like C or C++ enums, which are really just labels for integers.

Java enums are implemented more like classes - and they can even have multiple attributes.

public enum Ids {
    OPEN(100), CLOSE(200);

    private final int id;
    Ids(int id) { this.id = id; }
    public int getValue() { return id; }
}

The big difference is that they are type-safe which means you don't have to worry about assigning a COLOR enum to a SIZE variable.

See http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html for more.

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

Or just use this in your View(Razor page)

@item.ResgistrationhaseDate.ToString(string.Format("dd/MM/yyyy"))

I recommend that don't add date format in your model class

How do I exit a WPF application programmatically?

Summarizing, there are a few ways to do that.

1) Killing the process, which skip the finalization, error handling etc.:

Process.GetCurrentProcess().Kill();

2) Shutting down current application, which is probably the proper way because it calls the exit events:

Application.Current.Shutdown();

or

this.Shutdown();

(when clled in an instance of App-class)

3) Closing current app (all forms have to be closed/finished earlier):

this.Close(); 

(when clled in an instance of App-class)

4) Exiting the environment, which terminates the app:

Environment.Exit(0);

Also, You may want to read about exit statusses here

Spring Data JPA find by embedded object property

If you are using BookId as an combined primary key, then remember to change your interface from:

public interface QueuedBookRepo extends JpaRepository<QueuedBook, Long> {

to:

public interface QueuedBookRepo extends JpaRepository<QueuedBook, BookId> {

And change the annotation @Embedded to @EmbeddedId, in your QueuedBook class like this:

public class QueuedBook implements Serializable {

@EmbeddedId
@NotNull
private BookId bookId;

...

How do I get values from a SQL database into textboxes using C#?

using (SqlConnection connection =  new SqlConnection("Data Source=localhost;Initial Catalog=LoginScreen;Integrated Security=True"))
{
    SqlCommand command =
    new SqlCommand("select * from Pending_Tasks WHERE CustomerId=...", connection);
    connection.Open();

    SqlDataReader read= command.ExecuteReader();

    while (read.Read())
    {
        CustID.Text = (read["Customer_ID"].ToString());
        CustName.Text = (read["Customer_Name"].ToString());
        Add1.Text = (read["Address_1"].ToString());
        Add2.Text = (read["Address_2"].ToString());
        PostBox.Text = (read["Postcode"].ToString());
        PassBox.Text = (read["Password"].ToString());
        DatBox.Text = (read["Data_Important"].ToString());
        LanNumb.Text = (read["Landline"].ToString());
        MobNumber.Text = (read["Mobile"].ToString());
        FaultRep.Text = (read["Fault_Report"].ToString());
    }
    read.Close();
}

Make sure you have data in the query : select * from Pending_Tasks and you are using "using System.Data.SqlClient;"

"The certificate chain was issued by an authority that is not trusted" when connecting DB in VM Role from Azure website

Got hit by the same issue while accessing SQLServer from IIS. Adding TrustServerCertificate=True didnot help.

Could see a comment in MS docs: Make sure the SQLServer service account has access to the TLS Certificate you are using. (NT Service\MSSQLSERVER)

Open personal store and right click on the certificate -> manage private keys -> Add the SQL service account and give full control.

Restart the SQL service. It worked.

error: unknown type name ‘bool’

C99 does, if you have

#include <stdbool.h> 

If the compiler does not support C99, you can define it yourself:

// file : myboolean.h
#ifndef MYBOOLEAN_H
#define MYBOOLEAN_H

#define false 0
#define true 1
typedef int bool; // or #define bool int

#endif

(but note that this definition changes ABI for bool type so linking against external libraries which were compiled with properly defined bool may cause hard-to-diagnose runtime errors).

increase font size of hyperlink text html

There is a way simpler way. You put the href in a paragraph just created for that href. For example:

HREF name

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

you can use len(arr) as suggested in previous answers to get the length of the array. In case you want the dimensions of a 2D array you could use arr.shape returns height and width

Does Java SE 8 have Pairs or Tuples?

It appears that the full example can be solved without the use of any kind of Pair structure. The key is to filter on the column indexes, with the predicate checking the entire column, instead of mapping the column indexes to the number of false entries in that column.

The code that does this is here:

    System.out.println(
        IntStream.range(0, acyclic_graph.length)
            .filter(i -> IntStream.range(0, acyclic_graph.length)
                                  .noneMatch(j -> acyclic_graph[j][i]))
            .boxed()
            .collect(toList()));

This results in output of [0, 2, 4] which is I think the correct result requested by the OP.

Also note the boxed() operation that boxes the int values into Integer objects. This enables one to use the pre-existing toList() collector instead having to write out collector functions that do the boxing themselves.

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

You were close:

IF EXISTS (SELECT * FROM Table WHERE FieldValue='')
   SELECT TableID FROM Table WHERE FieldValue=''
ELSE
BEGIN
   INSERT INTO TABLE (FieldValue) VALUES ('')
   SELECT TableID FROM Table WHERE TableID=SCOPE_IDENTITY()
END

How to get all of the immediate subdirectories in Python

This method nicely does it all in one go.

from glob import glob
subd = [s.rstrip("/") for s in glob(parent_dir+"*/")]

How can I escape a single quote?

As you’re in the context of HTML, you need to use HTML to represent that character. And for HTML you need to use a numeric character reference &#39; (&#x27; hexadecimal):

<input type='text' id='abc' value='hel&#39;lo'>

Can I force a UITableView to hide the separator between empty cells?

For Swift:

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.tableFooterView = UIView()  // it's just 1 line, awesome!
}

How to diff a commit with its parent?

git diff 15dc8 15dce~1

~1 means 'parent', ~2 'grandparent, etc.

Conditionally Remove Dataframe Rows with R

Logic index:

d<-d[!(d$A=="B" & d$E==0),]

Why am I getting 'Assembly '*.dll' must be strong signed in order to be marked as a prerequisite.'?

If you tried all the other answers in this question and you:

  • Have multiple projects in your solution
  • Have a project (Project A) that references another project (Project B), whose project references a NuGet package.
  • In Project A, you used Intellisense/ReSharper to bring in the reference to the NuGet package referenced in Project B (this can happen when a method in Project B returns a type provided by the NuGet package and that method is used in Project A)
  • updated the NuGet package via NuGet Package Manager (or CLI).

...you may have separate versions of the NuGet packages DLL in your projects' References, as the reference created by Intellisense/ReSharper will be a "normal" reference, and not a NuGet reference as expected, so the NuGet update process won't find or update it!

To fix this, remove the reference in Project A, then use NuGet to install it, and make sure the NuGet packages in all projects are the same version. (as explain in this answer)


Life Pro Tip:

This issue can come up whenever ReSharper/Intellisense suggests to add a reference to your project. It can be much more deeply convoluted than the example above, with multiple interweaving projects and dependencies making it hard to track down. If the reference being suggested by ReSharper/Intellisense is actually from a NuGet package, use NuGet to install it.

Difference between decimal, float and double in .NET?

  • Decimal 128 bit (28-29 significant digits) In case of financial applications it is better to use Decimal types because it gives you a high level of accuracy and easy to avoid rounding errors Use decimal for non-integer math where precision is needed (e.g. money and currency)

  • Double 64 bit (15-16 digits) Double Types are probably the most normally used data type for real values, except handling money. Use double for non-integer math where the most precise answer isn't necessary.

  • Float 32 bit (7 digits) It is used mostly in graphic libraries because very high demands for processing powers, also used situations that can endure rounding errors.

Decimals are much slower than a double/float.

Decimals and Floats/Doubles cannot be compared without a cast whereas Floats and Doubles can.

Decimals also allow the encoding or trailing zeros.

Open link in new tab or window

You should add the target="_blank" and rel="noopener noreferrer" in the anchor tag.

For example:

<a target="_blank" rel="noopener noreferrer" href="http://your_url_here.html">Link</a>

Adding rel="noopener noreferrer" is not mandatory, but it's a recommended security measure. More information can be found in the links below.

Source:

Referencing value in a closed Excel workbook using INDIRECT?

=INDIRECT("'C:\Data["&A8&"]SheetNAME'!$G9")

where A8 contains myExcelFile.xlsm

and G9 contains your source workbook precious data.

The simplest possible JavaScript countdown timer?

If you want a real timer you need to use the date object.

Calculate the difference.

Format your string.

window.onload=function(){
      var start=Date.now(),r=document.getElementById('r');
      (function f(){
      var diff=Date.now()-start,ns=(((3e5-diff)/1e3)>>0),m=(ns/60)>>0,s=ns-m*60;
      r.textContent="Registration closes in "+m+':'+((''+s).length>1?'':'0')+s;
      if(diff>3e5){
         start=Date.now()
      }
      setTimeout(f,1e3);
      })();
}

Example

Jsfiddle

not so precise timer

var time=5*60,r=document.getElementById('r'),tmp=time;

setInterval(function(){
    var c=tmp--,m=(c/60)>>0,s=(c-m*60)+'';
    r.textContent='Registration closes in '+m+':'+(s.length>1?'':'0')+s
    tmp!=0||(tmp=time);
},1000);

JsFiddle

Truncating long strings with CSS: feasible yet?

OK, Firefox 7 implemented text-overflow: ellipsis as well as text-overflow: "string". Final release is planned for 2011-09-27.

Visual Studio 2010 shortcut to find classes and methods?

Left click on a method and press the F12 key to Go To Definition. Other Actions also available

React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

Mostly this is caused with an issue in your React/Client app. Adding this line to your client package.json solves it

"proxy": "http://localhost:5000/"

Note: Replace 5000, with the port number where your server is running

Reference: How to get create-react-app to work with a Node.js back-end API

javascript createElement(), style problem

I found this page when I was trying to set the backgroundImage attribute of a div, but hadn't wrapped the backgroundImage value with url(). This worked fine:

for (var i=0; i<20; i++) {
  // add a wrapper around an image element
  var wrapper = document.createElement('div');
  wrapper.className = 'image-cell';

  // add the image element
  var img = document.createElement('div');
  img.className = 'image';
  img.style.backgroundImage = 'url(http://via.placeholder.com/350x150)';

  // add the image to its container; add both to the body
  wrapper.appendChild(img);
  document.body.appendChild(wrapper);
}

Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

codeigniter needs to load the url helper to call the base_url() function.

use application->config->autoload.php

edit autoload helper array and add url helper..

base_url() function is working now..

ActiveXObject is not defined and can't find variable: ActiveXObject

ActiveXObject is non-standard and only supported by Internet Explorer on Windows.

There is no native cross browser way to write to the file system without using plugins, even the draft File API gives read only access.

If you want to work cross platform, then you need to look at such things as signed Java applets (keeping in mind that that will only work on platforms for which the Java runtime is available).

Resize Cross Domain Iframe Height

You need to have access as well on the site that you will be iframing. i found the best solution here: https://gist.github.com/MateuszFlisikowski/91ff99551dcd90971377

yourotherdomain.html

<script type='text/javascript' src="js/jquery.min.js"></script>
<script type='text/javascript'>
  // Size the parent iFrame
  function iframeResize() {
    var height = $('body').outerHeight(); // IMPORTANT: If body's height is set to 100% with CSS this will not work.
    parent.postMessage("resize::"+height,"*");
  }

  $(document).ready(function() {
    // Resize iframe
    setInterval(iframeResize, 1000);
  });
</script>

your website with iframe

<iframe src='example.html' id='edh-iframe'></iframe>
<script type='text/javascript'>
  // Listen for messages sent from the iFrame
  var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
  var eventer = window[eventMethod];
  var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

  eventer(messageEvent,function(e) {
    // If the message is a resize frame request
    if (e.data.indexOf('resize::') != -1) {
      var height = e.data.replace('resize::', '');
      document.getElementById('edh-iframe').style.height = height+'px';
    }
  } ,false);
</script>

What does "to stub" mean in programming?

You have also a very good testing frameworks to create such a stub. One of my preferrable is Mockito There is also EasyMock and others... But Mockito is great you should read it - very elegant and powerfull package

How to config Tomcat to serve images from an external folder outside webapps?

This is very simple and straight forward to server the static content from outside webapps folder in tomcat.

Simply edit the server.xml under $CATALINA_HOME/config/server.xml as below and restart the tomcat.

<Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        **<Context docBase="C:\Ankur\testFiles"  path="/companyLogo" />**

       <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

</Host>

Add the context element inside the host element with two attribute docBase and path.

1) docBase: represents the hard drive directory 2) path: represents the uri on which you want to serve the static content.

For example:If you have 7.png inside the C:\Ankur\testFiles directory then you can access the 7.png file like below:

http://localhost:8081/companyLogo/7.png

For more details, check the blog

"document.getElementByClass is not a function"

I tried

Document.getElementsByClassName('option0')

Which resulted in the error: Uncaught TypeError: Document.getElementsByClass is not a function

After that I tried:

document.getElementsByClassName('option0')

And it works!

Windows 7, 64 bit, DLL problems

I also ran into this problem, but the solution that seems to be a common thread here, and I saw elsewhere on the web, is "[re]install the redistributable package". However, for me that does not work, as the problem arose when running the installer for our product (which installs the redistributable package) to test our shiny new Visual Studio 2015 builds.

The issue came up because the DLL files listed are not located in the Visual Studio install path (for example, C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\redist) and thus had not been added to the install. These api-ms-win-* dlls get installed to a Windows 10 SDK install path as part of the Visual Studio 2015 install (e.g. C:\Program Files (x86)\Windows Kits\10\Redist).

Installing on Windows 10 worked fine, but installing on Windows 7 required adding these DLL files to our product install. For more information, see Update for Universal C Runtime in Windows which describes the addition of these dependencies caused by Visual Studio 2015 and provides downloads for various Windows platforms; also see Introducing the Universal CRT which describes the redesign of the CRT libraries. Of particular interest is item 6 under the section titled Distributing Software that uses the Universal CRT:

Updated September 11, 2015: App-local deployment of the Universal CRT is supported. To obtain the binaries for app-local deployment, install the Windows Software Development Kit (SDK) for Windows 10. The binaries will be installed to C:\Program Files (x86)\Windows Kits\10\Redist\ucrt. You will need to copy all of the DLLs with your app (note that the set of DLL files are necessary is different on different versions of Windows, so you must include all of the DLL files in order for your program to run on all supported versions of Windows).

How to compare two dates along with time in java

 // Get calendar set to the current date and time
Calendar cal = Calendar.getInstance();

// Set time of calendar to 18:00
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

// Check if current time is after 18:00 today
boolean afterSix = Calendar.getInstance().after(cal);

if (afterSix) {
    System.out.println("Go home, it's after 6 PM!");
}
else {
    System.out.println("Hello!");
}

Why does this CSS margin-top style not work?

Not sure why what you have doesn't work, but you can add

overflow: auto;

to the outer div.

Closing Excel Application Process in C# after Data Access

workbook.Close(0);
excelApp.Quit();

Worked for me.

Change Spinner dropdown icon

Have you tried to define a custom background in xml? decreasing the Spinner background width which is doing your arrow look like that.

Define a layer-list with a rectangle background and your custom arrow icon:

    <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/color_white" />
            <corners android:radius="2.5dp" />
        </shape>
    </item>
    <item android:right="64dp">
         <bitmap android:gravity="right|center_vertical"  
             android:src="@drawable/custom_spinner_icon">
         </bitmap>
    </item>
</layer-list>

Difference between Activity Context and Application Context

Use getApplicationContext() if you need something tied to a Context that itself will have global scope.

If you use Activity, then the new Activity instance will have a reference, which has an implicit reference to the old Activity, and the old Activity cannot be garbage collected.

How to call a PHP function on the click of a button

The onclick attribute in HTML calls JavaScript functions, not PHP functions.

jQuery return ajax result into outside variable

So this is long after the initial question, and technically it isn't a direct answer to how to use Ajax call to populate exterior variable as the question asks. However in research and responses it's been found to be extremely difficult to do this without disabling asynchronous functions within the call, or by descending into what seems like the potential for callback hell. My solution for this has been to use Axios. Using this has dramatically simplified my usages of asynchronous calls getting in the way of getting at data.

For example if I were trying to access session variables in PHP, like the User ID, via a call from JS this might be a problem. Doing something like this..

async function getSession() {
 'use strict';
 const getSession = await axios("http:" + url + "auth/" + "getSession");
 log(getSession.data);//test
 return getSession.data;
}

Which calls a PHP function that looks like this.

public function getSession() {
 $session = new SessionController();
 $session->Session();
 $sessionObj = new \stdClass();
 $sessionObj->user_id = $_SESSION["user_id"];
 echo json_encode($sessionObj);
}

To invoke this using Axios do something like this.

getSession().then(function (res) {
 log(res);//test
 anyVariable = res;
 anyFunction(res);//set any variable or populate another function waiting for the data
});

The result would be, in this case a Json object from PHP.

{"user_id":"1111111-1111-1111-1111-111111111111"}

Which you can either use in a function directly in the response section of the Axios call or set a variable or invoke another function.

Proper syntax for the Axios call would actually look like this.

getSession().then(function (res) {
 log(res);//test
 anyVariable = res;
 anyFunction(res);//set any variable or populate another function waiting for the data
}).catch(function (error) {
 console.log(error);
});

For proper error handling.

I hope this helps anyone having these issues. And yes I am aware this technically is not a direct answer to the question but given the answers supplied already I felt the need to provide this alternative solution which dramatically simplified my code on the client and server sides.

What is difference between Lightsail and EC2?

Lightsail VPSs are bundles of existing AWS products, offered through a significantly simplified interface. The difference is that Lightsail offers you a limited and fixed menu of options but with much greater ease of use. Other than the narrower scope of Lightsail in order to meet the requirements for simplicity and low cost, the underlying technology is the same.

The pre-defined bundles can be described:

% aws lightsail --region us-east-1 get-bundles
{
    "bundles": [
        {
            "name": "Nano",
            "power": 300,
            "price": 5.0,
            "ramSizeInGb": 0.5,
            "diskSizeInGb": 20,
            "transferPerMonthInGb": 1000,
            "cpuCount": 1,
            "instanceType": "t2.nano",
            "isActive": true,
            "bundleId": "nano_1_0"
        },
        ...
    ]
}

It's worth reading through the Amazon EC2 T2 Instances documentation, particularly the CPU Credits section which describes the base and burst performance characteristics of the underlying instances.

Importantly, since your Lightsail instances run in VPC, you still have access to the full spectrum of AWS services, e.g. S3, RDS, and so on, as you would from any EC2 instance.

PHP - concatenate or directly insert variables in string

Double-quoted strings are more elegant because you don't have to break up your string every time you need to insert a variable (like you must do with single-quoted strings).

However, if you need to insert the return value of a function, this cannot be inserted into a double-quoted string--even if you surround it with braces!

//syntax error!!
//$s = "Hello {trim($world)}!"

//the only option
$s = "Hello " . trim($world) . "!";

No more data to read from socket error

For errors like this you should involve oracle support. Unfortunately you do not mention what oracle release you are using. The error can be related to optimizer bind peeking. Depending on the oracle version different workarounds apply.

You have two ways to address this:

  • upgrade to 11.2
  • set oracle parameter _optim_peek_user_binds = false

Of course underscore parameters should only be set if advised by oracle support

Colspan all columns

For IE 6, you'll want to equal colspan to the number of columns in your table. If you have 5 columns, then you'll want: colspan="5".

The reason is that IE handles colspans differently, it uses the HTML 3.2 specification:

IE implements the HTML 3.2 definition, it sets colspan=0 as colspan=1.

The bug is well documented.

List all files from a directory recursively with Java

Java 8

public static void main(String[] args) throws IOException {

        Path start = Paths.get("C:\\data\\");
        try (Stream<Path> stream = Files.walk(start, Integer.MAX_VALUE)) {
            List<String> collect = stream
                .map(String::valueOf)
                .sorted()
                .collect(Collectors.toList());

            collect.forEach(System.out::println);
        }


    }

Download a file with Android, and showing the progress in a ProgressDialog

I found this blog post very helpful, Its using loopJ to download file, it has only one Simple function, will be helpful to some new android guys.

subtract time from date - moment js

You can create a much cleaner implementation with Moment.js Durations. No manual parsing necessary.

_x000D_
_x000D_
var time = moment.duration("00:03:15");_x000D_
var date = moment("2014-06-07 09:22:06");_x000D_
date.subtract(time);_x000D_
$('#MomentRocks').text(date.format())
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.js"></script>_x000D_
<span id="MomentRocks"></span>
_x000D_
_x000D_
_x000D_

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

Failed to run sdkmanager --list with Java 9

Update 2019-10:

As stated in the issue tracker, Google has been working on a new SDK tools release that runs on current JVMs (9+)!

You can download and use the new Android SDK Command-line Tools (1.0.0) inside Android Studio or by manually downloading them from the Google servers:

For the latest versions check the URLs inside the repository.xml.

If you manually unpack the command line tools, take care of placing them in a subfolder inside your $ANDROID_HOME (e.g. $ANDROID_HOME/cmdline-tools/...).

Ternary operator in PowerShell

The closest PowerShell construct I've been able to come up with to emulate that is:

@({'condition is false'},{'condition is true'})[$condition]

Could not autowire field:RestTemplate in Spring boot application

Please make sure two things:

1- Use @Bean annotation with the method.

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
    return builder.build();
}

2- Scope of this method should be public not private.

Complete Example -

@Service
public class MakeHttpsCallImpl implements MakeHttpsCall {

@Autowired
private RestTemplate restTemplate;

@Override
public String makeHttpsCall() {
    return restTemplate.getForObject("https://localhost:8085/onewayssl/v1/test",String.class);
}

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
    return builder.build();
}
}

What does the 'standalone' directive mean in XML?

  • The standalone directive is an optional attribute on the XML declaration.
  • Valid values are yes and no, where no is the default value.
  • The attribute is only relevant when a DTD is used. (The attribute is irrelevant when using a schema instead of a DTD.)
  • standalone="yes" means that the XML processor must use the DTD for validation only. In that case it will not be used for:
    • default values for attributes
    • entity declarations
    • normalization
  • Note that standalone="yes" may add validity constraints if the document uses an external DTD. When the document contains things that would require modification of the XML, such as default values for attributes, and standalone="yes" is used then the document is invalid.
  • standalone="yes" may help to optimize performance of document processing.

Source: The standalone pseudo-attribute is only relevant if a DTD is used

How many threads is too many?

If your threads are performing any kind of resource-intensive work (CPU/Disk) then you'll rarely see benefits beyond one or two, and too many will kill performance very quickly.

The 'best-case' is that your later threads will stall while the first ones complete, or some will have low-overhead blocks on resources with low contention. Worst-case is that you start thrashing the cache/disk/network and your overall throughput drops through the floor.

A good solution is to place requests in a pool that are then dispatched to worker threads from a thread-pool (and yes, avoiding continuous thread creation/destruction is a great first step).

The number of active threads in this pool can then be tweaked and scaled based on the findings of your profiling, the hardware you are running on, and other things that may be occurring on the machine.

How to run Java program in terminal with external library JAR

For compiling the java file having dependency on a jar

javac -cp path_of_the_jar/jarName.jar className.java

For executing the class file

java -cp .;path_of_the_jar/jarName.jar className

Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'"

I had the same problem for different package. I was installing pyinstaller in conda on Mac Mojave. I did

conda create --name ai37 python=3.7
conda activate ai37

I got the mentioned error when I tried to install pyinstaller using

pip install pyinstaller

I was able to install the pyinstaller with the following command

conda install -c conda-forge pyinstaller 

Jenkins returned status code 128 with github

I changed the permission of my .ssh/id_rsa (private key) to 604. chmod 700 id_rsa

pip: no module named _internal

my solution: first step like most other answer:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python2.7 get-pip.py --force-reinstall

second, add soft link

sudo ln -s /usr/local/bin/pip /usr/bin/pip