Programs & Examples On #Fault tolerance

Fault tolerance refers to a system's capability to isolate, compensate for and recover from failure with minimal impact to the end user. When using this tag - include tags indicating the system and/or technology you are working with (as additional support meta-data).

Compiling an application for use in highly radioactive environments

I've really read a lot of great answers!

Here is my 2 cent: build a statistical model of the memory/register abnormality, by writing a software to check the memory or to perform frequent register comparisons. Further, create an emulator, in the style of a virtual machine where you can experiment with the issue. I guess if you vary junction size, clock frequency, vendor, casing, etc would observe a different behavior.

Even our desktop PC memory has a certain rate of failure, which however doesn't impair the day to day work.

Eclipse CDT: no rule to make target all

I got this same error after renaming and moving around source files. None of the proposed solutions worked for me and I tracked the error to be the meta-files under Debug directory not being updated. Deleting the entire Debug directory and re-build the project solved the problem for me.

JavaScript: Check if mouse button down?

Well, you can't check if it's down after the event, but you can check if it's Up... If it's up.. it means that no longer is down :P lol

So the user presses the button down (onMouseDown event) ... and after that, you check if is up (onMouseUp). While it's not up, you can do what you need.

Add views in UIStackView programmatically

For the accepted answer when you try to hide any view inside stack view, the constraint works not correct.

Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<NSLayoutConstraint:0x618000086e50 UIView:0x7fc11c4051c0.height == 120   (active)>",
    "<NSLayoutConstraint:0x610000084fb0 'UISV-hiding' UIView:0x7fc11c4051c0.height == 0   (active)>"
)

Reason is when hide the view in stackView it will set the height to 0 to animate it.

Solution change the constraint priority as below.

import UIKit

class ViewController: UIViewController {

    let stackView = UIStackView()
    let a = UIView()
    let b = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()

        a.backgroundColor = UIColor.red
        a.widthAnchor.constraint(equalToConstant: 200).isActive = true
        let aHeight = a.heightAnchor.constraint(equalToConstant: 120)
        aHeight.isActive = true
        aHeight.priority = 999

        let bHeight = b.heightAnchor.constraint(equalToConstant: 120)
        bHeight.isActive = true
        bHeight.priority = 999
        b.backgroundColor = UIColor.green
        b.widthAnchor.constraint(equalToConstant: 200).isActive = true

        view.addSubview(stackView)
        stackView.backgroundColor = UIColor.blue
        stackView.addArrangedSubview(a)
        stackView.addArrangedSubview(b)
        stackView.axis = .vertical
        stackView.distribution = .equalSpacing
        stackView.translatesAutoresizingMaskIntoConstraints = false
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // Just add a button in xib file or storyboard and add connect this action.
    @IBAction func test(_ sender: Any) {
        a.isHidden = !a.isHidden
    }

}

Enable/Disable Anchor Tags using AngularJS

I'd expect anchor tags to lead to a static page with a url. I think that a buttons suits more to your use case, and then you can use ngDisabled to disable it. From the docs: https://docs.angularjs.org/api/ng/directive/ngDisabled

MongoDB - Update objects in a document's array (nested updating)

There is no way to do this in single query. You have to search the document in first query:

If document exists:

db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } , 
                {$inc : {"items.$.price" : 1} } , 
                false , 
                true);

Else

db.bar.update( {user_id : 123456 } , 
                {$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
                false , 
                true);

No need to add condition {$ne : "my_item_two" }.

Also in multithreaded enviourment you have to be careful that only one thread can execute the second (insert case, if document did not found) at a time, otherwise duplicate embed documents will be inserted.

How can I convert a date to GMT?

After searching for an hour or two ,I've found a simple solution below.

const date = new Date(`${date from client} GMT`);

inside double ticks, there is a date from client side plust GMT.

I'm first time commenting, constructive criticism will be welcomed.

AngularJS: How to set a variable inside of a template?

Use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit

<div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]">
  {{$index}} - {{day.iso}} - {{day.name}}
  Temperature: {{f.temperature}}<br>
  Humidity: {{f.humidity}}<br>
  ...
</div>

Example: http://jsfiddle.net/coma/UV4qF/

Converting milliseconds to a date (jQuery/JavaScript)

/Date(1383066000000)/

function convertDate(data) {
    var getdate = parseInt(data.replace("/Date(", "").replace(")/", ""));
    var ConvDate= new Date(getdate);
    return ConvDate.getDate() + "/" + ConvDate.getMonth() + "/" + ConvDate.getFullYear();
}

Twitter Bootstrap onclick event on buttons-radio

I see a lot of complicated answers, while this is super simple in Bootstrap 3:

Step 1: Use the official example code to create your radio button group, and give the container an id:

<div id="myButtons" class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected)
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option2" autocomplete="off"> Radio 2
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option3" autocomplete="off"> Radio 3
  </label>
</div>

Step 2: Use this jQuery handler:

$("#myButtons :input").change(function() {
    console.log(this); // points to the clicked input button
});

Try the fiddle demo

Count number of rows by group using dplyr

another approach is to use the double colons:

mtcars %>% 
  dplyr::group_by(cyl, gear) %>%
  dplyr::summarise(length(gear))

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

Following @Michelle Tilley solution, apparently it didn't work for me at first. Not sure why, maybe I am using chrome and different version of node. After did some minor tweaks, it is working for me now.

app.all('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

In case someone facing similar issue as mine, this might be helpful.

Save child objects automatically using JPA Hibernate

Following program describe how bidirectional relation work in hibernate.

When parent will save its list of child object will be auto save.

On Parent side:

    @Entity
    @Table(name="clients")
    public class Clients implements Serializable  {

         @Id
         @GeneratedValue(strategy = GenerationType.IDENTITY)     
         @OneToMany(mappedBy="clients", cascade=CascadeType.ALL)
          List<SmsNumbers> smsNumbers;
    }

And put the following annotation on the child side:

  @Entity
  @Table(name="smsnumbers")
  public class SmsNumbers implements Serializable {

     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     int id;
     String number;
     String status;
     Date reg_date;
     @ManyToOne
     @JoinColumn(name = "client_id")
     private Clients clients;

    // and getter setter.

 }

Main class:

 public static void main(String arr[])
 {
    Session session = HibernateUtil.openSession();
      //getting transaction object from session object
    session.beginTransaction();

    Clients cl=new Clients("Murali", "1010101010");
    SmsNumbers sms1=new SmsNumbers("99999", "Active", cl);
    SmsNumbers sms2=new SmsNumbers("88888", "InActive", cl);
    SmsNumbers sms3=new SmsNumbers("77777", "Active", cl);
    List<SmsNumbers> lstSmsNumbers=new ArrayList<SmsNumbers>();
    lstSmsNumbers.add(sms1);
    lstSmsNumbers.add(sms2);
    lstSmsNumbers.add(sms3);
    cl.setSmsNumbers(lstSmsNumbers);
    session.saveOrUpdate(cl);
    session.getTransaction().commit(); 
    session.close();    

 }

mysql update query with sub query

The main issue is that the inner query cannot be related to your where clause on the outer update statement, because the where filter applies first to the table being updated before the inner subquery even executes. The typical way to handle a situation like this is a multi-table update.

Update
  Competition as C
  inner join (
    select CompetitionId, count(*) as NumberOfTeams
    from PicksPoints as p
    where UserCompetitionID is not NULL
    group by CompetitionID
  ) as A on C.CompetitionID = A.CompetitionID
set C.NumberOfTeams = A.NumberOfTeams

Demo: http://www.sqlfiddle.com/#!2/a74f3/1

How to Display blob (.pdf) in an AngularJS app

Adding responseType to the request that is made from angular is indeed the solution, but for me it didn't work until I've set responseType to blob, not to arrayBuffer. The code is self explanatory:

    $http({
            method : 'GET',
            url : 'api/paperAttachments/download/' + id,
            responseType: "blob"
        }).then(function successCallback(response) {
            console.log(response);
             var blob = new Blob([response.data]);
             FileSaver.saveAs(blob, getFileNameFromHttpResponse(response));
        }, function errorCallback(response) {   
        });

OperationalError, no such column. Django

I did the following

  1. Delete my db.sqlite3 database
  2. python manage.py makemigrations
  3. python manage.py migrate

It renewed the database and fixed the issues without affecting my project. Please note you might need to do python manage.py createsuperuser because it will affect all your objects being created.

What is the unix command to see how much disk space there is and how much is remaining?

If you want to see how much space each folder ocuppes:

du -sh *

  • s – summarize
  • h – human readable
  • * – list of folders

Getting key with maximum value in dictionary?

Per the iterated solutions via comments in the selected answer...

In Python 3:

max(stats.keys(), key=(lambda k: stats[k]))

In Python 2:

max(stats.iterkeys(), key=(lambda k: stats[k]))

list all files in the folder and also sub folders

Use FileUtils from Apache commons.

listFiles

public static Collection<File> listFiles(File directory,
                                         String[] extensions,
                                         boolean recursive)
Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.
Parameters:
directory - the directory to search in
extensions - an array of extensions, ex. {"java","xml"}. If this parameter is null, all files are returned.
recursive - if true all subdirectories are searched as well
Returns:
an collection of java.io.File with the matching files

Anybody knows any knowledge base open source?

In addition to MediaWiki that was mentioned by Kenny, you might also look at MoinMoin.

Choosing between MediaWiki and MoinMoin can be a bit tough. Here are some points to consider:

MediaWiki

Pros:

  • Made for wikipedia, thus is very mature and scalable.
  • Fairly easy to set up.

    Cons:

  • Made soley for wikipedia. Thus it can be a bit of a pain to customize how you like it.

MoinMoin

Pros:

  • Very mature software.
  • Huge amount of plugins and third party modules available.

    Cons:

  • Can be a pain to install.

There are a huge amount of other wikis available, but those are the main two I would consider.

How to find if a file contains a given string using Windows command line

I've used a DOS command line to do this. Two lines, actually. The first one to make the "current directory" the folder where the file is - or the root folder of a group of folders where the file can be. The second line does the search.

CD C:\TheFolder
C:\TheFolder>FINDSTR /L /S /I /N /C:"TheString" *.PRG

You can find details about the parameters at this link.

Hope it helps!

How to group dataframe rows into list in pandas groupby

Use any of the following groupby and agg recipes.

# Setup
df = pd.DataFrame({
  'a': ['A', 'A', 'B', 'B', 'B', 'C'],
  'b': [1, 2, 5, 5, 4, 6],
  'c': ['x', 'y', 'z', 'x', 'y', 'z']
})
df

   a  b  c
0  A  1  x
1  A  2  y
2  B  5  z
3  B  5  x
4  B  4  y
5  C  6  z

To aggregate multiple columns as lists, use any of the following:

df.groupby('a').agg(list)
df.groupby('a').agg(pd.Series.tolist)

           b          c
a                      
A     [1, 2]     [x, y]
B  [5, 5, 4]  [z, x, y]
C        [6]        [z]

To group-listify a single column only, convert the groupby to a SeriesGroupBy object, then call SeriesGroupBy.agg. Use,

df.groupby('a').agg({'b': list})  # 4.42 ms 
df.groupby('a')['b'].agg(list)    # 2.76 ms - faster

a
A       [1, 2]
B    [5, 5, 4]
C          [6]
Name: b, dtype: object

TypeError: $(...).autocomplete is not a function

you missed jquery ui library. Use CDN of Jquery UI or if you want it locally then download the file from Jquery Ui

<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
<script src="YourJquery source path"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>

Volatile vs. Interlocked vs. lock

I did some test to see how the theory actually works: kennethxu.blogspot.com/2009/05/interlocked-vs-monitor-performance.html. My test was more focused on CompareExchnage but the result for Increment is similar. Interlocked is not necessary faster in multi-cpu environment. Here is the test result for Increment on a 2 years old 16 CPU server. Bare in mind that the test also involves the safe read after increase, which is typical in real world.

D:\>InterlockVsMonitor.exe 16
Using 16 threads:
          InterlockAtomic.RunIncrement         (ns):   8355 Average,   8302 Minimal,   8409 Maxmial
    MonitorVolatileAtomic.RunIncrement         (ns):   7077 Average,   6843 Minimal,   7243 Maxmial

D:\>InterlockVsMonitor.exe 4
Using 4 threads:
          InterlockAtomic.RunIncrement         (ns):   4319 Average,   4319 Minimal,   4321 Maxmial
    MonitorVolatileAtomic.RunIncrement         (ns):    933 Average,    802 Minimal,   1018 Maxmial

Finding all possible combinations of numbers to reach a given sum

C++ version of the same algorithm

#include <iostream>
#include <list>
void subset_sum_recursive(std::list<int> numbers, int target, std::list<int> partial)
{
        int s = 0;
        for (std::list<int>::const_iterator cit = partial.begin(); cit != partial.end(); cit++)
        {
            s += *cit;
        }
        if(s == target)
        {
                std::cout << "sum([";

                for (std::list<int>::const_iterator cit = partial.begin(); cit != partial.end(); cit++)
                {
                    std::cout << *cit << ",";
                }
                std::cout << "])=" << target << std::endl;
        }
        if(s >= target)
            return;
        int n;
        for (std::list<int>::const_iterator ai = numbers.begin(); ai != numbers.end(); ai++)
        {
            n = *ai;
            std::list<int> remaining;
            for(std::list<int>::const_iterator aj = ai; aj != numbers.end(); aj++)
            {
                if(aj == ai)continue;
                remaining.push_back(*aj);
            }
            std::list<int> partial_rec=partial;
            partial_rec.push_back(n);
            subset_sum_recursive(remaining,target,partial_rec);

        }
}

void subset_sum(std::list<int> numbers,int target)
{
    subset_sum_recursive(numbers,target,std::list<int>());
}
int main()
{
    std::list<int> a;
    a.push_back (3); a.push_back (9); a.push_back (8);
    a.push_back (4);
    a.push_back (5);
    a.push_back (7);
    a.push_back (10);
    int n = 15;
    //std::cin >> n;
    subset_sum(a, n);
    return 0;
}

how to get the value of css style using jquery

I doubt css understands left by itself. You need to use it specifying position. You are using .css() correctly

position: relative/absolute/whatever;
left: 900px;

heres a fiddle of it working

http://jsfiddle.net/gFLZe/

and without the position here's what you get

http://jsfiddle.net/gkkm5/

Change your if statement to be like this - with quotes around -900px

var n = $("items").css("left");

if(n == '-900px'){
    $(".items span").fadeOut("slow");
}

http://jsfiddle.net/gFLZe/1/

How do I improve ASP.NET MVC application performance?

Not an earth-shattering optimization, but I thought I'd throw this out there - Use CDN's for jQuery, etc..

Quote from ScottGu himself: The Microsoft Ajax CDN enables you to significantly improve the performance of ASP.NET Web Forms and ASP.NET MVC applications that use ASP.NET AJAX or jQuery. The service is available for free, does not require any registration, and can be used for both commercial and non-commercial purposes.

We even use the CDN for our webparts in Moss that use jQuery.

Android: Storing username and password?

You should use the Android AccountManager. It's purpose-built for this scenario. It's a little bit cumbersome but one of the things it does is invalidate the local credentials if the SIM card changes, so if somebody swipes your phone and throws a new SIM in it, your credentials won't be compromised.

This also gives the user a quick and easy way to access (and potentially delete) the stored credentials for any account they have on the device, all from one place.

SampleSyncAdapter (like @Miguel mentioned) is an example that makes use of stored account credentials.

SQLite - UPSERT *not* INSERT or REPLACE

Following Aristotle Pagaltzis and the idea of COALESCE from Eric B’s answer, here it is an upsert option to update only few columns or insert full row if it does not exist.

In this case, imagine that title and content should be updated, keeping the other old values when existing and inserting supplied ones when name not found:

NOTE id is forced to be NULL when INSERT as it is supposed to be autoincrement. If it is just a generated primary key then COALESCE can also be used (see Aristotle Pagaltzis comment).

WITH new (id, name, title, content, author)
     AS ( VALUES(100, 'about', 'About this site', 'Whatever new content here', 42) )
INSERT OR REPLACE INTO page (id, name, title, content, author)
SELECT
     old.id, COALESCE(old.name, new.name),
     new.title, new.content,
     COALESCE(old.author, new.author)
FROM new LEFT JOIN page AS old ON new.name = old.name;

So the general rule would be, if you want to keep old values, use COALESCE, when you want to update values, use new.fieldname

New self vs. new static

will I get the same results?

Not really. I don't know of a workaround for PHP 5.2, though.

What is the difference between new self and new static?

self refers to the same class in which the new keyword is actually written.

static, in PHP 5.3's late static bindings, refers to whatever class in the hierarchy you called the method on.

In the following example, B inherits both methods from A. The self invocation is bound to A because it's defined in A's implementation of the first method, whereas static is bound to the called class (also see get_called_class()).

class A {
    public static function get_self() {
        return new self();
    }

    public static function get_static() {
        return new static();
    }
}

class B extends A {}

echo get_class(B::get_self());  // A
echo get_class(B::get_static()); // B
echo get_class(A::get_self()); // A
echo get_class(A::get_static()); // A

How to get the directory of the currently running file?

This should do it:

import (
    "fmt"
    "log"
    "os"
    "path/filepath"
)

func main() {
    dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
    if err != nil {
            log.Fatal(err)
    }
    fmt.Println(dir)
}

npm install gives error "can't find a package.json file"

>> For Visual Studio Users using Package Manager Console <<

If you are using the Package Manager Console in Visual Studio and you want to execute:

npm install and get:

ENOENT: no such file or directory, open 'C:\Users...\YourProject\package.json'

Verify that you are executing the command in the correct directory.

VS by default uses the solution folder when opening the Package Manager Console.

Execute dir then you can see in which folder you currently are. Most probably in the solution folder, that's why you get this error. Now you have to cd to your project folder.

cd YourWebProject

Now npm install should work now, if not, then you have another issue.

Understanding events and event handlers in C#

Here is a code example which may help:

using System;
using System.Collections.Generic;
using System.Text;

namespace Event_Example
{
  // First we have to define a delegate that acts as a signature for the
  // function that is ultimately called when the event is triggered.
  // You will notice that the second parameter is of MyEventArgs type.
  // This object will contain information about the triggered event.

  public delegate void MyEventHandler(object source, MyEventArgs e);

  // This is a class which describes the event to the class that receives it.
  // An EventArgs class must always derive from System.EventArgs.

  public class MyEventArgs : EventArgs
  {
    private string EventInfo;

    public MyEventArgs(string Text) {
      EventInfo = Text;
    }

    public string GetInfo() {
      return EventInfo;
    }
  }

  // This next class is the one which contains an event and triggers it
  // once an action is performed. For example, lets trigger this event
  // once a variable is incremented over a particular value. Notice the
  // event uses the MyEventHandler delegate to create a signature
  // for the called function.

  public class MyClass
  {
    public event MyEventHandler OnMaximum;

    private int i;
    private int Maximum = 10;

    public int MyValue
    {
      get { return i; }
      set
      {
        if(value <= Maximum) {
          i = value;
        }
        else 
        {
          // To make sure we only trigger the event if a handler is present
          // we check the event to make sure it's not null.
          if(OnMaximum != null) {
            OnMaximum(this, new MyEventArgs("You've entered " +
              value.ToString() +
              ", but the maximum is " +
              Maximum.ToString()));
          }
        }
      }
    }
  }

  class Program
  {
    // This is the actual method that will be assigned to the event handler
    // within the above class. This is where we perform an action once the
    // event has been triggered.

    static void MaximumReached(object source, MyEventArgs e) {
      Console.WriteLine(e.GetInfo());
    }

    static void Main(string[] args) {
      // Now lets test the event contained in the above class.
      MyClass MyObject = new MyClass();
      MyObject.OnMaximum += new MyEventHandler(MaximumReached);
      for(int x = 0; x <= 15; x++) {
        MyObject.MyValue = x;
      }
      Console.ReadLine();
    }
  }
}

Two versions of python on linux. how to make 2.7 the default

Verify current version of python by:

$ python --version

then check python is symbolic link to which file.

  $ ll /usr/bin/python

Output Ex:

 lrwxrwxrwx 1 root root 9 Jun 16  2014 /usr/bin/python -> python2.7*

Check other available versions of python:

$ ls /usr/bin/python*

Output Ex:

/usr/bin/python     /usr/bin/python2.7-config  /usr/bin/python3.4         /usr/bin/python3.4m-config  /usr/bin/python3.6m         /usr/bin/python3m
/usr/bin/python2    /usr/bin/python2-config    /usr/bin/python3.4-config  /usr/bin/python3.6          /usr/bin/python3.6m-config  /usr/bin/python3m-config
/usr/bin/python2.7  /usr/bin/python3           /usr/bin/python3.4m        /usr/bin/python3.6-config   /usr/bin/python3-config     /usr/bin/python-config

If want to change current version of python to 3.6 version edit file ~/.bashrc:

vim ~/.bashrc

add below line in the end of file and save:

alias python=/usr/local/bin/python3.6

To install pip for python 3.6

$ sudo apt-get install python3.6 python3.6-dev
$ sudo curl https://bootstrap.pypa.io/ez_setup.py -o - | sudo python3.6
$ sudo easy_install pip

On Success, check current version of pip:

$ pip3 -V

Output Ex:

pip 1.5.4 from /usr/lib/python3/dist-packages (python 3.6)

How to get all count of mongoose model?

Using mongoose.js you can count documents,

  • count all
const count = await Schema.countDocuments();
  • count specific
const count = await Schema.countDocuments({ key: value });

Datetime equal or greater than today in MySQL

If the column have index and a function is applied on the column then index doesn't work and full table scan occurs, causing really slow query.

Bad Query; This would ignore index on the column date_time

select * from users
where Date(date_time) > '2010-10-10'

To utilize index on column created of type datetime comparing with today/current date, the following method can be used.

Solution for OP:

select * from users
where created > CONCAT(CURDATE(), ' 23:59:59')

Sample to get data for today:

select * from users
where 
    created >= CONCAT(CURDATE(), ' 00:00:00') AND
    created <= CONCAT(CURDATE(), ' 23:59:59')

Or use BETWEEN for short

select * from users 
where created BETWEEN 
      CONCAT(CURDATE(), ' 00:00:00') AND CONCAT(CURDATE(), ' 23:59:59')

Tip: If you have to do a lot of calculation or queries on dates as well as time, then it's very useful to save date and time in separate columns. (Divide & Conquer)

Difference between java.lang.RuntimeException and java.lang.Exception

From oracle documentation:

Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

Runtime exceptions represent problems that are the result of a programming problem and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way.

RuntimeExceptions are like "exceptions by invalid use of an api" examples of runtimeexceptions: IllegalStateException, NegativeArraySizeException, NullpointerException

With the Exceptions you must catch it explicitly because you can still do something to recover. Examples of Exceptions are: IOException, TimeoutException, PrintException...

Unable to start MySQL server

Mine did not start because the Server did not accept the 'Dedicated MySQL Server' setting in the Configuration.

How do I pause my shell script for a second before continuing?

And what about:

read -p "Press enter to continue"

How do I specify a password to 'psql' non-interactively?

An alternative to using the PGPASSWORD environment variable is to use the conninfo string according to the documentation:

An alternative way to specify connection parameters is in a conninfo string or a URI, which is used instead of a database name. This mechanism give you very wide control over the connection.

$ psql "host=<server> port=5432 dbname=<db> user=<user> password=<password>"

postgres=>

Using two values for one switch case statement

You can use:

case text1: case text4: 
     do stuff;
     break;

How to get Enum Value from index in Java?

I just tried the same and came up with following solution:

public enum Countries {
    TEXAS,
    FLORIDA,
    OKLAHOMA,
    KENTUCKY;

    private static Countries[] list = Countries.values();

    public static Countries getCountry(int i) {
        return list[i];
    }

    public static int listGetLastIndex() {
        return list.length - 1;
    }
}

The class has it's own values saved inside an array, and I use the array to get the enum at indexposition. As mentioned above arrays begin to count from 0, if you want your index to start from '1' simply change these two methods to:

public static String getCountry(int i) {
    return list[(i - 1)];
}

public static int listGetLastIndex() {
    return list.length;
}

Inside my Main I get the needed countries-object with

public static void main(String[] args) {
   int i = Countries.listGetLastIndex();
   Countries currCountry = Countries.getCountry(i);
}

which sets currCountry to the last country, in this case Countries.KENTUCKY.

Just remember this code is very affected by ArrayOutOfBoundsExceptions if you're using hardcoded indicies to get your objects.

Code formatting shortcuts in Android Studio for Operation Systems

Really, I went to this thread because of my Ubuntu locks screen after this shortcut Ctrl + Alt + L. So if you are have the same problem just go to the Settings - Keyboard - Shortcuts - System and change the default shortcut for the "Lock screen".

How do I get ruby to print a full backtrace instead of a truncated one?

You could also do this if you'd like a simple one-liner:

puts caller

DISTINCT clause with WHERE

May be by :

SELECT DISTINCT email,id FROM table where id='2';

Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

All the solutions here failed to work on my VS2013, however I put the #define _CRT_SECURE_NO_WARNINGS in the stdafx.h just before the #pragma once and all warnings were suppressed. Note: I only code for prototyping purposes to support my research so please make sure you understand the implications of this method when writing your code.

Hope this helps

CURL to access a page that requires a login from a different page

My answer is a mod of some prior answers from @JoeMills and @user.

  1. Get a cURL command to log into server:

    • Load login page for website and open Network pane of Developer Tools
      • In firefox, right click page, choose 'Inspect Element (Q)' and click on Network tab
    • Go to login form, enter username, password and log in
    • After you have logged in, go back to Network pane and scroll to the top to find the POST entry. Right click and choose Copy -> Copy as CURL
    • Paste this to a text editor and try this in command prompt to see if it works
      • Its possible that some sites have hardening that will block this type of login spoofing that would require more steps below to bypass.
  2. Modify cURL command to be able to save session cookie after login

    • Remove the entry -H 'Cookie: <somestuff>'
    • Add after curl at beginning -c login_cookie.txt
    • Try running this updated curl command and you should get a new file 'login_cookie.txt' in the same folder
  3. Call a new web page using this new cookie that requires you to be logged in

    • curl -b login_cookie.txt <url_that_requires_log_in>

I have tried this on Ubuntu 20.04 and it works like a charm.

How do I get the height and width of the Android Navigation Bar programmatically?

How to get the height of the navigation bar and status bar. This code works for me on some Huawei devices and Samsung devices. Egis's solution above is good, however, it is still incorrect on some devices. So, I improved it.

This is code to get the height of status bar

private fun getStatusBarHeight(resources: Resources): Int {
        var result = 0
        val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            result = resources.getDimensionPixelSize(resourceId)
        }
        return result
    }

This method always returns the height of navigation bar even when the navigation bar is hidden.

private fun getNavigationBarHeight(resources: Resources): Int {
    val resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android")
    return if (resourceId > 0) {
        resources.getDimensionPixelSize(resourceId)
    } else 0
}

NOTE: on Samsung A70, this method returns the height of the status bar + height of the navigation bar. On other devices (Huawei), it only returns the height of the Navigation bar and returns 0 when the navigation bar is hidden.

private fun getNavigationBarHeight(): Int {
        val display = activity?.windowManager?.defaultDisplay
        return if (display == null) {
            0
        } else {
            val realMetrics = DisplayMetrics()
            display.getRealMetrics(realMetrics)
            val metrics = DisplayMetrics()
            display.getMetrics(metrics)
            realMetrics.heightPixels - metrics.heightPixels
        }
    }

This is code to get height of navigation bar and status bar

val metrics = DisplayMetrics()
        activity?.windowManager?.defaultDisplay?.getRealMetrics(metrics)

        //resources is got from activity

        //NOTE: on SamSung A70, this height = height of status bar + height of Navigation bar
        //On other devices (Huawei), this height = height of Navigation bar
        val navigationBarHeightOrNavigationBarPlusStatusBarHeight = getNavigationBarHeight()

        val statusBarHeight = getStatusBarHeight(resources)
        //The method will always return the height of navigation bar even when the navigation bar was hidden.
        val realNavigationBarHeight = getNavigationBarHeight(resources)

        val realHeightOfStatusBarAndNavigationBar =
                if (navigationBarHeightOrNavigationBarPlusStatusBarHeight == 0 || navigationBarHeightOrNavigationBarPlusStatusBarHeight < statusBarHeight) {
                    //Huawei: navigation bar is hidden
                    statusBarHeight
                } else if (navigationBarHeightOrNavigationBarPlusStatusBarHeight == realNavigationBarHeight) {
                    //Huawei: navigation bar is visible
                    statusBarHeight + realNavigationBarHeight
                } else if (navigationBarHeightOrNavigationBarPlusStatusBarHeight < realNavigationBarHeight) {
                    //SamSung A70: navigation bar is still visible but it only displays as a under line
                    //navigationBarHeightOrNavigationBarPlusStatusBarHeight = navigationBarHeight'(under line) + statusBarHeight
                    navigationBarHeightOrNavigationBarPlusStatusBarHeight
                } else {
                    //SamSung A70: navigation bar is visible
                    //navigationBarHeightOrNavigationBarPlusStatusBarHeight == statusBarHeight + realNavigationBarHeight
                    navigationBarHeightOrNavigationBarPlusStatusBarHeight
                }

C++11 reverse range-based for-loop

Actually, in C++14 it can be done with a very few lines of code.

This is a very similar in idea to @Paul's solution. Due to things missing from C++11, that solution is a bit unnecessarily bloated (plus defining in std smells). Thanks to C++14 we can make it a lot more readable.

The key observation is that range-based for-loops work by relying on begin() and end() in order to acquire the range's iterators. Thanks to ADL, one doesn't even need to define their custom begin() and end() in the std:: namespace.

Here is a very simple-sample solution:

// -------------------------------------------------------------------
// --- Reversed iterable

template <typename T>
struct reversion_wrapper { T& iterable; };

template <typename T>
auto begin (reversion_wrapper<T> w) { return std::rbegin(w.iterable); }

template <typename T>
auto end (reversion_wrapper<T> w) { return std::rend(w.iterable); }

template <typename T>
reversion_wrapper<T> reverse (T&& iterable) { return { iterable }; }

This works like a charm, for instance:

template <typename T>
void print_iterable (std::ostream& out, const T& iterable)
{
    for (auto&& element: iterable)
        out << element << ',';
    out << '\n';
}

int main (int, char**)
{
    using namespace std;

    // on prvalues
    print_iterable(cout, reverse(initializer_list<int> { 1, 2, 3, 4, }));

    // on const lvalue references
    const list<int> ints_list { 1, 2, 3, 4, };
    for (auto&& el: reverse(ints_list))
        cout << el << ',';
    cout << '\n';

    // on mutable lvalue references
    vector<int> ints_vec { 0, 0, 0, 0, };
    size_t i = 0;
    for (int& el: reverse(ints_vec))
        el += i++;
    print_iterable(cout, ints_vec);
    print_iterable(cout, reverse(ints_vec));

    return 0;
}

prints as expected

4,3,2,1,
4,3,2,1,
3,2,1,0,
0,1,2,3,

NOTE std::rbegin(), std::rend(), and std::make_reverse_iterator() are not yet implemented in GCC-4.9. I write these examples according to the standard, but they would not compile in stable g++. Nevertheless, adding temporary stubs for these three functions is very easy. Here is a sample implementation, definitely not complete but works well enough for most cases:

// --------------------------------------------------
template <typename I>
reverse_iterator<I> make_reverse_iterator (I i)
{
    return std::reverse_iterator<I> { i };
}

// --------------------------------------------------
template <typename T>
auto rbegin (T& iterable)
{
    return make_reverse_iterator(iterable.end());
}

template <typename T>
auto rend (T& iterable)
{
    return make_reverse_iterator(iterable.begin());
}

// const container variants

template <typename T>
auto rbegin (const T& iterable)
{
    return make_reverse_iterator(iterable.end());
}

template <typename T>
auto rend (const T& iterable)
{
    return make_reverse_iterator(iterable.begin());
}

jQuery - add additional parameters on submit (NOT ajax)

This one did it for me:

var input = $("<input>")
               .attr("type", "hidden")
               .attr("name", "mydata").val("bla");
$('#form1').append(input);

is based on the Daff's answer, but added the NAME attribute to let it show in the form collection and changed VALUE to VAL Also checked the ID of the FORM (form1 in my case)

used the Firefox firebug to check whether the element was inserted.

Hidden elements do get posted back in the form collection, only read-only fields are discarded.

Michel

Handler vs AsyncTask vs Thread

public class RequestHandler {

    public String sendPostRequest(String requestURL,
                                  HashMap<String, String> postDataParams) {

        URL url;

        StringBuilder sb = new StringBuilder();
        try {
            url = new URL(requestURL);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);


            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            int responseCode = conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                sb = new StringBuilder();
                String response;
                while ((response = br.readLine()) != null){
                    sb.append(response);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }

}

Send an Array with an HTTP Get

That depends on what the target server accepts. There is no definitive standard for this. See also a.o. Wikipedia: Query string:

While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field (e.g. field1=value1&field1=value2&field2=value3).[4][5]

Generally, when the target server uses a strong typed programming language like Java (Servlet), then you can just send them as multiple parameters with the same name. The API usually offers a dedicated method to obtain multiple parameter values as an array.

foo=value1&foo=value2&foo=value3
String[] foo = request.getParameterValues("foo"); // [value1, value2, value3]

The request.getParameter("foo") will also work on it, but it'll return only the first value.

String foo = request.getParameter("foo"); // value1

And, when the target server uses a weak typed language like PHP or RoR, then you need to suffix the parameter name with braces [] in order to trigger the language to return an array of values instead of a single value.

foo[]=value1&foo[]=value2&foo[]=value3
$foo = $_GET["foo"]; // [value1, value2, value3]
echo is_array($foo); // true

In case you still use foo=value1&foo=value2&foo=value3, then it'll return only the first value.

$foo = $_GET["foo"]; // value1
echo is_array($foo); // false

Do note that when you send foo[]=value1&foo[]=value2&foo[]=value3 to a Java Servlet, then you can still obtain them, but you'd need to use the exact parameter name including the braces.

String[] foo = request.getParameterValues("foo[]"); // [value1, value2, value3]

Linq select object from list depending on objects attribute

I think you are looking for this?

var correctAnswer = Answers.First(a => a.Correct);

You can use single by typing :

var correctAnswer = Answers.Single(a => a.Correct);

Getting the name / key of a JToken with JSON.net

The default iterator for the JObject is as a dictionary iterating over key/value pairs.

JObject obj = JObject.Parse(response);
foreach (var pair in obj) {
    Console.WriteLine (pair.Key);
}

git add only modified changes and ignore untracked files

git commit -a -m "message"

-a : Includes all currently changed/deleted files in this commit. Keep in mind, however, that untracked (new) files are not included.

-m : Sets the commit's message

Change color of Label in C#

I am going to assume this is a WinForms questions (which it feels like, based on it being a "program" rather than a website/app). In which case you can simple do the following to change the text colour of a label:

myLabel.ForeColor = System.Drawing.Color.Red;

Or any other colour of your choice. If you want to be more specific you can use an RGB value like so:

myLabel.ForeColor = Color.FromArgb(0, 0, 0);//(R, G, B) (0, 0, 0 = black)

Having different colours for different users can be done a number of ways. For example, you could allow each user to specify their own RGB value colours, store these somewhere and then load them when the user "connects".

An alternative method could be to just use 2 colours - 1 for the current user (running the app) and another colour for everyone else. This would help the user quickly identify their own messages above others.

A third approach could be to generate the colour randomly - however you will likely get conflicting values that do not show well against your background, so I would suggest not taking this approach. You could have a pre-defined list of "acceptable" colours and just pop one from that list for each user that joins.

import android packages cannot be resolved

This import android packages cannot be resolved is also occurs when your using some library and that library is not in the same path where your application is there, or if you are importing the library and not coping library to the workspace

jQuery: Handle fallback for failed AJAX Request

I prefer to this approach because you can return the promise and use .then(successFunction, failFunction); anywhere you need to.

var promise = $.ajax({
    type: 'GET',
    dataType: 'json',
    url: url,
    timeout: 5000
  }).then(function( data, textStatus, jqXHR ) {
    alert('request successful');
  }, function( jqXHR, textStatus, errorThrown ) {
    alert('request failed');
});

//also access the success and fail using variable
promise.then(successFunction, failFunction);

When should null values of Boolean be used?

Boolean can be very helpful when you need three state. Like in software testing if Test is passed send true , if failed send false and if test case interrupted send null which will denote test case not executed .

AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

Use the following

recognizer = **cv2.face.LBPHFaceRecognizer_create()**

After you install:

pip install opencv-contrib-python

If using anaconda then in anaconda prompt:

conda install pip

then

pip install opencv-contrib-python

How can I check if two segments intersect?

You don't have to compute exactly where does the segments intersect, but only understand whether they intersect at all. This will simplify the solution.

The idea is to treat one segment as the "anchor" and separate the second segment into 2 points.
Now, you will have to find the relative position of each point to the "anchored" segment (OnLeft, OnRight or Collinear).
After doing so for both points, check that one of the points is OnLeft and the other is OnRight (or perhaps include Collinear position, if you wish to include improper intersections as well).

You must then repeat the process with the roles of anchor and separated segments.

An intersection exists if, and only if, one of the points is OnLeft and the other is OnRight. See this link for a more detailed explanation with example images for each possible case.

Implementing such method will be much easier than actually implementing a method that finds the intersection point (given the many corner cases which you will have to handle as well).

Update

The following functions should illustrate the idea (source: Computational Geometry in C).
Remark: This sample assumes the usage of integers. If you're using some floating-point representation instead (which could obviously complicate things), then you should determine some epsilon value to indicate "equality" (mostly for the IsCollinear evaluation).

// points "a" and "b" forms the anchored segment.
// point "c" is the evaluated point
bool IsOnLeft(Point a, Point b, Point c)
{
     return Area2(a, b, c) > 0;
}

bool IsOnRight(Point a, Point b, Point c)
{
     return Area2(a, b, c) < 0;
}

bool IsCollinear(Point a, Point b, Point c)
{
     return Area2(a, b, c) == 0;
}

// calculates the triangle's size (formed by the "anchor" segment and additional point)
int Area2(Point a, Point b, Point c)
{
     return (b.X - a.X) * (c.Y - a.Y) -
            (c.X - a.X) * (b.Y - a.Y);
}

Of course, when using these functions, one must remember to check that each segment lies "between" the other segment (since these are finite segments, and not infinite lines).

Also, using these functions you can understand whether you've got a proper or improper intersection.

  • Proper: There are no collinear points. The segments crosses each other "from side to side".
  • Improper: One segment only "touches" the other (at least one of the points is collinear to the anchored segment).

OnClickListener in Android Studio

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

    setContentView(R.layout.activity_my);
    titolorecuperato = (TextView) findViewById(R.id.textView);
    String stitolo = titolorecuperato.getText().toString();

    Button btnHome = (Button) findViewById(R.id.button);

    btnHome.setOnClickListener(new View.OnClickListener() {

       @Override
        public void onClick(View view) {

       }
});

same thing as Nic007 said before.

You do need to write code inside "onCreate" method. Sorry me too for the indent... (first comment here)

Storage permission error in Marshmallow

After lots of searching This code work for me:

Check the permission already has: Check WRITE_EXTERNAL_STORAGE permission Allowed or not?

if(isReadStorageAllowed()){
            //If permission is already having then showing the toast
            //Toast.makeText(SplashActivity.this,"You already have the permission",Toast.LENGTH_LONG).show();
            //Existing the method with return
            return;
        }else{
            requestStoragePermission();
        }



private boolean isReadStorageAllowed() {
    //Getting the permission status
    int result = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);

    //If permission is granted returning true
    if (result == PackageManager.PERMISSION_GRANTED)
        return true;

    //If permission is not granted returning false
    return false;
}

//Requesting permission
private void requestStoragePermission(){

    if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)){
        //If the user has denied the permission previously your code will come to this block
        //Here you can explain why you need this permission
        //Explain here why you need this permission
    }

    //And finally ask for the permission
    ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_WRITE_STORAGE);
}

Implement Override onRequestPermissionsResult method for checking is the user allow or denie

 @Override
 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    //Checking the request code of our request
    if(requestCode == REQUEST_WRITE_STORAGE){

        //If permission is granted
        if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){

            //Displaying a toast
            Toast.makeText(this,"Permission granted now you can read the storage",Toast.LENGTH_LONG).show();

        }else{
            //Displaying another toast if permission is not granted
            Toast.makeText(this,"Oops you just denied the permission",Toast.LENGTH_LONG).show();
        }
    }

java.lang.ClassNotFoundException: org.apache.log4j.Level

You need to download log4j and add in your classpath.

APR based Apache Tomcat Native library was not found on the java.library.path?

For Ubntu Users

 1. Install compilers
    #sudo apt-get install make
    #sudo apt-get install gcc

    2. Install openssl and development libraries
    #sudo apt-get install openssl
    #sudo apt-get install libssl-dev
    3. Install the APR package (Downloaded from http://apr.apache.org/)

    #tar -xzf apr-1.4.6.tar.gz
    #cd apr-1.4.6/
    #sudo ./configure
    #sudo make
    #sudo make install

    You should see the compiled file as
    /usr/local/apr/lib/libapr-1.a

    4. Download, compile and install Tomcat Native sourse package
    tomcat-native-1.1.27-src.tar.gz

    Extract the archive into some folder

    #tar -xzf tomcat-native-1.1.27-src.tar.gz
    #cd tomcat-native-1.1.27-src/jni/native
    #JAVA_HOME=/usr/lib/jvm/jdk1.7.0_21/
    #sudo ./configure --with-apr=/usr/local/apr --with-java-home=$JAVA_HOME
    #sudo make
    #sudo make install

    Now I have compiled Tomcat Native library in /usr/local/apr/libtcnative-1.so.0.1.27 and symbolic link file /usr/local/apr/@libtcnative-1.so pointed to the library

    5. Create or edit the $CATALINA_HOME/bin/setenv.sh file with following lines :
    export LD_LIBRARY_PATH='$LD_LIBRARY_PATH:/usr/local/apr/lib'

    6. Restart tomcat and see the desired result:

ImportError: No Module named simplejson

For anyone coming across this years later:

TL;DR check your pip version (2 vs 3)

I had this same issue and it was not fixed by running pip install simplejson despite pip insisting that it was installed. Then I realized that I had both python 2 and python 3 installed.

> python -V
Python 2.7.12
> pip -V
pip 9.0.1 from /usr/local/lib/python3.5/site-packages (python 3.5)

Installing with the correct version of pip is as easy as using pip2:

> pip2 install simplejson

and then python 2 can import simplejson fine.

Converting a POSTMAN request to Curl

Starting from Postman 8 you need to visit here

enter image description here

Android studio takes too much memory

You can speed up your Eclipse or Android Studio work, you just follow these:

  • Use/open single project at a time
  • clean your project after running your app in emulator every time
  • use mobile/external device instead of emulator
  • don't close emulator after using once, use same emulator for running app each time
  • Disable VCS by using File->Settings->Plugins and disable the following things :
    1.CVS Integration
    2.Git Integration
    3.GitHub
    4.Google Cloud Tools for Android Studio
    5.Subversion Integration

I am also using Android Studio with 4-GB installed main memory but following these statements really boost my Android Studio performance.

Why can't Python parse this JSON data?

If you're using Python3, you can try changing your (connection.json file) JSON to:

{
  "connection1": {
    "DSN": "con1",
    "UID": "abc",
    "PWD": "1234",
    "connection_string_python":"test1"
  }
  ,
  "connection2": {
    "DSN": "con2",
    "UID": "def",
    "PWD": "1234"
  }
}

Then using the following code:

connection_file = open('connection.json', 'r')
conn_string = json.load(connection_file)
conn_string['connection1']['connection_string_python'])
connection_file.close()
>>> test1

How to Use UTF-8 Collation in SQL Server database?

Two UDF to deal with UTF-8 in T-SQL:

CREATE Function UcsToUtf8(@src nvarchar(MAX)) returns varchar(MAX) as
begin
    declare @res varchar(MAX)='', @pi char(8)='%[^'+char(0)+'-'+char(127)+']%', @i int, @j int
    select @i=patindex(@pi,@src collate Latin1_General_BIN)
    while @i>0
    begin
        select @j=unicode(substring(@src,@i,1))
        if @j<0x800     select @res=@res+left(@src,@i-1)+char((@j&1984)/64+192)+char((@j&63)+128)
        else            select @res=@res+left(@src,@i-1)+char((@j&61440)/4096+224)+char((@j&4032)/64+128)+char((@j&63)+128)
        select @src=substring(@src,@i+1,datalength(@src)-1), @i=patindex(@pi,@src collate Latin1_General_BIN)
    end
    select @res=@res+@src
    return @res
end

CREATE Function Utf8ToUcs(@src varchar(MAX)) returns nvarchar(MAX) as
begin
    declare @i int, @res nvarchar(MAX)=@src, @pi varchar(18)
    select @pi='%[à-ï][€-¿][€-¿]%',@i=patindex(@pi,@src collate Latin1_General_BIN)
    while @i>0 select @res=stuff(@res,@i,3,nchar(((ascii(substring(@src,@i,1))&31)*4096)+((ascii(substring(@src,@i+1,1))&63)*64)+(ascii(substring(@src,@i+2,1))&63))), @src=stuff(@src,@i,3,'.'), @i=patindex(@pi,@src collate Latin1_General_BIN)
    select @pi='%[Â-ß][€-¿]%',@i=patindex(@pi,@src collate Latin1_General_BIN)
    while @i>0 select @res=stuff(@res,@i,2,nchar(((ascii(substring(@src,@i,1))&31)*64)+(ascii(substring(@src,@i+1,1))&63))), @src=stuff(@src,@i,2,'.'),@i=patindex(@pi,@src collate Latin1_General_BIN)
    return @res
end

Set value of textarea in jQuery

You can even use the below snippet.

$("textarea#ExampleMessage").append(result.exampleMessage);

Vagrant stuck connection timeout retrying

I got this when running vagrant/VirtualBox inside VirtualBox. I resolved this by running the vagrant machine in the host machine.

LINQ to SQL - Left Outer Join with multiple join conditions

It seems to me there is value in considering some rewrites to your SQL code before attempting to translate it.

Personally, I'd write such a query as a union (although I'd avoid nulls entirely!):

SELECT f.value
  FROM period as p JOIN facts AS f ON p.id = f.periodid
WHERE p.companyid = 100
      AND f.otherid = 17
UNION
SELECT NULL AS value
  FROM period as p
WHERE p.companyid = 100
      AND NOT EXISTS ( 
                      SELECT * 
                        FROM facts AS f
                       WHERE p.id = f.periodid
                             AND f.otherid = 17
                     );

So I guess I agree with the spirit of @MAbraham1's answer (though their code seems to be unrelated to the question).

However, it seems the query is expressly designed to produce a single column result comprising duplicate rows -- indeed duplicate nulls! It's hard not to come to the conclusion that this approach is flawed.

Java 8 lambdas, Function.identity() or t->t

In your example there is no big difference between str -> str and Function.identity() since internally it is simply t->t.

But sometimes we can't use Function.identity because we can't use a Function. Take a look here:

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);

this will compile fine

int[] arrayOK = list.stream().mapToInt(i -> i).toArray();

but if you try to compile

int[] arrayProblem = list.stream().mapToInt(Function.identity()).toArray();

you will get compilation error since mapToInt expects ToIntFunction, which is not related to Function. Also ToIntFunction doesn't have identity() method.

What is the difference between a .cpp file and a .h file?

Others have already offered good explanations, but I thought I should clarify the differences between the various extensions:

  Source Files for C: .c
  Header Files for C: .h

  Source Files for C++: .cpp
  Header Files for C++: .hpp

Of course, as it has already been pointed out, these are just conventions. The compiler doesn't actually pay any attention to them - it's purely for the benefit of the coder.

Using HttpClient and HttpPost in Android with post parameters

I've just checked and i have the same code as you and it works perferctly. The only difference is how i fill my List for the params :

I use a : ArrayList<BasicNameValuePair> params

and fill it this way :

 params.add(new BasicNameValuePair("apikey", apikey);

I do not use any JSONObject to send params to the webservices.

Are you obliged to use the JSONObject ?

hash function for string

I have tried these hash functions and got the following result. I have about 960^3 entries, each 64 bytes long, 64 chars in different order, hash value 32bit. Codes from here.

Hash function    | collision rate | how many minutes to finish
==============================================================
MurmurHash3      |           6.?% |                      4m15s
Jenkins One..    |           6.1% |                      6m54s   
Bob, 1st in link |          6.16% |                      5m34s
SuperFastHash    |            10% |                      4m58s
bernstein        |            20% |       14s only finish 1/20
one_at_a_time    |          6.16% |                       7m5s
crc              |          6.16% |                      7m56s

One strange things is that almost all the hash functions have 6% collision rate for my data.

How to hide Bootstrap previous modal when you opening new one?

The best that I've been able to do is

$(this).closest('.modal').modal('toggle');

This gets the modal holding the DOM object you triggered the event on (guessing you're clicking a button). Gets the closest parent '.modal' and toggles it. Obviously only works because it's inside the modal you clicked.

You can however do this:

$(".modal:visible").modal('toggle');

This gets the modal that is displaying (since you can only have one open at a time), and triggers the 'toggle' This would not work without ":visible"

Find the files existing in one directory but not in the other

Unsatisfied with all the replies, since most of them work very slowly and produce unnecessarily long output for large directories, I wrote my own Python script to compare two folders.

Unlike many other solutions, it doesn't compare contents of the files. Also it doesn't go inside subdirectories which are missing in another directory. So the output is quite concise and the script works fast.

#!/usr/bin/env python3

import os, sys

def compare_dirs(d1: "old directory name", d2: "new directory name"):
    def print_local(a, msg):
        print('DIR ' if a[2] else 'FILE', a[1], msg)
    # ensure validity
    for d in [d1,d2]:
        if not os.path.isdir(d):
            raise ValueError("not a directory: " + d)
    # get relative path
    l1 = [(x,os.path.join(d1,x)) for x in os.listdir(d1)]
    l2 = [(x,os.path.join(d2,x)) for x in os.listdir(d2)]
    # determine type: directory or file?
    l1 = sorted([(x,y,os.path.isdir(y)) for x,y in l1])
    l2 = sorted([(x,y,os.path.isdir(y)) for x,y in l2])
    i1 = i2 = 0
    common_dirs = []
    while i1<len(l1) and i2<len(l2):
        if l1[i1][0] == l2[i2][0]:      # same name
            if l1[i1][2] == l2[i2][2]:  # same type
                if l1[i1][2]:           # remember this folder for recursion
                    common_dirs.append((l1[i1][1], l2[i2][1]))
            else:
                print_local(l1[i1],'type changed')
            i1 += 1
            i2 += 1
        elif l1[i1][0]<l2[i2][0]:
            print_local(l1[i1],'removed')
            i1 += 1
        elif l1[i1][0]>l2[i2][0]:
            print_local(l2[i2],'added')
            i2 += 1
    while i1<len(l1):
        print_local(l1[i1],'removed')
        i1 += 1
    while i2<len(l2):
        print_local(l2[i2],'added')
        i2 += 1
    # compare subfolders recursively
    for sd1,sd2 in common_dirs:
        compare_dirs(sd1, sd2)

if __name__=="__main__":
    compare_dirs(sys.argv[1], sys.argv[2])

Sample usage:

user@laptop:~$ python3 compare_dirs.py dir1/ dir2/
DIR  dir1/out/flavor-domino removed
DIR  dir2/out/flavor-maxim2 added
DIR  dir1/target/vendor/flavor-domino removed
DIR  dir2/target/vendor/flavor-maxim2 added
FILE dir1/tmp/.kconfig-flavor_domino removed
FILE dir2/tmp/.kconfig-flavor_maxim2 added
DIR  dir2/tools/tools/LiveSuit_For_Linux64 added

Or if you want to see only files from the first directory:

user@laptop:~$ python3 compare_dirs.py dir2/ dir1/ | grep dir1
DIR  dir1/out/flavor-domino added
DIR  dir1/target/vendor/flavor-domino added
FILE dir1/tmp/.kconfig-flavor_domino added

P.S. If you need to compare file sizes and file hashes for potential changes, I published an updated script here: https://gist.github.com/amakukha/f489cbde2afd32817f8e866cf4abe779

Format a JavaScript string using placeholders and an object of substitutions?

I have written a code that lets you format string easily.

Use this function.

function format() {
    if (arguments.length === 0) {
        throw "No arguments";
    }
    const string = arguments[0];
    const lst = string.split("{}");
    if (lst.length !== arguments.length) {
        throw "Placeholder format mismatched";
    }
    let string2 = "";
    let off = 1;
    for (let i = 0; i < lst.length; i++) {
        if (off < arguments.length) {
            string2 += lst[i] + arguments[off++]
        } else {
            string2 += lst[i]
        }
    }
    return string2;
}

Example

format('My Name is {} and my age is {}', 'Mike', 26);

Output

My Name is Mike and my age is 26

Palindrome check in Javascript

SHORTEST CODE (31 chars)(ES6):

p=s=>s==[...s].reverse().join``
p('racecar'); //true

Keep in mind short code isn't necessarily the best. Readability and efficiency can matter more.

Where can I find error log files?

I am using Cent OS 6.6 with Apache and for me error log files are in

/usr/local/apache/log

Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?

in OpenSuse 12.1 the only thing required was:

zypper in php5-openssl

How do I link to a library with Code::Blocks?

The gdi32 library is already installed on your computer, few programs will run without it. Your compiler will (if installed properly) normally come with an import library, which is what the linker uses to make a binding between your program and the file in the system. (In the unlikely case that your compiler does not come with import libraries for the system libs, you will need to download the Microsoft Windows Platform SDK.)

To link with gdi32:

enter image description here

This will reliably work with MinGW-gcc for all system libraries (it should work if you use any other compiler too, but I can't talk about things I've not tried). You can also write the library's full name, but writing libgdi32.a has no advantage over gdi32 other than being more type work.
If it does not work for some reason, you may have to provide a different name (for example the library is named gdi32.lib for MSVC).

For libraries in some odd locations or project subfolders, you will need to provide a proper pathname (click on the "..." button for a file select dialog).

Which maven dependencies to include for spring 3.0?

Use a BOM to solve version issues.

you may find that a third-party library, or another Spring project, pulls in a transitive dependency to an older release. If you forget to explicitly declare a direct dependency yourself, all sorts of unexpected issues can arise.

To overcome such problems Maven supports the concept of a "bill of materials" (BOM) dependency.

https://docs.spring.io/spring/docs/4.3.18.RELEASE/spring-framework-reference/html/overview.html#overview-maven-bom

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-framework-bom</artifactId>
  <version>3.2.12.RELEASE</version>
  <type>pom</type>
</dependency>

No String-argument constructor/factory method to deserialize from String value ('')

This exception says that you are trying to deserialize the object "Address" from string "\"\"" instead of an object description like "{…}". The deserializer can't find a constructor of Address with String argument. You have to replace "" by {} to avoid this error.

Finding diff between current and last version

I don't really understand the meaning of "last version".

As the previous commit can be accessed with HEAD^, I think that you are looking for something like:

git diff HEAD^ HEAD

As of Git 1.8.5, @ is an alias for HEAD, so you can use:

git diff @~..@

The following will also work:

git show

If you want to know the diff between head and any commit you can use:

git diff commit_id HEAD

And this will launch your visual diff tool (if configured):

git difftool HEAD^ HEAD

Since comparison to HEAD is default you can omit it (as pointed out by Orient):

git diff @^
git diff HEAD^
git diff commit_id

Warnings

  • @ScottF and @Panzercrisis explain in the comments that on Windows the ~ character must be used instead of ^.

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

$('input[type="text"]').keyup(function(evt){
    var txt = $(this).val();


    // Regex taken from php.js (http://phpjs.org/functions/ucwords:569)
    $(this).val(txt.replace(/^(.)|\s(.)/g, function($1){ return $1.toUpperCase( ); }));
});

Converting pixels to dp

You should use dp just as you would pixels. That's all they are; display independent pixels. Use the same numbers you would on a medium density screen, and the size will be magically correct on a high density screen.

However, it sounds like what you need is the fill_parent option in your layout design. Use fill_parent when you want your view or control to expand to all the remaining size in the parent container.

Cassandra port usage - how are the ports used?

I resolved issue using below steps :

  1. Stop cassandara services

    sudo su -
    systemctl stop datastax-agent
    systemctl stop opscenterd
    systemctl stop app-dse
    
  2. Take backup and Change port from 9042 to 9035

    cp /opt/dse/resources/cassandra/conf/cassandra.yaml /opt/dse/resources/cassandra/conf/bkp_cassandra.yaml
    Vi /opt/dse/resources/cassandra/conf/cassandra.yaml
    native_transport_port: 9035
    
  3. Start Cassandra services

    systemctl start datastax-agent
    systemctl start opscenterd
    systemctl start app-dse
    
  4. create cqlshrc file.

    vi  /root/.cassandra/cqlshrc
    
    [connection]
    hostname = 198.168.1.100
    port = 9035
    

Thanks, Mahesh

Unstage a deleted file in git

Both questions are answered in git status.

To unstage adding a new file use git rm --cached filename.ext

# Changes to be committed:
#   (use "git rm --cached <file>..." to unstage)
#
#   new file:   test

To unstage deleting a file use git reset HEAD filename.ext

# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   deleted:    test

In the other hand, git checkout -- never unstage, it just discards non-staged changes.

Django model "doesn't declare an explicit app_label"

I had a similar issue, but I was able to solve mine by specifying explicitly the app_label using Meta Class in my models class

class Meta:
    app_label  = 'name_of_my_app'

Response.Redirect to new window

None of the previous examples worked for me, so I decided to post my solution. In the button click events, here is the code behind.

Dim URL As String = "http://www.google/?Search=" + txtExample.Text.ToString
URL = Page.ResolveClientUrl(URL)
btnSearch.OnClientClick = "window.open('" + URL + "'); return false;"

I was having to modify someone else's response.redirect code to open in a new browser.

How do I export html table data as .csv file?

I've briefly covered a simple way to do this with Google Spreadsheets (importHTML) and in Python (Pandas read_html and to_csv) as well as an example Python script in my SO answer here: https://stackoverflow.com/a/28083469/1588795.

How can I add "href" attribute to a link dynamically using JavaScript?

var a = document.getElementById('yourlinkId'); //or grab it by tagname etc
a.href = "somelink url"

Update Item to Revision vs Revert to Revision

The files in your working copy might look exactly the same after, but they are still very different actions -- the repository is in a completely different state, and you will have different options available to you after reverting than "updating" to an old revision.

Briefly, "update to" only affects your working copy, but "reverse merge and commit" will affect the repository.

If you "update" to an old revision, then the repository has not changed: in your example, the HEAD revision is still 100. You don't have to commit anything, since you are just messing around with your working copy. If you make modifications to your working copy and try to commit, you will be told that your working copy is out-of-date, and you will need to update before you can commit. If someone else working on the same repository performs an "update", or if you check out a second working copy, it will be r100.

However, if you "reverse merge" to an old revision, then your working copy is still based on the HEAD (assuming you are up-to-date) -- but you are creating a new revision to supersede the unwanted changes. You have to commit these changes, since you are changing the repository. Once done, any updates or new working copies based on the HEAD will show r101, with the contents you just committed.

Sql connection-string for localhost server

When using SQL Express, you need to specify \SQLExpress instance in your connection string:

string str = "Data Source=HARIHARAN-PC\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True" ;

Slide a layout up from bottom of screen

Here is what worked in the end for me.

Layouts:

activity_main.xml

<RelativeLayout
    android:id="@+id/main_screen"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:layout_alignParentTop="true"
    android:layout_alignParentBottom="true">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" 
        android:layout_alignParentTop="true"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:layout_centerInParent="true" />

    <Button
        android:id="@+id/slideButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Slide up / down"
        android:layout_alignParentBottom="true" 
        android:onClick="slideUpDown"/>

</RelativeLayout>

hidden_panel.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/hidden_panel"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Test" />
</LinearLayout>

Java: package com.example.slideuplayout;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;

public class MainActivity extends Activity {

private ViewGroup hiddenPanel;
private ViewGroup mainScreen;
private boolean isPanelShown;
private ViewGroup root;

int screenHeight = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mainScreen = (ViewGroup)findViewById(R.id.main_screen);
    ViewTreeObserver vto = mainScreen.getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
        @Override 
        public void onGlobalLayout() { 
            screenHeight = mainScreen.getHeight();
            mainScreen.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
        } 
    }); 

    root = (ViewGroup)findViewById(R.id.root);

    hiddenPanel = (ViewGroup)getLayoutInflater().inflate(R.layout.hidden_panel, root, false);
    hiddenPanel.setVisibility(View.INVISIBLE);

    root.addView(hiddenPanel);

    isPanelShown = false;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public void slideUpDown(final View view) {
    if(!isPanelShown) {
        // Show the panel
        mainScreen.layout(mainScreen.getLeft(),
                          mainScreen.getTop() - (screenHeight * 25/100), 
                          mainScreen.getRight(),
                          mainScreen.getBottom() - (screenHeight * 25/100));



        hiddenPanel.layout(mainScreen.getLeft(), mainScreen.getBottom(), mainScreen.getRight(), screenHeight);
        hiddenPanel.setVisibility(View.VISIBLE);

        Animation bottomUp = AnimationUtils.loadAnimation(this,
                R.anim.bottom_up);

        hiddenPanel.startAnimation(bottomUp);

        isPanelShown = true;
    }
    else {
        isPanelShown = false;

        // Hide the Panel
        Animation bottomDown = AnimationUtils.loadAnimation(this,
                R.anim.bottom_down);
        bottomDown.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationRepeat(Animation arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationEnd(Animation arg0) {
                isPanelShown = false;

                mainScreen.layout(mainScreen.getLeft(),
                          mainScreen.getTop() + (screenHeight * 25/100), 
                          mainScreen.getRight(),
                          mainScreen.getBottom() + (screenHeight * 25/100));

                hiddenPanel.layout(mainScreen.getLeft(), mainScreen.getBottom(), mainScreen.getRight(), screenHeight);
            }
        });
        hiddenPanel.startAnimation(bottomDown);
    }
}
}

DNS problem, nslookup works, ping doesn't

I know it's not your specific problem, but I faced the same symptoms when I configured a static IP address in the network adapter settings and forgot to enter a "Default Gateway".

Leaving the field blank, the network icon shows an Internet connection, and I could ping internal servers but not external ones, so I assumed it was a DNS problem. NSLookup still worked, but of course, ping failed to find the server (again, seemed like a DNS issue.) Anyway, one more thing to check. =P

Javascript - Track mouse position

Here is the simplest way to track your mouse position

Html

<body id="mouse-position" ></body>

js

document.querySelector('#mouse-position').addEventListener('mousemove', (e) => {
        console.log("mouse move X: ", e.clientX);
        console.log("mouse move X: ", e.screenX);


    }, );

know more

Python: How to get stdout after running os.system?

import subprocess
string="echo Hello world"
result=subprocess.getoutput(string)
print("result::: ",result)

Sort a two dimensional array based on one column

Assuming your array contains strings, you can use the following:

String[] data = new String[] { 
    "2009.07.25 20:24 Message A",
    "2009.07.25 20:17 Message G",
    "2009.07.25 20:25 Message B",
    "2009.07.25 20:30 Message D",
    "2009.07.25 20:01 Message F",
    "2009.07.25 21:08 Message E",
    "2009.07.25 19:54 Message R"
};

Arrays.sort(data, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        String t1 = s1.substring(0, 16); // date/time of s1
        String t2 = s2.substring(0, 16); // date/time of s2
        return t1.compareTo(t2);
    }
});

If you have a two-dimensional array, the solution is also very similar:

String[][] data = new String[][] { 
        { "2009.07.25 20:17", "Message G" },
        { "2009.07.25 20:25", "Message B" },
        { "2009.07.25 20:30", "Message D" },
        { "2009.07.25 20:01", "Message F" },
        { "2009.07.25 21:08", "Message E" },
        { "2009.07.25 19:54", "Message R" }
};

Arrays.sort(data, new Comparator<String[]>() {
    @Override
    public int compare(String[] s1, String[] s2) {
        String t1 = s1[0];
        String t2 = s2[0];
        return t1.compareTo(t2);
    }
});

When to use IMG vs. CSS background-image?

Just a small one to add, you should use the img tag if you want users to be able to 'right click' and 'save-image'/'save-picture', so if you intend to provide the image as a resource for others.

Using background image will (as far as I'm aware on most browsers) disable the option to save the image directly.

How do you get a timestamp in JavaScript?

var my_timestamp = ~~(Date.now()/1000);

How can I remove an element from a list, with lodash?

you can do it with _pull.

_.pull(obj["subTopics"] , {"subTopicId":2, "number":32});

check the reference

Excel VBA - Pass a Row of Cell Values to an Array and then Paste that Array to a Relative Reference of Cells

Since you are copying tha same data to all rows, you don't actually need to loop at all. Try this:

Sub ARRAYER()
    Dim Number_of_Sims As Long
    Dim rng As Range

    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    Number_of_Sims = 100000

    Set rng = Range("C4:G4")
    rng.Offset(1, 0).Resize(Number_of_Sims) = rng.Value

    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
End Sub

HAProxy redirecting http to https (ssl)

If you want to rewrite the url, you have to change your site virtualhost adding this lines:

### Enabling mod_rewrite
Options FollowSymLinks
RewriteEngine on

### Rewrite http:// => https://
RewriteCond %{SERVER_PORT} 80$
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,NC,L]

But, if you want to redirect all your requests on the port 80 to the port 443 of the web servers behind the proxy, you can try this example conf on your haproxy.cfg:

##########
# Global #
##########
global
    maxconn 100
    spread-checks 50
    daemon
    nbproc 4

############
# Defaults #
############
defaults
    maxconn 100
    log global
    mode http
    option dontlognull
    retries 3
    contimeout 60000
    clitimeout 60000
    srvtimeout 60000

#####################
# Frontend: HTTP-IN #
#####################
frontend http-in
    bind *:80
    option logasap
    option httplog
    option httpclose
    log global
    default_backend sslwebserver

#########################
# Backend: SSLWEBSERVER #
#########################
backend sslwebserver
    option httplog
    option forwardfor
    option abortonclose
    log global
    balance roundrobin
    # Server List
    server sslws01 webserver01:443 check
    server sslws02 webserver02:443 check
    server sslws03 webserver03:443 check

I hope this help you

Showing which files have changed between two revisions

And if you are looking for changes only among certain file(s), then:

git diff branch1 branch2 -- myfile1.js myfile2.js

branch1 is optional and your current branch (the branch you are on) will be considered by default if branch1 is not provided. e.g:

git diff master -- controller/index.js

Don't understand why UnboundLocalError occurs (closure)

try this

counter = 0

def increment():
  global counter
  counter += 1

increment()

pandas three-way joining multiple dataframes on columns

You could try this if you have 3 dataframes

# Merge multiple dataframes
df1 = pd.DataFrame(np.array([
    ['a', 5, 9],
    ['b', 4, 61],
    ['c', 24, 9]]),
    columns=['name', 'attr11', 'attr12'])
df2 = pd.DataFrame(np.array([
    ['a', 5, 19],
    ['b', 14, 16],
    ['c', 4, 9]]),
    columns=['name', 'attr21', 'attr22'])
df3 = pd.DataFrame(np.array([
    ['a', 15, 49],
    ['b', 4, 36],
    ['c', 14, 9]]),
    columns=['name', 'attr31', 'attr32'])

pd.merge(pd.merge(df1,df2,on='name'),df3,on='name')

alternatively, as mentioned by cwharland

df1.merge(df2,on='name').merge(df3,on='name')

When to use StringBuilder in Java

The + operator uses public String concat(String str) internally. This method copies the characters of the two strings, so it has memory requirements and runtime complexity proportional to the length of the two strings. StringBuilder works more efficent.

However I have read here that the concatination code using the + operater is changed to StringBuilder on post Java 4 compilers. So this might not be an issue at all. (Though I would really check this statement if I depend on it in my code!)

Struct inheritance in C++

Of course. In C++, structs and classes are nearly identical (things like defaulting to public instead of private are among the small differences).

Reference alias (calculated in SELECT) in WHERE clause

You can't reference an alias except in ORDER BY because SELECT is the second last clause that's evaluated. Two workarounds:

SELECT BalanceDue FROM (
  SELECT (InvoiceTotal - PaymentTotal - CreditTotal) AS BalanceDue
  FROM Invoices
) AS x
WHERE BalanceDue > 0;

Or just repeat the expression:

SELECT (InvoiceTotal - PaymentTotal - CreditTotal) AS BalanceDue
FROM Invoices
WHERE  (InvoiceTotal - PaymentTotal - CreditTotal)  > 0;

I prefer the latter. If the expression is extremely complex (or costly to calculate) you should probably consider a computed column (and perhaps persisted) instead, especially if a lot of queries refer to this same expression.

PS your fears seem unfounded. In this simple example at least, SQL Server is smart enough to only perform the calculation once, even though you've referenced it twice. Go ahead and compare the plans; you'll see they're identical. If you have a more complex case where you see the expression evaluated multiple times, please post the more complex query and the plans.

Here are 5 example queries that all yield the exact same execution plan:

SELECT LEN(name) + column_id AS x
FROM sys.all_columns
WHERE LEN(name) + column_id > 30;

SELECT x FROM (
SELECT LEN(name) + column_id AS x
FROM sys.all_columns
) AS x
WHERE x > 30;

SELECT LEN(name) + column_id AS x
FROM sys.all_columns
WHERE column_id + LEN(name) > 30;

SELECT name, column_id, x FROM (
SELECT name, column_id, LEN(name) + column_id AS x
FROM sys.all_columns
) AS x
WHERE x > 30;

SELECT name, column_id, x FROM (
SELECT name, column_id, LEN(name) + column_id AS x
FROM sys.all_columns
) AS x
WHERE LEN(name) + column_id > 30;

Resulting plan for all five queries:

enter image description here

How can I apply styles to multiple classes at once?

.abc, .xyz { margin-left: 20px; }

is what you are looking for.

How to check if a .txt file is in ASCII or UTF-8 format in Windows environment?

If you use Windows 10 and has Windows Subsystem for Linux (WSL), it can be easily done by typing "file " from the shell.

For example:

$ file code.cpp

code.cpp: C source, UTF-8 Unicode (with BOM) text, with CRLF line terminators

PHP session lost after redirect

I had the same problem and found the easiest way. I simply redirected to a redirect .html with 1 line of JS

<!DOCTYPE html>
<html>
<script type="text/javascript">
<!--
window.location = "admin_index.php";
//–>
</script>
</html>

instead of PHP

header_remove();
header('Location: admin_login.php');
die;

I hope this helps.

Love Gram

Scanner is never closed

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

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

The following untracked working tree files would be overwritten by merge, but I don't care

The only commands that worked for me were:

git fetch --all
git reset --hard origin/{{your branch name}}

How to extract text from an existing docx file using python-docx

I had a similar issue so I found a workaround (remove hyperlink tags thanks to regular expressions so that only a paragraph tag remains). I posted this solution on https://github.com/python-openxml/python-docx/issues/85 BP

How can I exclude all "permission denied" messages from "find"?

Use:

find . 2>/dev/null > files_and_folders

This hides not just the Permission denied errors, of course, but all error messages.

If you really want to keep other possible errors, such as too many hops on a symlink, but not the permission denied ones, then you'd probably have to take a flying guess that you don't have many files called 'permission denied' and try:

find . 2>&1 | grep -v 'Permission denied' > files_and_folders

If you strictly want to filter just standard error, you can use the more elaborate construction:

find . 2>&1 > files_and_folders | grep -v 'Permission denied' >&2

The I/O redirection on the find command is: 2>&1 > files_and_folders |. The pipe redirects standard output to the grep command and is applied first. The 2>&1 sends standard error to the same place as standard output (the pipe). The > files_and_folders sends standard output (but not standard error) to a file. The net result is that messages written to standard error are sent down the pipe and the regular output of find is written to the file. The grep filters the standard output (you can decide how selective you want it to be, and may have to change the spelling depending on locale and O/S) and the final >&2 means that the surviving error messages (written to standard output) go to standard error once more. The final redirection could be regarded as optional at the terminal, but would be a very good idea to use it in a script so that error messages appear on standard error.

There are endless variations on this theme, depending on what you want to do. This will work on any variant of Unix with any Bourne shell derivative (Bash, Korn, …) and any POSIX-compliant version of find.

If you wish to adapt to the specific version of find you have on your system, there may be alternative options available. GNU find in particular has a myriad options not available in other versions — see the currently accepted answer for one such set of options.

MongoDB logging all queries

Setting profilinglevel to 2 is another option to log all queries.

What does "zend_mm_heap corrupted" mean

A lot of people are mentioning disabling XDebug to solve the issue. This obviously isn't viable in a lot of instances, as it's enabled for a reason - to debug your code.

I had the same issue, and noticed that if I stopped listening for XDebug connections in my IDE (PhpStorm 2019.1 EAP), the error stopped occurring.

The actual fix, for me, was removing any existing breakpoints.

A possibility for this being a valid fix is that PhpStorm is sometimes not that good at removing breakpoints that no longer reference valid lines of code after files have been changed externally (e.g. by git)

Edit: Found the corresponding bug report in the xdebug issue tracker: https://bugs.xdebug.org/view.php?id=1647

Convert java.time.LocalDate into java.util.Date type

Simple

public Date convertFrom(LocalDate date) {
    return java.sql.Timestamp.valueOf(date.atStartOfDay());
}

How to get the location of the DLL currently executing?

You are looking for System.Reflection.Assembly.GetExecutingAssembly()

string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string xmlFileName = Path.Combine(assemblyFolder,"AggregatorItems.xml");

Note:

The .Location property returns the location of the currently running DLL file.

Under some conditions the DLL is shadow copied before execution, and the .Location property will return the path of the copy. If you want the path of the original DLL, use the Assembly.GetExecutingAssembly().CodeBase property instead.

.CodeBase contains a prefix (file:\), which you may need to remove.

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

csvreader.next() Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.

Non greedy (reluctant) regex matching in sed?

sed -E interprets regular expressions as extended (modern) regular expressions

Update: -E on MacOS X, -r in GNU sed.

Input and output numpy arrays to h5py

h5py provides a model of datasets and groups. The former is basically arrays and the latter you can think of as directories. Each is named. You should look at the documentation for the API and examples:

http://docs.h5py.org/en/latest/quick.html

A simple example where you are creating all of the data upfront and just want to save it to an hdf5 file would look something like:

In [1]: import numpy as np
In [2]: import h5py
In [3]: a = np.random.random(size=(100,20))
In [4]: h5f = h5py.File('data.h5', 'w')
In [5]: h5f.create_dataset('dataset_1', data=a)
Out[5]: <HDF5 dataset "dataset_1": shape (100, 20), type "<f8">

In [6]: h5f.close()

You can then load that data back in using: '

In [10]: h5f = h5py.File('data.h5','r')
In [11]: b = h5f['dataset_1'][:]
In [12]: h5f.close()

In [13]: np.allclose(a,b)
Out[13]: True

Definitely check out the docs:

http://docs.h5py.org

Writing to hdf5 file depends either on h5py or pytables (each has a different python API that sits on top of the hdf5 file specification). You should also take a look at other simple binary formats provided by numpy natively such as np.save, np.savez etc:

http://docs.scipy.org/doc/numpy/reference/routines.io.html

What does "all" stand for in a makefile?

Not sure it stands for anything special. It's just a convention that you supply an 'all' rule, and generally it's used to list all the sub-targets needed to build the entire project, hence the name 'all'. The only thing special about it is that often times people will put it in as the first target in the makefile, which means that just typing 'make' alone will do the same thing as 'make all'.

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

Since C++11 std::regex_search can also be used to provide even more complex expressions matching. The following example handles also floating numbers thorugh std::stof and a subsequent cast to int.

However the parseInt method shown below could throw a std::invalid_argument exception if the prefix is not matched; this can be easily adapted depending on the given application:

#include <iostream>
#include <regex>

int parseInt(const std::string &str, const std::string &prefix) {
  std::smatch match;
  std::regex_search(str, match, std::regex("^" + prefix + "([+-]?(?=\\.?\\d)\\d*(?:\\.\\d*)?(?:[Ee][+-]?\\d+)?)$"));
  return std::stof(match[1]);
}

int main() {
    std::cout << parseInt("foo=13.3", "foo=") << std::endl;
    std::cout << parseInt("foo=-.9", "foo=") << std::endl;
    std::cout << parseInt("foo=+13.3", "foo=") << std::endl;
    std::cout << parseInt("foo=-0.133", "foo=") << std::endl;
    std::cout << parseInt("foo=+00123456", "foo=") << std::endl;
    std::cout << parseInt("foo=-06.12e+3", "foo=") << std::endl;

//    throw std::invalid_argument
//    std::cout << parseInt("foo=1", "bar=") << std::endl;

    return 0;
}

The kind of magic of the regex pattern is well detailed in the following answer.

EDIT: the previous answer did not performed the conversion to integer.

Best way to list files in Java, sorted by Date Modified?

A slightly more modernized version of the answer of @jason-orendorf.

Note: this implementation keeps the original array untouched, and returns a new array. This might or might not be desirable.

files = Arrays.stream(files)
        .map(FileWithLastModified::ofFile)
        .sorted(comparingLong(FileWithLastModified::lastModified))
        .map(FileWithLastModified::file)
        .toArray(File[]::new);

private static class FileWithLastModified {
    private final File file;
    private final long lastModified;

    private FileWithLastModified(File file, long lastModified) {
        this.file = file;
        this.lastModified = lastModified;
    }

    public static FileWithLastModified ofFile(File file) {
        return new FileWithLastModified(file, file.lastModified());
    }

    public File file() {
        return file;
    }

    public long lastModified() {
        return lastModified;
    }
}

But again, all credits to @jason-orendorf for the idea!

Importing text file into excel sheet

you can write .WorkbookConnection.Delete after .Refresh BackgroundQuery:=False this will delete text file external connection.

How to initialize a private static const map in C++?

I often use this pattern and recommend you to use it as well:

class MyMap : public std::map<int, int>
{
public:
    MyMap()
    {
        //either
        insert(make_pair(1, 2));
        insert(make_pair(3, 4));
        insert(make_pair(5, 6));
        //or
        (*this)[1] = 2;
        (*this)[3] = 4;
        (*this)[5] = 6;
    }
} const static my_map;

Sure it is not very readable, but without other libs it is best we can do. Also there won't be any redundant operations like copying from one map to another like in your attempt.

This is even more useful inside of functions: Instead of:

void foo()
{
   static bool initComplete = false;
   static Map map;
   if (!initComplete)
   {
      initComplete = true;
      map= ...;
   }
}

Use the following:

void bar()
{
    struct MyMap : Map
    {
      MyMap()
      {
         ...
      }
    } static mymap;
}

Not only you don't need here to deal with boolean variable anymore, you won't have hidden global variable that is checked if initializer of static variable inside function was already called.

How to use session in JSP pages to get information?

Suppose you want to use, say ID in any other webpage then you can do it by following code snippet :

String id=(String)session.getAttribute("uid");

Here uid is the attribute in which you have stored the ID earlier. You can set it by:

session.setAttribute("uid",id);

What is the facade design pattern?

Facade Design Pattern comes under Structural Design Pattern. In short Facade means the exterior appearance. It means in Facade design pattern we hide something and show only what actually client requires. Read more at below blog: http://www.sharepointcafe.net/2017/03/facade-design-pattern-in-aspdotnet.html

Modifying the "Path to executable" of a windows service

You can delete the service:

sc delete ServiceName

Then recreate the service.

Listing only directories in UNIX

The following

find * -maxdepth 0 -type d

basically filters the expansion of '*', i.e. all entries in the current dir, by the -type d condition.

Advantage is that, output is same as ls -1 *, but only with directories and entries do not start with a dot

How to identify and switch to the frame in selenium webdriver when frame does not have id

You also can use src to switch to frame, here is what you can use:

driver.switchTo().frame(driver.findElement(By.xpath(".//iframe[@src='https://tssstrpms501.corp.trelleborg.com:12001/teamworks/process.lsw?zWorkflowState=1&zTaskId=4581&zResetContext=true&coachDebugTrace=none']")));

What happens if you mount to a non-empty mount point with fuse?

Just add -o nonempty in command line, like this:

s3fs -o nonempty  <bucket-name> </mount/point/>

Why is using onClick() in HTML a bad practice?

There are a few reasons:

  1. I find it aids maintenence to separate markup, i.e. the HTML and client-side scripts. For example, jQuery makes it easy to add event handlers programatically.

  2. The example you give would be broken in any user agent that doesn't support javascript, or has javascript turned off. The concept of progressive enhancement would encourage a simple hyperlink to /map/ for user agents without javascript, then adding a click handler prgramatically for user agents that support javascript.

For example:

Markup:

<a id="example" href="/map/">link</a>

Javascript:

$(document).ready(function(){

    $("#example").click(function(){
        popup('/map/', 300, 300, 'map');
        return false;
    });

})

the MySQL service on local computer started and then stopped

The same problem happened with me also, nothing worked... I first deleted the service (in my case MySQL80 and MySQL) by command:

sc delete MySQL80
sc delete MySql

and then reinstalled MySQL. Mine was MySQL 8.0. And then everything was back to normal.

Creating custom function in React component

Another way:

export default class Archive extends React.Component { 

  saySomething = (something) => {
    console.log(something);
  }

  handleClick = (e) => {
    this.saySomething("element clicked");
  }

  componentDidMount() {
    this.saySomething("component did mount");
  }

  render() {
    return <button onClick={this.handleClick} value="Click me" />;
  }
}

In this format you don't need to use bind

form_for but to post to a different action

If you want to pass custom Controller to a form_for while rendering a partial form you can use this:

<%= render 'form', :locals => {:controller => 'my_controller', :action => 'my_action'}%>

and then in the form partial use this local variable like this:

<%= form_for(:post, :url => url_for(:controller => locals[:controller], :action => locals[:action]), html: {class: ""} ) do |f| -%>

Arduino Sketch upload issue - avrdude: stk500_recv(): programmer is not responding

I found the cause of this...

Changing my serial port to /dev/tty.usbmodem2131 fixed it. It turns out I was using the wrong serial port this whole time!

$rootScope.$broadcast vs. $scope.$emit

They are not doing the same job: $emit dispatches an event upwards through the scope hierarchy, while $broadcast dispatches an event downwards to all child scopes.

Change event on select with knockout binding, how can I know if it is a real change?

If you use an observable instead of a primitive value, the select will not raise change events on initial binding. You can continue to bind to the change event, rather than subscribing directly to the observable.

What is the difference between H.264 video and MPEG-4 video?

They are names for the same standard from two different industries with different naming methods, the guys who make & sell movies and the guys who transfer the movies over the internet. Since 2003: "MPEG 4 Part 10" = "H.264" = "AVC". Before that the relationship was a little looser in that they are not equal but an "MPEG 4 Part 2" decoder can render a stream that's "H.263". The Next standard is "MPEG H Part 2" = "H.265" = "HEVC"

How to Set a Custom Font in the ActionBar Title?

Try using This

TextView headerText= new TextView(getApplicationContext());
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
headerText.setLayoutParams(lp);
headerText.setText("Welcome!");
headerText.setTextSize(20);
headerText.setTextColor(Color.parseColor("#FFFFFF"));
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/wesfy_regular.ttf");
headerText.setTypeface(tf);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(headerText);

How to detect a remote side socket close?

You can also check for socket output stream error while writing to client socket.

out.println(output);
if(out.checkError())
{
    throw new Exception("Error transmitting data.");
}

HTML: how to make 2 tables with different CSS

Of course, just assign seperate css classes to both tables.

<table class="style1"></table>
<table class="style2"></table>

.css

table.style1 { //your css here}
table.style2 { //your css here}

How to count the number of observations in R like Stata command count

The with function will let you use shorthand column references and sum will count TRUE results from the expression(s).

sum(with(aaa, sex==1 & group1==2))
## [1] 3

sum(with(aaa, sex==1 & group2=="A"))
## [1] 2

As @mnel pointed out, you can also do:

nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3

nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2

The benefit of that is that you can do:

nrow(aaa)
## [1] 6

And, the behaviour matches Stata's count almost exactly (syntax notwithstanding).

Fastest way to compute entropy in Python

BiEntropy wont be the fastest way of computing entropy, but it is rigorous and builds upon Shannon Entropy in a well defined way. It has been tested in various fields including image related applications. It is implemented in Python on Github.

AngularJS resource promise

/*link*/
$q.when(scope.regions).then(function(result) {
    console.log(result);
});
var Regions = $resource('mocks/regions.json');
$scope.regions = Regions.query().$promise.then(function(response) {
    return response;
});

Evaluate if list is empty JSTL

empty is an operator:

The empty operator is a prefix operation that can be used to determine whether a value is null or empty.

<c:if test="${empty myObject.featuresList}">

Execution failed for task :':app:mergeDebugResources'. Android Studio

For me upgrading gradle version and plugin to the latest version did the trick.

Create a Date with a set timezone without using a string representation

I was having a similar problem with a date picker. My research led to a very simple solution, without any extra libraries or hardcoded multipliers.

Key info:

  1. ISO is the Javascript preferred date standard. Assume date utilities will likely return date values in that format.
    • My date picker displays the date in a localized format: mm/dd/yyyy

    • However, it returns the date value in the ISO format: yyyy-mm-dd

      //Select "08/12/2020" in Date Picker date_input 
      
      var input = $('#date_input').val();  //input: 2020-08-12
      
  1. Date.getTimezoneOffset() returns the offset in minutes.

Examples:

If you use the default returned date value without modifying the string format, the Date might not get set to your timezone. This can lead to unexpected results.

var input = $('#date_input').val();  //input: 2020-08-12
var date = new Date(input);          //This get interpreted as an ISO date, already in UTC
//date:                             Tue Aug 11 2020 20:00:00 GMT-0400 (Eastern Daylight Time)
//date.toUTCString():               Wed, 12 Aug 2020 00:00:00 GMT
//date.toLocaleDateString('en-US'):       8/11/2020

Using a different date string format than the ISO standard yyyy-mm-dd applies your timezone to the Date.

var date = new Date("08/12/2020");  //This gets interpreted as local timezone
//date:                             Wed Aug 12 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
//date.toUTCString():               Wed, 12 Aug 2020 04:00:00 GMT
//date.toLocaleDateString('en-US'):       8/12/2020

Solution:

To apply your timezone to the format-agnostic Date without doing string manipulation, use Date.getTimezoneOffset() with Minutes. This works with either original date string format (i.e. UTC dates or localized dates). It provides a consistent result which can then be converted accurately to UTC for storage or interacting with other code.

var input = $('#date_input').val();
var date = new Date(input);
date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
//date:                             Wed Aug 12 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
//date.toUTCString():               Wed, 12 Aug 2020 04:00:00 GMT
//date.toLocaleDateString('en-US'):       8/12/2020
                

How do I convert an object to an array?

Single-dimensional arrays

For converting single-dimension arrays, you can cast using (array) or there's get_object_vars, which Benoit mentioned in his answer.

// Cast to an array
$array = (array) $object;
// get_object_vars
$array = get_object_vars($object);

They work slightly different from each other. For example, get_object_vars will return an array with only publicly accessible properties unless it is called from within the scope of the object you're passing (ie in a member function of the object). (array), on the other hand, will cast to an array with all public, private and protected members intact on the array, though all public now, of course.

Multi-dimensional arrays

A somewhat dirty method is to use PHP >= 5.2's native JSON functions to encode to JSON and then decode back to an array. This will not include private and protected members, however, and is not suitable for objects that contain data that cannot be JSON encoded (such as binary data).

// The second parameter of json_decode forces parsing into an associative array
$array = json_decode(json_encode($object), true);

Alternatively, the following function will convert from an object to an array including private and protected members, taken from here and modified to use casting:

function objectToArray ($object) {
    if(!is_object($object) && !is_array($object))
        return $object;

    return array_map('objectToArray', (array) $object);
}

Take nth column in a text file

You can use the cut command:

cut -d' ' -f3,5 < datafile.txt

prints

1657 19.6117
1410 18.8302
3078 18.6695
2434 14.0508
3129 13.5495

the

  • -d' ' - mean, use space as a delimiter
  • -f3,5 - take and print 3rd and 5th column

The cut is much faster for large files as a pure shell solution. If your file is delimited with multiple whitespaces, you can remove them first, like:

sed 's/[\t ][\t ]*/ /g' < datafile.txt | cut -d' ' -f3,5

where the (gnu) sed will replace any tab or space characters with a single space.

For a variant - here is a perl solution too:

perl -lanE 'say "$F[2] $F[4]"' < datafile.txt

How to specify new GCC path for CMake

This not only works with cmake, but also with ./configure and make:

./configure CC=/usr/local/bin/gcc CXX=/usr/local/bin/g++

Which is resulting in:

checking for gcc... /usr/local/bin/gcc
checking whether the C compiler works... yes

PHP Converting Integer to Date, reverse of strtotime

The time() function displays the seconds between now and the unix epoch , 01 01 1970 (00:00:00 GMT). The strtotime() transforms a normal date format into a time() format. So the representation of that date into seconds will be : 1388516401

Source: http://www.php.net/time

Add single element to array in numpy

a[0] isn't an array, it's the first element of a and therefore has no dimensions.

Try using a[0:1] instead, which will return the first element of a inside a single item array.

Show hide div using codebehind

There are a few ways to handle rendering/showing controls on the page and you should take note to what happens with each method.

Rendering and Visibility

There are some instances where elements on your page don't need to be rendered for the user because of some type of logic or database value. In this case, you can prevent rendering (creating the control on the returned web page) altogether. You would want to do this if the control doesn't need to be shown later on the client side because no matter what, the user viewing the page never needs to see it.

Any controls or elements can have their visibility set from the server side. If it is a plain old html element, you just need to set the runat attribute value to server on the markup page.

<div id="myDiv" runat="server"></div>

The decision to render the div or not can now be done in the code behind class like so:

myDiv.Visible = someConditionalBool;

If set to true, it will be rendered on the page and if it's false it won't be rendered at all, not even hidden.

Client Side Hiding

Hiding an element is done on the client side only. Meaning, it's rendered but it has a display CSS style set on it which instructs your browser to not show it to the user. This is beneficial when you want to hide/show things based on user input. It's important to know that the element CAN be hidden on the server side too as long as the element/control has runat=server set just as I explained in the previous example.

Hiding in the Code Behind Class

To hide an element that you want rendered to the page but hidden is another simple single line of code:

myDiv.Style["display"] = "none";

If you have a need to remove the display style server side, it can be done by removing the display style, or setting it to a different value like inline or block (values described here).

myDiv.Style.Remove("display");
// -- or --
myDiv.Style["display"] = "inline";

Hiding on the Client Side with javascript

Using plain old javascript, you can easily hide the same element in this manner

var myDivElem = document.getElementById("myDiv");
myDivElem.style.display = "none";

// then to show again
myDivElem.style.display = "";

jQuery makes hiding elements a little simpler if you prefer to use jQuery:

var myDiv = $("#<%=myDiv.ClientID%>");
myDiv.hide();

// ... and to show 
myDiv.show();

Open terminal here in Mac OS finder

I mostly use this function:

cf() {
  cd "$(osascript -e 'tell app "Finder" to POSIX path of (insertion location as alias)')"
}

You could also assign a shortcut to a script like the ones below.

Reuse an existing tab or create a new window (Terminal):

tell application "Finder" to set p to POSIX path of (insertion location as alias)
tell application "Terminal"
    if (exists window 1) and not busy of window 1 then
        do script "cd " & quoted form of p in window 1
    else
        do script "cd " & quoted form of p
    end if
    activate
end tell

Reuse an existing tab or create a new tab (Terminal):

tell application "Finder" to set p to POSIX path of (insertion location as alias)
tell application "Terminal"
    if not (exists window 1) then reopen
    activate
    if busy of window 1 then
        tell application "System Events" to keystroke "t" using command down
    end if
    do script "cd " & quoted form of p in window 1
end tell

Always create a new tab (iTerm 2):

tell application "Finder" to set p to POSIX path of (insertion location as alias)
tell application "iTerm"
    if exists current terminal then
        current terminal
    else
        make new terminal
    end if
    tell (launch session "Default") of result to write text "cd " & quoted form of p
    activate
end tell

The first two scripts have two advantages compared to the services added in 10.7:

  • They use the folder on the title bar instead of requiring you to select a folder first.
  • They reuse the frontmost tab if it is not busy, e.g. running a command, displaying a man page, or running emacs.

Android and setting alpha for (image) view alpha

I am not sure about the XML but you can do it by code in the following way.

ImageView myImageView = new ImageView(this);
myImageView.setAlpha(xxx);

In pre-API 11:

  • range is from 0 to 255 (inclusive), 0 being transparent and 255 being opaque.

In API 11+:

  • range is from 0f to 1f (inclusive), 0f being transparent and 1f being opaque.

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

Adding to the answers above -

To use in a script, use the following :-

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

TypeError: 'module' object is not callable

check the import statements since a module is not callable. In Python, everything (including functions, methods, modules, classes etc.) is an object.

How to set ChartJS Y axis title?

In Chart.js version 2.0 this is possible:

options = {
  scales: {
    yAxes: [{
      scaleLabel: {
        display: true,
        labelString: 'probability'
      }
    }]
  }
}

See axes labelling documentation for more details.

JavaScript onclick redirect

Just do

onclick="SubmitFrm"

The javascript: prefix is only required for link URLs.

how to stop a running script in Matlab

MATLAB doesn't respond to Ctrl-C while executing a mex implemented function such as svd. Also when MATLAB is allocating big chunk of memory it doesn't respond. A good practice is to always run your functions for small amount of data, and when all test passes run it for actual scale. When time is an issue, you would want to analyze how much time each segment of code runs as well as their rough time complexity.

How do I resolve a path relative to an ASP.NET MVC 4 application root?

In the action you can call:

this.Request.PhysicalPath

that returns the physical path in reference to the current controller. If you only need the root path call:

this.Request.PhysicalApplicationPath

Convert base64 png data to javascript file objects

You can create a Blob from your base64 data, and then read it asDataURL:

var img_b64 = canvas.toDataURL('image/png');
var png = img_b64.split(',')[1];

var the_file = new Blob([window.atob(png)],  {type: 'image/png', encoding: 'utf-8'});

var fr = new FileReader();
fr.onload = function ( oFREvent ) {
    var v = oFREvent.target.result.split(',')[1]; // encoding is messed up here, so we fix it
    v = atob(v);
    var good_b64 = btoa(decodeURIComponent(escape(v)));
    document.getElementById("uploadPreview").src = "data:image/png;base64," + good_b64;
};
fr.readAsDataURL(the_file);

Full example (includes junk code and console log): http://jsfiddle.net/tTYb8/


Alternatively, you can use .readAsText, it works fine, and its more elegant.. but for some reason text does not sound right ;)

fr.onload = function ( oFREvent ) {
    document.getElementById("uploadPreview").src = "data:image/png;base64,"
    + btoa(oFREvent.target.result);
};
fr.readAsText(the_file, "utf-8"); // its important to specify encoding here

Full example: http://jsfiddle.net/tTYb8/3/

Calling the base class constructor from the derived class constructor

The base-class constructor is already automatically called by your derived-class constructor. In C++, if the base class has a default constructor (takes no arguments, can be auto-generated by the compiler!), and the derived-class constructor does not invoke another base-class constructor in its initialisation list, the default constructor will be called. I.e. your code is equivalent to:

class PetStore: public Farm
{
public :
    PetStore()
    : Farm()     // <---- Call base-class constructor in initialision list
    {
     idF=0;
    };
private:
    int idF;
    string nameF;
}

Remove Item from ArrayList

remove(int index) method of arraylist removes the element at the specified position(index) in the list. After removing arraylist items shifts any subsequent elements to the left.

Means if a arraylist contains {20,15,30,40}

I have called the method: arraylist.remove(1)

then the data 15 will be deleted and 30 & 40 these two items will be left shifted by 1.

For this reason you have to delete higher index item of arraylist first.

So..for your given situation..the code will be..

ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
list.add("F");
list.add("G");
list.add("H");

int i[] = {1,3,5};

for (int j = i.length-1; j >= 0; j--) {
    list.remove(i[j]);
}

What causes a SIGSEGV

SigSegV means a signal for memory access violation, trying to read or write from/to a memory area that your process does not have access to. These are not C or C++ exceptions and you can’t catch signals. It’s possible indeed to write a signal handler that ignores the problem and allows continued execution of your unstable program in undefined state, but it should be obvious that this is a very bad idea.

Most of the time this is because of a bug in the program. The memory address given can help debug what’s the problem (if it’s close to zero then it’s likely a null pointer dereference, if the address is something like 0xadcedfe then it’s intentional safeguard or a debug check, etc.)

One way of “catching” the signal is to run your stuff in a separate child process that can then abruptly terminate without taking your main process down with it. Finding the root cause and fixing it is obviously preferred over workarounds like this.

Is there a Subversion command to reset the working copy?

Pure Windows cmd/bat solution:

svn cleanup .
svn revert -R .
For /f "tokens=1,2" %%A in ('svn status --no-ignore') Do (
     If [%%A]==[?] ( Call :UniDelete %%B
     ) Else If [%%A]==[I] Call :UniDelete %%B
   )
svn update .
goto :eof

:UniDelete delete file/dir
IF EXIST "%1\*" (
    RD /S /Q "%1"
) Else (
    If EXIST "%1" DEL /S /F /Q "%1"
)
goto :eof

Resize on div element

You can change your text or Content or Attribute depend on Screen size: HTML:

<p class="change">Frequently Asked Questions (FAQ)</p>
<p class="change">Frequently Asked Questions </p>

Javascript:

<script>
const changeText = document.querySelector('.change');
function resize() {
  if((window.innerWidth<500)&&(changeText.textContent="Frequently Asked Questions (FAQ)")){
    changeText.textContent="FAQ";
  } else {
    changeText.textContent="Frequently Asked Questions (FAQ)";
  }
}
window.onresize = resize;
</script>

Split string based on a regular expression

When you use re.split and the split pattern contains capturing groups, the groups are retained in the output. If you don't want this, use a non-capturing group instead.

Meaning of = delete after function declaration

A deleted function is implicitly inline

(Addendum to existing answers)

... And a deleted function shall be the first declaration of the function (except for deleting explicit specializations of function templates - deletion should be at the first declaration of the specialization), meaning you cannot declare a function and later delete it, say, at its definition local to a translation unit.

Citing [dcl.fct.def.delete]/4:

A deleted function is implicitly inline. ( Note: The one-definition rule ([basic.def.odr]) applies to deleted definitions. — end note ] A deleted definition of a function shall be the first declaration of the function or, for an explicit specialization of a function template, the first declaration of that specialization. [ Example:

struct sometype {
  sometype();
};
sometype::sometype() = delete;      // ill-formed; not first declaration

end example )

A primary function template with a deleted definition can be specialized

Albeit a general rule of thumb is to avoid specializing function templates as specializations do not participate in the first step of overload resolution, there are arguable some contexts where it can be useful. E.g. when using a non-overloaded primary function template with no definition to match all types which one would not like implicitly converted to an otherwise matching-by-conversion overload; i.e., to implicitly remove a number of implicit-conversion matches by only implementing exact type matches in the explicit specialization of the non-defined, non-overloaded primary function template.

Before the deleted function concept of C++11, one could do this by simply omitting the definition of the primary function template, but this gave obscure undefined reference errors that arguably gave no semantic intent whatsoever from the author of primary function template (intentionally omitted?). If we instead explicitly delete the primary function template, the error messages in case no suitable explicit specialization is found becomes much nicer, and also shows that the omission/deletion of the primary function template's definition was intentional.

#include <iostream>
#include <string>

template< typename T >
void use_only_explicit_specializations(T t);

template<>
void use_only_explicit_specializations<int>(int t) {
    std::cout << "int: " << t;
}

int main()
{
    const int num = 42;
    const std::string str = "foo";
    use_only_explicit_specializations(num);  // int: 42
    //use_only_explicit_specializations(str); // undefined reference to `void use_only_explicit_specializations< ...
}

However, instead of simply omitting a definition for the primary function template above, yielding an obscure undefined reference error when no explicit specialization matches, the primary template definition can be deleted:

#include <iostream>
#include <string>

template< typename T >
void use_only_explicit_specializations(T t) = delete;

template<>
void use_only_explicit_specializations<int>(int t) {
    std::cout << "int: " << t;
}

int main()
{
    const int num = 42;
    const std::string str = "foo";
    use_only_explicit_specializations(num);  // int: 42
    use_only_explicit_specializations(str);
    /* error: call to deleted function 'use_only_explicit_specializations' 
       note: candidate function [with T = std::__1::basic_string<char>] has 
       been explicitly deleted
       void use_only_explicit_specializations(T t) = delete; */
}

Yielding a more more readable error message, where the deletion intent is also clearly visible (where an undefined reference error could lead to the developer thinking this an unthoughtful mistake).

Returning to why would we ever want to use this technique? Again, explicit specializations could be useful to implicitly remove implicit conversions.

#include <cstdint>
#include <iostream>

void warning_at_best(int8_t num) { 
    std::cout << "I better use -Werror and -pedantic... " << +num << "\n";
}

template< typename T >
void only_for_signed(T t) = delete;

template<>
void only_for_signed<int8_t>(int8_t t) {
    std::cout << "UB safe! 1 byte, " << +t << "\n";
}

template<>
void only_for_signed<int16_t>(int16_t t) {
    std::cout << "UB safe! 2 bytes, " << +t << "\n";
}

int main()
{
    const int8_t a = 42;
    const uint8_t b = 255U;
    const int16_t c = 255;
    const float d = 200.F;

    warning_at_best(a); // 42
    warning_at_best(b); // implementation-defined behaviour, no diagnostic required
    warning_at_best(c); // narrowing, -Wconstant-conversion warning
    warning_at_best(d); // undefined behaviour!

    only_for_signed(a);
    only_for_signed(c);

    //only_for_signed(b);  
    /* error: call to deleted function 'only_for_signed' 
       note: candidate function [with T = unsigned char] 
             has been explicitly deleted
       void only_for_signed(T t) = delete; */

    //only_for_signed(d);
    /* error: call to deleted function 'only_for_signed' 
       note: candidate function [with T = float] 
             has been explicitly deleted
       void only_for_signed(T t) = delete; */
}

Call to a member function fetch_assoc() on boolean in <path>

Please use if condition with while loop and try.

eg.

if ($result = $conn->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {

    }
    /* free result set */
    $result->free();
}

Pass array to ajax request in $.ajax()

Just use the JSON.stringify method and pass it through as the "data" parameter for the $.ajax function, like follows:

$.ajax({
    type: "POST",
    url: "index.php",
    dataType: "json",
    data: JSON.stringify({ paramName: info }),
    success: function(msg){
        $('.answer').html(msg);
    }
});

You just need to make sure you include the JSON2.js file in your page...

How to set the height and the width of a textfield in Java?

xyz.setColumns() method is control the width of TextField.

import java.awt.*;
import javax.swing.*;



class miniproj extends JFrame {

  public static void main(String[] args)
  {
    JFrame frame=new JFrame();
    JPanel panel=new JPanel();
    frame.setSize(400,400);
    frame.setTitle("Registration");


    JLabel lablename=new JLabel("Enter your name");
    TextField tname=new TextField(30);
    tname.setColumns(45);

    JLabel lableemail=new JLabel("Enter your Email");
    TextField email=new TextField(30);
    email.setColumns(45);
    JLabel lableaddress=new JLabel("Enter your address");
    TextField address=new TextField(30);
    address.setColumns(45);
    address.setFont(Font.getFont(Font.SERIF));
    JLabel lablepass=new JLabel("Enter your password");
    TextField pass=new TextField(30);
    pass.setColumns(45);

    JButton login=new JButton();
    JButton create=new JButton();
    login.setPreferredSize(new Dimension(90,30));
    login.setText("Login");
    create.setPreferredSize(new Dimension(90,30));
    create.setText("Create");



    panel.add(lablename);
    panel.add(tname);
    panel.add(lableemail);
    panel.add(email);
    panel.add(lableaddress);
    panel.add(address);
    panel.add(lablepass);
    panel.add(pass);
    panel.add(create);
    panel.add(login);



    frame.add(panel);
    frame.setVisible(true);
  }
}

enter image description here

How to fill color in a cell in VBA?

You need to use cell.Text = "#N/A" instead of cell.Value = "#N/A". The error in the cell is actually just text stored in the cell.

How to hide image broken Icon using only CSS/HTML?

There is no way for CSS/HTML to know if the image is broken link, so you are going to have to use JavaScript no matter what

But here is a minimal method for either hiding the image, or replacing the source with a backup.

<img src="Error.src" onerror="this.style.display='none'"/>

or

<img src="Error.src" onerror="this.src='fallback-img.jpg'"/>

Update

You can apply this logic to multiple images at once by doing something like this:

_x000D_
_x000D_
document.addEventListener("DOMContentLoaded", function(event) {_x000D_
   document.querySelectorAll('img').forEach(function(img){_x000D_
   img.onerror = function(){this.style.display='none';};_x000D_
   })_x000D_
});
_x000D_
<img src="error.src">_x000D_
<img src="error.src">_x000D_
<img src="error.src">_x000D_
<img src="error.src">
_x000D_
_x000D_
_x000D_

Update 2

For a CSS option see michalzuber's answer below. You can't hide the entire image, but you change how the broken icon looks.

How to build PDF file from binary string returned from a web-service using javascript

Is there any solution like building a pdf file on file system in order to let the user download it?

Try setting responseType of XMLHttpRequest to blob , substituting download attribute at a element for window.open to allow download of response from XMLHttpRequest as .pdf file

var request = new XMLHttpRequest();
request.open("GET", "/path/to/pdf", true); 
request.responseType = "blob";
request.onload = function (e) {
    if (this.status === 200) {
        // `blob` response
        console.log(this.response);
        // create `objectURL` of `this.response` : `.pdf` as `Blob`
        var file = window.URL.createObjectURL(this.response);
        var a = document.createElement("a");
        a.href = file;
        a.download = this.response.name || "detailPDF";
        document.body.appendChild(a);
        a.click();
        // remove `a` following `Save As` dialog, 
        // `window` regains `focus`
        window.onfocus = function () {                     
          document.body.removeChild(a)
        }
    };
};
request.send();

How to read a file into a variable in shell?

As Ciro Santilli notes using command substitutions will drop trailing newlines. Their workaround adding trailing characters is great, but after using it for quite some time I decided I needed a solution that didn't use command substitution at all.

My approach now uses read along with the printf builtin's -v flag in order to read the contents of stdin directly into a variable.

# Reads stdin into a variable, accounting for trailing newlines. Avoids
# needing a subshell or command substitution.
# Note that NUL bytes are still unsupported, as Bash variables don't allow NULs.
# See https://stackoverflow.com/a/22607352/113632
read_input() {
  # Use unusual variable names to avoid colliding with a variable name
  # the user might pass in (notably "contents")
  : "${1:?Must provide a variable to read into}"
  if [[ "$1" == '_line' || "$1" == '_contents' ]]; then
    echo "Cannot store contents to $1, use a different name." >&2
    return 1
  fi

  local _line _contents=()
   while IFS='' read -r _line; do
     _contents+=("$_line"$'\n')
   done
   # include $_line once more to capture any content after the last newline
   printf -v "$1" '%s' "${_contents[@]}" "$_line"
}

This supports inputs with or without trailing newlines.

Example usage:

$ read_input file_contents < /tmp/file
# $file_contents now contains the contents of /tmp/file

Iterating over and deleting from Hashtable in Java

You need to use an explicit java.util.Iterator to iterate over the Map's entry set rather than being able to use the enhanced For-loop syntax available in Java 6. The following example iterates over a Map of Integer, String pairs, removing any entry whose Integer key is null or equals 0.

Map<Integer, String> map = ...

Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();

while (it.hasNext()) {
  Map.Entry<Integer, String> entry = it.next();

  // Remove entry if key is null or equals 0.
  if (entry.getKey() == null || entry.getKey() == 0) {
    it.remove();
  }
}

Fastest way to write huge data in text file Java

You might try removing the BufferedWriter and just using the FileWriter directly. On a modern system there's a good chance you're just writing to the drive's cache memory anyway.

It takes me in the range of 4-5 seconds to write 175MB (4 million strings) -- this is on a dual-core 2.4GHz Dell running Windows XP with an 80GB, 7200-RPM Hitachi disk.

Can you isolate how much of the time is record retrieval and how much is file writing?

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

public class FileWritingPerfTest {
    

private static final int ITERATIONS = 5;
private static final double MEG = (Math.pow(1024, 2));
private static final int RECORD_COUNT = 4000000;
private static final String RECORD = "Help I am trapped in a fortune cookie factory\n";
private static final int RECSIZE = RECORD.getBytes().length;

public static void main(String[] args) throws Exception {
    List<String> records = new ArrayList<String>(RECORD_COUNT);
    int size = 0;
    for (int i = 0; i < RECORD_COUNT; i++) {
        records.add(RECORD);
        size += RECSIZE;
    }
    System.out.println(records.size() + " 'records'");
    System.out.println(size / MEG + " MB");
    
    for (int i = 0; i < ITERATIONS; i++) {
        System.out.println("\nIteration " + i);
        
        writeRaw(records);
        writeBuffered(records, 8192);
        writeBuffered(records, (int) MEG);
        writeBuffered(records, 4 * (int) MEG);
    }
}

private static void writeRaw(List<String> records) throws IOException {
    File file = File.createTempFile("foo", ".txt");
    try {
        FileWriter writer = new FileWriter(file);
        System.out.print("Writing raw... ");
        write(records, writer);
    } finally {
        // comment this out if you want to inspect the files afterward
        file.delete();
    }
}

private static void writeBuffered(List<String> records, int bufSize) throws IOException {
    File file = File.createTempFile("foo", ".txt");
    try {
        FileWriter writer = new FileWriter(file);
        BufferedWriter bufferedWriter = new BufferedWriter(writer, bufSize);
    
        System.out.print("Writing buffered (buffer size: " + bufSize + ")... ");
        write(records, bufferedWriter);
    } finally {
        // comment this out if you want to inspect the files afterward
        file.delete();
    }
}

private static void write(List<String> records, Writer writer) throws IOException {
    long start = System.currentTimeMillis();
    for (String record: records) {
        writer.write(record);
    }
    // writer.flush(); // close() should take care of this
    writer.close(); 
    long end = System.currentTimeMillis();
    System.out.println((end - start) / 1000f + " seconds");
}
}

How do I find out what version of WordPress is running?

Yet another way to find the WordPress version is using WP-CLI: Command line interface for WordPress:

wp core version

Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

That's done for header files so that the contents only appear once in each preprocessed source file, even if it's included more than once (usually because it's included from other header files). The first time it's included, the symbol CLASS_H (known as an include guard) hasn't been defined yet, so all the contents of the file are included. Doing this defines the symbol, so if it's included again, the contents of the file (inside the #ifndef/#endif block) are skipped.

There's no need to do this for the source file itself since (normally) that's not included by any other files.

For your last question, class.h should contain the definition of the class, and declarations of all its members, associated functions, and whatever else, so that any file that includes it has enough information to use the class. The implementations of the functions can go in a separate source file; you only need the declarations to call them.

How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)

In Sublime3 (Windows):

Some users may get an inverted screen using the Ctrl+Alt+? in windows. To Solve this go to

Preferences->Key Bindings-User

And add these two lines at the end of the file just before closing brackets:

{ "keys": ["ctrl+alt+pageup"], "command": "select_lines", "args": {"forward": false} },

{ "keys": ["ctrl+alt+pagedown"], "command": "select_lines", "args": {"forward": true} } 

Or use your own keys.

How to initialize const member variable in a class?

Another solution is

class T1
{
    enum
    {
        t = 100
    };

    public:
    T1();
};

So t is initialised to 100 and it cannot be changed and it is private.

How to select into a variable in PL/SQL when the result might be null?

From all the answers above, Björn's answer seems to be the most elegant and short. I personally used this approach many times. MAX or MIN function will do the job equally well. Complete PL/SQL follows, just the where clause should be specified.

declare v_column my_table.column%TYPE;
begin
    select MIN(column) into v_column from my_table where ...;
    DBMS_OUTPUT.PUT_LINE('v_column=' || v_column);
end;

What is [Serializable] and when should I use it?

Here is short example of how serialization works. I was also learning about the same and I found two links useful. What Serialization is and how it can be done in .NET.

A sample program explaining serialization

If you don't understand the above program a much simple program with explanation is given here.

How to pop an alert message box using PHP?

See this example :

<?php
echo "<div id='div1'>text</div>"
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="js/jquery1.3.2/jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {
            $('#div1').click(function () {
                alert('I clicked');
            });
        });
</script>
</head>
<body>

</body>
</html>

Difference between wait and sleep

Here, I have listed few important differences between wait() and sleep() methods.
PS: Also click on the links to see library code (internal working, just play around a bit for better understanding).

wait()

  1. wait() method releases the lock.
  2. wait() is the method of Object class.
  3. wait() is the non-static method - public final void wait() throws InterruptedException { //...}
  4. wait() should be notified by notify() or notifyAll() methods.
  5. wait() method needs to be called from a loop in order to deal with false alarm.

  6. wait() method must be called from synchronized context (i.e. synchronized method or block), otherwise it will throw IllegalMonitorStateException

sleep()

  1. sleep() method doesn't release the lock.
  2. sleep() is the method of java.lang.Thread class.
  3. sleep() is the static method - public static void sleep(long millis, int nanos) throws InterruptedException { //... }
  4. after the specified amount of time, sleep() is completed.
  5. sleep() better not to call from loop(i.e. see code below).
  6. sleep() may be called from anywhere. there is no specific requirement.

Ref: Difference between Wait and Sleep

Code snippet for calling wait and sleep method

synchronized(monitor){
    while(condition == true){ 
        monitor.wait()  //releases monitor lock
    }

    Thread.sleep(100); //puts current thread on Sleep    
}

thread transition to different thread states

How do I fix a NoSuchMethodError?

NoSuchMethodError : I have spend couple of hours fixing this issue, finally fixed it by just renaming package name , clean and build ... Try clean build first if it doesn't works try renaming the class name or package name and clean build...it should be fixed. Good luck.

How to specify non-default shared-library path in GCC Linux? Getting "error while loading shared libraries" when running

There are two ways to achieve that:

  • Use -rpath linker option:

gcc XXX.c -o xxx.out -L$HOME/.usr/lib -lXX -Wl,-rpath=/home/user/.usr/lib

  • Use LD_LIBRARY_PATH environment variable - put this line in your ~/.bashrc file:

    export LD_LIBRARY_PATH=/home/user/.usr/lib

This will work even for a pre-generated binaries, so you can for example download some packages from the debian.org, unpack the binaries and shared libraries into your home directory, and launch them without recompiling.

For a quick test, you can also do (in bash at least):

LD_LIBRARY_PATH=/home/user/.usr/lib ./xxx.out

which has the advantage of not changing your library path for everything else.

C++ Singleton design pattern

This is about object life-time management. Suppose you have more than singletons in your software. And they depend on Logger singleton. During application destruction, suppose another singleton object uses Logger to log its destruction steps. You have to guarantee that Logger should be cleaned up last. Therefore, please also check out this paper: http://www.cs.wustl.edu/~schmidt/PDF/ObjMan.pdf

How Should I Set Default Python Version In Windows?

Try modifying the path in the windows registry (HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment).

Caveat: Don't break the registry :)

Passing a String by Reference in Java?

String is an immutable object in Java. You can use the StringBuilder class to do the job you're trying to accomplish, as follows:

public static void main(String[] args)
{
    StringBuilder sb = new StringBuilder("hello, world!");
    System.out.println(sb);
    foo(sb);
    System.out.println(sb);

}

public static void foo(StringBuilder str)
{
    str.delete(0, str.length());
    str.append("String has been modified");
}

Another option is to create a class with a String as a scope variable (highly discouraged) as follows:

class MyString
{
    public String value;
}

public static void main(String[] args)
{
    MyString ms = new MyString();
    ms.value = "Hello, World!";

}

public static void foo(MyString str)
{
    str.value = "String has been modified";
}