Programs & Examples On #Hpricot

Hpricot is a Ruby library intended for parsing HTML. Until the release of Nokogiri, a competing HTML and css parser, Hpricot was the defacto HTML parser for the ruby community.

ruby 1.9: invalid byte sequence in UTF-8

I've encountered string, which had mixings of English, Russian and some other alphabets, which caused exception. I need only Russian and English, and this currently works for me:

ec1 = Encoding::Converter.new "UTF-8","Windows-1251",:invalid=>:replace,:undef=>:replace,:replace=>""
ec2 = Encoding::Converter.new "Windows-1251","UTF-8",:invalid=>:replace,:undef=>:replace,:replace=>""
t = ec2.convert ec1.convert t

Options for HTML scraping?

When it comes to extracting data from an HTML document on the server-side, Node.js is a fantastic option. I have used it successfully with two modules called request and cheerio.

You can see an example how it works here.

Control cannot fall through from one case label

Since it wasn't mentioned in the other answers, I'd like to add that if you want case SearchAuthors to be executed right after the first case, just like omitting the break in some other programming languages where that is allowed, you can simply use goto.

switch (searchType)
{
    case "SearchBooks":
    Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
    Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
    goto case "SearchAuthors";

    case "SearchAuthors":
    Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
    Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
    break;
}

Spring: Why do we autowire the interface and not the implemented class?

How does spring know which polymorphic type to use.

As long as there is only a single implementation of the interface and that implementation is annotated with @Component with Spring's component scan enabled, Spring framework can find out the (interface, implementation) pair. If component scan is not enabled, then you have to define the bean explicitly in your application-config.xml (or equivalent spring configuration file).

Do I need @Qualifier or @Resource?

Once you have more than one implementation, then you need to qualify each of them and during auto-wiring, you would need to use the @Qualifier annotation to inject the right implementation, along with @Autowired annotation. If you are using @Resource (J2EE semantics), then you should specify the bean name using the name attribute of this annotation.

Why do we autowire the interface and not the implemented class?

Firstly, it is always a good practice to code to interfaces in general. Secondly, in case of spring, you can inject any implementation at runtime. A typical use case is to inject mock implementation during testing stage.

interface IA
{
  public void someFunction();
}


class B implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someBfunc()
  {
     //doing b things
  }
}


class C implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someCfunc()
  {
     //doing C things
  }
}

class MyRunner
{
     @Autowire
     @Qualifier("b") 
     IA worker;

     ....
     worker.someFunction();
}

Your bean configuration should look like this:

<bean id="b" class="B" />
<bean id="c" class="C" />
<bean id="runner" class="MyRunner" />

Alternatively, if you enabled component scan on the package where these are present, then you should qualify each class with @Component as follows:

interface IA
{
  public void someFunction();
}

@Component(value="b")
class B implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someBfunc()
  {
     //doing b things
  }
}


@Component(value="c")
class C implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someCfunc()
  {
     //doing C things
  }
}

@Component    
class MyRunner
{
     @Autowire
     @Qualifier("b") 
     IA worker;

     ....
     worker.someFunction();
}

Then worker in MyRunner will be injected with an instance of type B.

Add shadow to custom shape on Android

This question may be old, but for anybody in future that wants a simple way to achieve complex shadow effects check out my library here https://github.com/BluRe-CN/ComplexView

Using the library, you can change shadow colors, tweak edges and so much more. Here's an example to achieve what you seek for.

<com.blure.complexview.ComplexView
        android:layout_width="400dp"
        android:layout_height="600dp"
        app:radius="10dp"
        app:shadow="true"
        app:shadowSpread="2">

        <com.blure.complexview.ComplexView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:color="#fdfcfc"
            app:radius="10dp" />
    </com.blure.complexview.ComplexView>

To change the shadow color, use app:shadowColor="your color code".

jQuery animate backgroundColor

Try this one:

(function($) {  

            var i = 0;  

            var someBackground = $(".someBackground");  
            var someColors = [ "yellow", "red", "blue", "pink" ];  


            someBackground.css('backgroundColor', someColors[0]);  

            window.setInterval(function() {  
                i = i == someColors.length ? 0 : i;  
                someBackground.animate({backgroundColor: someColors[i]}, 3000);  
                i++;  
            }, 30);  

})(jQuery);  

you can preview example here: http://jquerydemo.com/demo/jquery-animate-background-color.aspx

Easiest way to pass an AngularJS scope variable from directive to controller?

Edited on 2014/8/25: Here was where I forked it.

Thanks @anvarik.

Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @

<div ng-controller="MyCtrl">
    <h2>Parent Scope</h2>
    <input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i>    
    <br><br>
    <!-- attribute-foo binds to a DOM attribute which is always
    a string. That is why we are wrapping it in curly braces so
    that it can be interpolated. -->
    <my-component attribute-foo="{{foo}}" binding-foo="foo"
        isolated-expression-foo="updateFoo(newFoo)" >
        <h2>Attribute</h2>
        <div>
            <strong>get:</strong> {{isolatedAttributeFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedAttributeFoo">
            <i>// This does not update the parent scope.</i>
        </div>
        <h2>Binding</h2>
        <div>
            <strong>get:</strong> {{isolatedBindingFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedBindingFoo">
            <i>// This does update the parent scope.</i>
        </div>
        <h2>Expression</h2>    
        <div>
            <input ng-model="isolatedFoo">
            <button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
            <i>// And this calls a function on the parent scope.</i>
        </div>
    </my-component>
</div>
var myModule = angular.module('myModule', [])
    .directive('myComponent', function () {
        return {
            restrict:'E',
            scope:{
                /* NOTE: Normally I would set my attributes and bindings
                to be the same name but I wanted to delineate between
                parent and isolated scope. */                
                isolatedAttributeFoo:'@attributeFoo',
                isolatedBindingFoo:'=bindingFoo',
                isolatedExpressionFoo:'&'
            }        
        };
    })
    .controller('MyCtrl', ['$scope', function ($scope) {
        $scope.foo = 'Hello!';
        $scope.updateFoo = function (newFoo) {
            $scope.foo = newFoo;
        }
    }]);

Animation CSS3: display + opacity

HOW TO ANIMATE OPACITY WITH CSS:
this is my code:
the CSS code

_x000D_
_x000D_
.item {   
    height:200px;
    width:200px;
    background:red;
    opacity:0;
    transition: opacity 1s ease-in-out;
}

.item:hover {
    opacity: 1;
}
code {
    background: linear-gradient(to right,#fce4ed,#ffe8cc);
}
_x000D_
<div class="item">

</div>
<p><code> move mouse over top of this text</code></p>
_x000D_
_x000D_
_x000D_

or check this demo file

function vote(){
var vote = getElementById("yourOpinion")
if(this.workWithYou):
vote += 1 };
lol

SQL LEFT-JOIN on 2 fields for MySQL

Let's try this way:

select 
    a.ip, 
    a.os, 
    a.hostname, 
    a.port, 
    a.protocol, 
    b.state
from a
left join b 
    on a.ip = b.ip 
        and a.port = b.port /*if you has to filter by columns from right table , then add this condition in ON clause*/
where a.somecolumn = somevalue /*if you have to filter by some column from left table, then add it to where condition*/

So, in where clause you can filter result set by column from right table only on this way:

...
where b.somecolumn <> (=) null

How can I escape square brackets in a LIKE clause?

There is a problem in that whilst:

LIKE 'WC[[]R]S123456' 

and:

LIKE 'WC\[R]S123456' ESCAPE '\'

Both work for SQL Server but neither work for Oracle.

It seems that there is no ISO/IEC 9075 way to recognize a pattern involving a left brace.

Changing the row height of a datagridview

What you have to do is to set the MinimumHeight property of the row. Not only the Height property. That's the key. Put the code bellow in the CellPainting event of the datagridview

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
   foreach(DataGridViewRow x in dataGridView1.Rows)
   {
     x.MinimumHeight = 50;
   }
}

What's the best way to loop through a set of elements in JavaScript?

Here's a nice form of a loop I often use. You create the iterated variable from the for statement and you don't need to check the length property, which can be expensive specially when iterating through a NodeList. However, you must be careful, you can't use it if any of the values in array could be "falsy". In practice, I only use it when iterating over an array of objects that does not contain nulls (like a NodeList). But I love its syntactic sugar.

var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}];

for (var i=0, item; item = list[i]; i++) {
  // Look no need to do list[i] in the body of the loop
  console.log("Looping: index ", i, "item" + item);
}

Note that this can also be used to loop backwards (as long as your list doesn't have a ['-1'] property)

var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}];

for (var i = list.length - 1, item; item = list[i]; i--) {
  console.log("Looping: index ", i, "item", item);
}

ES6 Update

for...of gives you the name but not the index, available since ES6

for (let item of list) {
    console.log("Looping: index ", "Sorry!!!", "item" + item);
}

NoClassDefFoundError in Java: com/google/common/base/Function

you don't have the "google-collections" library on your classpath.

There are a number of ways to add libraries to your classpath, so please provide more info regarding how you are executing your program.

if from the command line, you can add libraries to the classpath via

java -classpath path/lib.jar ...

How to pass event as argument to an inline event handler in JavaScript?

Since inline events are executed as functions you can simply use arguments.

<p id="p" onclick="doSomething.apply(this, arguments)">

and

function doSomething(e) {
  if (!e) e = window.event;
  // 'e' is the event.
  // 'this' is the P element
}

The 'event' that is mentioned in the accepted answer is actually the name of the argument passed to the function. It has nothing to do with the global event.

What is the Ruby <=> (spaceship) operator?

The spaceship method is useful when you define it in your own class and include the Comparable module. Your class then gets the >, < , >=, <=, ==, and between? methods for free.

class Card
  include Comparable
  attr_reader :value

  def initialize(value)
    @value = value
  end

  def <=> (other) #1 if self>other; 0 if self==other; -1 if self<other
    self.value <=> other.value
  end

end

a = Card.new(7)
b = Card.new(10)
c = Card.new(8)

puts a > b # false
puts c.between?(a,b) # true

# Array#sort uses <=> :
p [a,b,c].sort # [#<Card:0x0000000242d298 @value=7>, #<Card:0x0000000242d248 @value=8>, #<Card:0x0000000242d270 @value=10>]

Assigning multiple styles on an HTML element

You needed to do it like this:

_x000D_
_x000D_
<h2 style="text-align: center;font-family: Tahoma">TITLE</h2>
_x000D_
_x000D_
_x000D_

Hope it helped.

Local storage in Angular 2

Use Angular2 @LocalStorage module, which is described as:

This little Angular2/typescript decorator makes it super easy to save and restore automatically a variable state in your directive (class property) using HTML5' LocalStorage.

If you need to use cookies, you should take a look at: https://www.npmjs.com/package/angular2-cookie

Javascript - Get Image height

Try with JQuery:

<script type="text/javascript">
function jquery_get_width_height()
{
    var imgWidth = $("#img").width();
    var imgHeight = $("#img").height();
    alert("JQuery -- " + "imgWidth: " + imgWidth + " - imgHeight: " + imgHeight);
}
</script>

or

<script type="text/javascript">
function javascript_get_width_height()
{
    var img = document.getElementById('img');
    alert("JavaSript -- " + "imgWidth: " + img.width + " - imgHeight: " + img.height);
}
</script>

What's the difference between "app.render" and "res.render" in express.js?

Here are some differences:

  1. You can call app.render on root level and res.render only inside a route/middleware.

  2. app.render always returns the html in the callback function, whereas res.render does so only when you've specified the callback function as your third parameter. If you call res.render without the third parameter/callback function the rendered html is sent to the client with a status code of 200.

    Take a look at the following examples.

    • app.render

      app.render('index', {title: 'res vs app render'}, function(err, html) {
          console.log(html)
      });
      
      // logs the following string (from default index.jade)
      <!DOCTYPE html><html><head><title>res vs app render</title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>res vs app render</h1><p>Welcome to res vs app render</p></body></html>
      
    • res.render without third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'})
      })
      
      // also renders index.jade but sends it to the client 
      // with status 200 and content-type text/html on GET /render
      
    • res.render with third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'}, function(err, html) {
              console.log(html);
              res.send('done');
          })
      })
      
      // logs the same as app.render and sends "done" to the client instead 
      // of the content of index.jade
      
  3. res.render uses app.render internally to render template files.

  4. You can use the render functions to create html emails. Depending on your structure of your app, you might not always have acces to the app object.

    For example inside an external route:

    app.js

    var routes = require('routes');
    
    app.get('/mail', function(req, res) {
        // app object is available -> app.render
    })
    
    app.get('/sendmail', routes.sendmail);
    

    routes.js

    exports.sendmail = function(req, res) {
        // can't use app.render -> therefore res.render
    }
    

How to get client IP address in Laravel 5+

If you call this function then you easily get the client's IP address. I have already used this in my existing project:

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

Python "expected an indented block"

in python .....intendation matters, e.g.:

if a==1:
    print("hey")

if a==2:
   print("bye")

print("all the best")

In this case "all the best" will be printed if either of the two conditions executes, but if it would have been like this

if a==2:
   print("bye")
   print("all the best")

then "all the best" will be printed only if a==2

Better way to find control in ASP.NET

The following example defines a Button1_Click event handler. When invoked, this handler uses the FindControl method to locate a control with an ID property of TextBox2 on the containing page. If the control is found, its parent is determined using the Parent property and the parent control's ID is written to the page. If TextBox2 is not found, "Control Not Found" is written to the page.

private void Button1_Click(object sender, EventArgs MyEventArgs)
{
      // Find control on page.
      Control myControl1 = FindControl("TextBox2");
      if(myControl1!=null)
      {
         // Get control's parent.
         Control myControl2 = myControl1.Parent;
         Response.Write("Parent of the text box is : " + myControl2.ID);
      }
      else
      {
         Response.Write("Control not found");
      }
}

AngularJS - value attribute for select

you can use

state.name for state in states track by state.code

Where states in the JSON array, state is the variable name for each object in the array.

Hope this helps

Server Discovery And Monitoring engine is deprecated

This worked for me

For folks using MongoClient try this:

MongoClient.connect(connectionurl, 
  {useUnifiedTopology: true, useNewUrlParser: true},  callback() {

For mongoose:

mongoose.connect(connectionurl, 
         {useUnifiedTopology: true, useNewUrlParser: true}).then(()=>{

Remove other connectionOptions

jquery $(window).height() is returning the document height

I think your document must be having enough space in the window to display its contents. That means there is no need to scroll down to see any more part of the document. In that case, document height would be equal to the window height.

"You may need an appropriate loader to handle this file type" with Webpack and Babel

If you are using Webpack > 3 then you only need to install babel-preset-env, since this preset accounts for es2015, es2016 and es2017.

var path = require('path');
let webpack = require("webpack");

module.exports = {
    entry: {
        app: './app/App.js',
        vendor: ["react","react-dom"]
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, '../public')
    },
    module: {
        rules: [{
            test: /\.jsx?$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader?cacheDirectory=true',
            }
        }]
    }
};

This picks up its configuration from my .babelrc file:

{
    "presets": [
        [
            "env",
            {
                "targets": {
                    "browsers":["last 2 versions"],
                    "node":"current"
                }
            }
        ],["react"]
    ]
}

How to get a list of installed Jenkins plugins with name and version pair

Another option for Python users:

from jenkinsapi.jenkins import Jenkins

#get the server instance
jenkins_url = 'http://<jenkins-hostname>:<jenkins-port>/jenkins'
server = Jenkins(jenkins_url, username = '<user>', password = '<password>')

#get the installed plugins as list and print the pairs
plugins_dictionary = server.get_plugins().get_plugins_dict()
for key, value in plugins_dictionary.iteritems():
    print "Plugin name: %s, version: %s" %(key, value.version)

Logout button php

When you want to destroy a session completely, you need to do more then just

session_destroy();

First, you should unset any session variables. Then you should destroy the session followed by closing the write of the session. This can be done by the following:

<?php
session_start();
unset($_SESSION);
session_destroy();
session_write_close();
header('Location: /');
die;
?>

The reason you want have a separate script for a logout is so that you do not accidently execute it on the page. So make a link to your logout script, then the header will redirect to the root of your site.

Edit:

You need to remove the () from your exit code near the top of your script. it should just be

exit;

Resource leak: 'in' is never closed

If you are using JDK7 or 8, you can use try-catch with resources.This will automatically close the scanner.

try ( Scanner scanner = new Scanner(System.in); )
  {
    System.out.println("Enter the width of the Rectangle: ");
    width = scanner.nextDouble();
    System.out.println("Enter the height of the Rectangle: ");
    height = scanner.nextDouble();
  }
catch(Exception ex)
{
    //exception handling...do something (e.g., print the error message)
    ex.printStackTrace();
}

Convert pyQt UI to python

I've ran into the same problem recently. After finding the correct path to the pyuic4 file using the file finder I've ran:

C:\Users\ricckli.qgis2\python\plugins\qgis2leaf>C:\OSGeo4W64\bin\pyuic4 -o ui_q gis2leaf.py ui_qgis2leaf.ui

As you can see my ui file was placed in this folder...

QT Creator was installed separately and the pyuic4 file was placed there with the OSGEO4W installer

ERROR 1130 (HY000): Host '' is not allowed to connect to this MySQL server

$mysql -u root --host=127.0.0.1 -p

mysql>use mysql

mysql>GRANT ALL ON *.* to root@'%' IDENTIFIED BY 'redhat@123';

mysql>FLUSH PRIVILEGES;

mysql> SELECT host FROM mysql.user WHERE User = 'root';

Is it possible to import modules from all files in a directory, using a wildcard?

You can use async import():

import fs = require('fs');

and then:

fs.readdir('./someDir', (err, files) => {
 files.forEach(file => {
  const module = import('./' + file).then(m =>
    m.callSomeMethod();
  );
  // or const module = await import('file')
  });
});

How do I detect unsigned integer multiply overflow?

Some compilers provide access to the integer overflow flag in the CPU which you could then test but this isn't standard.

You could also test for the possibility of overflow before you perform the multiplication:

if ( b > ULONG_MAX / a ) // a * b would overflow

how to add background image to activity?

We can easily place the background image in PercentFrameLayout using the ImageView. We have to set the scaleType attribute value="fitXY" and in the foreground we can also display other view's like textview or button.

 <android.support.percent.PercentFrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        >
        <ImageView
            android:src="@drawable/logo"
            android:id="@+id/im1"
            android:scaleType="fitXY"
            android:layout_height="match_parent"
            android:layout_width="match_parent"/>
<EditText android:layout_gravity="center_horizontal"
        android:hint="Enter Username"
        android:id="@+id/et1"
        android:layout_height="wrap_content"
        app:layout_widthPercent="50%"
        app:layout_marginTopPercent="30%"
        />
<Button
    android:layout_gravity="center_horizontal"
    android:text="Login"
    android:id="@+id/b1"
    android:layout_height="wrap_content"
    app:layout_widthPercent="50%"
    app:layout_marginTopPercent="40%"/>
</android.support.percent.PercentFrameLayout>

A cron job for rails: best practices?

In our project we first used whenever gem, but confronted some problems.

We then switched to RUFUS SCHEDULER gem, which turned out to be very easy and reliable for scheduling tasks in Rails.

We have used it for sending weekly & daily mails, and even for running some periodic rake tasks or any method.

The code used in this is like:

    require 'rufus-scheduler'

    scheduler = Rufus::Scheduler.new

    scheduler.in '10d' do
      # do something in 10 days
    end

    scheduler.at '2030/12/12 23:30:00' do
      # do something at a given point in time
    end

    scheduler.every '3h' do
      # do something every 3 hours
    end

    scheduler.cron '5 0 * * *' do
      # do something every day, five minutes after midnight
      # (see "man 5 crontab" in your terminal)
    end

To learn more: https://github.com/jmettraux/rufus-scheduler

How to create a responsive image that also scales up in Bootstrap 3

I guess image is than corrupted. Example: image size is 195px X 146px.

It will work inside lower resolutions like tablets. When you have 1280 X 800 resolution it will force larger as there is also width 100 %. Maybe CSS inside media query like icons fonts is the best solution.

Listen to changes within a DIV and act accordingly

If possible you can change the div to an textarea and use .change().

Another solution could be use a hidden textarea and update the textarea same time as you update the div. Then use .change() on the hidden textarea.

You can also use http://www.jacklmoore.com/autosize/ to make the text area act more like a div.

<style>
.hidden{
display:none
}
</style>

<textarea class="hidden" rows="4" cols="50">

</textarea>


$("#hiddentextarea").change(function() {

alert('Textarea changed');

})

Update: It seems like textarea has to be defocused after updated, for more info: How do I set up a listener in jQuery/javascript to monitor a if a value in the textbox has changed?

Catching FULL exception message

I keep coming back to these questions trying to figure out where exactly the data I'm interested in is buried in what is truly a monolithic ErrorRecord structure. Almost all answers give piecemeal instructions on how to pull certain bits of data.

But I've found it immensely helpful to dump the entire object with ConvertTo-Json so that I can visually see LITERALLY EVERYTHING in a comprehensible layout.

    try {
        Invoke-WebRequest...
    }
    catch {
        Write-Host ($_ | ConvertTo-Json)
    }

Use ConvertTo-Json's -Depth parameter to expand deeper values, but use extreme caution going past the default depth of 2 :P

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertto-json

Custom Drawable for ProgressBar/ProgressDialog

Your style should look like this:

<style parent="@android:style/Widget.ProgressBar" name="customProgressBar">
    <item name="android:indeterminateDrawable">@anim/mp3</item>
</style>

How to save username and password with Mercurial?

NOBODY above explained/clarified terms to a novice user. They get confused by the terms

.hg/hgrc -- this file is used for Repository, at local/workspace location / in actual repository's .hg folder.

~/.hgrc -- this file is different than the below one. this file resides at ~ or home directory.

myremote.xxxx=..... bb.xxxx=......

This is one of the lines under [auth] section/directive, while using mercurial keyring extension. Make sure the server name you put there, matches with what you use while doing "hg clone" otherwise keyring will say, user not found. bb or myremote in the line below, are "alias name" that you MUST give while doing "hg clone http:/.../../repo1 bb or myremote" otherwise, it wont work or you have to make sure your local repository's .hg/hgrc file contain same alias, ie (what you gave while doing hg clone .. as last parameter).

PS the following links for clear details, sorry for quickly written grammar.

ex: If inside ~/.hgrc (user's home directory in Linux/Unix) or mercurial.ini in Windows at user's home directory, contains, the following line and if you do

`"hg clone http://.../.../reponame myremote"`

, then you'll never be prompted for user credentials more than once per http repo link. In ~/.hgrc under [extensions] a line for "mercurial_keyring = " or "hgext.mercurial_keyring = /path/to/your/mercurial_keyring.py" .. one of these lines should be there.

[auth]
myremote.schemes = http https
myremote.prefix = thsusncdnvm99/hg
myremote.username = c123456

I'm trying to find out how to set the PREFIX property so that user can clone or perform any Hg operations without username/password prompts and without worrying about what he mentioned in the http://..../... for servername while using the Hg repo link. It can be IP, servername or server's FQDN

How to change XML Attribute

If the attribute you want to change doesn't exist or has been accidentally removed, then an exception occurs. I suggest you first create a new attribute and send it to a function like the following:

private void SetAttrSafe(XmlNode node,params XmlAttribute[] attrList)
    {
        foreach (var attr in attrList)
        {
            if (node.Attributes[attr.Name] != null)
            {
                node.Attributes[attr.Name].Value = attr.Value;
            }
            else
            {
                node.Attributes.Append(attr);
            }
        }
    }

Usage:

   XmlAttribute attr = dom.CreateAttribute("name");
   attr.Value = value;
   SetAttrSafe(node, attr);

Common sources of unterminated string literal

You might try running the script through JSLint.

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

Modern solution:

let blob = await fetch(url).then(r => r.blob());

The url can be an object url or a normal url.

Get specific line from text file using just shell script

Assuming line is a variable which holds your required line number, if you can use head and tail, then it is quite simple:

head -n $line file | tail -1

If not, this should work:

x=0
want=5
cat lines | while read line; do
  x=$(( x+1 ))
  if [ $x -eq "$want" ]; then
    echo $line
    break
  fi
done

Logging levels - Logback - rule-of-thumb to assign log levels

Not different for other answers, my framework have almost the same levels:

  1. Error: critical logical errors on application, like a database connection timeout. Things that call for a bug-fix in near future
  2. Warn: not-breaking issues, but stuff to pay attention for. Like a requested page not found
  3. Info: used in functions/methods first line, to show a procedure that has been called or a step gone ok, like a insert query done
  4. log: logic information, like a result of an if statement
  5. debug: variable contents relevant to be watched permanently

Member '<method>' cannot be accessed with an instance reference

I know this is an old thread, but I just spent 3 hours trying to figure out what my issue was. I ordinarily know what this error means, but you can run into this in a more subtle way as well. My issue was my client class (the one calling a static method from an instance class) had a property of a different type but named the same as the static method. The error reported by the compiler was the same as reported here, but the issue was basically name collision.

For anyone else getting this error and none of the above helps, try fully qualifying your instance class with the namespace name. ..() so the compiler can see the exact name you mean.

Image height and width not working?

You have a class on your CSS that is overwriting your width and height, the class reads as such:

.postItem img {
    height: auto;
    width: 450px;
}

Remove that and your width/height properties on the img tag should work.

Check if the number is integer

For a vector m, m[round(m) != m] will return the indices of values in the vector that are not integers.

php exec command (or similar) to not wait for result

"exec nohup setsid your_command"

the nohup allows your_command to continue even though the process that launched may terminate first. If it does, the the SIGNUP signal will be sent to your_command causing it to terminate (unless it catches that signal and ignores it).

How do I convert a numpy array to (and display) an image?

this could be a possible code solution:

from skimage import io
import numpy as np
data=np.random.randn(5,2)
io.imshow(data)

Python: Finding differences between elements of a list

A functional approach:

>>> import operator
>>> a = [1,3,5,7,11,13,17,21]
>>> map(operator.sub, a[1:], a[:-1])
[2, 2, 2, 4, 2, 4, 4]

Using generator:

>>> import operator, itertools
>>> g1,g2 = itertools.tee((x*x for x in xrange(5)),2)
>>> list(itertools.imap(operator.sub, itertools.islice(g1,1,None), g2))
[1, 3, 5, 7]

Using indices:

>>> [a[i+1]-a[i] for i in xrange(len(a)-1)]
[2, 2, 2, 4, 2, 4, 4]

How do I write a bash script to restart a process if it dies?

The easiest way to do it is using flock on file. In Python script you'd do

lf = open('/tmp/script.lock','w')
if(fcntl.flock(lf, fcntl.LOCK_EX|fcntl.LOCK_NB) != 0): 
   sys.exit('other instance already running')
lf.write('%d\n'%os.getpid())
lf.flush()

In shell you can actually test if it's running:

if [ `flock -xn /tmp/script.lock -c 'echo 1'` ]; then 
   echo 'it's not running'
   restart.
else
   echo -n 'it's already running with PID '
   cat /tmp/script.lock
fi

But of course you don't have to test, because if it's already running and you restart it, it'll exit with 'other instance already running'

When process dies, all it's file descriptors are closed and all locks are automatically removed.

How to apply style classes to td classes?

When using with a reactive bootstrap table, i did not find that the

table.classname td {

syntax worked as there was no <table> tag at all. Often modules like this don't use the outer tag but just dive right in maybe using <thead> and <tbody> for grouping at most.

Simply specifying like this worked great though

td.classname {
    max-width: 500px;
    text-overflow: initial;
    white-space: wrap;
    word-wrap: break-word;
}

as it directly overrides the <td> and can be used only on the elements you want to change. Maybe in your case use

thead.medium td {
  font-size: 40px; 
}
tbody.small td {
  font-size:25px;
}

for consistent font sizing with a bigger header.

Keep only date part when using pandas.to_datetime

This worked for me on UTC Timestamp (2020-08-19T09:12:57.945888)

for di, i in enumerate(df['YourColumnName']):
    df['YourColumnName'][di] = pd.Timestamp(i)

CSS horizontal centering of a fixed div?

Here's another two-div solution. Tried to keep it concise and not hardcoded. First, the expectable html:

<div id="outer">
  <div id="inner">
    content
  </div>
</div>

The principle behind the following css is to position some side of "outer", then use the fact that it assumes the size of "inner" to relatively shift the latter.

#outer {
  position: fixed;
  left: 50%;          // % of window
}
#inner {
  position: relative;
  left: -50%;         // % of outer (which auto-matches inner width)
}

This approach is similar to Quentin's, but inner can be of variable size.

How do I convert a string to enum in TypeScript?

Given you use typescript: Many of the solutions above might not work or are overly complex.

Situation: The strings are not the same as the enum values (casing differs)

enum Color {
  Green = "green",
  Red = "red"
}

Just use:

const color = "green" as Color

Please note that this does not guarantee a valid enum.

Is it possible to return empty in react render function?

Yes you can, but instead of blank, simply return null if you don't want to render anything from component, like this:

return (null);

Another important point is, inside JSX if you are rendering element conditionally, then in case of condition=false, you can return any of these values false, null, undefined, true. As per DOC:

booleans (true/false), null, and undefined are valid children, they will be Ignored means they simply don’t render.

All these JSX expressions will render to the same thing:

<div />

<div></div>

<div>{false}</div>

<div>{null}</div>

<div>{undefined}</div>

<div>{true}</div>

Example:

Only odd values will get rendered, because for even values we are returning null.

_x000D_
_x000D_
const App = ({ number }) => {_x000D_
  if(number%2) {_x000D_
    return (_x000D_
      <div>_x000D_
        Number: {number}_x000D_
      </div>_x000D_
    )_x000D_
  }_x000D_
  _x000D_
  return (null);           //===> notice here, returning null for even values_x000D_
}_x000D_
_x000D_
const data = [1,2,3,4,5,6];_x000D_
_x000D_
ReactDOM.render(_x000D_
  <div>_x000D_
    {data.map(el => <App key={el} number={el} />)}_x000D_
  </div>,_x000D_
  document.getElementById('app')_x000D_
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<div id='app' />
_x000D_
_x000D_
_x000D_

Border for an Image view in Android?

ImageView in xml file

<ImageView
            android:id="@+id/myImage"
            android:layout_width="100dp"
            android:layout_height="100dp"

            android:padding="1dp"
            android:scaleType="centerCrop"
            android:cropToPadding="true"
            android:background="@drawable/border_image"

            android:src="@drawable/ic_launcher" />

save below code with the name of border_image.xml and it should be in drawable folder

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <gradient
        android:angle="270"
        android:endColor="#ffffff"
        android:startColor="#ffffff" />

    <corners android:radius="0dp" />

    <stroke
        android:width="0.7dp"
        android:color="#b4b4b4" />
</shape>

if you want to give rounded corner to the border of image then you may change a line in border.xml file

<corners android:radius="4dp" />

How do I configure Apache 2 to run Perl CGI scripts?

For those like me who have been groping your way through much-more-than-you-need-to-know-right-now tutorials and Docs, and just want to see the thing working for starters, I found the only thing I had to do was add:

AddHandler cgi-script .pl .cgi

To my configuration file.

http://httpd.apache.org/docs/2.2/mod/mod_mime.html#addhandler

For my situation this works best as I can put my perl script anywhere I want, and just add the .pl or .cgi extension.

Dave Sherohman's answer mentions the AddHandler solution also.

Of course you still must make sure the permissions/ownership on your script are set correctly, especially that the script will be executable. Take note of who the "user" is when run from an http request - eg, www or www-data.

How can I shuffle an array?

Use the modern version of the Fisher–Yates shuffle algorithm:

/**
 * Shuffles array in place.
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

ES2015 (ES6) version

/**
 * Shuffles array in place. ES6 version
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

Note however, that swapping variables with destructuring assignment causes significant performance loss, as of October 2017.

Use

var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);

Implementing prototype

Using Object.defineProperty (method taken from this SO answer) we can also implement this function as a prototype method for arrays, without having it show up in loops such as for (i in arr). The following will allow you to call arr.shuffle() to shuffle the array arr:

Object.defineProperty(Array.prototype, 'shuffle', {
    value: function() {
        for (let i = this.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this[i], this[j]] = [this[j], this[i]];
        }
        return this;
    }
});

Right align and left align text in same HTML table cell

If you want them on separate lines do what Balon said. If you want them on the same lines, do:

<td>
  <div style="float:left;width:50%;">this is left</div>
  <div style="float:right;width:50%;">this is right</div>
</td>

How to merge two sorted arrays into a sorted array?

A minor improvement, but after the main loop, you could use System.arraycopy to copy the tail of either input array when you get to the end of the other. That won't change the O(n) performance characteristics of your solution, though.

insert data from one table to another in mysql

If there is a primary key like "id" you have to exclude it for example my php table has: id, col2,col3,col4 columns. id is primary key so if I run this code:

INSERT INTO php  (SELECT * FROM php);

I probably get this error:

#1062 - Duplicate entry '1' for key 'PRIMARY'

So here is the solution, I excluded "id" key:

INSERT INTO php ( col2,col3,col4)  (SELECT col2,col3,col4 FROM php2);

So my new php table has all php2 table rows anymore.

How to convert UTF-8 byte[] to string?

BitConverter class can be used to convert a byte[] to string.

var convertedString = BitConverter.ToString(byteAttay);

Documentation of BitConverter class can be fount on MSDN

Adding a column to an existing table in a Rails migration

You can also do this .. rails g migration add_column_to_users email:string

then rake db:migrate also add :email attribute in your user controller ;

for more detail check out http://guides.rubyonrails.org/active_record_migrations.html

using sql count in a case statement

select sum(rsp_ind = 0) as `New`,
       sum(rsp_ind = 1) as `Accepted` 
from tb_a

JavaScript closures vs. anonymous functions

According to the closure definition:

A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

You are using closure if you define a function which use a variable which is defined outside of the function. (we call the variable a free variable).
They all use closure(even in the 1st example).

Get domain name

I'm going to add an answer to try to clear up a few things here as there seems to be some confusion. The main issue is that people are asking the wrong question, or at least not being specific enough.

What does a computer's "domain" actually mean?

When we talk about a computer's "domain", there are several things that we might be referring to. What follows is not an exhaustive list, but it covers the most common cases:

  • A user or computer security principal may belong to an Active Directory domain.
  • The network stack's primary DNS search suffix may be referred to as the computer's "domain".
  • A DNS name that resolves to the computer's IP address may be referred to as the computer's "domain".

Which one do I want?

This is highly dependent on what you are trying to do. The original poster of this question was looking for the computer's "Active Directory domain", which probably means they are looking for the domain to which either the computer's security principal or a user's security principal belongs. Generally you want these when you are trying to talk to Active Directory in some way. Note that the current user principal and the current computer principal are not necessarily in the same domain.

Pieter van Ginkel's answer is actually giving you the local network stack's primary DNS suffix (the same thing that's shown in the top section of the output of ipconfig /all). In the 99% case, this is probably the same as the domain to which both the computer's security principal and the currently authenticated user's principal belong - but not necessarily. Generally this is what you want when you are trying to talk to devices on the LAN, regardless of whether or not the devices are anything to do with Active Directory. For many applications, this will still be a "good enough" answer for talking to Active Directory.

The last option, a DNS name, is a lot fuzzier and more ambiguous than the other two. Anywhere between zero and infinity DNS records may resolve to a given IP address - and it's not necessarily even clear which IP address you are interested in. user2031519's answer refers to the value of HTTP_HOST, which is specifically useful when determining how the user resolved your HTTP server in order to send the request you are currently processing. This is almost certainly not what you want if you are trying to do anything with Active Directory.

How do I get them?

Domain of the current user security principal

This one's nice and simple, it's what Tim's answer is giving you.

System.Environment.UserDomainName

Domain of the current computer security principal

This is probably what the OP wanted, for this one we're going to have to ask Active Directory about it.

System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain()

This one will throw a ActiveDirectoryObjectNotFoundException if the local machine is not part of domain, or the domain controller cannot be contacted.

Network stack's primary DNS suffix

This is what Pieter van Ginkel's answer is giving you. It's probably not exactly what you want, but there's a good chance it's good enough for you - if it isn't, you probably already know why.

System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName

DNS name that resolves to the computer's IP address

This one's tricky and there's no single answer to it. If this is what you are after, comment below and I will happily discuss your use-case and help you to work out the best solution (and expand on this answer in the process).

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

Here is specifically what worked for me only when the Excel file being queried was not open and when running the SQL Server Service as me [as a user that has access to the file system]. I see pieces of my answer already given elsewhere, so I apologize for any redundancy, but for the sake of a more succinct answer:

USE [master]
GO

EXEC sp_configure 'Show Advanced Options', 1
RECONFIGURE
GO

EXEC sp_configure 'Ad Hoc Distributed Queries', 1
RECONFIGURE
GO

EXEC sp_MSSet_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
GO

EXEC sp_MSSet_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
GO


SELECT * 
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
                'Excel 12.0;Database=C:\MyExcelFile.xlsx',
                'SELECT * FROM [MyExcelSheetName$]')

Are Git forks actually Git clones?

Apart from the fact that cloning is from server to your machine and forking is making a copy on the server itself, an important difference is that when we clone, we actually get all the branches, labels, etc.

But when we fork, we actually only get the current files in the master branch, nothing other than that. This means we don't get the other branches, etc.

Hence if you have to merge something back to the original repository, it is a inter-repository merge and will definitely need higher privileges.

Fork is not a command in Git; it is just a concept which GitHub implements. Remember Git was designed to work in peer-to-peer environment without the need to synchronize stuff with any master copy. The server is just another peer, but we look at it as a master copy.

How do I remove the old history from a git repository?

Just create a graft of the parent of your new root commit to no parent (or to an empty commit, e.g. the real root commit of your repository). E.g. echo "<NEW-ROOT-SHA1>" > .git/info/grafts

After creating the graft, it takes effect right away; you should be able to look at git log and see that the unwanted old commits have gone away:

$ echo 4a46bc886318679d8b15e05aea40b83ff6c3bd47 > .git/info/grafts
$ git log --decorate | tail --lines=11
commit cb3da2d4d8c3378919844b29e815bfd5fdc0210c
Author: Your Name <[email protected]>
Date:   Fri May 24 14:04:10 2013 +0200

    Another message

commit 4a46bc886318679d8b15e05aea40b83ff6c3bd47 (grafted)
Author: Your Name <[email protected]>
Date:   Thu May 23 22:27:48 2013 +0200

    Some message

If all looks as intended, you can just do a simple git filter-branch -- --all to make it permanent.

BEWARE: after doing the filter-branch step, all commit ids will have changed, so anybody using the old repo must never merge with anyone using the new repo.

How would you do a "not in" query with LINQ?

var secondEmails = (from item in list2
                    select new { Email = item.Email }
                   ).ToList();

var matches = from item in list1
              where !secondEmails.Contains(item.Email)
              select new {Email = item.Email};

Conditional formatting based on another cell's value

Basically all you need to do is add $ as prefix at column letter and row number. Please see image below

enter image description here

Getting Java version at runtime

The simplest way (java.specification.version):

double version = Double.parseDouble(System.getProperty("java.specification.version"));

if (version == 1.5) {
    // 1.5 specific code
} else {
    // ...
}

or something like (java.version):

String[] javaVersionElements = System.getProperty("java.version").split("\\.");

int major = Integer.parseInt(javaVersionElements[1]);

if (major == 5) {
    // 1.5 specific code
} else {
    // ...
}

or if you want to break it all up (java.runtime.version):

String discard, major, minor, update, build;

String[] javaVersionElements = System.getProperty("java.runtime.version").split("\\.|_|-b");

discard = javaVersionElements[0];
major   = javaVersionElements[1];
minor   = javaVersionElements[2];
update  = javaVersionElements[3];
build   = javaVersionElements[4];

Dots in URL causes 404 with ASP.NET mvc and IIS

After some poking around I found that relaxedUrlToFileSystemMapping did not work at all for me, what worked in my case was setting RAMMFAR to true, the same is valid for (.net 4.0 + mvc3) and (.net 4.5 + mvc4).

<system.webserver>
    <modules runAllManagedModulesForAllRequests="true">

Be aware when setting RAMMFAR true Hanselman post about RAMMFAR and performance

Scrolling an iframe with JavaScript?

var $iframe = document.getElementByID('myIfreme');
var childDocument = iframe.contentDocument ? iframe.contentDocument : iframe.contentWindow.document;
 childDocument.documentElement.scrollTop = 0;

Use FontAwesome or Glyphicons with css :before

@keithwyland answer is great. Here's a SCSS mixin:

@mixin font-awesome($content){
    font-family: FontAwesome;
    font-weight: normal;
    font-style: normal;
    display: inline-block;
    text-decoration: inherit;
    content: $content;
}

Usage:

@include font-awesome("\f054");

How do I type a TAB character in PowerShell?

TAB has a specific meaning in PowerShell. It's for command completion. So if you enter "getch" and then type a TAB. It changes what you typed into "GetChildItem" (it corrects the case, even though that's unnecessary).

From your question, it looks like TAB completion and command completion would overload the TAB key. I'm pretty sure the PowerShell designers didn't want that.

Link to a section of a webpage

Hashtags at the end of the URL bring a visitor to the element with the ID: e.g.

http://stackoverflow.com/questions/8424785/link-to-a-section-of-a-webpage#answers 

Would bring you to where the DIV with the ID 'answers' begins. Also, you can use the name attribute in anchor tags, to create the same effect.

Resource

Can two or more people edit an Excel document at the same time?

yes if it is SharePoint 2010 and above by using the Office feature co-authoring

Visual Studio "Could not copy" .... during build

If you're running into this issue using Visual Studio Code (vsCode) and/or you're sticking to terminal commands, the clean command will delete the build files and typically fix the issue described:

dotnet clean

Then, you can return to running:

dotnet build

or

dotnet run

How to view the committed files you have not pushed yet?

git diff HEAD origin/master

Where origin is the remote repository and master is the default branch where you will push. Also, do a git fetch before the diff so that you are not diffing against a stale origin/master.

P.S. I am also new to git, so in case the above is wrong, please rectify.

wget can't download - 404 error

You need to add the referer field in the headers of the HTTP request. With wget, you just need the --header arg :

wget http://www.icerts.com/images/logo.jpg --header "Referer: www.icerts.com"

And the result :

--2011-10-02 02:00:18--  http://www.icerts.com/images/logo.jpg
Résolution de www.icerts.com (www.icerts.com)... 97.74.86.3
Connexion vers www.icerts.com (www.icerts.com)|97.74.86.3|:80...connecté.
requête HTTP transmise, en attente de la réponse...200 OK
Longueur: 6102 (6,0K) [image/jpeg]
Sauvegarde en : «logo.jpg»

"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3

Typical error on Windows because the default user directory is C:\user\<your_user>, so when you want to use this path as an string parameter into a Python function, you get a Unicode error, just because the \u is a Unicode escape. Any character not numeric after this produces an error.

To solve it, just double the backslashes: C:\\user\\<\your_user>...

Error: «Could not load type MvcApplication»

[Extracted from question]

If you are getting this error: "Could not load type MvcApplication", look at the Output path of your project and make sure it is set to 'bin\'. The problem is that the AspNetCompiler cannot find the files if they are not in the default location.

Another side effect of changing the output folder is that you will not be able to debug your code and it comes up with a message saying that the Assembly info cannot be found.

How to convert list of key-value tuples into dictionary?

>>> dict([('A', 1), ('B', 2), ('C', 3)])
{'A': 1, 'C': 3, 'B': 2}

How to modify memory contents using GDB?

As Nikolai has said you can use the gdb 'set' command to change the value of a variable.

You can also use the 'set' command to change memory locations. eg. Expanding on Nikolai's example:

(gdb) l
6       {
7           int i;
8           struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10

(gdb) p &i
$2 = (int *) 0xbfbb0000
(gdb) set *((int *) 0xbfbb0000) = 20
(gdb) p i
$3 = 20

This should work for any valid pointer, and can be cast to any appropriate data type.

Quickest way to convert XML to JSON in Java

The only problem with JSON in Java is that if your XML has a single child, but is an array, it will convert it to an object instead of an array. This can cause problems if you dynamically always convert from XML to JSON, where if your example XML has only one element, you return an object, but if it has 2+, you return an array, which can cause parsing issues for people using the JSON.

Infoscoop's XML2JSON class has a way of tagging elements that are arrays before doing the conversion, so that arrays can be properly mapped, even if there is only one child in the XML.

Here is an example of using it (in a slightly different language, but you can also see how arrays is used from the nodelist2json() method of the XML2JSON link).

Shell script to get the process ID on Linux

If you already know the process then this will be useful:

PID=`ps -eaf | grep <process> | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
echo "killing $PID"
kill -9 $PID
fi

Difference between Grunt, NPM and Bower ( package.json vs bower.json )

Npm and Bower are both dependency management tools. But the main difference between both is npm is used for installing Node js modules but bower js is used for managing front end components like html, css, js etc.

A fact that makes this more confusing is that npm provides some packages which can be used in front-end development as well, like grunt and jshint.

These lines add more meaning

Bower, unlike npm, can have multiple files (e.g. .js, .css, .html, .png, .ttf) which are considered the main file(s). Bower semantically considers these main files, when packaged together, a component.

Edit: Grunt is quite different from Npm and Bower. Grunt is a javascript task runner tool. You can do a lot of things using grunt which you had to do manually otherwise. Highlighting some of the uses of Grunt:

  1. Zipping some files (e.g. zipup plugin)
  2. Linting on js files (jshint)
  3. Compiling less files (grunt-contrib-less)

There are grunt plugins for sass compilation, uglifying your javascript, copy files/folders, minifying javascript etc.

Please Note that grunt plugin is also an npm package.

Question-1

When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json

It really depends where does this package belong to. If it is a node module(like grunt,request) then it will go in package.json otherwise into bower json.

Question-2

When should I ever install packages explicitly like that without adding them to the file that manages dependencies

It does not matter whether you are installing packages explicitly or mentioning the dependency in .json file. Suppose you are in the middle of working on a node project and you need another project, say request, then you have two options:

  • Edit the package.json file and add a dependency on 'request'
  • npm install

OR

  • Use commandline: npm install --save request

--save options adds the dependency to package.json file as well. If you don't specify --save option, it will only download the package but the json file will be unaffected.

You can do this either way, there will not be a substantial difference.

How can I control the speed that bootstrap carousel slides in items?

With Bootstrap 4, just use this CSS:

.carousel .carousel-item {
    transition-duration: 3s;
}

Change 3s to the duration of your choice.

How can I detect keydown or keypress event in angular.js?

You were on the right track with your "ng-keydown" attribute on the input, but you missed a simple step. Just because you put the ng-keydown attribute there, doesn't mean angular knows what to do with it. That's where "directives" come into play. You used the attribute correctly, but you now need to write a directive that will tell angular what to do when it sees that attribute on an html element.

The following is an example of how you would do that. We'll rename the directive from ng-keydown to on-keydown (to avoid breaking the "best practice" found here):

var mod = angular.module('mydirectives');
mod.directive('onKeydown', function() {
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
             // this next line will convert the string
             // function name into an actual function
             var functionToCall = scope.$eval(attrs.ngKeydown);
             elem.on('keydown', function(e){
                  // on the keydown event, call my function
                  // and pass it the keycode of the key
                  // that was pressed
                  // ex: if ENTER was pressed, e.which == 13
                  functionToCall(e.which);
             });
        }
    };
});

The directive simple tells angular that when it sees an HTML attribute called "ng-keydown", it should listen to the element that has that attribute and call whatever function is passed to it. In the html you would have the following:

<input type="text" on-keydown="onKeydown">

And then in your controller (just like you already had), you would add a function to your controller's scope that is called "onKeydown", like so:

$scope.onKeydown = function(keycode){
    // do something with the keycode
}

Hopefully that helps either you or someone else who wants to know

jquery datatables hide column

You can hide columns by this command:

fnSetColumnVis( 1, false );

Where first parameter is index of column and second parameter is visibility.

Via: http://www.datatables.net/api - function fnSetColumnVis

Sound alarm when code finishes

Why use python at all? You might forget to remove it and check it into a repository. Just run your python command with && and another command to run to do the alerting.

python myscript.py && 
    notify-send 'Alert' 'Your task is complete' && 
    paplay /usr/share/sounds/freedesktop/stereo/suspend-error.oga

or drop a function into your .bashrc. I use apython here but you could override 'python'

function apython() {
    /usr/bin/python $*
    notify-send 'Alert' "python $* is complete"
    paplay /usr/share/sounds/freedesktop/stereo/suspend-error.oga
}

How to prevent default event handling in an onclick method?

It would be too tedious to alter function usages in all html pages to return false.

So here is a tested solution that patches only the function itself:

function callmymethod(myVal) {
    // doing custom things with myVal

    // cancel default event action
    var event = window.event || callmymethod.caller.arguments[0];
    event.preventDefault ? event.preventDefault() : (event.returnValue = false);

    return false;
}    

This correctly prevents IE6, IE11 and latest Chrome from visiting href="#" after onclick event handler completes.

Credits:

The endpoint reference (EPR) for the Operation not found is

I had this same problem using curl to send a soap request. Solved it by adding "content-type: text/xml" to the http header.

I hope this helps someone.

Spring cron expression for every after 30 minutes

Graphically, the cron syntax for Quarz is (source):

+-------------------- second (0 - 59)
|  +----------------- minute (0 - 59)
|  |  +-------------- hour (0 - 23)
|  |  |  +----------- day of month (1 - 31)
|  |  |  |  +-------- month (1 - 12)
|  |  |  |  |  +----- day of week (0 - 6) (Sunday=0 or 7)
|  |  |  |  |  |  +-- year [optional]
|  |  |  |  |  |  |
*  *  *  *  *  *  * command to be executed 

So if you want to run a command every 30 minutes you can say either of these:

0 0/30 * * * * ?
0 0,30 * * * * ?

You can check crontab expressions using either of these:

  • crontab.guru — (disclaimer: I am not related to that page at all, only that I find it very useful). This page uses UNIX style of cron that does not have seconds in it, while Spring does as the first field.
  • Cron Expression Generator & Explainer - Quartz — cron formatter, allowing seconds also.

Retrieving data from a POST method in ASP.NET

The data from the request (content, inputs, files, querystring values) is all on this object HttpContext.Current.Request
To read the posted content

StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream);
string requestFromPost = reader.ReadToEnd();

To navigate through the all inputs

foreach (string key in HttpContext.Current.Request.Form.AllKeys)
{
   string value = HttpContext.Current.Request.Form[key];
}

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

If statements for Checkboxes

In VB.Net

If Check1.checked and Not (Check2.checked) Then

ElseIf Check2.Checked and not Check1.Checked then

End If

How do I print the content of a .txt file in Python?

How to read and print the content of a txt file

Assume you got a file called file.txt that you want to read in a program and the content is this:

this is the content of the file
with open you can read it and
then with a loop you can print it
on the screen. Using enconding='utf-8'
you avoid some strange convertions of
caracters. With strip(), you avoid printing
an empty line between each (not empty) line

You can read this content: write the following script in notepad:

with open("file.txt", "r", encoding="utf-8") as file:
    for line in file:
        print(line.strip())

save it as readfile.py for example, in the same folder of the txt file.

Then you run it (shift + right click of the mouse and select the prompt from the contextual menu) writing in the prompt:

C:\examples> python readfile.py

You should get this. Play attention to the word, they have to be written just as you see them and to the indentation. It is important in python. Use always the same indentation in each file (4 spaces are good).

output

this is the content of the file
with open you can read it and
then with a loop you can print it
on the screen. Using enconding='utf-8'
you avoid some strange convertions of
caracters. With strip(), you avoid printing
an empty line between each (not empty) line

Missing include "bits/c++config.h" when cross compiling 64 bit program on 32 bit in Ubuntu

On my 64 bit system I noticed that the following directory existed:

/usr/include/c++/4.4/x86_64-linux-gnu/32/bits

It would then make sense that on my 32 bit system that had been setup for 64bit cross compiling there should be a corresponding directory like:

/usr/include/c++/4.4/i686-linux-gnu/64/bits

I double checked and this directory did not exist. Running g++ with the verbose parameter showed that the compiler was actually looking for something in this location:

jesse@shalored:~/projects/test$ g++ -v -m64 main.cpp 
Using built-in specs.
Target: i686-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.4.4-14ubuntu5' --with-bugurl=file:///usr/share/doc/gcc-4.4/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.4 --enable-shared --enable-multiarch --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.4 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-objc-gc --enable-targets=all --disable-werror --with-arch-32=i686 --with-tune=generic --enable-checking=release --build=i686-linux-gnu --host=i686-linux-gnu --target=i686-linux-gnu
Thread model: posix
gcc version 4.4.5 (Ubuntu/Linaro 4.4.4-14ubuntu5) 
COLLECT_GCC_OPTIONS='-v' '-m64' '-shared-libgcc' '-mtune=generic'
 /usr/lib/gcc/i686-linux-gnu/4.4.5/cc1plus -quiet -v -imultilib 64 -D_GNU_SOURCE main.cpp -D_FORTIFY_SOURCE=2 -quiet -dumpbase main.cpp -m64 -mtune=generic -auxbase main -version -fstack-protector -o /tmp/ccMvIfFH.s
ignoring nonexistent directory "/usr/include/c++/4.4/i686-linux-gnu/64"
ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"
ignoring nonexistent directory "/usr/lib/gcc/i686-linux-gnu/4.4.5/../../../../i686-linux-gnu/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/include/c++/4.4
 /usr/include/c++/4.4/backward
 /usr/local/include
 /usr/lib/gcc/i686-linux-gnu/4.4.5/include
 /usr/lib/gcc/i686-linux-gnu/4.4.5/include-fixed
 /usr/include/x86_64-linux-gnu
 /usr/include
End of search list.
GNU C++ (Ubuntu/Linaro 4.4.4-14ubuntu5) version 4.4.5 (i686-linux-gnu)
    compiled by GNU C version 4.4.5, GMP version 4.3.2, MPFR version 3.0.0-p3.
GGC heuristics: --param ggc-min-expand=98 --param ggc-min-heapsize=128197
Compiler executable checksum: 1fe36891f4a5f71e4a498e712867261c
In file included from main.cpp:1:
/usr/include/c++/4.4/iostream:39: fatal error: bits/c++config.h: No such file or directory
compilation terminated.

The error regarding the ignoring nonexistent directory was the clue. Unfortunately, I still don't know what package I need to install to have this directory show up so I just copied the /usr/include/c++/4.4/x86_64-linux-gnu/bits directory from my 64 bit machine to /usr/include/c++/4.4/i686-linux-gnu/64/bits on my 32 machine.

Now compiling with just the -m64 works correctly. The major drawback is that this is still not the correct way to do things and I am guessing the next time Update Manager installs and update to g++ things may break.

Return value of x = os.system(..)

os.system() returns the (encoded) process exit value. 0 means success:

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

The output you see is written to stdout, so your console or terminal, and not returned to the Python caller.

If you wanted to capture stdout, use subprocess.check_output() instead:

x = subprocess.check_output(['whoami'])

Pause Console in C++ program

Which is best way to pause the console in C++ programs?

system("pause"); and getch(); (which comes from the DOS world, IIRC) are both unportable.

Is cin.get() is better to use to pause console?

As the only one portable and standard option, I would say it is, but I personally believe one should not write interactive console programs, i.e. programs which actually pause the console or prompt for input (unless there is a really good reason for that, because that makes shell scripting much harder). Console programs should interact with the user via command line arguments (or at least that kind of interaction should be the default one).

Just in case you need pausing the program for the my-program-is-launched-from-the-IDE-and-immediately-closed-but-I-don't-have-enough-time-to-see-the-result reason — don't do that. Just configure your IDE or launch console programs right from the console.

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

I resolved this by adding @Transactional to the base/generic Hibernate DAO implementation class (the parent class which implements the saveOrUpdate() method inherited by the DAO I use in the main program), i.e. the @Transactional needs to be specified on the actual class which implements the method. My assumption was instead that if I declared @Transactional on the child class then it included all of the methods that were inherited by the child class. However it seems that the @Transactional annotation only applies to methods implemented within a class and not to methods inherited by a class.

best way to get folder and file list in Javascript

In my project I use this function for getting huge amount of files. It's pretty fast (put require("FS") out to make it even faster):

var _getAllFilesFromFolder = function(dir) {

    var filesystem = require("fs");
    var results = [];

    filesystem.readdirSync(dir).forEach(function(file) {

        file = dir+'/'+file;
        var stat = filesystem.statSync(file);

        if (stat && stat.isDirectory()) {
            results = results.concat(_getAllFilesFromFolder(file))
        } else results.push(file);

    });

    return results;

};

usage is clear:

_getAllFilesFromFolder(__dirname + "folder");

Get the current year in JavaScript

Create a new Date() object and call getFullYear():

new Date().getFullYear()
// returns the current year

Hijacking the accepted answer to provide some basic example context like a footer that always shows the current year:

<footer>
    &copy; <span id="year"></span>
</footer>

Somewhere else executed after the HTML above has been loaded:

<script>
    document.getElementById("year").innerHTML = new Date().getFullYear();
</script>

_x000D_
_x000D_
document.getElementById("year").innerHTML = new Date().getFullYear();
_x000D_
footer {_x000D_
  text-align: center;_x000D_
  font-family: sans-serif;_x000D_
}
_x000D_
<footer>_x000D_
    &copy; <span id="year">2018</span> by FooBar_x000D_
</footer>
_x000D_
_x000D_
_x000D_

Set cookies for cross origin requests

Pim's answer is very helpful. In my case, I have to use

Expires / Max-Age: "Session"

If it is a dateTime, even it is not expired, it still won't send the cookie to the backend:

Expires / Max-Age: "Thu, 21 May 2020 09:00:34 GMT"

Hope it is helpful for future people who may meet same issue.

How can I create an MSI setup?

Look for Windows Installer XML (WiX)

How can I delete Docker's images?

To delete some Docker image you must execute the following command:

$ docker rmi <docker_image_id>

So, to delete all Docker images you can execute the following command:

$ docker rmi $(docker images -q)

Now, if you want delete all Docker images (including images that are in use), you can add the flag -f, for example:

$ docker rmi -f $(docker images -q)

When does System.getProperty("java.io.tmpdir") return "c:\temp"

In MS Windows the temporary directory is set by the environment variable TEMP. In XP, the temporary directory was set per-user as Local Settings\Temp.

If you change your TEMP environment variable to C:\temp, then you get the same when you run :

System.out.println(System.getProperty("java.io.tmpdir"));

How do I find the PublicKeyToken for a particular dll?

Using sn.exe utility:

sn -T YourAssembly.dll

or loading the assembly in Reflector.

Could not find method compile() for arguments Gradle

Make sure that you are editing the correct build.gradle file. I received this error when editing android/build.gradle rather than android/app/build.gradle.

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

For users of SQL 2000, the actual command that will provide this information is:

select c.text
from sysobjects     o
join syscomments    c on c.id = o.id
where o.name = '<view_name_here>'
  and o.type      = 'V'

Spring not autowiring in unit tests with JUnit

Missing Context file location in configuration can cause this, one approach to solve this:

  • Specifying Context file location in ContextConfiguration

like:

@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })

More details

@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })
public class UserServiceTest extends AbstractJUnit4SpringContextTests {}

Reference:Thanks to @Xstian

Check whether specific radio button is checked

$("input[@name='<%=test2.ClientID%>']:checked");

use this and here ClientID fetch random id created by .net.

Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

NSLog(@"%@",CGRectCreateDictionaryRepresentation(rect));

Passing parameters in Javascript onClick event

This happens because the i propagates up the scope once the function is invoked. You can avoid this issue using a closure.

for (var i = 0; i < 10; i++) {
   var link = document.createElement('a');
   link.setAttribute('href', '#');
   link.innerHTML = i + '';
   link.onclick = (function() {
      var currentI = i;
      return function() { 
          onClickLink(currentI + '');
      }
   })();
   div.appendChild(link);
   div.appendChild(document.createElement('BR'));
}

Or if you want more concise syntax, I suggest you use Nick Craver's solution.

How to log out user from web site using BASIC authentication?

Sending https://invalid_login@hostname works fine everywhere except Safari on Mac (well, not checked Edge but should work there too).

Logout doesn't work in Safari when a user selects 'remember password' in the HTTP Basic Authentication popup. In this case the password is stored in Keychain Access (Finder > Applications > Utilities > Keychain Access (or CMD+SPACE and type "Keychain Access")). Sending https://invalid_login@hostname doesn't affect Keychain Access, so with this checkbox it is not possible to logout on Safari on Mac. At least it is how it works for me.

MacOS Mojave (10.14.6), Safari 12.1.2.

The code below works fine for me in Firefox (73), Chrome (80) and Safari (12). When a user navigates to a logout page the code is executed and drops the credentials.

    //It should return 401, necessary for Safari only
    const logoutUrl = 'https://example.com/logout'; 
    const xmlHttp = new XMLHttpRequest();
    xmlHttp.open('POST', logoutUrl, true, 'logout');
    xmlHttp.send();

Also for some reason Safari doesn't save credentials in the HTTP Basic Authentication popup even when the 'remember password' is selected. The other browsers do this correctly.

How can I mimic the bottom sheet from the Maps app?

Maybe you can try my answer https://github.com/AnYuan/AYPannel, inspired by Pulley. Smooth transition from moving the drawer to scrolling the list. I added a pan gesture on the container scroll view, and set shouldRecognizeSimultaneouslyWithGestureRecognizer to return YES. More detail in my github link above. Wish to help.

Is there a way to specify a default property value in Spring XML?

http://thiamteck.blogspot.com/2008/04/spring-propertyplaceholderconfigurer.html points out that "local properties" defined on the bean itself will be considered defaults to be overridden by values read from files:

<bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  <property name="location"><value>my_config.properties</value></property>  
  <property name="properties">  
    <props>  
      <prop key="entry.1">123</prop>  
    </props>  
  </property>  
</bean> 

How to format LocalDate to string?

Could be short as:

LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));

Powershell: How can I stop errors from being displayed in a script?

Windows PowerShell provides two mechanisms for reporting errors: one mechanism for terminating errors and another mechanism for non-terminating errors.

Internal CmdLets code can call a ThrowTerminatingError method when an error occurs that does not or should not allow the cmdlet to continue to process its input objects. The script writter can them use exception to catch these error.

EX :

try
{
  Your database code
}
catch
{
  Error reporting/logging
}

Internal CmdLets code can call a WriteError method to report non-terminating errors when the cmdlet can continue processing the input objects. The script writer can then use -ErrorAction option to hide the messages, or use the $ErrorActionPreference to setup the entire script behaviour.

Reading InputStream as UTF-8

Solved my own problem. This line:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

needs to be:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));

or since Java 7:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));

Failed to find Build Tools revision 23.0.1

I had this error:

Failed to find Build Tools revision 23.0.2

When you got updated/installed:

  1. Android SDK Build Tools
  2. Android SDK Tools

Change version number in build.gradle

FROM

buildToolsVersion "23.0.2"

TO

buildToolsVersion "25.0.2"

How to find what Build Tools version you have

find: missing argument to -exec

Also, if anyone else has the "find: missing argument to -exec" this might help:

In some shells you don't need to do the escaping, i.e. you don't need the "\" in front of the ";".

find <file path> -name "myFile.*" -exec rm - f {} ;

Equivalent of "continue" in Ruby

Ruby has two other loop/iteration control keywords: redo and retry. Read more about them, and the difference between them, at Ruby QuickTips.

Find index of last occurrence of a sub-string using T-SQL

You are limited to small list of functions for text data type.

All I can suggest is start with PATINDEX, but work backwards from DATALENGTH-1, DATALENGTH-2, DATALENGTH-3 etc until you get a result or end up at zero (DATALENGTH-DATALENGTH)

This really is something that SQL Server 2000 simply can't handle.

Edit for other answers : REVERSE is not on the list of functions that can be used with text data in SQL Server 2000

PHP How to find the time elapsed since a date time?

Had to do this recently - hope this helps someone. It doesn't cater for every possibility, but met my needs for a project.

https://github.com/duncanheron/twitter_date_format

https://github.com/duncanheron/twitter_date_format/blob/master/twitter_date_format.php

Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")

The best thing you can do is leave out the action attribute altogether. If you leave it out, the form will be submitted to the document's address, i.e. the same page.

It is also possible to leave it empty, and any browser implementing HTML's form submission algorithm will treat it as equivalent to the document's address, which it does mainly because that's how browsers currently work:

8. Let action be the submitter element's action.

9. If action is the empty string, let action be the document's address.

Note: This step is a willful violation of RFC 3986, which would require base URL processing here. This violation is motivated by a desire for compatibility with legacy content. [RFC3986]

This definitely works in all current browsers, but may not work as expected in some older browsers ("browsers do weird things with an empty action="" attribute"), which is why the spec strongly discourages authors from leaving it empty:

The action and formaction content attributes, if specified, must have a value that is a valid non-empty URL potentially surrounded by spaces.

Execute specified function every X seconds

Use System.Windows.Forms.Timer.

private Timer timer1; 
public void InitTimer()
{
    timer1 = new Timer();
    timer1.Tick += new EventHandler(timer1_Tick);
    timer1.Interval = 2000; // in miliseconds
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    isonline();
}

You can call InitTimer() in Form1_Load().

Can you set a border opacity in CSS?

It's easy, use a solid shadow with 0 offset:

#foo {
  border-radius: 1px;
  box-shadow: 0px 0px 0px 8px rgba(0,0,0,0.3);       
}

Also, if you set a border-radius to the element, it gives you pretty rounded borders

jsFiddle Demo

enter image description here

Access parent's parent from javascript object

In this case, you could use life to reference the parent object. Or you could store a reference to life in the users object. There can't be a fixed parent available to you in the language, because users is just a reference to an object, and there could be other references...

var death = { residents : life.users };
life.users.smallFurryCreaturesFromAlphaCentauri = { exist : function() {} };
// death.residents.smallFurryCreaturesFromAlphaCentauri now exists
//  - because life.users references the same object as death.residents!

You might find it helpful to use something like this:

function addChild(ob, childName, childOb)
{
   ob[childName] = childOb;
   childOb.parent = ob;
}

var life= {
        mameAndDestroy : function(group){ },
        kiss : function(group){ }
};

addChild(life, 'users', {
   guys : function(){ this.parent.mameAndDestroy(this.girls); },
   girls : function(){ this.parent.kiss(this.boys); },
   });

// life.users.parent now exists and points to life

What to use now Google News API is deprecated?

I'm running into the same issue with one of my own apps. So far I've found the only non-deprecated way to access Google News data is through their RSS feeds. They have a feed for each section and also a useful search function. However, these are only for noncommercial use.

As for viable alternatives I'll be trying out these two services: Feedzilla, Daylife

std::string to float or double

The C++ 11 way is to use std::stod and std::to_string. Both work in Visual Studio 11.

Replace values in list using Python

>>> L = range (11)
>>> [ x if x%2 == 1 else None for x in L ]
[None, 1, None, 3, None, 5, None, 7, None, 9, None]

JavaScript private methods

Using self invoking function and call

JavaScript uses prototypes and does't have classes (or methods for that matter) like Object Oriented languages. A JavaScript developer need to think in JavaScript.

Wikipedia quote:

Unlike many object-oriented languages, there is no distinction between a function definition and a method definition. Rather, the distinction occurs during function calling; when a function is called as a method of an object, the function's local this keyword is bound to that object for that invocation.

Solution using a self invoking function and the call function to call the private "method" :

var MyObject = (function () {
    
  // Constructor
  function MyObject(foo) {
    this._foo = foo;
  }

  function privateFun(prefix) {
    return prefix + this._foo;
  }
    
  MyObject.prototype.publicFun = function () {
    return privateFun.call(this, ">>");
  }
    
  return MyObject;

}());
var myObject = new MyObject("bar");
myObject.publicFun();      // Returns ">>bar"
myObject.privateFun(">>"); // ReferenceError: private is not defined

The call function allows us to call the private function with the appropriate context (this).

Simpler with Node.js

If you are using Node.js, you don't need the IIFE because you can take advantage of the module loading system:

function MyObject(foo) {
  this._foo = foo;
}
    
function privateFun(prefix) {
  return prefix + this._foo;
}

MyObject.prototype.publicFun = function () {
  return privateFun.call(this, ">>");
}
    
module.exports= MyObject;

Load the file:

var MyObject = require("./MyObject");
    
var myObject = new MyObject("bar");
myObject.publicFun();      // Returns ">>bar"
myObject.privateFun(">>"); // ReferenceError: private is not defined

(new!) Native private methods in future JavaScript versions

TC39 private methods and getter/setters for JavaScript classes proposal is stage 3. That means any time soon, JavaScript will implement private methods natively!

Note that JavaScript private class fields already exists in modern JavaScript versions.

Here is an example of how it is used:

class MyObject {

  // Private field
  #foo;
    
  constructor(foo) {
    this.#foo = foo;
  }

  #privateFun(prefix) {
   return prefix + this.#foo;
  }
    
  publicFun() {
    return this.#privateFun(">>");
  }

}

You may need a JavaScript transpiler/compiler to run this code on old JavaScript engines.

PS: If you wonder why the # prefix, read this.

(deprecated) ES7 with the Bind Operator

Warning: The bind operator TC39 proposition is near dead https://github.com/tc39/proposal-bind-operator/issues/53#issuecomment-374271822

The bind operator :: is an ECMAScript proposal and is implemented in Babel (stage 0).

export default class MyObject {
  constructor (foo) {
    this._foo = foo;
  }

  publicFun () {
    return this::privateFun(">>");
  }
}

function privateFun (prefix) {
  return prefix + this._foo;
}

"Object doesn't support property or method 'find'" in IE

Just for the purpose of mentioning underscore's find method works in IE with no problem.

How to get the clicked link's href with jquery?

Suppose we have three anchor tags like ,

<a  href="ID=1" class="testClick">Test1.</a>
<br />
<a  href="ID=2" class="testClick">Test2.</a>
<br />
<a  href="ID=3" class="testClick">Test3.</a>

now in script

$(".testClick").click(function () {
        var anchorValue= $(this).attr("href");
        alert(anchorValue);
});

use this keyword instead of className (testClick)

ggplot2, change title size

+ theme(plot.title = element_text(size=22))

Here is the full set of things you can change in element_text:

element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
  hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
  color = NULL)

Detect whether current Windows version is 32 bit or 64 bit

Using Windows Powershell, if the following expression returns true, then it's a 64 bit OS:

(([Array](Get-WmiObject -Class Win32_Processor | Select-Object AddressWidth))[0].AddressWidth -eq 64)

This was taken and modified from: http://depsharee.blogspot.com/2011/06/how-do-detect-operating-system.html (Method #3). I've tested this on Win7 64 bit (in both 32 and 64 bit PowerShell sessions), and XP 32 bit.

How to solve maven 2.6 resource plugin dependency?

Step 1 : Check the proxy configured in eclipse is correct or not ? (Window->Preferences->General->Network Connections).

Step 2 : Right Click on Project-> Go to Maven -> Update the project

Step 3: Run as Maven Install.

==== By Following these steps, i am able to solve this error.

What is a CSRF token? What is its importance and how does it work?

Cross-Site Request Forgery (CSRF) in simple words

  • Assume you are currently logged into your online banking at www.mybank.com
  • Assume a money transfer from mybank.com will result in a request of (conceptually) the form http://www.mybank.com/transfer?to=<SomeAccountnumber>;amount=<SomeAmount>. (Your account number is not needed, because it is implied by your login.)
  • You visit www.cute-cat-pictures.org, not knowing that it is a malicious site.
  • If the owner of that site knows the form of the above request (easy!) and correctly guesses you are logged into mybank.com (requires some luck!), they could include on their page a request like http://www.mybank.com/transfer?to=123456;amount=10000 (where 123456 is the number of their Cayman Islands account and 10000 is an amount that you previously thought you were glad to possess).
  • You retrieved that www.cute-cat-pictures.org page, so your browser will make that request.
  • Your bank cannot recognize this origin of the request: Your web browser will send the request along with your www.mybank.com cookie and it will look perfectly legitimate. There goes your money!

This is the world without CSRF tokens.

Now for the better one with CSRF tokens:

  • The transfer request is extended with a third argument: http://www.mybank.com/transfer?to=123456;amount=10000;token=31415926535897932384626433832795028841971.
  • That token is a huge, impossible-to-guess random number that mybank.com will include on their own web page when they serve it to you. It is different each time they serve any page to anybody.
  • The attacker is not able to guess the token, is not able to convince your web browser to surrender it (if the browser works correctly...), and so the attacker will not be able to create a valid request, because requests with the wrong token (or no token) will be refused by www.mybank.com.

Result: You keep your 10000 monetary units. I suggest you donate some of that to Wikipedia.

(Your mileage may vary.)

EDIT from comment worth reading:

It would be worthy to note that script from www.cute-cat-pictures.org normally does not have access to your anti-CSRF token from www.mybank.com because of HTTP access control. This note is important for some people who unreasonably send a header Access-Control-Allow-Origin: * for every website response without knowing what it is for, just because they can't use the API from another website.

TypeError: cannot perform reduce with flexible type

It looks like your 'trainData' is a list of strings:

['-214' '-153' '-58' ..., '36' '191' '-37']

Change your 'trainData' to a numeric type.

 import numpy as np
 np.array(['1','2','3']).astype(np.float)

Converting JavaScript object with numeric keys into array

It's actually very straight forward with jQuery's $.map

var arr = $.map(obj, function(el) { return el });

FIDDLE

and almost as easy without jQuery as well, converting the keys to an array and then mapping back the values with Array.map

var arr = Object.keys(obj).map(function(k) { return obj[k] });

FIDDLE

That's assuming it's already parsed as a javascript object, and isn't actually JSON, which is a string format, in that case a run through JSON.parse would be necessary as well.

In ES2015 there's Object.values to the rescue, which makes this a breeze

var arr = Object.values(obj);

How to serve up a JSON response using Go?

You may use this package renderer, I have written to solve this kind of problem, it's a wrapper to serve JSON, JSONP, XML, HTML etc.

php return 500 error but no error log

If you still have 500 error and no logs you can try to execute from command line:

php -f file.php

it will not work exactly like in a browser (from server) but if there is syntax error in your code, you will see error message in console.

How to retrieve GET parameters from JavaScript

With the window.location object. This code gives you GET without the question mark.

window.location.search.substr(1)

From your example it will return returnurl=%2Fadmin

EDIT: I took the liberty of changing Qwerty's answer, which is really good, and as he pointed I followed exactly what the OP asked:

function findGetParameter(parameterName) {
    var result = null,
        tmp = [];
    location.search
        .substr(1)
        .split("&")
        .forEach(function (item) {
          tmp = item.split("=");
          if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
        });
    return result;
}

I removed the duplicated function execution from his code, replacing it a variable ( tmp ) and also I've added decodeURIComponent, exactly as OP asked. I'm not sure if this may or may not be a security issue.

Or otherwise with plain for loop, which will work even in IE8:

function findGetParameter(parameterName) {
    var result = null,
        tmp = [];
    var items = location.search.substr(1).split("&");
    for (var index = 0; index < items.length; index++) {
        tmp = items[index].split("=");
        if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
    }
    return result;
}

What's the difference between passing by reference vs. passing by value?

Examples:

class Dog 
{ 
public:
    barkAt( const std::string& pOtherDog ); // const reference
    barkAt( std::string pOtherDog ); // value
};

const & is generally best. You don't incur the construction and destruction penalty. If the reference isn't const your interface is suggesting that it will change the passed in data.

Where should my npm modules be installed on Mac OS X?

/usr/local/lib/node_modules is the correct directory for globally installed node modules.

/usr/local/share/npm/lib/node_modules makes no sense to me. One issue here is that you're confused because there are two directories called node_modules:

/usr/local/lib/node_modules
/usr/local/lib/node_modules/npm/node_modules

The latter seems to be node modules that came with Node, e.g., lodash, when the former is Node modules that I installed using npm.

Skip first line(field) in loop using CSV file?

Probably you want something like:

firstline = True
for row in kidfile:
    if firstline:    #skip first line
        firstline = False
        continue
    # parse the line

An other way to achive the same result is calling readline before the loop:

kidfile.readline()   # skip the first line
for row in kidfile:
    #parse the line

How to map calculated properties with JPA and Hibernate

Take a look at Blaze-Persistence Entity Views which works on top of JPA and provides first class DTO support. You can project anything to attributes within Entity Views and it will even reuse existing join nodes for associations if possible.

Here is an example mapping

@EntityView(Order.class)
interface OrderSummary {
  Integer getId();
  @Mapping("SUM(orderPositions.price * orderPositions.amount * orderPositions.tax)")
  BigDecimal getOrderAmount();
  @Mapping("COUNT(orderPositions)")
  Long getItemCount();
}

Fetching this will generate a JPQL/HQL query similar to this

SELECT
  o.id,
  SUM(p.price * p.amount * p.tax),
  COUNT(p.id)
FROM
  Order o
LEFT JOIN
  o.orderPositions p
GROUP BY
  o.id

Here is a blog post about custom subquery providers which might be interesting to you as well: https://blazebit.com/blog/2017/entity-view-mapping-subqueries.html

SyntaxError: Unexpected token o in JSON at position 1

Unexpected 'O' error is thrown when JSON data or String happens to get parsed.

If it's string, it's already stringfied. Parsing ends up with Unexpected 'O' error.

I faced similar( although in different context), I solved the following error by removing JSON Producer.

    @POST
    @Produces({ **MediaType.APPLICATION_JSON**})
    public Response login(@QueryParam("agentID") String agentID , Officer aOffcr ) {
      return Response.status(200).entity("OK").build();

  }

The response contains "OK" string return. The annotation marked as @Produces({ **MediaType.APPLICATION_JSON})** tries to parse the string to JSON format which results in Unexpected 'O'.

Removing @Produces({ MediaType.APPLICATION_JSON}) works fine. Output : OK

Beware: Also, on client side, if you make ajax request and use JSON.parse("OK"), it throws Unexpected token 'O'

O is the first letter of the string

JSON.parse(object) compares with jQuery.parseJSON(object);

JSON.parse('{ "name":"Yergalem", "city":"Dover"}'); --- Works Fine

Spring MVC: Error 400 The request sent by the client was syntactically incorrect

The @RequestParam String action suggests there is a parameter present within the request with the name action which is absent in your form. You must either:

  1. Submit a parameter named value e.g. <input name="action" />
  2. Set the required parameter to false within the @RequestParam e.g. @RequestParam(required=false)

Extracting specific selected columns to new DataFrame as a copy

If you want to have a new data frame then:

import pandas as pd
old = pd.DataFrame({'A' : [4,5], 'B' : [10,20], 'C' : [100,50], 'D' : [-30,-50]})
new=  old[['A', 'C', 'D']]

How do I debug error ECONNRESET in Node.js?

A simple tcp server I had for serving the flash policy file was causing this. I can now catch the error using a handler:

# serving the flash policy file
net = require("net")

net.createServer((socket) =>
  //just added
  socket.on("error", (err) =>
    console.log("Caught flash policy server socket error: ")
    console.log(err.stack)
  )

  socket.write("<?xml version=\"1.0\"?>\n")
  socket.write("<!DOCTYPE cross-domain-policy SYSTEM \"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd\">\n")
  socket.write("<cross-domain-policy>\n")
  socket.write("<allow-access-from domain=\"*\" to-ports=\"*\"/>\n")
  socket.write("</cross-domain-policy>\n")
  socket.end()
).listen(843)

Swift 2: Call can throw, but it is not marked with 'try' and the error is not handled

You have to catch the error just as you're already doing for your save() call and since you're handling multiple errors here, you can try multiple calls sequentially in a single do-catch block, like so:

func deleteAccountDetail() {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()
    request.entity = entityDescription

    do {
        let fetchedEntities = try self.Context!.executeFetchRequest(request) as! [AccountDetail]

        for entity in fetchedEntities {
            self.Context!.deleteObject(entity)
        }

        try self.Context!.save()
    } catch {
        print(error)
    }
}

Or as @bames53 pointed out in the comments below, it is often better practice not to catch the error where it was thrown. You can mark the method as throws then try to call the method. For example:

func deleteAccountDetail() throws {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()

    request.entity = entityDescription

    let fetchedEntities = try Context.executeFetchRequest(request) as! [AccountDetail]

    for entity in fetchedEntities {
        self.Context!.deleteObject(entity)
    }

    try self.Context!.save()
}

Where can I download JSTL jar

You can download JSTL 1.1 here and JSTL 1.2 here.

See also:

How to install Visual C++ Build tools?

I had the same issue too, the problem is exacerbated with the download link now only working for Visual Studio 2017, and installing the package from the download link did nothing for VS2015, although it took up 5gB of space.

I looked everywhere on how to do it with the Nu Get package manager and I couldn't find the solution.

It turns out it's even simpler than that, all you have to do is right-click the project or solution in the Solution Explorer from within Visual Studio, and click "Install Missing Components"

Can I have multiple primary keys in a single table?

(Have been studying these, a lot)

Candidate keys - A minimal column combination required to uniquely identify a table row.
Compound keys - 2 or more columns.

  • Multiple Candidate keys can exist in a table.
    • Primary KEY - Only one of the candidate keys that is chosen by us
    • Alternate keys - All other candidate keys
      • Both Primary Key & Alternate keys can be Compound keys

Sources:
https://en.wikipedia.org/wiki/Superkey
https://en.wikipedia.org/wiki/Candidate_key
https://en.wikipedia.org/wiki/Primary_key
https://en.wikipedia.org/wiki/Compound_key

How to import JsonConvert in C# application?

If you are developing a .Net Core WebApi or WebSite you dont not need to install newtownsoft.json to perform json serialization/deserealization

Just make sure that your controller method returns a JsonResult and call return Json(<objectoToSerialize>); like this example

namespace WebApi.Controllers
{
    [Produces("application/json")]
    [Route("api/Accounts")]
    public class AccountsController : Controller
    {
        // GET: api/Transaction
        [HttpGet]
        public JsonResult Get()
        {
            List<Account> lstAccounts;

            lstAccounts = AccountsFacade.GetAll();

            return Json(lstAccounts);
        }
    }
}

If you are developing a .Net Framework WebApi or WebSite you need to use NuGet to download and install the newtonsoft json package

"Project" -> "Manage NuGet packages" -> "Search for "newtonsoft json". -> click "install".

namespace WebApi.Controllers
{
    [Produces("application/json")]
    [Route("api/Accounts")]
    public class AccountsController : Controller
    {
        // GET: api/Transaction
        [HttpGet]
        public JsonResult Get()
        {
            List<Account> lstAccounts;

            lstAccounts = AccountsFacade.GetAll();

            //This line is different !! 
            return new JsonConvert.SerializeObject(lstAccounts);
        }
    }
}

More details can be found here - https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-2.1

How to get the EXIF data from a file using C#

Here is a link to another similar SO question, which has an answer pointing to this good article on "Reading, writing and photo metadata" in .Net.

Adding local .aar files to Gradle build using "flatDirs" is not working

This solution is working with Android Studio 4.0.1.

Apart from creating a new module as suggested in above solution, you can try this solution.

If you have multiple modules in your application and want to add aar to just one of the module then this solution come handy.

In your root project build.gradle

add

repositories {
mavenCentral()
flatDir {
    dirs 'libs'
}

Then in the module where you want to add the .aar file locally. simply add below lines of code.

dependencies {
api fileTree(include: ['*.aar'], dir: 'libs')
implementation files('libs/<yourAarName>.aar')

}

Happy Coding :)

Angular ng-if="" with multiple arguments

Just to clarify, be aware bracket placement is important!

These can be added to any HTML tags... span, div, table, p, tr, td etc.

AngularJS

ng-if="check1 && !check2" -- AND NOT
ng-if="check1 || check2" -- OR
ng-if="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets

Angular2+

*ngIf="check1 && !check2" -- AND NOT
*ngIf="check1 || check2" -- OR
*ngIf="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets

It's best practice not to do calculations directly within ngIfs, so assign the variables within your component, and do any logic there.

boolean check1 = Your conditional check here...
...

Integer to IP Address - C

#include "stdio.h"

void print_ip(int ip) {
   unsigned char bytes[4];
   int i;
   for(i=0; i<4; i++) {
      bytes[i] = (ip >> i*8) & 0xFF;
   }
   printf("%d.%d.%d.%d\n", bytes[3], bytes[2], bytes[1], bytes[0]);
}

int main() {
   int ip = 0xDEADBEEF;
   print_ip(ip);   
}

AcquireConnection method call to the connection manager <Excel Connection Manager> failed with error code 0xC0202009

I don't think it's 64/32 bit error. My Dev machine and DB server are 32bit. But I could make it work. I had to set Delay Validation property of Data Flow tasks to TRUE.

How to convert a UTF-8 string into Unicode?

What you have seems to be a string incorrectly decoded from another encoding, likely code page 1252, which is US Windows default. Here's how to reverse, assuming no other loss. One loss not immediately apparent is the non-breaking space (U+00A0) at the end of your string that is not displayed. Of course it would be better to read the data source correctly in the first place, but perhaps the data source was stored incorrectly to begin with.

using System;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        string junk = "déjÃ\xa0";  // Bad Unicode string

        // Turn string back to bytes using the original, incorrect encoding.
        byte[] bytes = Encoding.GetEncoding(1252).GetBytes(junk);

        // Use the correct encoding this time to convert back to a string.
        string good = Encoding.UTF8.GetString(bytes);
        Console.WriteLine(good);
    }
}

Result:

déjà

When should I use a table variable vs temporary table in sql server?

I totally agree with Abacus (sorry - don't have enough points to comment).

Also, keep in mind it doesn't necessarily come down to how many records you have, but the size of your records.

For instance, have you considered the performance difference between 1,000 records with 50 columns each vs 100,000 records with only 5 columns each?

Lastly, maybe you're querying/storing more data than you need? Here's a good read on SQL optimization strategies. Limit the amount of data you're pulling, especially if you're not using it all (some SQL programmers do get lazy and just select everything even though they only use a tiny subset). Don't forget the SQL query analyzer may also become your best friend.

Check if at least two out of three booleans are true

return (a==b) ? a : c;

Explanation:

If a==b, then both are true or both are false. If both are true, we have found our two true booleans, and can return true (by returning a). If both are false there cannot be two true booleans even if c is true, so we return false (by returning a). That's the (a==b) ? a part. What about : c ? Well if a==b is false, then exactly one of a or b must be true, so we have found the first true boolean, and the only thing left that matters is if c is also true, so we return c as the answer.

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

I'll try to make you understand with the help of an example. Suppose you had a relational table (STUDENT) with two columns and ID(int) and NAME(String). Now as ORM you would've made an entity class somewhat like as follows:-

package com.kashyap.default;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author vaibhav.kashyap
 *
 */
@Entity
@Table(name = "STUDENT")
public class Student implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -1354919370115428781L;

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name = "NAME")
    private String name;

    public Student(){

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Lets assume table already had entries. Now if somebody asks you add another column of "AGE" (int)

ALTER TABLE STUDENT ADD AGE int NULL

You'll have to set default values as NULL to add another column in a pre-filled table. This makes you add another field in the class. Now the question arises whether you'll be using a primitive data type or non primitive wrapper data type for declaring the field.

@Column(name = "AGE")
private int age;

or

@Column(name = "AGE")
private INTEGER age;

you'll have to declare the field as non primitive wrapper data type because the container will try to map the table with the entity. Hence it wouldn't able to map NULL values (default) if you won't declare field as wrapper & would eventually throw "Null value was assigned to a property of primitive type setter" Exception.

Can a unit test project load the target application's app.config file?

Whether you're using Team System Test or NUnit, the best practice is to create a separate Class Library for your tests. Simply adding an App.config to your Test project will automatically get copied to your bin folder when you compile.

If your code is reliant on specific configuration tests, the very first test I would write validates that the configuration file is available (so that I know I'm not insane) :

<configuration>
   <appSettings>
       <add key="TestValue" value="true" />
   </appSettings>
</configuration>

And the test:

[TestFixture]
public class GeneralFixture
{
     [Test]
     public void VerifyAppDomainHasConfigurationSettings()
     {
          string value = ConfigurationManager.AppSettings["TestValue"];
          Assert.IsFalse(String.IsNullOrEmpty(value), "No App.Config found.");
     }
}

Ideally, you should be writing code such that your configuration objects are passed into your classes. This not only separates you from the configuration file issue, but it also allows you to write tests for different configuration scenarios.

public class MyObject
{
     public void Configure(MyConfigurationObject config)
     {
          _enabled = config.Enabled;
     }

     public string Foo()
     {
         if (_enabled)
         {
             return "foo!";
         }
         return String.Empty;
     }

     private bool _enabled;
}

[TestFixture]
public class MyObjectTestFixture
{
     [Test]
     public void CanInitializeWithProperConfig()
     {
         MyConfigurationObject config = new MyConfigurationObject();
         config.Enabled = true;

         MyObject myObj = new MyObject();
         myObj.Configure(config);

         Assert.AreEqual("foo!", myObj.Foo());
     }
}

How to set time zone of a java.util.Date?

java.util.Calendar is the usual way to handle time zones using just JDK classes. Apache Commons has some further alternatives/utilities that may be helpful. Edit Spong's note reminded me that I've heard really good things about Joda-Time (though I haven't used it myself).

Android SDK Manager Not Installing Components

The Access denied is because Windows doesn't give the default write and modify permission to the files in its install drive viz. c: To resolve this issue I usually use a separate drive or in your case, you need to set the access rights to the specific folder in the options right click -> options > security -> edit enter image description here

WPF User Control Parent

DependencyObject parent = ExVisualTreeHelper.FindVisualParent<UserControl>(this);

LINQ Group By into a Dictionary Object

I cannot comment on @Michael Blackburn, but I guess you got the downvote because the GroupBy is not necessary in this case.

Use it like:

var lookupOfCustomObjects = listOfCustomObjects.ToLookup(o=>o.PropertyName);
var listWithAllCustomObjectsWithPropertyName = lookupOfCustomObjects[propertyName]

Additionally, I've seen this perform way better than when using GroupBy().ToDictionary().

ValueError: unsupported pickle protocol: 3, python2 pickle can not load the file dumped by python 3 pickle?

You should write the pickled data with a lower protocol number in Python 3. Python 3 introduced a new protocol with the number 3 (and uses it as default), so switch back to a value of 2 which can be read by Python 2.

Check the protocolparameter in pickle.dump. Your resulting code will look like this.

pickle.dump(your_object, your_file, protocol=2)

There is no protocolparameter in pickle.load because pickle can determine the protocol from the file.

How to parseInt in Angular.js

<input type="number" string-to-number ng-model="num1">
<input type="number" string-to-number ng-model="num2">

Total: {{num1 + num2}}

and in js :

parseInt($scope.num1) + parseInt($scope.num2)

Navigation Drawer (Google+ vs. YouTube)

There is a great implementation of NavigationDrawer that follows the Google Material Design Guidelines (and compatible down to API 10) - The MaterialDrawer library (link to GitHub). As of time of writing, May 2017, it's actively supported.

It's available in Maven Central repo. Gradle dependency setup:

compile 'com.mikepenz:materialdrawer:5.9.1'

Maven dependency setup:

<dependency>
    <groupId>com.mikepenz</groupId>
    <artifactId>materialdrawer</artifactId>
    <version>5.9.1</version>
</dependency>

enter image description here enter image description here

Use VBA to Clear Immediate Window?

I tested this code based on all the comments above. Seems to work flawlessly. Comments?

Sub ResetImmediate()  
        Debug.Print String(5, "*") & " Hi there mom. " & String(5, "*") & vbTab & "Smile"  
        Application.VBE.Windows("Immediate").SetFocus  
        Application.SendKeys "^g ^a {DEL} {HOME}"  
        DoEvents  
        Debug.Print "Bye Mom!"  
End Sub

Previously used the Debug.Print String(200, chr(10)) which takes advantage of the Buffer overflow limit of 200 lines. Didn't like this method much but it works.

"message failed to fetch from registry" while trying to install any module

The below method worked for me, Kudos to github user : midnightcodr

Make sure You remove any nodejs/npm packages already installed.

sudo apt-get purge nodejs

sudo apt-get purge npm

Now Install Node js using the command below( Thanks to midnightcodr on github)

curl -L https://raw.github.com/midnightcodr/rpi_node_install/master/setup.sh | bash -s 0.10.24

Note that you can invoke node with command node and not nodejs.

Once node is installed , Install npm

sudo apt-get install npm

How to extract numbers from a string and get an array of ints?

Pattern p = Pattern.compile("[0-9]+");
Matcher m = p.matcher(myString);
while (m.find()) {
    int n = Integer.parseInt(m.group());
    // append n to list
}
// convert list to array, etc

You can actually replace [0-9] with \d, but that involves double backslash escaping, which makes it harder to read.

How to get current SIM card number in Android?

You have everything right, but the problem is with getLine1Number() function.

getLine1Number()- this method returns the phone number string for line 1, i.e the MSISDN for a GSM phone. Return null if it is unavailable.

this method works only for few cell phone but not all phones.

So, if you need to perform operations according to the sim(other than calling), then you should use getSimSerialNumber(). It is always unique, valid and it always exists.

How to link an input button to a file select window?

If you want to allow the user to browse for a file, you need to have an input type="file" The closest you could get to your requirement would be to place the input type="file" on the page and hide it. Then, trigger the click event of the input when the button is clicked:

#myFileInput {
    display:none;
}

<input type="file" id="myFileInput" />
<input type="button"
       onclick="document.getElementById('myFileInput').click()" 
       value="Select a File" />

Here's a working fiddle.

Note: I would not recommend this approach. The input type="file" is the mechanism that users are accustomed to using for uploading a file.

ffmpeg usage to encode a video to H264 codec format

I have a Centos 5 system that I wasn't able to get this working on. So I built a new Fedora 17 system (actually a VM in VMware), and followed the steps at the ffmpeg site to build the latest and greatest ffmpeg.

I took some shortcuts - I skipped all the yum erase commands, added freshrpms according to their instructions:

wget http://ftp.freshrpms.net/pub/freshrpms/fedora/linux/9/freshrpms-release/freshrpms-release-1.1-1.fc.noarch.rpm
rpm -ivh rpmfusion-free-release-stable.noarch.rpm

Then I loaded the stuff that was already readily available:

yum install lame libogg libtheora libvorbis lame-devel libtheora-devel

Afterwards, I only built the following from scratch: libvpx vo-aacenc-0.1.2 x264 yasm-1.2.0 ffmpeg

Then this command encoded with no problems (the audio was already in AAC, so I didn't recode it):

ffmpeg -i input.mov -c:v libx264 -preset slow -crf 22 -c:a copy output.mp4

The result looks just as good as the original to me, and is about 1/4 of the size!

Hashing a file in Python

For the correct and efficient computation of the hash value of a file (in Python 3):

  • Open the file in binary mode (i.e. add 'b' to the filemode) to avoid character encoding and line-ending conversion issues.
  • Don't read the complete file into memory, since that is a waste of memory. Instead, sequentially read it block by block and update the hash for each block.
  • Eliminate double buffering, i.e. don't use buffered IO, because we already use an optimal block size.
  • Use readinto() to avoid buffer churning.

Example:

import hashlib

def sha256sum(filename):
    h  = hashlib.sha256()
    b  = bytearray(128*1024)
    mv = memoryview(b)
    with open(filename, 'rb', buffering=0) as f:
        for n in iter(lambda : f.readinto(mv), 0):
            h.update(mv[:n])
    return h.hexdigest()

Customizing the template within a Directive

The above answers unfortunately don't quite work. In particular, the compile stage does not have access to scope, so you can't customize the field based on dynamic attributes. Using the linking stage seems to offer the most flexibility (in terms of asynchronously creating dom, etc.) The below approach addresses that:

<!-- Usage: -->
<form>
  <form-field ng-model="formModel[field.attr]" field="field" ng-repeat="field in fields">
</form>
// directive
angular.module('app')
.directive('formField', function($compile, $parse) {
  return { 
    restrict: 'E', 
    compile: function(element, attrs) {
      var fieldGetter = $parse(attrs.field);

      return function (scope, element, attrs) {
        var template, field, id;
        field = fieldGetter(scope);
        template = '..your dom structure here...'
        element.replaceWith($compile(template)(scope));
      }
    }
  }
})

I've created a gist with more complete code and a writeup of the approach.

Correlation heatmap

Another alternative is to use the heatmap function in seaborn to plot the covariance. This example uses the Auto data set from the ISLR package in R (the same as in the example you showed).

import pandas.rpy.common as com
import seaborn as sns
%matplotlib inline

# load the R package ISLR
infert = com.importr("ISLR")

# load the Auto dataset
auto_df = com.load_data('Auto')

# calculate the correlation matrix
corr = auto_df.corr()

# plot the heatmap
sns.heatmap(corr, 
        xticklabels=corr.columns,
        yticklabels=corr.columns)

enter image description here

If you wanted to be even more fancy, you can use Pandas Style, for example:

cmap = cmap=sns.diverging_palette(5, 250, as_cmap=True)

def magnify():
    return [dict(selector="th",
                 props=[("font-size", "7pt")]),
            dict(selector="td",
                 props=[('padding', "0em 0em")]),
            dict(selector="th:hover",
                 props=[("font-size", "12pt")]),
            dict(selector="tr:hover td:hover",
                 props=[('max-width', '200px'),
                        ('font-size', '12pt')])
]

corr.style.background_gradient(cmap, axis=1)\
    .set_properties(**{'max-width': '80px', 'font-size': '10pt'})\
    .set_caption("Hover to magify")\
    .set_precision(2)\
    .set_table_styles(magnify())

enter image description here

Why do I need to configure the SQL dialect of a data source?

Short answer

"The irony of JDBC is that, although the programming interfaces are portable, the SQL language is not. Despite the many attempts to standardize it, it is still rare to write SQL of any complexity that will run unchanged on two major database platforms. Even where the SQL dialects are similar, each database performs differently depending on the structure of the query, necessitating vendor-specific tuning in most cases."

..stolen from Pro JPA 2 Mastering the Java Persistence API, chapter 1, page 9

So, we might think of JDBC as the ultimate specification that abstracts away everything related to databases, but it isn't.

A quote from the JDBC specification, chapter 4.4, page 20:

The driver layer may mask differences between standard SQL:2003 syntax and the native dialect supported by the data source.

May is no guarantee that the driver will, and therefore we should provide the dialect in order to have a working application. In a best-case scenario, the application will work but might not run as effectively as it could if the persistence provider knew which dialect to use. In the case of Hibernate he will refuse to deploy your application unless you feed him the dialect.

What about JPQL then?

The JDBC specification does not mention the word JPQL. JDBC is a standardized way of database access. Go read this JavaDoc and you will find that once the application can access the database, what must be fed into the JDBC compliant driver is vanilla = undecorated SQL.

It is worth noting that JPQL is a query language, not a data definition language (DDL). So even if we could feed the JDBC driver with JPQL, that would be of no use for the persistence provider during the phase of parsing the persistence.xml file and setting up tables.

Closer look at the property

For your reference, here is an example for Hibernate and EclipseLink on how to specify a Java DB dialect in the persistence.xml file:

<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyTenSevenDialect"/>
<property name="eclipselink.target-database" value="JavaDB"/>

Is the property mandatory?

In theory, the property has not been standardized and the JPA 2.1 specification says not a word about SQL dialects. So we're out of luck and must turn to vendor specific empirical studies and documentation thereof.

Hibernate refuse to accept a deployment archive that hasn't specified the property rendering the archive undeployable. Hibernate documentation says:

Always set the hibernate.dialect property to the correct org.hibernate.dialect.Dialect subclass for your database.

So that is pretty clear. Do note that the dialects listed in the documentation are specifically targeting one or the other vendor. There is no "generic" dialect or anything like that. Given then that the property is an absolute requirement for a successful deployment, you would expect that the documentation of the WildFly application server which bundles Hibernate should say something, but it doesn't.

EclipseLink on the other hand is a bit more forgiving. If you don't provide the property, the deployment deploys (without warning too). EclipseLink documentation says:

Use the eclipselink.target-database property to specify the database to use, controlling custom operations and SQL generation for the specified database.

The talk is about "custom operations and SQL generation", meaning it is bit vague if you ask me. But one thing is clear: They don't say that the property is mandatory. Also note that one of the available values is "Database" which represent "a generic database" target. Hmm, what "dialect" would that be? SQL 2.0?? But then again, the property is called "target-database" and not "dialect" so maybe "Database" translates to no SQL at all lol. Moving on to the GlassFish server which bundles EclipseLink. Documentation (page "6-3") says:

You can specify the optional eclipselink.target-database property to guarantee that the database type is correct.

So GlassFish argues that the property is "optional" and the value added is a "guarantee" that I am actually using Java DB - in case I didn't know.

Conclusion

Copy-paste whatever you can find on google and pray to God.

What is WEB-INF used for in a Java EE web application?

The Servlet 2.4 specification says this about WEB-INF (page 70):

A special directory exists within the application hierarchy named WEB-INF. This directory contains all things related to the application that aren’t in the document root of the application. The WEB-INF node is not part of the public document tree of the application. No file contained in the WEB-INF directory may be served directly to a client by the container. However, the contents of the WEB-INF directory are visible to servlet code using the getResource and getResourceAsStream method calls on the ServletContext, and may be exposed using the RequestDispatcher calls.

This means that WEB-INF resources are accessible to the resource loader of your Web-Application and not directly visible for the public.

This is why a lot of projects put their resources like JSP files, JARs/libraries and their own class files or property files or any other sensitive information in the WEB-INF folder. Otherwise they would be accessible by using a simple static URL (usefull to load CSS or Javascript for instance).

Your JSP files can be anywhere though from a technical perspective. For instance in Spring you can configure them to be in WEB-INF explicitly:

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    p:prefix="/WEB-INF/jsp/" 
    p:suffix=".jsp" >
</bean>

The WEB-INF/classes and WEB-INF/lib folders mentioned in Wikipedia's WAR files article are examples of folders required by the Servlet specification at runtime.

It is important to make the difference between the structure of a project and the structure of the resulting WAR file.

The structure of the project will in some cases partially reflect the structure of the WAR file (for static resources such as JSP files or HTML and JavaScript files, but this is not always the case.

The transition from the project structure into the resulting WAR file is done by a build process.

While you are usually free to design your own build process, nowadays most people will use a standardized approach such as Apache Maven. Among other things Maven defines defaults for which resources in the project structure map to what resources in the resulting artifact (the resulting artifact is the WAR file in this case). In some cases the mapping consists of a plain copy process in other cases the mapping process includes a transformation, such as filtering or compiling and others.

One example: The WEB-INF/classes folder will later contain all compiled java classes and resources (src/main/java and src/main/resources) that need to be loaded by the Classloader to start the application.

Another example: The WEB-INF/lib folder will later contain all jar files needed by the application. In a maven project the dependencies are managed for you and maven automatically copies the needed jar files to the WEB-INF/lib folder for you. That explains why you don't have a lib folder in a maven project.

CSS: Set a background color which is 50% of the width of the window

if you want to use linear-gradient with 50% of height:

background: linear-gradient(to bottom, red 0%, blue 100%) no-repeat;
background-size: calc(100%) calc(50%);
background-position: top;

Remove spaces from a string in VB.NET

2015: Newer LINQ & lambda.

  1. As this is an old Q (and Answer), just thought to update it with newer 2015 methods.
  2. The original "space" can refer to non-space whitespace (ie, tab, newline, paragraph separator, line feed, carriage return, etc, etc).
  3. Also, Trim() only remove the spaces from the front/back of the string, it does not remove spaces inside the string; eg: " Leading and Trailing Spaces " will become "Leading and Trailing Spaces", but the spaces inside are still present.

Function RemoveWhitespace(fullString As String) As String
    Return New String(fullString.Where(Function(x) Not Char.IsWhiteSpace(x)).ToArray())
End Function

This will remove ALL (white)-space, leading, trailing and within the string.

Programmatically saving image to Django ImageField

This is might not be the answer you are looking for. but you can use charfield to store the path of the file instead of ImageFile. In that way you can programmatically associate uploaded image to field without recreating the file.

How to debug Angular JavaScript Code

Despite the question is answered, it could be interesting to take a look at ng-inspector

"while :" vs. "while true"

The colon is a built-in command that does nothing, but returns 0 (success). Thus, it's shorter (and faster) than calling an actual command to do the same thing.

Cannot add a project to a Tomcat server in Eclipse

  1. Right click on the project name in the Package Explorer view.
  2. Select Properties
  3. Select Project Facets
  4. Click on the Runtimes tab
  5. Check Server
  6. Click on OK

And now:

  1. Right click on the server name in the Servers view
  2. Click on Add and Remove...
  3. Move resources to the right column