Programs & Examples On #Textile

Textile is a lightweight markup language originally developed by Dean Allen and billed as a "humane web text generator". Textile converts its marked-up text input to valid, well-formed XHTML.

Representing Directory & File Structure in Markdown Syntax

There is an NPM module for this:

npm dree

It allows you to have a representation of a directory tree as a string or an object. Using it with the command line will allow you to save the representation in a txt file.

Example:

$ npm dree parse myDirectory --dest ./generated --name tree

Abstract methods in Java

If you use the java keyword abstract you cannot provide an implementation.

Sometimes this idea comes from having a background in C++ and mistaking the virtual keyword in C++ as being "almost the same" as the abstract keyword in Java.

In C++ virtual indicates that a method can be overridden and polymorphism will follow, but abstract in Java is not the same thing. In Java abstract is more like a pure virtual method, or one where the implementation must be provided by a subclass. Since Java supports polymorphism without the need to declare it, all methods are virtual from a C++ point of view. So if you want to provide a method that might be overridden, just write it as a "normal" method.

Now to protect a method from being overridden, Java uses the keyword final in coordination with the method declaration to indicate that subclasses cannot override the method.

Adding an arbitrary line to a matplotlib plot in ipython notebook

Using vlines:

import numpy as np
np.random.seed(5)
x = arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
p =  plot(x, y, "o")
vlines(70,100,250)

The basic call signatures are:

vlines(x, ymin, ymax)
hlines(y, xmin, xmax)

Simulation of CONNECT BY PRIOR of Oracle in SQL Server

The SQL standard way to implement recursive queries, as implemented e.g. by IBM DB2 and SQL Server, is the WITH clause. See this article for one example of translating a CONNECT BY into a WITH (technically a recursive CTE) -- the example is for DB2 but I believe it will work on SQL Server as well.

Edit: apparently the original querant requires a specific example, here's one from the IBM site whose URL I already gave. Given a table:

CREATE TABLE emp(empid  INTEGER NOT NULL PRIMARY KEY,
                 name   VARCHAR(10),
                 salary DECIMAL(9, 2),
                 mgrid  INTEGER);

where mgrid references an employee's manager's empid, the task is, get the names of everybody who reports directly or indirectly to Joan. In Oracle, that's a simple CONNECT:

SELECT name 
  FROM emp
  START WITH name = 'Joan'
  CONNECT BY PRIOR empid = mgrid

In SQL Server, IBM DB2, or PostgreSQL 8.4 (as well as in the SQL standard, for what that's worth;-), the perfectly equivalent solution is instead a recursive query (more complex syntax, but, actually, even more power and flexibility):

WITH n(empid, name) AS 
   (SELECT empid, name 
    FROM emp
    WHERE name = 'Joan'
        UNION ALL
    SELECT nplus1.empid, nplus1.name 
    FROM emp as nplus1, n
    WHERE n.empid = nplus1.mgrid)
SELECT name FROM n

Oracle's START WITH clause becomes the first nested SELECT, the base case of the recursion, to be UNIONed with the recursive part which is just another SELECT.

SQL Server's specific flavor of WITH is of course documented on MSDN, which also gives guidelines and limitations for using this keyword, as well as several examples.

Why is null an object and what's the difference between null and undefined?

TLDR

undefined is a primitive value in JavaScript that indicates the implicit absence of a value. Uninitialized variables automatically have this value, and functions without an explicit return statement, return undefined.

null is also a primitive value in JavaScript. It indicates the intentional absence of an object value. null in JavaScript was designed to enable interoperability with Java.

typeof null returns "object" because of a peculiarity in the design of the language, stemming from the demand that JavaScript be interoperable with Java. It does not mean null is an instance of an object. It means: given the tree of primitive types in JavaScript, null is part of the "object-type primitive" subtree. This is explained more fully below.

Details

undefined is a primitive value that represents the implicit absence of a value. Note that undefined was not directly accessible until JavaScript 1.3 in 1998. This tells us that null was intended to be the value used by programmers when explicitly indicating the absence of a value. Uninitialized variables automatically have the value undefined. undefined is a one-of-a-kind type in the ECMAScript specification.

null is a primitive value that represents the intentional absence of an object value. null is also a one-of-a-kind type in the ECMAScript specification.

null in JavaScript was designed with a view to enable interoperability with Java, both from a "look" perspective, and from a programatic perspective (eg the LiveConnect Java/JS bridge planned for 1996). Both Brendan Eich and others have since expressed distaste at the inclusion of two "absence of value" values, but in 1995 Eich was under orders to "make [JavaScript] look like Java".

Brendan Eich:

If I didn't have "Make it look like Java" as an order from management, and I had more time (hard to unconfound these two causal factors), then I would have preferred a Self-like "everything's an object" approach: no Boolean, Number, String wrappers. No undefined and null. Sigh.

In order to accommodate Java's concept of null which, due to the strongly-typed nature of Java, can only be assigned to variables typed to a reference type (rather primitives), Eich chose to position the special null value at the top of the object prototype chain (ie. the top of the reference types), and to include the null type as part of the set of "object-type primitives".

The typeof operator was added shortly thereafter in JavaScript 1.1, released on 19th August 1996.

From the V8 blog:

typeof null returns object, and not null, despite null being a type of its own. To understand why, consider that the set of all JavaScript types is divided into two groups:

  1. objects (i.e. the Object type)
  2. primitives (i.e. any non-object value)

As such, null means “no object value”, whereas undefined means “no value”.

enter image description here

Following this line of thought, Brendan Eich designed JavaScript to make typeof return 'object' for all values on the right-hand side, i.e. all objects and null values, in the spirit of Java. That’s why typeof null === 'object' despite the spec having a separate null type.

enter image description here

So Eich designed the heirarchy of primitive types to enable interoperability with Java. This led to him positioning null along with the "object-type primitives" on the heirarchy. To refelct this, when typeof was added to the language shortly thereafter, he chose typeof null to return "object".

The surprise expressed by JavaScript developers at typeof null === "object" is the result of an impedance mismatch (or abstraction leak) between a weakly-typed language (JavaScript) that has both null and undefined, and another, strongly-typed language (Java) that only has null, and in which null is strictly defined to refer to a reference type (not a primitive type).

Note that this is all logical, reasonable and defensible. typeof null === "object" is not a bug, but a second-order effect of having to accommodate Java interoperability.

A number of imperfect backwards rationalisations and/or conventions have emerged, including that undefined indicates implicit absence of a value, and that null indicates intentional absence of a value; or that undefined is the absence of a value, and null is specifically the absence of an object value.

A relevant conversation with Brendan Eich, screenshotted for posterity:

enter image description here

How to execute AngularJS controller function on page load?

Dimitri's/Mark's solution didn't work for me but using the $timeout function seems to work well to ensure your code only runs after the markup is rendered.

# Your controller, including $timeout

var $scope.init = function(){
 //your code
}

$timeout($scope.init)

Hope it helps.

How to add data into ManyToMany field?

There's a whole page of the Django documentation devoted to this, well indexed from the contents page.

As that page states, you need to do:

my_obj.categories.add(fragmentCategory.objects.get(id=1))

or

my_obj.categories.create(name='val1')

How to get current url in view in asp.net core 1.0

You need scheme, host, path and queryString

@string.Format("{0}://{1}{2}{3}", Context.Request.Scheme, Context.Request.Host, Context.Request.Path, Context.Request.QueryString)

or using new C#6 feature "String interpolation"

@($"{Context.Request.Scheme}://{Context.Request.Host}{Context.Request.Path}{Context.Request.QueryString}")

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

If you are using intellij and want to use gradle you need to add this to the dependencies section of build.gradle file:

testImplementation("org.junit.jupiter:junit-jupiter-api:5.4.2")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.4.2")

How to set Java classpath in Linux?

You have to use ':' colon instead of ';' semicolon.

As it stands now you try to execute the jar file which has not the execute bit set, hence the Permission denied.

And the variable must be CLASSPATH not classpath.

Google Maps how to Show city or an Area outline

I have try twitter geo api, failed.

Google map api, failed, so far, no way you can get city limit by any api.

twitter api geo endpoint will NOT give you city boundary,

what they provide you is ONLY bounding box with 5 point(lat, long)

this is what I get from twitter api geo for San Francisco enter image description here

In a simple to understand explanation, what is Runnable in Java?

A Runnable is basically a type of class (Runnable is an Interface) that can be put into a thread, describing what the thread is supposed to do.

The Runnable Interface requires of the class to implement the method run() like so:

public class MyRunnableTask implements Runnable {
     public void run() {
         // do stuff here
     }
}

And then use it like this:

Thread t = new Thread(new MyRunnableTask());
t.start();

If you did not have the Runnable interface, the Thread class, which is responsible to execute your stuff in the other thread, would not have the promise to find a run() method in your class, so you could get errors. That is why you need to implement the interface.

Advanced: Anonymous Type

Note that you do not need to define a class as usual, you can do all of that inline:

Thread t = new Thread(new Runnable() {
    public void run() {
        // stuff here
    }
});
t.start();

This is similar to the above, only you don't create another named class.

Nested ifelse statement

# Read in the data.

idnat=c("french","french","french","foreign")
idbp=c("mainland","colony","overseas","foreign")

# Initialize the new variable.

idnat2=as.character(vector())

# Logically evaluate "idnat" and "idbp" for each case, assigning the appropriate level to "idnat2".

for(i in 1:length(idnat)) {
  if(idnat[i] == "french" & idbp[i] == "mainland") {
    idnat2[i] = "mainland"
} else if (idnat[i] == "french" & (idbp[i] == "colony" | idbp[i] == "overseas")) {
  idnat2[i] = "overseas"
} else {
  idnat2[i] = "foreign"
} 
}

# Create a data frame with the two old variables and the new variable.

data.frame(idnat,idbp,idnat2) 

How can I copy a file from a remote server to using Putty in Windows?

It worked using PSCP. Instructions:

  1. Download PSCP.EXE from Putty download page
  2. Open command prompt and type set PATH=<path to the pscp.exe file>
  3. In command prompt point to the location of the pscp.exe using cd command
  4. Type pscp
  5. use the following command to copy file form remote server to the local system

    pscp [options] [user@]host:source target
    

So to copy the file /etc/hosts from the server example.com as user fred to the file c:\temp\example-hosts.txt, you would type:

pscp [email protected]:/etc/hosts c:\temp\example-hosts.txt

Artificially create a connection timeout error

I would like to point everybody's attention to pathod

With a config (taken from their examples) of 200:b@100:dr you'll get a connection that randomly drops.

Change default date time format on a single database in SQL Server

You can only change the language on the whole server, not individual databases. However if you need to support the UK you can run the following command before all inputs and outputs:

set language 'british english'

Or if you are having issues entering datatimes from your application you might want to consider a universal input type such as

1-Dec-2008

How to add checkboxes to JTABLE swing

1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,

2) AbstractTableModel should be useful, where is in the JTable required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel,

3) consider using DefaultTableModel, (if you are not sure about how to works) instead of AbstractTableModel,

table_with_BooleanType_column

could be generated from simple code:

import javax.swing.*;
import javax.swing.table.*;

public class TableCheckBox extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TableCheckBox() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
        };
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            /*@Override
            public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
            }*/
            @Override
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return Integer.class;
                    case 3:
                        return Double.class;
                    default:
                        return Boolean.class;
                }
            }
        };
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TableCheckBox frame = new TableCheckBox();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocation(150, 150);
                frame.setVisible(true);
            }
        });
    }
}

Duplicate headers received from server

The server SHOULD put double quotes around the filename, as mentioned by @cusman and @Touko in their replies.

For example:

Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");

How to get the current taxonomy term ID (not the slug) in WordPress?

Nevermind! I found it :)

get_queried_object()->term_id;

Random number generator only generating one random number

For ease of re-use throughout your application a static class may help.

public static class StaticRandom
{
    private static int seed;

    private static ThreadLocal<Random> threadLocal = new ThreadLocal<Random>
        (() => new Random(Interlocked.Increment(ref seed)));

    static StaticRandom()
    {
        seed = Environment.TickCount;
    }

    public static Random Instance { get { return threadLocal.Value; } }
}

You can use then use static random instance with code such as

StaticRandom.Instance.Next(1, 100);

How to sort a dataframe by multiple column(s)

You can use the order() function directly without resorting to add-on tools -- see this simpler answer which uses a trick right from the top of the example(order) code:

R> dd[with(dd, order(-z, b)), ]
    b x y z
4 Low C 9 2
2 Med D 3 1
1  Hi A 8 1
3  Hi A 9 1

Edit some 2+ years later: It was just asked how to do this by column index. The answer is to simply pass the desired sorting column(s) to the order() function:

R> dd[order(-dd[,4], dd[,1]), ]
    b x y z
4 Low C 9 2
2 Med D 3 1
1  Hi A 8 1
3  Hi A 9 1
R> 

rather than using the name of the column (and with() for easier/more direct access).

Android WebView, how to handle redirects in app instead of opening a browser

Create a WebViewClient, and override the shouldOverrideUrlLoading method.

webview.setWebViewClient(new WebViewClient() {
    public boolean shouldOverrideUrlLoading(WebView view, String url){
        // do your handling codes here, which url is the requested url
        // probably you need to open that url rather than redirect:
        view.loadUrl(url);
        return false; // then it is not handled by default action
   }
});

how to open *.sdf files?

If you simply need to view the table and run queries on it you can use this third party sdf viewer. It is a lightweight viewer that has all the basic functionalities and is ready to use after install.

and ofcourse, its Free.

Aligning rotated xticklabels with their respective xticks

You can set the horizontal alignment of ticklabels, see the example below. If you imagine a rectangular box around the rotated label, which side of the rectangle do you want to be aligned with the tickpoint?

Given your description, you want: ha='right'

n=5

x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Ticklabel %i' % i for i in range(n)]

fig, axs = plt.subplots(1,3, figsize=(12,3))

ha = ['right', 'center', 'left']

for n, ax in enumerate(axs):
    ax.plot(x,y, 'o-')
    ax.set_title(ha[n])
    ax.set_xticks(x)
    ax.set_xticklabels(xlabels, rotation=40, ha=ha[n])

enter image description here

How to make a class property?

If you use Django, it has a built in @classproperty decorator.

from django.utils.decorators import classproperty

How to compare two dates along with time in java

Since Date implements Comparable<Date>, it is as easy as:

date1.compareTo(date2);

As the Comparable contract stipulates, it will return a negative integer/zero/positive integer if date1 is considered less than/the same as/greater than date2 respectively (ie, before/same/after in this case).

Note that Date has also .after() and .before() methods which will return booleans instead.

How do I edit a file after I shell to a Docker container?

An easy way to edit a few lines would be:

echo "deb http://deb.debian.org/debian stretch main" > sources.list

npm install won't install devDependencies

I have the same issue because I set the NODE_ENV=production while building Docker. Then I add one more npm install --only=dev. Everything works fine. I need the devDependencies for building TypeSciprt modules

RUN npm install
RUN npm install --only=dev

Jquery, set value of td in a table?

Try the code below :

$('#detailInfo').html('your value')

Pandas: Convert Timestamp to datetime.date

Use the .date method:

In [11]: t = pd.Timestamp('2013-12-25 00:00:00')

In [12]: t.date()
Out[12]: datetime.date(2013, 12, 25)

In [13]: t.date() == datetime.date(2013, 12, 25)
Out[13]: True

To compare against a DatetimeIndex (i.e. an array of Timestamps), you'll want to do it the other way around:

In [21]: pd.Timestamp(datetime.date(2013, 12, 25))
Out[21]: Timestamp('2013-12-25 00:00:00')

In [22]: ts = pd.DatetimeIndex([t])

In [23]: ts == pd.Timestamp(datetime.date(2013, 12, 25))
Out[23]: array([ True], dtype=bool)

How can I get the count of line in a file in an efficient way?

This is about as efficient as it can get, buffered binary read, no string conversion,

FileInputStream stream = new FileInputStream("/tmp/test.txt");
byte[] buffer = new byte[8192];
int count = 0;
int n;
while ((n = stream.read(buffer)) > 0) {
    for (int i = 0; i < n; i++) {
        if (buffer[i] == '\n') count++;
    }
}
stream.close();
System.out.println("Number of lines: " + count);

Maven not found in Mac OSX mavericks

brew install maven

Please ensure that you've installed the latest Xcode and Command Line tools.

xcode-select --install

Difference between attr_accessor and attr_accessible

attr_accessor is a Ruby method that gives you setter and getter methods to an instance variable of the same name. So it is equivalent to

class MyModel
  def my_variable
    @my_variable
  end
  def my_variable=(value)
    @my_variable = value
  end
end

attr_accessible is a Rails method that determines what variables can be set in a mass assignment.

When you submit a form, and you have something like MyModel.new params[:my_model] then you want to have a little bit more control, so that people can't submit things that you don't want them to.

You might do attr_accessible :email so that when someone updates their account, they can change their email address. But you wouldn't do attr_accessible :email, :salary because then a person could set their salary through a form submission. In other words, they could hack their way to a raise.

That kind of information needs to be explicitly handled. Just removing it from the form isn't enough. Someone could go in with firebug and add the element into the form to submit a salary field. They could use the built in curl to submit a new salary to the controller update method, they could create a script that submits a post with that information.

So attr_accessor is about creating methods to store variables, and attr_accessible is about the security of mass assignments.

Barcode scanner for mobile phone for Website in form

Scandit is a startup whose goal is to replace bulky, expensive laser barcode scanners with cheap mobile phones.

There are SDKs for Android, iOS, Windows, C API/Linux, React Native, Cordova/PhoneGap, Xamarin.

There is also Scandit Barcode Scanner SDK for the Web which the WebAssembly version of the SDK. It runs in modern browsers, also on phones.

There's a client library that also provides a barcode picker component. It can be used like this:

<div id="barcode-picker" style="max-width: 1280px; max-height: 80%;"></div>

<script src="https://unpkg.com/scandit-sdk"></script>
<script>
    console.log('Loading...');
    ScanditSDK.configure("xxx", {
engineLocation: "https://unpkg.com/scandit-sdk/build/"
    }).then(() => {
      console.log('Loaded');
      ScanditSDK.BarcodePicker.create(document.getElementById('barcode-picker'), {
        playSoundOnScan: true,
        vibrateOnScan: true
      }).then(function(barcodePicker) {
        console.log("Ready");
        barcodePicker.applyScanSettings(new ScanditSDK.ScanSettings({
          enabledSymbologies: ["ean8", "ean13", "upca", "upce", "code128", "code39", "code93", "itf", "qr"],
          codeDuplicateFilter: 1000
        }));
        barcodePicker.onScan(function(barcodes) {
          console.log(barcodes);
        });
      });
    });
</script>

Disclaimer: I work for Scandit

How to remove all white spaces from a given text file

If you want to remove ALL whitespace, even newlines:

perl -pe 's/\s+//g' file

Getting parts of a URL (Regex)

A single regex to parse and breakup a full URL including query parameters and anchors e.g.

https://www.google.com/dir/1/2/search.html?arg=0-a&arg1=1-b&arg3-c#hash

^((http[s]?|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$

RexEx positions:

url: RegExp['$&'],

protocol:RegExp.$2,

host:RegExp.$3,

path:RegExp.$4,

file:RegExp.$6,

query:RegExp.$7,

hash:RegExp.$8

you could then further parse the host ('.' delimited) quite easily.

What I would do is use something like this:

/*
    ^(.*:)//([A-Za-z0-9\-\.]+)(:[0-9]+)?(.*)$
*/
proto $1
host $2
port $3
the-rest $4

the further parse 'the rest' to be as specific as possible. Doing it in one regex is, well, a bit crazy.

Android List View Drag and Drop sort

I have been working on this for some time now. Tough to get right, and I don't claim I do, but I'm happy with it so far. My code and several demos can be found at

Its use is very similar to the TouchInterceptor (on which the code is based), although significant implementation changes have been made.

DragSortListView has smooth and predictable scrolling while dragging and shuffling items. Item shuffles are much more consistent with the position of the dragging/floating item. Heterogeneous-height list items are supported. Drag-scrolling is customizable (I demonstrate rapid drag scrolling through a long list---not that an application comes to mind). Headers/Footers are respected. etc.?? Take a look.

Laravel update model with unique validation rule for attribute

Laravel 5.8 simple and easy

you can do this all in a form request with quite nicely. . .

first make a field by which you can pass the id (invisible) in the normal edit form. i.e.,

 <div class="form-group d-none">
      <input class="form-control" name="id" type="text" value="{{ $example->id }}" >
 </div>

... Then be sure to add the Rule class to your form request like so:

use Illuminate\Validation\Rule;

... Add the Unique rule ignoring the current id like so:

public function rules()
{
    return [
          'example_field_1'  => ['required', Rule::unique('example_table')->ignore($this->id)],
          'example_field_2'  => 'required',

    ];

... Finally type hint the form request in the update method the same as you would the store method, like so:

 public function update(ExampleValidation $request, Examle $example)
{
    $example->example_field_1 = $request->example_field_1;
    ...
    $example->save();

    $message = "The aircraft was successully updated";


    return  back()->with('status', $message);


}

This way you won't repeat code unnecessarily :-)

Convert a list of characters into a string

h = ['a','b','c','d','e','f']
g = ''
for f in h:
    g = g + f

>>> g
'abcdef'

A CORS POST request works from plain JavaScript, but why not with jQuery?

Another possibility is that setting dataType: json causes JQuery to send the Content-Type: application/json header. This is considered a non-standard header by CORS, and requires a CORS preflight request. So a few things to try:

1) Try configuring your server to send the proper preflight responses. This will be in the form of additional headers like Access-Control-Allow-Methods and Access-Control-Allow-Headers.

2) Drop the dataType: json setting. JQuery should request Content-Type: application/x-www-form-urlencoded by default, but just to be sure, you can replace dataType: json with contentType: 'application/x-www-form-urlencoded'

How to convert uint8 Array to base64 Encoded String?

function Uint8ToBase64(u8Arr){
  var CHUNK_SIZE = 0x8000; //arbitrary number
  var index = 0;
  var length = u8Arr.length;
  var result = '';
  var slice;
  while (index < length) {
    slice = u8Arr.subarray(index, Math.min(index + CHUNK_SIZE, length)); 
    result += String.fromCharCode.apply(null, slice);
    index += CHUNK_SIZE;
  }
  return btoa(result);
}

You can use this function if you have a very large Uint8Array. This is for Javascript, can be useful in case of FileReader readAsArrayBuffer.

"Missing return statement" within if / for / while

If you put return statement in if, while or for statement then it may or may not return value. If it will not go inside these statement then also that method should return some value ( that could be null). To ensure that, compiler will force you to write this return statement which is after if, while or for.

But if you write if / else block and each one of them is having return in it then compiler knows that either if or else will get execute and method will return a value. So this time compiler will not force you.

if(condition)
{
 return;
}
else
{
 return;
}

How to change screen resolution of Raspberry Pi

Just run the following simple command on Raspberry Pi 3 running Raspbian Jessie.

run terminal and type

sudo raspi-config

Go to: >Advanced Option > Resolution > just set your resolution compatible fit with your screen.

then

reboot

If you didn't found the menu on configuration, please update your raspberry pi software configuration tool (raspi-config).

That's all TQ.

Does C# have extension properties?

For the moment it is still not supported out of the box by Roslyn compiler ...

Until now, the extension properties were not seen as valuable enough to be included in the previous versions of C# standard. C# 7 and C# 8.0 have seen this as proposal champion but it wasn't released yet, most of all because even if there is already an implementation, they want to make it right from the start.

But it will ...

There is an extension members item in the C# 7 work list so it may be supported in the near future. The current status of extension property can be found on Github under the related item.

However, there is an even more promising topic which is the "extend everything" with a focus on especially properties and static classes or even fields.

Moreover you can use a workaround

As specified in this article, you can use the TypeDescriptor capability to attach an attribute to an object instance at runtime. However, it is not using the syntax of the standard properties.
It's a little bit different from just syntactic sugar adding a possibility to define an extended property like
string Data(this MyClass instance) as an alias for extension method
string GetData(this MyClass instance) as it stores data into the class.

I hope that C#7 will provide a full featured extension everything (properties and fields), however on that point, only time will tell.

And feel free to contribute as the software of tomorrow will come from the community.

Update: August 2016

As dotnet team published what's new in C# 7.0 and from a comment of Mads Torgensen:

Extension properties: we had a (brilliant!) intern implement them over the summer as an experiment, along with other kinds of extension members. We remain interested in this, but it’s a big change and we need to feel confident that it’s worth it.

It seems that extension properties and other members, are still good candidates to be included in a future release of Roslyn, but maybe not the 7.0 one.

Update: May 2017

The extension members has been closed as duplicate of extension everything issue which is closed too. The main discussion was in fact about Type extensibility in a broad sense. The feature is now tracked here as a proposal and has been removed from 7.0 milestone.

Update: August, 2017 - C# 8.0 proposed feature

While it still remains only a proposed feature, we have now a clearer view of what would be its syntax. Keep in mind that this will be the new syntax for extension methods as well:

public interface IEmployee 
{
    public decimal Salary { get; set; }
}

public class Employee
{
    public decimal Salary { get; set; }
}

public extension MyPersonExtension extends Person : IEmployee
{
    private static readonly ConditionalWeakTable<Person, Employee> _employees = 
        new ConditionalWeakTable<Person, Employee>();


    public decimal Salary
    {
        get 
        {
            // `this` is the instance of Person
            return _employees.GetOrCreate(this).Salary; 
        }
        set 
        {
            Employee employee = null;
            if (!_employees.TryGetValue(this, out employee)
            {
                employee = _employees.GetOrCreate(this);
            }
            employee.Salary = value;
        }
    }
}

IEmployee person = new Person();
var salary = person.Salary;

Similar to partial classes, but compiled as a separate class/type in a different assembly. Note you will also be able to add static members and operators this way. As mentioned in Mads Torgensen podcast, the extension won't have any state (so it cannot add private instance members to the class) which means you won't be able to add private instance data linked to the instance. The reason invoked for that is it would imply to manage internally dictionaries and it could be difficult (memory management, etc...). For this, you can still use the TypeDescriptor/ConditionalWeakTable technique described earlier and with the property extension, hides it under a nice property.

Syntax is still subject to change as implies this issue. For example, extends could be replaced by for which some may feel more natural and less java related.

Update December 2018 - Roles, Extensions and static interface members

Extension everything didn't make it to C# 8.0, because of some of drawbacks explained as the end of this GitHub ticket. So, there was an exploration to improve the design. Here, Mads Torgensen explains what are roles and extensions and how they differs:

Roles allow interfaces to be implemented on specific values of a given type. Extensions allow interfaces to be implemented on all values of a given type, within a specific region of code.

It can be seen at a split of previous proposal in two use cases. The new syntax for extension would be like this:

public extension ULongEnumerable of ulong
{
    public IEnumerator<byte> GetEnumerator()
    {
        for (int i = sizeof(ulong); i > 0; i--)
        {
            yield return unchecked((byte)(this >> (i-1)*8));
        }
    }
}

then you would be able to do this:

foreach (byte b in 0x_3A_9E_F1_C5_DA_F7_30_16ul)
{
    WriteLine($"{e.Current:X}");
}

And for a static interface:

public interface IMonoid<T> where T : IMonoid<T>
{
    static T operator +(T t1, T t2);
    static T Zero { get; }
}

Add an extension property on int and treat the int as IMonoid<int>:

public extension IntMonoid of int : IMonoid<int>
{
    public static int Zero => 0;
}

ASP.NET Core Identity - get current user

Assuming your code is inside an MVC controller:

public class MyController : Microsoft.AspNetCore.Mvc.Controller

From the Controller base class, you can get the IClaimsPrincipal from the User property

System.Security.Claims.ClaimsPrincipal currentUser = this.User;

You can check the claims directly (without a round trip to the database):

bool IsAdmin = currentUser.IsInRole("Admin");
var id = _userManager.GetUserId(User); // Get user id:

Other fields can be fetched from the database's User entity:

  1. Get the user manager using dependency injection

    private UserManager<ApplicationUser> _userManager;
    
    //class constructor
    public MyController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }
    
  2. And use it:

    var user = await _userManager.GetUserAsync(User);
    var email = user.Email;
    

How to solve munmap_chunk(): invalid pointer error in C++

The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[] with an index read from stream. Try vector::at() instead of vector::operator[]. This won't solve your problem, but will show which assignment to the vector causes error.

ArrayList filter

As you didn't give us very much information, I'm assuming the language you're writing the code in is C#. First of all: Prefer System.Collections.Generic.List over an ArrayList. Secondly: One way would be to loop through every item in the list and check whether it contains "How". Another way would be to use LINQ. Here's a quick example that filters out every item which doesn't contain "How":

var list = new List<string>();
list.AddRange(new string[] {
    "How are you?",
    "How you doing?",
    "Joe",
    "Mike", });

foreach (string str in list.Where(s => s.Contains("How")))
{
    Console.WriteLine(str);
}
Console.ReadLine();

What is a "thread" (really)?

I am going to use a lot of text from the book Operating Systems Concepts by ABRAHAM SILBERSCHATZ, PETER BAER GALVIN and GREG GAGNE along with my own understanding of things.

Process

Any application resides in the computer in the form of text (or code).

We emphasize that a program by itself is not a process. A program is a passive entity, such as a file containing a list of instructions stored on disk (often called an executable file).

When we start an application, we create an instance of execution. This instance of execution is called a process. EDIT:(As per my interpretation, analogous to a class and an instance of a class, the instance of a class being a process. )

An example of processes is that of Google Chrome. When we start Google Chrome, 3 processes are spawned:

• The browser process is responsible for managing the user interface as well as disk and network I/O. A new browser process is created when Chrome is started. Only one browser process is created.

Renderer processes contain logic for rendering web pages. Thus, they contain the logic for handling HTML, Javascript, images, and so forth. As a general rule, a new renderer process is created for each website opened in a new tab, and so several renderer processes may be active at the same time.

• A plug-in process is created for each type of plug-in (such as Flash or QuickTime) in use. Plug-in processes contain the code for the plug-in as well as additional code that enables the plug-in to communicate with associated renderer processes and the browser process.

Thread

To answer this I think you should first know what a processor is. A Processor is the piece of hardware that actually performs the computations. EDIT: (Computations like adding two numbers, sorting an array, basically executing the code that has been written)

Now moving on to the definition of a thread.

A thread is a basic unit of CPU utilization; it comprises a thread ID, a program counter, a register set, and a stack.

EDIT: Definition of a thread from intel's website:

A Thread, or thread of execution, is a software term for the basic ordered sequence of instructions that can be passed through or processed by a single CPU core.

So, if the Renderer process from the Chrome application sorts an array of numbers, the sorting will take place on a thread/thread of execution. (The grammar regarding threads seems confusing to me)

My Interpretation of Things

A process is an execution instance. Threads are the actual workers that perform the computations via CPU access. When there are multiple threads running for a process, the process provides common memory.

EDIT: Other Information that I found useful to give more context

All modern day computer have more than one threads. The number of threads in a computer depends on the number of cores in a computer.

Concurrent Computing:

From Wikipedia:

Concurrent computing is a form of computing in which several computations are executed during overlapping time periods—concurrently—instead of sequentially (one completing before the next starts). This is a property of a system—this may be an individual program, a computer, or a network—and there is a separate execution point or "thread of control" for each computation ("process").

So, I could write a program which calculates the sum of 4 numbers:

(1 + 3) + (4 + 5)

In the program to compute this sum (which will be one process running on a thread of execution) I can fork another process which can run on a different thread to compute (4 + 5) and return the result to the original process, while the original process calculates the sum of (1 + 3).

HTML5 live streaming

It is not possible to use the RTMP protocol in HTML 5, because the RTMP protocol is only used between the server and the flash player. So you can use the other streaming protocols for viewing the streaming videos in HTML 5.

How to set zoom level in google map

Here is a function I use:

var map =  new google.maps.Map(document.getElementById('map'), {
            center: new google.maps.LatLng(52.2, 5),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            zoom: 7
        });

function zoomTo(level) {
        google.maps.event.addListener(map, 'zoom_changed', function () {
            zoomChangeBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function (event) {
                if (this.getZoom() > level && this.initialZoom == true) {
                    this.setZoom(level);
                    this.initialZoom = false;
                }
                google.maps.event.removeListener(zoomChangeBoundsListener);
            });
        });
    }

How can I beautify JSON programmatically?

Programmatic formatting solution:

The JSON.stringify method supported by many modern browsers (including IE8) can output a beautified JSON string:

JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4);    // stringify with 4 spaces at each level
Demo: http://jsfiddle.net/AndyE/HZPVL/

This method is also included with json2.js, for supporting older browsers.

Manual formatting solution

If you don't need to do it programmatically, Try JSON Lint. Not only will it prettify your JSON, it will validate it at the same time.

How to adjust the size of y axis labels only in R?

ucfagls is right, providing you use the plot() command. If not, please give us more detail.

In any case, you can control every axis seperately by using the axis() command and the xaxt/yaxt options in plot(). Using the data of ucfagls, this becomes :

plot(Y ~ X, data=foo,yaxt="n")
axis(2,cex.axis=2)

the option yaxt="n" is necessary to avoid that the plot command plots the y-axis without changing. For the x-axis, this works exactly the same :

plot(Y ~ X, data=foo,xaxt="n")
axis(1,cex.axis=2)

See also the help files ?par and ?axis


Edit : as it is for a barplot, look at the options cex.axis and cex.names :

tN <- table(sample(letters[1:5],100,replace=T,p=c(0.2,0.1,0.3,0.2,0.2)))

op <- par(mfrow=c(1,2))
barplot(tN, col=rainbow(5),cex.axis=0.5) # for the Y-axis
barplot(tN, col=rainbow(5),cex.names=0.5) # for the X-axis
par(op)

alt text

Source file 'Properties\AssemblyInfo.cs' could not be found

delete the assemeblyinfo.cs file from project under properties menu and rebulid it.

Update date + one year in mysql

You could use DATE_ADD : (or ADDDATE with INTERVAL)

UPDATE table SET date = DATE_ADD(date, INTERVAL 1 YEAR) 

The HTTP request is unauthorized with client authentication scheme 'Ntlm'. The authentication header received from the server was 'Negotiate,NTLM'

If both your client and service is installed on the same machine, and you are facing this problem with the correct (read: tried and tested elsewhere) client and service configurations, then this might be worth checking.

Check host entries in your host file

%windir%/system32/drivers/etc/hosts

Check to see if you are accessing your web service with a hostname, and that same hostname has been associated with an IP address in the hosts file mentioned above. If yes, NTLM/Windows credentials will NOT be passed from the client to the service as any request for that hostname will be routed again at the machine level.

Try either of the following

  • Remove the host entry of that hostname from the hosts file
  • OR
  • If removing host entry is not possible, then try accessing your service with another hostname. You might also try with IP address instead of hostname

Edit: Somehow the above situation is relevant on a load-balanced scenario. However, if removing the host entries is not possible, then disabling loop back check on the machine will help. Refer method 2 in the article https://support.microsoft.com/en-us/kb/896861

Jenkins: Cannot define variable in pipeline stage

Agree with @Pom12, @abayer. To complete the answer you need to add script block

Try something like this:

pipeline {
    agent any
    environment {
        ENV_NAME = "${env.BRANCH_NAME}"
    }

    // ----------------

    stages {
        stage('Build Container') {
            steps {
                echo 'Building Container..'

                script {
                    if (ENVIRONMENT_NAME == 'development') {
                        ENV_NAME = 'Development'
                    } else if (ENVIRONMENT_NAME == 'release') {
                        ENV_NAME = 'Production'
                    }
                }
                echo 'Building Branch: ' + env.BRANCH_NAME
                echo 'Build Number: ' + env.BUILD_NUMBER
                echo 'Building Environment: ' + ENV_NAME

                echo "Running your service with environemnt ${ENV_NAME} now"
            }
        }
    }
}

Website screenshots

It all depends on how you wish to take the screenshot.

You could do this via PHP, using a webservice to get the image for you

grabz.it has a webservice to do just this, here's an article showing a simple example of using the service.

http://www.phpbuilder.com/articles/news-reviews/miscellaneous/capture-screenshots-in-php-with-grabzit-120524022959.html

Java how to sort a Linked List?

In order to sort Strings alphabetically you will need to use a Collator, like:

 LinkedList<String> list = new LinkedList<String>();
 list.add("abc");
 list.add("Bcd");
 list.add("aAb");
 Collections.sort(list, new Comparator<String>() {
     @Override
     public int compare(String o1, String o2) {
         return Collator.getInstance().compare(o1, o2);
     }
 });

Because if you just call Collections.sort(list) you will have trouble with strings that contain uppercase characters.

For instance in the code I pasted, after the sorting the list will be: [aAb, abc, Bcd] but if you just call Collections.sort(list); you will get: [Bcd, aAb, abc]

Note: When using a Collator you can specify the locale Collator.getInstance(Locale.ENGLISH) this is usually pretty handy.

document.getElementById('btnid').disabled is not working in firefox and chrome

Try setting the disabled attribute directly:

if ( someCondition == true ) {
   document.getElementById('btn1').setAttribute('disabled', 'disabled');
} else {
   document.getElementById('btn1').removeAttribute('disabled');
}

Multiple IF statements between number ranges

I suggest using vlookup function to get the nearest match.


Step 1

Prepare data range and name it: 'numberRange':

enter image description here

Select the range. Go to menu: Data ? Named ranges... ? define the new named range.

Step 2

Use this simple formula:

=VLOOKUP(A2,numberRange,2)

enter image description here


This way you can ommit errors, and easily correct the result.

SMTPAuthenticationError when sending mail using gmail and python

Your code looks correct. Try logging in through your browser and if you are able to access your account come back and try your code again. Just make sure that you have typed your username and password correct

EDIT: Google blocks sign-in attempts from apps which do not use modern security standards (mentioned on their support page). You can however, turn on/off this safety feature by going to the link below:

Go to this link and select Turn On
https://www.google.com/settings/security/lesssecureapps

Bootstrap center heading

Per your comments, to center all headings all you have to do is add text-align:center to all of them at the same time, like so:

CSS

    h1, h2, h3, h4, h5, h6 {
        text-align: center;
    }

Error in strings.xml file in Android

post your complete string. Though, my guess is there is an apostrophe (') character in your string. replace it with (\') and it will fix the issue. for example,

//strings.xml
<string name="terms">
Hey Mr. Android, are you stuck?  Here, I\'ll clear a path for you.  
</string>

Ref:

http://www.mrexcel.com/forum/showthread.php?t=195353

https://code.google.com/archive/p/replicaisland/issues/48

Technically what is the main difference between Oracle JDK and OpenJDK?

Technical differences are a consequence of the goal of each one (OpenJDK is meant to be the reference implementation, open to the community, while Oracle is meant to be a commercial one)

They both have "almost" the same code of the classes in the Java API; but the code for the virtual machine itself is actually different, and when it comes to libraries, OpenJDK tends to use open libraries while Oracle tends to use closed ones; for instance, the font library.

What REALLY happens when you don't free after malloc?

=== What about future proofing and code reuse? ===

If you don't write the code to free the objects, then you are limiting the code to only being safe to use when you can depend on the memory being free'd by the process being closed ... i.e. small one-time use projects or "throw-away"[1] projects)... where you know when the process will end.

If you do write the code that free()s all your dynamically allocated memory, then you are future proofing the code and letting others use it in a larger project.


[1] regarding "throw-away" projects. Code used in "Throw-away" projects has a way of not being thrown away. Next thing you know ten years have passed and your "throw-away" code is still being used).

I heard a story about some guy who wrote some code just for fun to make his hardware work better. He said "just a hobby, won't be big and professional". Years later lots of people are using his "hobby" code.

T-SQL Subquery Max(Date) and Joins

Try this:

Select *,
    Price = (Select top 1 Price 
             From MyPrices 
             where PartID = mp.PartID 
             order by PriceDate desc
            )
from MyParts mp

Write a file in UTF-8 using FileWriter (Java)?

use OutputStream instead of FileWriter to set encoding type

// file is your File object where you want to write you data 
OutputStream outputStream = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
outputStreamWriter.write(json); // json is your data 
outputStreamWriter.flush();
outputStreamWriter.close();

UICollectionView spacing margins

In swift 4 and autoLayout, you can use sectionInset like this:

let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.itemSize = CGSize(width: (view.frame.width-40)/2, height: (view.frame.width40)/2) // item size
        layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10) // here you can add space to 4 side of item
        collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) // set layout to item
        collectionView?.register(ProductCategoryCell.self, forCellWithReuseIdentifier: cellIdentifier) // registerCell
        collectionView?.backgroundColor = .white // background color of UICollectionView
        view.addSubview(collectionView!) // add UICollectionView to view

Passing an array/list into a Python function

def sumlist(items=[]):
    sum = 0
    for i in items:
        sum += i

    return sum

t=sumlist([2,4,8,1])
print(t)

How to Compare a long value is equal to Long value

long a = 1111;
Long b = new Long(1113);

System.out.println(b.equals(a) ? "equal" : "different");
System.out.println((long) b == a ? "equal" : "different");

Is the 'as' keyword required in Oracle to define an alias?

Both are correct. Oracle allows the use of both.

Dynamically fill in form values with jQuery

Assuming this example HTML:

<input type="text" name="email" id="email" />
<input type="text" name="first_name" id="first_name" />
<input type="text" name="last_name" id="last_name" />

You could have this javascript:

$("#email").bind("change", function(e){
  $.getJSON("http://yourwebsite.com/lokup.php?email=" + $("#email").val(),
        function(data){
          $.each(data, function(i,item){
            if (item.field == "first_name") {
              $("#first_name").val(item.value);
            } else if (item.field == "last_name") {
              $("#last_name").val(item.value);
            }
          });
        });
});

Then just you have a PHP script (in this case lookup.php) that takes an email in the query string and returns a JSON formatted array back with the values you want to access. This is the part that actually hits the database to look up the values:

<?php
//look up the record based on email and get the firstname and lastname
...

//build the JSON array for return
$json = array(array('field' => 'first_name', 
                    'value' => $firstName), 
              array('field' => 'last_name', 
                    'value' => $last_name));
echo json_encode($json );
?>

You'll want to do other things like sanitize the email input, etc, but should get you going in the right direction.

SQL datetime format to date only

SELECT Subject, CONVERT(varchar(10),DeliveryDate) as DeliveryDate
from Email_Administration 
where MerchantId =@ MerchantID

Style input type file?

Same solution via Jquery. Works if you have more than one file input in the page.

$j(".filebutton").click(function() {
    var input = $j(this).next().find('input');
    input.click();
});

$j(".fileinput").change(function(){

    var file = $j(this).val();
    var fileName = file.split("\\");
    var pai =$j(this).parent().parent().prev();
    pai.html(fileName[fileName.length-1]);
    event.preventDefault();
});

CSS background image in :after element

As AlienWebGuy said, you can use background-image. I'd suggest you use background, but it will need three more properties after the URL:

background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") 0 0 no-repeat;

Explanation: the two zeros are x and y positioning for the image; if you want to adjust where the background image displays, play around with these (you can use both positive and negative values, e.g: 1px or -1px).

No-repeat says you don't want the image to repeat across the entire background. This can also be repeat-x and repeat-y.

How can I detect if Flash is installed and if not, display a hidden div that informs the user?

@Drewid's answer didn't work in my Firefox 25 if the flash plugin is just disabled but installed.

@invertedSpear's comment in that answer worked in firefox but not in any IE version.

So combined both their code and got this. Tested in Google Chrome 31, Firefox 25, IE 8-10. Thanks Drewid and invertedSpear :)

var hasFlash = false;
try {
  var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
  if (fo) {
    hasFlash = true;
  }
} catch (e) {
  if (navigator.mimeTypes
        && navigator.mimeTypes['application/x-shockwave-flash'] != undefined
        && navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) {
    hasFlash = true;
  }
}

How to get pip to work behind a proxy server

The pip's proxy parameter is, according to pip --help, in the form scheme://[user:passwd@]proxy.server:port

You should use the following:

pip install --proxy http://user:password@proxyserver:port TwitterApi

Also, the HTTP_PROXY env var should be respected.

Note that in earlier versions (couldn't track down the change in the code, sorry, but the doc was updated here), you had to leave the scheme:// part out for it to work, i.e. pip install --proxy user:password@proxyserver:port

How to iterate over the keys and values with ng-repeat in AngularJS?

    Use below code it is working to display your key and value here is key start with 1:
         <tr ng-repeat="(key,value) in alert_list" >
                   <td>{{key +1}}</td>
                   <td>{{value.title}}</td>
                 </tr>
Below is document link for it. 

https://docs.angularjs.org/api/ng/directive/ngRepeat

Returning a boolean from a Bash function

It might work if you rewrite this function myfun(){ ... return 0; else return 1; fi;} as this function myfun(){ ... return; else false; fi;}. That is if false is the last instruction in the function you get false result for whole function but return interrupts function with true result anyway. I believe it's true for my bash interpreter at least.

"Large data" workflows using pandas

One more variation

Many of the operations done in pandas can also be done as a db query (sql, mongo)

Using a RDBMS or mongodb allows you to perform some of the aggregations in the DB Query (which is optimized for large data, and uses cache and indexes efficiently)

Later, you can perform post processing using pandas.

The advantage of this method is that you gain the DB optimizations for working with large data, while still defining the logic in a high level declarative syntax - and not having to deal with the details of deciding what to do in memory and what to do out of core.

And although the query language and pandas are different, it's usually not complicated to translate part of the logic from one to another.

Get Unix timestamp with C++

Windows uses a different epoch and time units: see Convert Windows Filetime to second in Unix/Linux

What std::time() returns on Windows is (as yet) unknown to me (;-))

Configure Nginx with proxy_pass

Give this a try...

server {
    listen   80;
    server_name  dev.int.com;
    access_log off;
    location / {
        proxy_pass http://IP:8080;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:8080/jira  /;
        proxy_connect_timeout 300;
    }

    location ~ ^/stash {
        proxy_pass http://IP:7990;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:7990/  /stash;
        proxy_connect_timeout 300;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/local/nginx/html;
    }
}

How to display Wordpress search results?

Check whether your template in theme folder contains search.php and searchform.php or not.

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

Alternatively if you want to grab the private and public keys from a PuTTY formated key file you can use puttygen on *nix systems. For most apt-based systems puttygen is part of the putty-tools package.

Outputting a private key from a PuTTY formated keyfile:

$ puttygen keyfile.pem -O private-openssh -o avdev.pvk

For the public key:

$ puttygen keyfile.pem -L

Is nested function a good approach when required by only one function?

Generally, no, do not define functions inside functions.

Unless you have a really good reason. Which you don't.

Why not?

What is a really good reason to define functions inside functions?

When what you actually want is a dingdang closure.

Get a random item from a JavaScript array

Use underscore (or loDash :)):

var randomArray = [
   '#cc0000','#00cc00', '#0000cc'
];

// use _.sample
var randomElement = _.sample(randomArray);

// manually use _.random
var randomElement = randomArray[_.random(randomArray.length-1)];

Or to shuffle an entire array:

// use underscore's shuffle function
var firstRandomElement = _.shuffle(randomArray)[0];

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/

Two onClick actions one button

Additional attributes (in this case, the second onClick) will be ignored. So, instead of onclick calling both fbLikeDump(); and WriteCookie();, it will only call fbLikeDump();. To fix, simply define a single onclick attribute and call both functions within it:

<input type="button" value="Don't show this again! " onclick="fbLikeDump();WriteCookie();" />

How to clear out session on log out

session.abandon() will not remove the sessionID cookie from the browser. Therefore any new requests after this will take the same session ID. Hence, use Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", "")); after session.abandon().

Chrome Extension - Get DOM content

For those who tried gkalpak answer and it did not work,

be aware that chrome will add the content script to a needed page only when your extension enabled during chrome launch and also a good idea restart browser after making these changes

Invoke JSF managed bean action on page load

calling bean action from a will be a good idea,keep attribute autoRun="true" example below

<p:remoteCommand autoRun="true" name="myRemoteCommand" action="#{bean.action}" partialSubmit="true" update=":form" />

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

LocalDate to java.util.Date and vice versa simplest conversion?

I solved this question with solution below

  import org.joda.time.LocalDate;
  Date myDate = new Date();
  LocalDate localDate = LocalDate.fromDateFields(myDate);
  System.out.println("My date using Date" Nov 18 11:23:33 BRST 2016);
  System.out.println("My date using joda.time LocalTime" 2016-11-18);

In this case localDate print your date in this format "yyyy-MM-dd"

Correct way to delete cookies server-side

Sending the same cookie value with ; expires appended will not destroy the cookie.

Invalidate the cookie by setting an empty value and include an expires field as well:

Set-Cookie: token=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT

Note that you cannot force all browsers to delete a cookie. The client can configure the browser in such a way that the cookie persists, even if it's expired. Setting the value as described above would solve this problem.

How to open the command prompt and insert commands using Java?

I know that people recommend staying away from rt.exec(String), but this works, and I don't know how to change it into the array version.

rt.exec("cmd.exe /c cd \""+new_dir+"\" & start cmd.exe /k \"java -flag -flag -cp terminal-based-program.jar\"");

Pass a data.frame column name to a function

This answer will cover many of the same elements as existing answers, but this issue (passing column names to functions) comes up often enough that I wanted there to be an answer that covered things a little more comprehensively.

Suppose we have a very simple data frame:

dat <- data.frame(x = 1:4,
                  y = 5:8)

and we'd like to write a function that creates a new column z that is the sum of columns x and y.

A very common stumbling block here is that a natural (but incorrect) attempt often looks like this:

foo <- function(df,col_name,col1,col2){
      df$col_name <- df$col1 + df$col2
      df
}

#Call foo() like this:    
foo(dat,z,x,y)

The problem here is that df$col1 doesn't evaluate the expression col1. It simply looks for a column in df literally called col1. This behavior is described in ?Extract under the section "Recursive (list-like) Objects".

The simplest, and most often recommended solution is simply switch from $ to [[ and pass the function arguments as strings:

new_column1 <- function(df,col_name,col1,col2){
    #Create new column col_name as sum of col1 and col2
    df[[col_name]] <- df[[col1]] + df[[col2]]
    df
}

> new_column1(dat,"z","x","y")
  x y  z
1 1 5  6
2 2 6  8
3 3 7 10
4 4 8 12

This is often considered "best practice" since it is the method that is hardest to screw up. Passing the column names as strings is about as unambiguous as you can get.

The following two options are more advanced. Many popular packages make use of these kinds of techniques, but using them well requires more care and skill, as they can introduce subtle complexities and unanticipated points of failure. This section of Hadley's Advanced R book is an excellent reference for some of these issues.

If you really want to save the user from typing all those quotes, one option might be to convert bare, unquoted column names to strings using deparse(substitute()):

new_column2 <- function(df,col_name,col1,col2){
    col_name <- deparse(substitute(col_name))
    col1 <- deparse(substitute(col1))
    col2 <- deparse(substitute(col2))

    df[[col_name]] <- df[[col1]] + df[[col2]]
    df
}

> new_column2(dat,z,x,y)
  x y  z
1 1 5  6
2 2 6  8
3 3 7 10
4 4 8 12

This is, frankly, a bit silly probably, since we're really doing the same thing as in new_column1, just with a bunch of extra work to convert bare names to strings.

Finally, if we want to get really fancy, we might decide that rather than passing in the names of two columns to add, we'd like to be more flexible and allow for other combinations of two variables. In that case we'd likely resort to using eval() on an expression involving the two columns:

new_column3 <- function(df,col_name,expr){
    col_name <- deparse(substitute(col_name))
    df[[col_name]] <- eval(substitute(expr),df,parent.frame())
    df
}

Just for fun, I'm still using deparse(substitute()) for the name of the new column. Here, all of the following will work:

> new_column3(dat,z,x+y)
  x y  z
1 1 5  6
2 2 6  8
3 3 7 10
4 4 8 12
> new_column3(dat,z,x-y)
  x y  z
1 1 5 -4
2 2 6 -4
3 3 7 -4
4 4 8 -4
> new_column3(dat,z,x*y)
  x y  z
1 1 5  5
2 2 6 12
3 3 7 21
4 4 8 32

So the short answer is basically: pass data.frame column names as strings and use [[ to select single columns. Only start delving into eval, substitute, etc. if you really know what you're doing.

C++ - Hold the console window open?

If your problem is retaining the Console Window within Visual Studio without modifying your application (c-code) and are running it with Ctrl+F5 (when running Ctrl+F5) but the window is still closing the principal hint is to set the /SUBSYSTEM:CONSOLE linker option in your Visual Studio project.

as explained by DJMooreTX in http://social.msdn.microsoft.com/Forums/en-US/vcprerelease/thread/21073093-516c-49d2-81c7-d960f6dc2ac6

1) Open up your project, and go to the Solution Explorer. If you're following along with me in K&R, your "Solution" will be 'hello' with 1 project under it, also 'hello' in bold.

  1. Right click on the 'hello" (or whatever your project name is.)

  2. Choose "Properties" from the context menu.

  3. Choose Configuration Properties>Linker>System.

  4. For the "Subsystem" property in the right-hand pane, click the drop-down box in the right hand column.

  5. Choose "Console (/SUBSYSTEM:CONSOLE)"

  6. Click Apply, wait for it to finish doing whatever it does, then click OK. (If "Apply" is grayed out, choose some other subsystem option, click Apply, then go back and apply the console option. My experience is that OK by itself won't work.)

Now do Boris' CTRL-F5, wait for your program to compile and link, find the console window under all the other junk on your desktop, and read your program's output, followed by the beloved "Press any key to continue...." prompt.

Again, CTRL-F5 and the subsystem hints work together; they are not separate options.

How to declare a variable in MySQL?

There are mainly three types of variables in MySQL:

  1. User-defined variables (prefixed with @):

    You can access any user-defined variable without declaring it or initializing it. If you refer to a variable that has not been initialized, it has a value of NULL and a type of string.

    SELECT @var_any_var_name
    

    You can initialize a variable using SET or SELECT statement:

    SET @start = 1, @finish = 10;    
    

    or

    SELECT @start := 1, @finish := 10;
    
    SELECT * FROM places WHERE place BETWEEN @start AND @finish;
    

    User variables can be assigned a value from a limited set of data types: integer, decimal, floating-point, binary or nonbinary string, or NULL value.

    User-defined variables are session-specific. That is, a user variable defined by one client cannot be seen or used by other clients.

    They can be used in SELECT queries using Advanced MySQL user variable techniques.

  2. Local Variables (no prefix) :

    Local variables needs to be declared using DECLARE before accessing it.

    They can be used as local variables and the input parameters inside a stored procedure:

    DELIMITER //
    
    CREATE PROCEDURE sp_test(var1 INT) 
    BEGIN   
        DECLARE start  INT unsigned DEFAULT 1;  
        DECLARE finish INT unsigned DEFAULT 10;
    
        SELECT  var1, start, finish;
    
        SELECT * FROM places WHERE place BETWEEN start AND finish; 
    END; //
    
    DELIMITER ;
    
    CALL sp_test(5);
    

    If the DEFAULT clause is missing, the initial value is NULL.

    The scope of a local variable is the BEGIN ... END block within which it is declared.

  3. Server System Variables (prefixed with @@):

    The MySQL server maintains many system variables configured to a default value. They can be of type GLOBAL, SESSION or BOTH.

    Global variables affect the overall operation of the server whereas session variables affect its operation for individual client connections.

    To see the current values used by a running server, use the SHOW VARIABLES statement or SELECT @@var_name.

    SHOW VARIABLES LIKE '%wait_timeout%';
    
    SELECT @@sort_buffer_size;
    

    They can be set at server startup using options on the command line or in an option file. Most of them can be changed dynamically while the server is running using SET GLOBAL or SET SESSION:

    -- Syntax to Set value to a Global variable:
    SET GLOBAL sort_buffer_size=1000000;
    SET @@global.sort_buffer_size=1000000;
    
    -- Syntax to Set value to a Session variable:
    SET sort_buffer_size=1000000;
    SET SESSION sort_buffer_size=1000000;
    SET @@sort_buffer_size=1000000;
    SET @@local.sort_buffer_size=10000;
    

How to import spring-config.xml of one project into spring-config.xml of another project?

<import resource="classpath*:spring-config.xml" /> 

This is the most suitable one for class path configuration. Particularly when you are searching for the .xml files in a different project which is in your class path.

Print PHP Call Stack

I have adapted Don Briggs's answer above to use internal error logging instead of public printing, which may be your big concern when working on a live server. Also, added few more modifications like option to include full file path instead of basic name (because, there could be files with same name in different paths), and also (for those who require it) a complete node stack output:

class debugUtils {
    public static function callStack($stacktrace) {
        error_log(str_repeat("=", 100));
        $i = 1;
        foreach($stacktrace as $node) {
            // uncomment next line to debug entire node stack
            // error_log(print_r($node, true));
            error_log( $i . '.' . ' file: ' .$node['file'] . ' | ' . 'function: ' . $node['function'] . '(' . ' line: ' . $node['line'] . ')' );
            $i++;
        }
        error_log(str_repeat("=", 100));
    } 
}

// call debug stack
debugUtils::callStack(debug_backtrace());

Is it possible to iterate through JSONArray?

Not with an iterator.

For org.json.JSONArray, you can do:

for (int i = 0; i < arr.length(); i++) {
  arr.getJSONObject(i);
}

For javax.json.JsonArray, you can do:

for (int i = 0; i < arr.size(); i++) {
  arr.getJsonObject(i);
}

Visual C++ executable and missing MSVCR100d.dll

This problem explained in MSDN Library and as I understand installing Microsoft's Redistributable Package can help.

But sometimes the following solution can be used (as developer's side solution):

In your Visual Studio, open Project properties -> Configuration properties -> C/C++ -> Code generation and change option Runtime Library to /MT instead of /MD

Auto margins don't center image in page

For a bootstrap button:

display: table; 
margin: 0 auto;

java.net.SocketException: Connection reset

I had the same error. I found the solution for problem now. The problem was client program was finishing before server read the streams.

How to use java.Set

Since it is a HashSet you will need to override hashCode and equals methods. http://preciselyconcise.com/java/collections/d_set.php has an example explaining how to implement hashCode and equals methods

How to check if running in Cygwin, Mac or Linux?

I guess the uname answer is unbeatable, mainly in terms of cleanliness.

Although it takes a ridiculous time to execute, I found that testing for specific files presence also gives me good and quicker results, since I'm not invoking an executable:

So,

[ -f /usr/bin/cygwin1.dll ] && echo Yep, Cygwin running

just uses a quick Bash file presence check. As I'm on Windows right now, I can't tell you any specific files for Linuxes and Mac OS X from my head, but I'm pretty sure they do exist. :-)

Validation of radio button group using jQuery validation plugin

As per Brandon's answer. But if you're using ASP.NET MVC which uses unobtrusive validation, you can add the data-val attribute to the first one. I also like to have labels for each radio button for usability.

<span class="field-validation-valid" data-valmsg-for="color" data-valmsg-replace="true"></span>
<p><input type="radio" name="color" id="red" value="R" data-val="true" data-val-required="Please choose one of these options:"/> <label for="red">Red</label></p>
<p><input type="radio" name="color" id="green" value="G"/> <label for="green">Green</label></p>
<p><input type="radio" name="color" id="blue" value="B"/> <label for="blue">Blue</label></p>

How do I create directory if it doesn't exist to create a file?

You can use following code

  DirectoryInfo di = Directory.CreateDirectory(path);

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Postgres: How to do Composite keys?

The error you are getting is in line 3. i.e. it is not in

CONSTRAINT no_duplicate_tag UNIQUE (question_id, tag_id)

but earlier:

CREATE TABLE tags
     (
              (question_id, tag_id) NOT NULL,

Correct table definition is like pilcrow showed.

And if you want to add unique on tag1, tag2, tag3 (which sounds very suspicious), then the syntax is:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    UNIQUE (tag1, tag2, tag3)
);

or, if you want to have the constraint named according to your wish:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    CONSTRAINT some_name UNIQUE (tag1, tag2, tag3)
);

What is the meaning of curly braces?

A dictionary is something like an array that's accessed by keys (e.g. strings,...) rather than just plain sequential numbers. It contains key/value pairs, you can look up values using a key like using a phone book: key=name, number=value.

For defining such a dictionary, you use this syntax using curly braces, see also: http://wiki.python.org/moin/SimplePrograms

Store a closure as a variable in Swift

Depends on your needs there is an addition to accepted answer. You may also implement it like this:

var parseCompletion: (() ->Void)!

and later in some func assign to it

func someHavyFunc(completion: @escaping () -> Void){
    self.parseCompletion = completion
}

and in some second function use it

func someSecondFunc(){
    if let completion = self.parseCompletion {
        completion()
    }
}

note that @escaping parameter is a mandatory here

How to get the indexpath.row when an element is activated?

Sometimes button may be inside of another view of UITableViewCell. In that case superview.superview may not give the cell object and hence the indexPath will be nil.

In that case we should keep finding the superview until we get the cell object.

Function to get cell object by superview

func getCellForView(view:UIView) -> UITableViewCell?
{
    var superView = view.superview

    while superView != nil
    {
        if superView is UITableViewCell
        {
            return superView as? UITableViewCell
        }
        else
        {
            superView = superView?.superview
        }
    }

    return nil
}

Now we can get indexPath on button tap as below

@IBAction func tapButton(_ sender: UIButton)
{
    let cell = getCellForView(view: sender)
    let indexPath = myTabelView.indexPath(for: cell)
}

How to add System.Windows.Interactivity to project?

Alternative solution is to modify your current Visual Studio installation in the Visual Studio Installer

Win+R %ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vs_installer.exe

adding the Blend for Visual Studio SDK for .NET 'Individual component' under 'SDKs, libraries, and frameworks':

enter image description here after adding this component System.Windows.Interactivity should appear in its regular location Add Reference/Assemblies/Extensions.


It appears this would only work for VS2017 or earlier. For later versions, please refer to other answers.

form_for but to post to a different action

I have done it like that

<%= form_for :user, url: {action: "update", params: {id: @user.id}} do |f| %>

Note the optional parameter id set to user instance id attribute.

Set up git to pull and push all branches

If you are moving branches to a new repo from an old one and do NOT have all the old repo branches local, you will need to track them first.

for remote in `git branch -r | grep -v '\->'`; do git branch --track $remote; done

Then add your new remote repo:

git remote add bb <path-to-new-repo>

Then you can push all using this command:

git push -u bb --all

Or you can configure the repo using the git config commands noted in the other responses here if you are not doing this one time or are only looking to move local branches.

The important point, the other responses only push all LOCAL branches. If the branches only exist on an alternate REMOTE repository they will not move without tracking them first. The for loop presented here will help with that.

Opening popup windows in HTML

HTML alone does not support this. You need to use some JS.

And also consider nowadays people use popup blocker in browsers.

<a href="javascript:window.open('document.aspx','mypopuptitle','width=600,height=400')">open popup</a>

nginx error "conflicting server name" ignored

There should be only one localhost defined, check sites-enabled or nginx.conf.

Disable native datepicker in Google Chrome

This works for me:

;
(function ($) {
    $(document).ready(function (event) {
        $(document).on('click input', 'input[type="date"], input[type="text"].date-picker', function (e) {
            var $this = $(this);
            $this.prop('type', 'text').datepicker({
                showOtherMonths: true,
                selectOtherMonths: true,
                showButtonPanel: true,
                changeMonth: true,
                changeYear: true,
                dateFormat: 'yy-mm-dd',
                showWeek: true,
                firstDay: 1
            });

            setTimeout(function() {
                $this.datepicker('show');
            }, 1);
        });
    });
})(jQuery, jQuery.ui);

See also:

How can I disable the new Chrome HTML5 date input?

http://zizhujy.com/blog/post/2014/09/18/Add-date-picker-to-dynamically-generated-input-elements.aspx

How can I pass a member function where a free function is expected?

I asked a similar question (C++ openframeworks passing void from other classes) but the answer I found was clearer so here the explanation for future records:

it’s easier to use std::function as in:

 void draw(int grid, std::function<void()> element)

and then call as:

 grid.draw(12, std::bind(&BarrettaClass::draw, a, std::placeholders::_1));

or even easier:

  grid.draw(12, [&]{a.draw()});

where you create a lambda that calls the object capturing it by reference

Calling remove in foreach loop in Java

I didn't know about iterators, however here's what I was doing until today to remove elements from a list inside a loop:

List<String> names = .... 
for (i=names.size()-1;i>=0;i--) {    
    // Do something    
    names.remove(i);
} 

This is always working, and could be used in other languages or structs not supporting iterators.

How to check if a string "StartsWith" another string?

I am not sure for javascript but in typescript i did something like

var str = "something";
(<String>str).startsWith("some");

I guess it should work on js too. I hope it helps!

How to move text up using CSS when nothing is working

Your footer container is constricting the width of the inner element with an explicit width on itself, which sees the text clipped at the end and wrapped onto a new line, so change that:

div#fv2-footer-container {
  width: 1090px;
  ...

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, use raw_input(). Don't forget you can add a prompt string in your input() call to create one less print statement. input("GUESS THAT NUMBER!").

TypeError: unsupported operand type(s) for -: 'str' and 'int'

For future reference Python is strongly typed. Unlike other dynamic languages, it will not automagically cast objects from one type or the other (say from str to int) so you must do this yourself. You'll like that in the long-run, trust me!

Hibernate Criteria Join with 3 Tables

The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:

Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();

This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.

Fork() function in C

First a link to some documentation of fork()

http://pubs.opengroup.org/onlinepubs/009695399/functions/fork.html

The pid is provided by the kernel. Every time the kernel create a new process it will increase the internal pid counter and assign the new process this new unique pid and also make sure there are no duplicates. Once the pid reaches some high number it will wrap and start over again.

So you never know what pid you will get from fork(), only that the parent will keep it's unique pid and that fork will make sure that the child process will have a new unique pid. This is stated in the documentation provided above.

If you continue reading the documentation you will see that fork() return 0 for the child process and the new unique pid of the child will be returned to the parent. If the child want to know it's own new pid you will have to query for it using getpid().

pid_t pid = fork()
if(pid == 0) {
    printf("this is a child: my new unique pid is %d\n", getpid());
} else {
    printf("this is the parent: my pid is %d and I have a child with pid %d \n", getpid(), pid);
}

and below is some inline comments on your code

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main() {
    pid_t pid1, pid2, pid3;
    pid1=0, pid2=0, pid3=0;
    pid1= fork(); /* A */
    if(pid1 == 0){
        /* This is child A */
        pid2=fork(); /* B */
        pid3=fork(); /* C */
    } else {
        /* This is parent A */
        /* Child B and C will never reach this code */
        pid3=fork(); /* D */
        if(pid3==0) {
            /* This is child D fork'ed from parent A */
            pid2=fork(); /* E */
        }
        if((pid1 == 0)&&(pid2 == 0)) {
            /* pid1 will never be 0 here so this is dead code */
            printf("Level 1\n");
        }
        if(pid1 !=0) {
            /* This is always true for both parent and child E */
            printf("Level 2\n");
        }
        if(pid2 !=0) {
           /* This is parent E (same as parent A) */
           printf("Level 3\n");
        }
        if(pid3 !=0) {
           /* This is parent D (same as parent A) */
           printf("Level 4\n");
        }
    }
    return 0;
}

How do I set up the database.yml file in Rails?

The database.yml is the file where you set up all the information to connect to the database. It differs depending on the kind of DB you use. You can find more information about this in the Rails Guide or any tutorial explaining how to setup a rails project.

The information in the database.yml file is scoped by environment, allowing you to get a different setting for testing, development or production. It is important that you keep those distinct if you don't want the data you use for development deleted by mistake while running your test suite.

Regarding source control, you should not commit this file but instead create a template file for other developers (called database.yml.template). When deploying, the convention is to create this database.yml file in /shared/config directly on the server.

With SVN: svn propset svn:ignore config "database.yml"

With Git: Add config/database.yml to the .gitignore file or with git-extra git ignore config/database.yml


... and now, some examples:

SQLite

adapter: sqlite3
database: db/db_dev_db.sqlite3
pool: 5
timeout: 5000

MYSQL

adapter: mysql
database: my_db
hostname: 127.0.0.1
username: root
password: 
socket: /tmp/mysql.sock
pool: 5
timeout: 5000

MongoDB with MongoID (called mongoid.yml, but basically the same thing)

host: <%= ENV['MONGOID_HOST'] %>
port: <%= ENV['MONGOID_PORT'] %>
username: <%= ENV['MONGOID_USERNAME'] %>
password: <%= ENV['MONGOID_PASSWORD'] %>
database: <%= ENV['MONGOID_DATABASE'] %>
# slaves:
#   - host: slave1.local
#     port: 27018
#   - host: slave2.local
#     port: 27019

Remove/ truncate leading zeros by javascript/jquery

Simply try to multiply by one as following:

"00123" * 1;              // Get as number
"00123" * 1 + "";       // Get as string

Convert data.frame column to a vector?

as.vector(unlist(aframe['a2']))

Quickly create large file on a Windows system

fsutil file createnew <filename> <length>

where <length> is in bytes.

For example, to create a 1MB (Windows MB or MiB) file named 'test', this code can be used.

fsutil file createnew test 1048576

fsutil requires administrative privileges though.

How to use ng-repeat without an html element

for a solution that really works

html

<remove  ng-repeat-start="itemGroup in Groups" ></remove>
   html stuff in here including inner repeating loops if you want
<remove  ng-repeat-end></remove>

add an angular.js directive

//remove directive
(function(){
    var remove = function(){

        return {    
            restrict: "E",
            replace: true,
            link: function(scope, element, attrs, controller){
                element.replaceWith('<!--removed element-->');
            }
        };

    };
    var module = angular.module("app" );
    module.directive('remove', [remove]);
}());

for a brief explanation,

ng-repeat binds itself to the <remove> element and loops as it should, and because we have used ng-repeat-start / ng-repeat-end it loops a block of html not just an element.

then the custom remove directive places the <remove> start and finish elements with <!--removed element-->

How to take complete backup of mysql database using mysqldump command line utility

On MySQL 5.7 its work for me, I'm using CentOS7.

For taking Dump.

Command :

mysqldump -u user_name -p database_name -R -E > file_name.sql

Exemple :

mysqldump -u root -p mr_sbc_clean -R -E > mr_sbc_clean_dump.sql

For deploying Dump.

Command :

mysql -u user_name -p database_name < file_name.sql

Exemple :

mysql -u root -p mr_sbc_clean_new < mr_sbc_clean_dump.sql

PHP : send mail in localhost

I spent hours on this. I used to not get errors but mails were never sent. Finally I found a solution and I would like to share it.

<?php
include 'nav.php';
/*
    Download PhpMailer from the following link:
    https://github.com/Synchro/PHPMailer (CLick on Download zip on the right side)
    Extract the PHPMailer-master folder into your xampp->htdocs folder
    Make changes in the following code and its done :-)

    You will receive the mail with the name Root User.
    To change the name, go to class.phpmailer.php file in your PHPMailer-master folder,
    And change the name here: 
    public $FromName = 'Root User';
*/
require("PHPMailer-master/PHPMailerAutoload.php"); //or select the proper destination for this file if your page is in some   //other folder
ini_set("SMTP","ssl://smtp.gmail.com"); 
ini_set("smtp_port","465"); //No further need to edit your configuration files.
$mail = new PHPMailer();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->SMTPSecure = "ssl";
$mail->Username = "[email protected]"; //account with which you want to send mail. Or use this account. i dont care :-P
$mail->Password = "trials.php.php"; //this account's password.
$mail->Port = "465";
$mail->isSMTP();  // telling the class to use SMTP
$rec1="[email protected]"; //receiver. email addresses to which u want to send the mail.
$mail->AddAddress($rec1);
$mail->Subject  = "Eventbook";
$mail->Body     = "Hello hi, testing";
$mail->WordWrap = 200;
if(!$mail->Send()) {
echo 'Message was not sent!.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo  //Fill in the document.location thing
'<script type="text/javascript">
                        if(confirm("Your mail has been sent"))
                        document.location = "/";
        </script>';
}
?>

Eclipse count lines of code

There's always the "brute force":

  1. Search->File

  2. Type the following in "Containing text" -> ^.*$. Then check the "Regular Expression" checkbox

  3. Type the following in "File name patterns" -> *.java

  4. Click "Search"

  5. Check the number of matches in the "Search" Tab.

Cannot implicitly convert type 'int' to 'short'

The line

 Int16 answer = firstNo + secondNo;

is interpreted as

 Int16 answer = (Int32) (firstNo + secondNo);

Simply because there is no such thing as Int16 arithmetic.

The simple solution: Do not use Int16. Use Int32 or simply int.

int is your default integer type. short and long are only used in special cases.

How to find schema name in Oracle ? when you are connected in sql session using read only user

How about the following 3 statements?

-- change to your schema

ALTER SESSION SET CURRENT_SCHEMA=yourSchemaName;

-- check current schema

SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL;

-- generate drop table statements

SELECT 'drop table ', table_name, 'cascade constraints;' FROM ALL_TABLES WHERE OWNER = 'yourSchemaName';

COPY the RESULT and PASTE and RUN.

How to print to console in pytest?

According to the pytest docs, pytest --capture=sys should work. If you want to capture standard out inside a test, refer to the capsys fixture.

CSS table column autowidth

If you want to make sure that last row does not wrap and thus size the way you want it, have a look at

td {
 white-space: nowrap;
}

Java: Best way to iterate through a Collection (here ArrayList)

There is additionally collections’ stream() util with Java 8

collection.forEach((temp) -> {
            System.out.println(temp);
});

or

collection.forEach(System.out::println);

More information about Java 8 stream and collections for wonderers link

print call stack in C or C++

Boost stacktrace

Documented at: https://www.boost.org/doc/libs/1_66_0/doc/html/stacktrace/getting_started.html#stacktrace.getting_started.how_to_print_current_call_stack

This is the most convenient option I've seen so far, because it:

  • can actually print out the line numbers.

    It just makes calls to addr2line however, which is ugly and might be slow if your are taking too many traces.

  • demangles by default

  • Boost is header only, so no need to modify your build system most likely

boost_stacktrace.cpp

#include <iostream>

#define BOOST_STACKTRACE_USE_ADDR2LINE
#include <boost/stacktrace.hpp>

void my_func_2(void) {
    std::cout << boost::stacktrace::stacktrace() << std::endl;
}

void my_func_1(double f) {
    (void)f;
    my_func_2();
}

void my_func_1(int i) {
    (void)i;
    my_func_2();
}

int main(int argc, char **argv) {
    long long unsigned int n;
    if (argc > 1) {
        n = strtoul(argv[1], NULL, 0);
    } else {
        n = 1;
    }
    for (long long unsigned int i = 0; i < n; ++i) {
        my_func_1(1);   // line 28
        my_func_1(2.0); // line 29
    }
}

Unfortunately, it seems to be a more recent addition, and the package libboost-stacktrace-dev is not present in Ubuntu 16.04, only 18.04:

sudo apt-get install libboost-stacktrace-dev
g++ -fno-pie -ggdb3 -O0 -no-pie -o boost_stacktrace.out -std=c++11 \
  -Wall -Wextra -pedantic-errors boost_stacktrace.cpp -ldl
./boost_stacktrace.out

We have to add -ldl at the end or else compilation fails.

Output:

 0# boost::stacktrace::basic_stacktrace<std::allocator<boost::stacktrace::frame> >::basic_stacktrace() at /usr/include/boost/stacktrace/stacktrace.hpp:129
 1# my_func_1(int) at /home/ciro/test/boost_stacktrace.cpp:18
 2# main at /home/ciro/test/boost_stacktrace.cpp:29 (discriminator 2)
 3# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
 4# _start in ./boost_stacktrace.out

 0# boost::stacktrace::basic_stacktrace<std::allocator<boost::stacktrace::frame> >::basic_stacktrace() at /usr/include/boost/stacktrace/stacktrace.hpp:129
 1# my_func_1(double) at /home/ciro/test/boost_stacktrace.cpp:13
 2# main at /home/ciro/test/boost_stacktrace.cpp:27 (discriminator 2)
 3# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
 4# _start in ./boost_stacktrace.out

The output and is further explained on the "glibc backtrace" section below, which is analogous.

Note how my_func_1(int) and my_func_1(float), which are mangled due to function overload, were nicely demangled for us.

Note that the first int calls is off by one line (28 instead of 27 and the second one is off by two lines (27 instead of 29). It was suggested in the comments that this is because the following instruction address is being considered, which makes 27 become 28, and 29 jump off the loop and become 27.

We then observe that with -O3, the output is completely mutilated:

 0# boost::stacktrace::basic_stacktrace<std::allocator<boost::stacktrace::frame> >::size() const at /usr/include/boost/stacktrace/stacktrace.hpp:215
 1# my_func_1(double) at /home/ciro/test/boost_stacktrace.cpp:12
 2# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
 3# _start in ./boost_stacktrace.out

 0# boost::stacktrace::basic_stacktrace<std::allocator<boost::stacktrace::frame> >::size() const at /usr/include/boost/stacktrace/stacktrace.hpp:215
 1# main at /home/ciro/test/boost_stacktrace.cpp:31
 2# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6
 3# _start in ./boost_stacktrace.out

Backtraces are in general irreparably mutilated by optimizations. Tail call optimization is a notable example of that: What is tail call optimization?

Benchmark run on -O3:

time  ./boost_stacktrace.out 1000 >/dev/null

Output:

real    0m43.573s
user    0m30.799s
sys     0m13.665s

So as expected, we see that this method is extremely slow likely to to external calls to addr2line, and is only going to be feasible if a limited number of calls are being made.

Each backtrace print seems to take hundreds of milliseconds, so be warned that if a backtrace happens very often, program performance will suffer significantly.

Tested on Ubuntu 19.10, GCC 9.2.1, boost 1.67.0.

glibc backtrace

Documented at: https://www.gnu.org/software/libc/manual/html_node/Backtraces.html

main.c

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

/* Paste this on the file you want to debug. */
#include <stdio.h>
#include <execinfo.h>
void print_trace(void) {
    char **strings;
    size_t i, size;
    enum Constexpr { MAX_SIZE = 1024 };
    void *array[MAX_SIZE];
    size = backtrace(array, MAX_SIZE);
    strings = backtrace_symbols(array, size);
    for (i = 0; i < size; i++)
        printf("%s\n", strings[i]);
    puts("");
    free(strings);
}

void my_func_3(void) {
    print_trace();
}

void my_func_2(void) {
    my_func_3();
}

void my_func_1(void) {
    my_func_3();
}

int main(void) {
    my_func_1(); /* line 33 */
    my_func_2(); /* line 34 */
    return 0;
}

Compile:

gcc -fno-pie -ggdb3 -O3 -no-pie -o main.out -rdynamic -std=c99 \
  -Wall -Wextra -pedantic-errors main.c

-rdynamic is the key required option.

Run:

./main.out

Outputs:

./main.out(print_trace+0x2d) [0x400a3d]
./main.out(main+0x9) [0x4008f9]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0) [0x7f35a5aad830]
./main.out(_start+0x29) [0x400939]

./main.out(print_trace+0x2d) [0x400a3d]
./main.out(main+0xe) [0x4008fe]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0) [0x7f35a5aad830]
./main.out(_start+0x29) [0x400939]

So we immediately see that an inlining optimization happened, and some functions were lost from the trace.

If we try to get the addresses:

addr2line -e main.out 0x4008f9 0x4008fe

we obtain:

/home/ciro/main.c:21
/home/ciro/main.c:36

which is completely off.

If we do the same with -O0 instead, ./main.out gives the correct full trace:

./main.out(print_trace+0x2e) [0x4009a4]
./main.out(my_func_3+0x9) [0x400a50]
./main.out(my_func_1+0x9) [0x400a68]
./main.out(main+0x9) [0x400a74]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0) [0x7f4711677830]
./main.out(_start+0x29) [0x4008a9]

./main.out(print_trace+0x2e) [0x4009a4]
./main.out(my_func_3+0x9) [0x400a50]
./main.out(my_func_2+0x9) [0x400a5c]
./main.out(main+0xe) [0x400a79]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0) [0x7f4711677830]
./main.out(_start+0x29) [0x4008a9]

and then:

addr2line -e main.out 0x400a74 0x400a79

gives:

/home/cirsan01/test/main.c:34
/home/cirsan01/test/main.c:35

so the lines are off by just one, TODO why? But this might still be usable.

Conclusion: backtraces can only possibly show perfectly with -O0. With optimizations, the original backtrace is fundamentally modified in the compiled code.

I couldn't find a simple way to automatically demangle C++ symbols with this however, here are some hacks:

Tested on Ubuntu 16.04, GCC 6.4.0, libc 2.23.

glibc backtrace_symbols_fd

This helper is a bit more convenient than backtrace_symbols, and produces basically identical output:

/* Paste this on the file you want to debug. */
#include <execinfo.h>
#include <stdio.h>
#include <unistd.h>
void print_trace(void) {
    size_t i, size;
    enum Constexpr { MAX_SIZE = 1024 };
    void *array[MAX_SIZE];
    size = backtrace(array, MAX_SIZE);
    backtrace_symbols_fd(array, size, STDOUT_FILENO);
    puts("");
}

Tested on Ubuntu 16.04, GCC 6.4.0, libc 2.23.

glibc backtrace with C++ demangling hack 1: -export-dynamic + dladdr

Adapted from: https://gist.github.com/fmela/591333/c64f4eb86037bb237862a8283df70cdfc25f01d3

This is a "hack" because it requires changing the ELF with -export-dynamic.

glibc_ldl.cpp

#include <dlfcn.h>     // for dladdr
#include <cxxabi.h>    // for __cxa_demangle

#include <cstdio>
#include <string>
#include <sstream>
#include <iostream>

// This function produces a stack backtrace with demangled function & method names.
std::string backtrace(int skip = 1)
{
    void *callstack[128];
    const int nMaxFrames = sizeof(callstack) / sizeof(callstack[0]);
    char buf[1024];
    int nFrames = backtrace(callstack, nMaxFrames);
    char **symbols = backtrace_symbols(callstack, nFrames);

    std::ostringstream trace_buf;
    for (int i = skip; i < nFrames; i++) {
        Dl_info info;
        if (dladdr(callstack[i], &info)) {
            char *demangled = NULL;
            int status;
            demangled = abi::__cxa_demangle(info.dli_sname, NULL, 0, &status);
            std::snprintf(
                buf,
                sizeof(buf),
                "%-3d %*p %s + %zd\n",
                i,
                (int)(2 + sizeof(void*) * 2),
                callstack[i],
                status == 0 ? demangled : info.dli_sname,
                (char *)callstack[i] - (char *)info.dli_saddr
            );
            free(demangled);
        } else {
            std::snprintf(buf, sizeof(buf), "%-3d %*p\n",
                i, (int)(2 + sizeof(void*) * 2), callstack[i]);
        }
        trace_buf << buf;
        std::snprintf(buf, sizeof(buf), "%s\n", symbols[i]);
        trace_buf << buf;
    }
    free(symbols);
    if (nFrames == nMaxFrames)
        trace_buf << "[truncated]\n";
    return trace_buf.str();
}

void my_func_2(void) {
    std::cout << backtrace() << std::endl;
}

void my_func_1(double f) {
    (void)f;
    my_func_2();
}

void my_func_1(int i) {
    (void)i;
    my_func_2();
}

int main() {
    my_func_1(1);
    my_func_1(2.0);
}

Compile and run:

g++ -fno-pie -ggdb3 -O0 -no-pie -o glibc_ldl.out -std=c++11 -Wall -Wextra \
  -pedantic-errors -fpic glibc_ldl.cpp -export-dynamic -ldl
./glibc_ldl.out 

output:

1             0x40130a my_func_2() + 41
./glibc_ldl.out(_Z9my_func_2v+0x29) [0x40130a]
2             0x40139e my_func_1(int) + 16
./glibc_ldl.out(_Z9my_func_1i+0x10) [0x40139e]
3             0x4013b3 main + 18
./glibc_ldl.out(main+0x12) [0x4013b3]
4       0x7f7594552b97 __libc_start_main + 231
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xe7) [0x7f7594552b97]
5             0x400f3a _start + 42
./glibc_ldl.out(_start+0x2a) [0x400f3a]

1             0x40130a my_func_2() + 41
./glibc_ldl.out(_Z9my_func_2v+0x29) [0x40130a]
2             0x40138b my_func_1(double) + 18
./glibc_ldl.out(_Z9my_func_1d+0x12) [0x40138b]
3             0x4013c8 main + 39
./glibc_ldl.out(main+0x27) [0x4013c8]
4       0x7f7594552b97 __libc_start_main + 231
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xe7) [0x7f7594552b97]
5             0x400f3a _start + 42
./glibc_ldl.out(_start+0x2a) [0x400f3a]

Tested on Ubuntu 18.04.

glibc backtrace with C++ demangling hack 2: parse backtrace output

Shown at: https://panthema.net/2008/0901-stacktrace-demangled/

This is a hack because it requires parsing.

TODO get it to compile and show it here.

libunwind

TODO does this have any advantage over glibc backtrace? Very similar output, also requires modifying the build command, but not part of glibc so requires an extra package installation.

Code adapted from: https://eli.thegreenplace.net/2015/programmatic-access-to-the-call-stack-in-c/

main.c

/* This must be on top. */
#define _XOPEN_SOURCE 700

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

/* Paste this on the file you want to debug. */
#define UNW_LOCAL_ONLY
#include <libunwind.h>
#include <stdio.h>
void print_trace() {
    char sym[256];
    unw_context_t context;
    unw_cursor_t cursor;
    unw_getcontext(&context);
    unw_init_local(&cursor, &context);
    while (unw_step(&cursor) > 0) {
        unw_word_t offset, pc;
        unw_get_reg(&cursor, UNW_REG_IP, &pc);
        if (pc == 0) {
            break;
        }
        printf("0x%lx:", pc);
        if (unw_get_proc_name(&cursor, sym, sizeof(sym), &offset) == 0) {
            printf(" (%s+0x%lx)\n", sym, offset);
        } else {
            printf(" -- error: unable to obtain symbol name for this frame\n");
        }
    }
    puts("");
}

void my_func_3(void) {
    print_trace();
}

void my_func_2(void) {
    my_func_3();
}

void my_func_1(void) {
    my_func_3();
}

int main(void) {
    my_func_1(); /* line 46 */
    my_func_2(); /* line 47 */
    return 0;
}

Compile and run:

sudo apt-get install libunwind-dev
gcc -fno-pie -ggdb3 -O3 -no-pie -o main.out -std=c99 \
  -Wall -Wextra -pedantic-errors main.c -lunwind

Either #define _XOPEN_SOURCE 700 must be on top, or we must use -std=gnu99:

Run:

./main.out

Output:

0x4007db: (main+0xb)
0x7f4ff50aa830: (__libc_start_main+0xf0)
0x400819: (_start+0x29)

0x4007e2: (main+0x12)
0x7f4ff50aa830: (__libc_start_main+0xf0)
0x400819: (_start+0x29)

and:

addr2line -e main.out 0x4007db 0x4007e2

gives:

/home/ciro/main.c:34
/home/ciro/main.c:49

With -O0:

0x4009cf: (my_func_3+0xe)
0x4009e7: (my_func_1+0x9)
0x4009f3: (main+0x9)
0x7f7b84ad7830: (__libc_start_main+0xf0)
0x4007d9: (_start+0x29)

0x4009cf: (my_func_3+0xe)
0x4009db: (my_func_2+0x9)
0x4009f8: (main+0xe)
0x7f7b84ad7830: (__libc_start_main+0xf0)
0x4007d9: (_start+0x29)

and:

addr2line -e main.out 0x4009f3 0x4009f8

gives:

/home/ciro/main.c:47
/home/ciro/main.c:48

Tested on Ubuntu 16.04, GCC 6.4.0, libunwind 1.1.

libunwind with C++ name demangling

Code adapted from: https://eli.thegreenplace.net/2015/programmatic-access-to-the-call-stack-in-c/

unwind.cpp

#define UNW_LOCAL_ONLY
#include <cxxabi.h>
#include <libunwind.h>
#include <cstdio>
#include <cstdlib>
#include <iostream>

void backtrace() {
  unw_cursor_t cursor;
  unw_context_t context;

  // Initialize cursor to current frame for local unwinding.
  unw_getcontext(&context);
  unw_init_local(&cursor, &context);

  // Unwind frames one by one, going up the frame stack.
  while (unw_step(&cursor) > 0) {
    unw_word_t offset, pc;
    unw_get_reg(&cursor, UNW_REG_IP, &pc);
    if (pc == 0) {
      break;
    }
    std::printf("0x%lx:", pc);

    char sym[256];
    if (unw_get_proc_name(&cursor, sym, sizeof(sym), &offset) == 0) {
      char* nameptr = sym;
      int status;
      char* demangled = abi::__cxa_demangle(sym, nullptr, nullptr, &status);
      if (status == 0) {
        nameptr = demangled;
      }
      std::printf(" (%s+0x%lx)\n", nameptr, offset);
      std::free(demangled);
    } else {
      std::printf(" -- error: unable to obtain symbol name for this frame\n");
    }
  }
}

void my_func_2(void) {
    backtrace();
    std::cout << std::endl; // line 43
}

void my_func_1(double f) {
    (void)f;
    my_func_2();
}

void my_func_1(int i) {
    (void)i;
    my_func_2();
}  // line 54

int main() {
    my_func_1(1);
    my_func_1(2.0);
}

Compile and run:

sudo apt-get install libunwind-dev
g++ -fno-pie -ggdb3 -O0 -no-pie -o unwind.out -std=c++11 \
  -Wall -Wextra -pedantic-errors unwind.cpp -lunwind -pthread
./unwind.out

Output:

0x400c80: (my_func_2()+0x9)
0x400cb7: (my_func_1(int)+0x10)
0x400ccc: (main+0x12)
0x7f4c68926b97: (__libc_start_main+0xe7)
0x400a3a: (_start+0x2a)

0x400c80: (my_func_2()+0x9)
0x400ca4: (my_func_1(double)+0x12)
0x400ce1: (main+0x27)
0x7f4c68926b97: (__libc_start_main+0xe7)
0x400a3a: (_start+0x2a)

and then we can find the lines of my_func_2 and my_func_1(int) with:

addr2line -e unwind.out 0x400c80 0x400cb7

which gives:

/home/ciro/test/unwind.cpp:43
/home/ciro/test/unwind.cpp:54

TODO: why are the lines off by one?

Tested on Ubuntu 18.04, GCC 7.4.0, libunwind 1.2.1.

GDB automation

We can also do this with GDB without recompiling by using: How to do an specific action when a certain breakpoint is hit in GDB?

Although if you are going to print the backtrace a lot, this will likely be less fast than the other options, but maybe we can reach native speeds with compile code, but I'm lazy to test it out now: How to call assembly in gdb?

main.cpp

void my_func_2(void) {}

void my_func_1(double f) {
    my_func_2();
}

void my_func_1(int i) {
    my_func_2();
}

int main() {
    my_func_1(1);
    my_func_1(2.0);
}

main.gdb

start
break my_func_2
commands
  silent
  backtrace
  printf "\n"
  continue
end
continue

Compile and run:

g++ -ggdb3 -o main.out main.cpp
gdb -nh -batch -x main.gdb main.out

Output:

Temporary breakpoint 1 at 0x1158: file main.cpp, line 12.

Temporary breakpoint 1, main () at main.cpp:12
12          my_func_1(1);
Breakpoint 2 at 0x555555555129: file main.cpp, line 1.
#0  my_func_2 () at main.cpp:1
#1  0x0000555555555151 in my_func_1 (i=1) at main.cpp:8
#2  0x0000555555555162 in main () at main.cpp:12

#0  my_func_2 () at main.cpp:1
#1  0x000055555555513e in my_func_1 (f=2) at main.cpp:4
#2  0x000055555555516f in main () at main.cpp:13

[Inferior 1 (process 14193) exited normally]

TODO I wanted to do this with just -ex from the command line to not have to create main.gdb but I couldn't get the commands to work there.

Tested in Ubuntu 19.04, GDB 8.2.

Linux kernel

How to print the current thread stack trace inside the Linux kernel?

libdwfl

This was originally mentioned at: https://stackoverflow.com/a/60713161/895245 and it might be the best method, but I have to benchmark a bit more, but please go upvote that answer.

TODO: I tried to minimize the code in that answer, which was working, to a single function, but it is segfaulting, let me know if anyone can find why.

dwfl.cpp

#include <cassert>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>

#include <cxxabi.h> // __cxa_demangle
#include <elfutils/libdwfl.h> // Dwfl*
#include <execinfo.h> // backtrace
#include <unistd.h> // getpid

// https://stackoverflow.com/questions/281818/unmangling-the-result-of-stdtype-infoname
std::string demangle(const char* name) {
    int status = -4;
    std::unique_ptr<char, void(*)(void*)> res {
        abi::__cxa_demangle(name, NULL, NULL, &status),
        std::free
    };
    return (status==0) ? res.get() : name ;
}

std::string debug_info(Dwfl* dwfl, void* ip) {
    std::string function;
    int line = -1;
    char const* file;
    uintptr_t ip2 = reinterpret_cast<uintptr_t>(ip);
    Dwfl_Module* module = dwfl_addrmodule(dwfl, ip2);
    char const* name = dwfl_module_addrname(module, ip2);
    function = name ? demangle(name) : "<unknown>";
    if (Dwfl_Line* dwfl_line = dwfl_module_getsrc(module, ip2)) {
        Dwarf_Addr addr;
        file = dwfl_lineinfo(dwfl_line, &addr, &line, nullptr, nullptr, nullptr);
    }
    std::stringstream ss;
    ss << ip << ' ' << function;
    if (file)
        ss << " at " << file << ':' << line;
    ss << std::endl;
    return ss.str();
}

std::string stacktrace() {
    // Initialize Dwfl.
    Dwfl* dwfl = nullptr;
    {
        Dwfl_Callbacks callbacks = {};
        char* debuginfo_path = nullptr;
        callbacks.find_elf = dwfl_linux_proc_find_elf;
        callbacks.find_debuginfo = dwfl_standard_find_debuginfo;
        callbacks.debuginfo_path = &debuginfo_path;
        dwfl = dwfl_begin(&callbacks);
        assert(dwfl);
        int r;
        r = dwfl_linux_proc_report(dwfl, getpid());
        assert(!r);
        r = dwfl_report_end(dwfl, nullptr, nullptr);
        assert(!r);
        static_cast<void>(r);
    }

    // Loop over stack frames.
    std::stringstream ss;
    {
        void* stack[512];
        int stack_size = ::backtrace(stack, sizeof stack / sizeof *stack);
        for (int i = 0; i < stack_size; ++i) {
            ss << i << ": ";

            // Works.
            ss << debug_info(dwfl, stack[i]);

#if 0
            // TODO intended to do the same as above, but segfaults,
            // so possibly UB In above function that does not blow up by chance?
            void *ip = stack[i];
            std::string function;
            int line = -1;
            char const* file;
            uintptr_t ip2 = reinterpret_cast<uintptr_t>(ip);
            Dwfl_Module* module = dwfl_addrmodule(dwfl, ip2);
            char const* name = dwfl_module_addrname(module, ip2);
            function = name ? demangle(name) : "<unknown>";
            // TODO if I comment out this line it does not blow up anymore.
            if (Dwfl_Line* dwfl_line = dwfl_module_getsrc(module, ip2)) {
              Dwarf_Addr addr;
              file = dwfl_lineinfo(dwfl_line, &addr, &line, nullptr, nullptr, nullptr);
            }
            ss << ip << ' ' << function;
            if (file)
                ss << " at " << file << ':' << line;
            ss << std::endl;
#endif
        }
    }
    dwfl_end(dwfl);
    return ss.str();
}

void my_func_2() {
    std::cout << stacktrace() << std::endl;
    std::cout.flush();
}

void my_func_1(double f) {
    (void)f;
    my_func_2();
}

void my_func_1(int i) {
    (void)i;
    my_func_2();
}

int main(int argc, char **argv) {
    long long unsigned int n;
    if (argc > 1) {
        n = strtoul(argv[1], NULL, 0);
    } else {
        n = 1;
    }
    for (long long unsigned int i = 0; i < n; ++i) {
        my_func_1(1);
        my_func_1(2.0);
    }
}

Compile and run:

sudo apt install libdw-dev
g++ -fno-pie -ggdb3 -O0 -no-pie -o dwfl.out -std=c++11 -Wall -Wextra -pedantic-errors dwfl.cpp -ldw
./dwfl.out

Output:

0: 0x402b74 stacktrace[abi:cxx11]() at /home/ciro/test/dwfl.cpp:65
1: 0x402ce0 my_func_2() at /home/ciro/test/dwfl.cpp:100
2: 0x402d7d my_func_1(int) at /home/ciro/test/dwfl.cpp:112
3: 0x402de0 main at /home/ciro/test/dwfl.cpp:123
4: 0x7f7efabbe1e3 __libc_start_main at ../csu/libc-start.c:342
5: 0x40253e _start at ../csu/libc-start.c:-1

0: 0x402b74 stacktrace[abi:cxx11]() at /home/ciro/test/dwfl.cpp:65
1: 0x402ce0 my_func_2() at /home/ciro/test/dwfl.cpp:100
2: 0x402d66 my_func_1(double) at /home/ciro/test/dwfl.cpp:107
3: 0x402df1 main at /home/ciro/test/dwfl.cpp:121
4: 0x7f7efabbe1e3 __libc_start_main at ../csu/libc-start.c:342
5: 0x40253e _start at ../csu/libc-start.c:-1

Benchmark run:

g++ -fno-pie -ggdb3 -O3 -no-pie -o dwfl.out -std=c++11 -Wall -Wextra -pedantic-errors dwfl.cpp -ldw
time ./dwfl.out 1000 >/dev/null

Output:

real    0m3.751s
user    0m2.822s
sys     0m0.928s

So we see that this method is 10x faster than Boost's stacktrace, and might therefore be applicable to more use cases.

Tested in Ubuntu 19.10 amd64, libdw-dev 0.176-1.1.

See also

With CSS, how do I make an image span the full width of the page as a background image?

If you're hoping to use background-image: url(...);, I don't think you can. However, if you want to play with layering, you can do something like this:

<img class="bg" src="..." />

And then some CSS:

.bg
{
  width: 100%;
  z-index: 0;
}

You can now layer content above the stretched image by playing with z-indexes and such. One quick note, the image can't be contained in any other elements for the width: 100%; to apply to the whole page.

Here's a quick demo if you can't rely on background-size: http://jsfiddle.net/bB3Uc/

Running Python on Windows for Node.js dependencies

This is most easiest way to let NPM do everything for you

npm --add-python-to-path='true' --debug install --global windows-build-tools

How to get the last element of an array in Ruby?

Use -1 index (negative indices count backward from the end of the array):

a[-1] # => 5
b[-1] # => 6

or Array#last method:

a.last # => 5
b.last # => 6

In a URL, should spaces be encoded using %20 or +?

According to the W3C (and they are the official source on these things), a space character in the query string (and in the query string only) may be encoded as either "%20" or "+". From the section "Query strings" under "Recommendations":

Within the query string, the plus sign is reserved as shorthand notation for a space. Therefore, real plus signs must be encoded. This method was used to make query URIs easier to pass in systems which did not allow spaces.

According to section 3.4 of RFC2396 which is the official specification on URIs in general, the "query" component is URL-dependent:

3.4. Query Component The query component is a string of information to be interpreted by the resource.

   query         = *uric

Within a query component, the characters ";", "/", "?", ":", "@", "&", "=", "+", ",", and "$" are reserved.

It is therefore a bug in the other software if it does not accept URLs with spaces in the query string encoded as "+" characters.

As for the third part of your question, one way (though slightly ugly) to fix the output from URLEncoder.encode() is to then call replaceAll("\\+","%20") on the return value.

How to reference image resources in XAML?

If the image is in your resources folder and its build action is set to Resource. You can reference the image in XAML as follows:

"pack://application:,,,/Resources/Search.png"

Assuming you do not have any folder structure under the Resources folder and it is an application. For example I use:

ImageSource="pack://application:,,,/Resources/RibbonImages/CloseButton.png"

when I have a folder named RibbonImages under Resources folder.

Easy way to concatenate two byte arrays

byte[] result = new byte[a.length + b.length];
// copy a to result
System.arraycopy(a, 0, result, 0, a.length);
// copy b to result
System.arraycopy(b, 0, result, a.length, b.length);

Create mysql table directly from CSV file using the CSV Storage engine?

I'm recommended use MySQL Workbench where is import data. Workbench allows the user to create a new table from a file in CSV or JSON format. It handles table schema and data import in just a few clicks through the wizard.

In MySQL Workbench, use the context menu on table list and click Table Data Import Wizard.

MySQL Workbench image

More from the MySQL Workbench 6.5.1 Table Data Export and Import Wizard documentation. Download MySQL Workbench here.

vertical-align image in div

Old question but nowadays CSS3 makes vertical alignment really simple!

Just add to the <div> this css:

display:flex;
align-items:center;
justify-content:center;

JSFiddle demo

Live Example:

_x000D_
_x000D_
.img_thumb {_x000D_
    float: left;_x000D_
    height: 120px;_x000D_
    margin-bottom: 5px;_x000D_
    margin-left: 9px;_x000D_
    position: relative;_x000D_
    width: 147px;_x000D_
    background-color: rgba(0, 0, 0, 0.5);_x000D_
    border-radius: 3px;_x000D_
    display:flex;_x000D_
    align-items:center;_x000D_
    justify-content:center;_x000D_
}
_x000D_
<div class="img_thumb">_x000D_
    <a class="images_class" href="http://i.imgur.com/2FMLuSn.jpg" rel="images">_x000D_
       <img src="http://i.imgur.com/2FMLuSn.jpg" title="img_title" alt="img_alt" />_x000D_
    </a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Check if Variable is Empty - Angular 2

Angular 4 empty data if else

if(this.data == 0)
{
alert("Null data");
}
else
{
//some logic
}

Alter column, add default constraint

Actually you have to Do Like below Example, which will help to Solve the Issue...

drop table ABC_table

create table ABC_table
(
    names varchar(20),
    age int
)

ALTER TABLE ABC_table
ADD CONSTRAINT MyConstraintName
DEFAULT 'This is not NULL' FOR names

insert into ABC(age) values(10)

select * from ABC

How to convert strings into integers in Python?

If it's only a tuple of tuples, something like rows=[map(int, row) for row in rows] will do the trick. (There's a list comprehension and a call to map(f, lst), which is equal to [f(a) for a in lst], in there.)

Eval is not what you want to do, in case there's something like __import__("os").unlink("importantsystemfile") in your database for some reason. Always validate your input (if with nothing else, the exception int() will raise if you have bad input).

AngularJS - Create a directive that uses ng-model

You only need ng-model when you need to access the model's $viewValue or $modelValue. See NgModelController. And in that case, you would use require: '^ngModel'.

For the rest, see Roys answer.

Increment a database field by 1

This is more a footnote to a number of the answers above which suggest the use of ON DUPLICATE KEY UPDATE, BEWARE that this is NOT always replication safe, so if you ever plan on growing beyond a single server, you'll want to avoid this and use two queries, one to verify the existence, and then a second to either UPDATE when a row exists, or INSERT when it does not.

What is time_t ultimately a typedef to?

Under Visual Studio 2008, it defaults to an __int64 unless you define _USE_32BIT_TIME_T. You're better off just pretending that you don't know what it's defined as, since it can (and will) change from platform to platform.

Editor does not contain a main type

Try 'Update Project'. Once I did this, The Run as Java Application option appeared.

How to switch to other branch in Source Tree to commit the code?

Hi I'm also relatively new but I can give you basic help.

  1. To switch to another branch use "Checkout". Just click on your branch and then on the button "checkout" at the top.

UPDATE 12.01.2016:

The bold line is the current branch.

You can also just double click a branch to use checkout.


  1. Your first answer I think depends on the repository you use (like github or bitbucket). Maybe the "Show hosted repository"-Button can help you (Left panel, bottom, right button = database with cog)

And here some helpful links:

Easy Git Guide

Git-flow - Git branching model

Tips on branching with sourcetree

Global Git ignore

You should create an exclude file for this. Check out this gist which is pretty self explanatory.

To address your question though, you may need to either de-index the .tmproj file (if you've already added it to the index) with git rm --cached path/to/.tmproj, or git add and commit your .gitignore file.

How do I get the name of a Ruby class?

You want to call .name on the object's class:

result.class.name

How can I open Windows Explorer to a certain directory from within a WPF app?

This should work:

Process.Start(@"<directory goes here>")

Or if you'd like a method to run programs/open files and/or folders:

private void StartProcess(string path)
{
    ProcessStartInfo StartInformation = new ProcessStartInfo();

    StartInformation.FileName = path;

    Process process = Process.Start(StartInformation);

    process.EnableRaisingEvents = true;
}

And then call the method and in the parenthesis put either the directory of the file and/or folder there or the name of the application. Hope this helped!

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

It is used to find the how many rows contain data in a worksheet that contains data in the column "A". The full usage is

 lastRowIndex = ws.Cells(ws.Rows.Count, "A").End(xlUp).row

Where ws is a Worksheet object. In the questions example it was implied that the statement was inside a With block

With ws
    lastRowIndex = .Cells(.Rows.Count, "A").End(xlUp).row
End With
  1. ws.Rows.Count returns the total count of rows in the worksheet (1048576 in Excel 2010).
  2. .Cells(.Rows.Count, "A") returns the bottom most cell in column "A" in the worksheet

Then there is the End method. The documentation is ambiguous as to what it does.

Returns a Range object that represents the cell at the end of the region that contains the source range

Particularly it doesn't define what a "region" is. My understanding is a region is a contiguous range of non-empty cells. So the expected usage is to start from a cell in a region and find the last cell in that region in that direction from the original cell. However there are multiple exceptions for when you don't use it like that:

  • If the range is multiple cells, it will use the region of rng.cells(1,1).
  • If the range isn't in a region, or the range is already at the end of the region, then it will travel along the direction until it enters a region and return the first encountered cell in that region.
  • If it encounters the edge of the worksheet it will return the cell on the edge of that worksheet.

So Range.End is not a trivial function.

  1. .row returns the row index of that cell.

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

If you want to use rollback, then use start transaction and otherwise forget all those things,

By default, MySQL automatically commits the changes to the database.

To force MySQL not to commit these changes automatically, execute following:

SET autocommit = 0;
//OR    
SET autocommit = OFF

To enable the autocommit mode explicitly:

SET autocommit = 1;
//OR    
SET autocommit = ON;

Python Pandas counting and summing specific conditions

I usually use numpy sum over the logical condition column:

>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame({'Age' : [20,24,18,5,78]})
>>> np.sum(df['Age'] > 20)
2

This seems to me slightly shorter than the solution presented above

How to compare only Date without Time in DateTime types in Linq to SQL with Entity Framework?

In your join or where clause, use the Date property of the column. Behind the scenes, this executes a CONVERT(DATE, <expression>) operation. This should allow you to compare dates without the time.

PHP: cannot declare class because the name is already in use

I had this problem before and to fix this, Just make sure :

  1. You did not create an instance of this class before
  2. If you call this from a class method, make sure the __destruct is set on the class you called from.

My problem (before) :
I had class : Core, Router, Permissions and Render Core include's the Router class, Router then calls Permissions class, then Router __destruct calls the Render class and the error "Cannot declare class because the name is already in use" appeared.

Solution :
I added __destruct on Permission class and the __destruct was empty and it's fixed...

Bootstrap dropdown sub menu missing

Updated 2018

The dropdown-submenu has been removed in Bootstrap 3 RC. In the words of Bootstrap author Mark Otto..

"Submenus just don't have much of a place on the web right now, especially the mobile web. They will be removed with 3.0" - https://github.com/twbs/bootstrap/pull/6342

But, with a little extra CSS you can get the same functionality.

Bootstrap 4 (navbar submenu on hover)

.navbar-nav li:hover > ul.dropdown-menu {
    display: block;
}
.dropdown-submenu {
    position:relative;
}
.dropdown-submenu>.dropdown-menu {
    top:0;
    left:100%;
    margin-top:-6px;
}

Navbar submenu dropdown hover
Navbar submenu dropdown hover (right aligned)
Navbar submenu dropdown click (right aligned)
Navbar dropdown hover (no submenu)


Bootstrap 3

Here is an example that uses 3.0 RC 1: http://bootply.com/71520

Here is an example that uses Bootstrap 3.0.0 (final): http://bootply.com/86684

CSS

.dropdown-submenu {
    position:relative;
}
.dropdown-submenu>.dropdown-menu {
    top:0;
    left:100%;
    margin-top:-6px;
    margin-left:-1px;
    -webkit-border-radius:0 6px 6px 6px;
    -moz-border-radius:0 6px 6px 6px;
    border-radius:0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
    display:block;
}
.dropdown-submenu>a:after {
    display:block;
    content:" ";
    float:right;
    width:0;
    height:0;
    border-color:transparent;
    border-style:solid;
    border-width:5px 0 5px 5px;
    border-left-color:#cccccc;
    margin-top:5px;
    margin-right:-10px;
}
.dropdown-submenu:hover>a:after {
    border-left-color:#ffffff;
}
.dropdown-submenu.pull-left {
    float:none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
    left:-100%;
    margin-left:10px;
    -webkit-border-radius:6px 0 6px 6px;
    -moz-border-radius:6px 0 6px 6px;
    border-radius:6px 0 6px 6px;
}

Sample Markup

<div class="navbar navbar-default navbar-fixed-top" role="navigation">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">  
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
        </div>
        <div class="collapse navbar-collapse navbar-ex1-collapse">
            <ul class="nav navbar-nav">
                <li class="menu-item dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Drop Down<b class="caret"></b></a>
                    <ul class="dropdown-menu">
                        <li class="menu-item dropdown dropdown-submenu">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Level 1</a>
                            <ul class="dropdown-menu">
                                <li class="menu-item ">
                                    <a href="#">Link 1</a>
                                </li>
                                <li class="menu-item dropdown dropdown-submenu">
                                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Level 2</a>
                                    <ul class="dropdown-menu">
                                        <li>
                                            <a href="#">Link 3</a>
                                        </li>
                                    </ul>
                                </li>
                            </ul>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</div>

P.S. - Example in navbar that adjusts left position: http://bootply.com/92442

How to clear all <div>s’ contents inside a parent <div>?

jQuery's empty() function does just that:

$('#masterdiv').empty();

clears the master div.

$('#masterdiv div').empty();

clears all the child divs, but leaves the master intact.

How to simulate POST request?

Postman is the best application to test your APIs !

You can import or export your routes and let him remember all your body requests ! :)

EDIT : This comment is 5 yea's old and deprecated :D

Here's the new Postman App : https://www.postman.com/

curl : (1) Protocol https not supported or disabled in libcurl

Got the same error when using curl on https site like

curl https://api.dis...

as pointed out by ganesh, it was because my version of curl wasn't ssl enabled. went back and downloaded the version with ssl and it worked fine.

How to write and save html file in python?

You can create multi-line strings by enclosing them in triple quotes. So you can store your HTML in a string and pass that string to write():

html_str = """
<table border=1>
     <tr>
       <th>Number</th>
       <th>Square</th>
     </tr>
     <indent>
     <% for i in range(10): %>
       <tr>
         <td><%= i %></td>
         <td><%= i**2 %></td>
       </tr>
     </indent>
</table>
"""

Html_file= open("filename","w")
Html_file.write(html_str)
Html_file.close()

How to remove duplicate objects in a List<MyObject> without equals/hashcode?

Create a new class that wraps your Blog object and provides the equality/hashcode method you need. For maximum efficiency I would add two static methods on the wrapper, one to convert Blogs list -> Blog Wrapper list and the other to convert Blog Wrapper list -> Blog list. Then you would:

  1. Convert your blog list to blog wrapper list
  2. Add your blog wrapper list to a Hash Set
  3. Get the condensed blog wrapper list back out of the Hash Set
  4. Convert the blog wrapper list to a blog list

Code for Blog Wrapper would be something like this:

import java.util.ArrayList;
import java.util.List;

public class BlogWrapper {
    public static List<Blog> unwrappedList(List<BlogWrapper> blogWrapperList) {
        if (blogWrapperList == null)
            return new ArrayList<Blog>(0);

        List<Blog> blogList = new ArrayList<Blog>(blogWrapperList.size());
        for (BlogWrapper bW : blogWrapperList) {
            blogList.add(bW.getBlog());
        }

        return blogList;
    }

    public static List<BlogWrapper> wrappedList(List<Blog> blogList) {
        if (blogList == null)
            return new ArrayList<BlogWrapper>(0);

        List<BlogWrapper> blogWrapperList = new ArrayList<BlogWrapper>(blogList
                .size());
        for (Blog b : blogList) {
            blogWrapperList.add(new BlogWrapper(b));
        }

        return blogWrapperList;
    }

    private Blog blog = null;

    public BlogWrapper() {
        super();
    }

    public BlogWrapper(Blog aBlog) {
        super();
        setBlog(aBlog);
    }

    public boolean equals(Object other) {
        // Your equality logic here
        return super.equals(other);
    }

    public Blog getBlog() {
        return blog;
    }

    public int hashCode() {
        // Your hashcode logic here
        return super.hashCode();
    }

    public void setBlog(Blog blog) {
        this.blog = blog;
    }
}

And you could use this like so:

List<BlogWrapper> myBlogWrappers = BlogWrapper.wrappedList(your blog list here);
Set<BlogWrapper> noDupWrapSet = new HashSet<BlogWrapper>(myBlogWrappers);
List<BlogWrapper> noDupWrapList = new ArrayList<BlogWrapper>(noDupSet);
List<Blog> noDupList = BlogWrapper.unwrappedList(noDupWrapList);

Quite obviously you can make the above code more efficient, particularly by making the wrap and unwrap methods on Blog Wrapper take collections instead of Lists.

An alternative route to wrapping the Blog class would be to use a byte code manipulation library like BCEL to actually change the equals and hashcode method for Blog. But of course, that could have unintended consequences to the rest of your code if they require the original equals/hashcode behaviour.

Selecting multiple columns in a Pandas dataframe

Assuming your column names (df.columns) are ['index','a','b','c'], then the data you want is in the third and fourth columns. If you don't know their names when your script runs, you can do this

newdf = df[df.columns[2:4]] # Remember, Python is zero-offset! The "third" entry is at slot two.

As EMS points out in his answer, df.ix slices columns a bit more concisely, but the .columns slicing interface might be more natural, because it uses the vanilla one-dimensional Python list indexing/slicing syntax.

Warning: 'index' is a bad name for a DataFrame column. That same label is also used for the real df.index attribute, an Index array. So your column is returned by df['index'] and the real DataFrame index is returned by df.index. An Index is a special kind of Series optimized for lookup of its elements' values. For df.index it's for looking up rows by their label. That df.columns attribute is also a pd.Index array, for looking up columns by their labels.

How to convert JSON to string?

JSON.stringify()

Convert a value to JSON, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.

How to get the Enum Index value in C#

One reason that the designers c# might have chosen to NOT have enums auto convert was to prevent accidentally mixing different enum types...

e.g. this is bad code followed by a good version
enum ParkingLevel { GroundLevel, FirstFloor};
enum ParkingFacing { North, East, South, West }
void Test()
{
    var parking = ParkingFacing.North; // NOT A LEVEL
    // WHOOPS at least warning in editor/compile on calls
    WhichLevel(parking); 

    // BAD  wrong type of index, no warning
    var info = ParkinglevelArray[ (int)parking ];
}


// however you can write this, looks complicated 
// but avoids using casts every time AND stops miss-use
void Test()
{
  ParkingLevelManager levels = new ParkingLevelManager();
  // assign info to each level
  var parking = ParkingFacing.North;

  // Next line wrong mixing type 
  // but great you get warning in editor or at compile time      
  var info=levels[parking];

  // and.... no cast needed for correct use
  var pl = ParkingLevel.GroundLevel;
  var infoCorrect=levels[pl];

}
class ParkingLevelInfo { /*...*/ }
class ParkingLevelManager
{
    List<ParkingLevelInfo> m_list;
    public ParkingLevelInfo this[ParkingLevel x] 
 { get{ return m_list[(int)x]; } }}

UIDevice uniqueIdentifier deprecated - What to do now?

Apple has hidden the UDID from all public APIs, starting with iOS 7. Any UDID that begins with FFFF is a fake ID. The "Send UDID" apps that previously worked can no longer be used to gather UDID for test devices. (sigh!)

The UDID is shown when a device is connected to XCode (in the organizer), and when the device is connected to iTunes (although you have to click on 'Serial Number' to get the Identifier to display.

If you need to get the UDID for a device to add to a provisioning profile, and can't do it yourself in XCode, you will have to walk them through the steps to copy/paste it from iTunes.

Is there a way since (iOS 7's release) to get the UDID without using iTunes on a PC/Mac?

Convert hexadecimal string (hex) to a binary string

With all zeroes:

static String hexToBin(String s) {
    String preBin = new BigInteger(s, 16).toString(2);
    Integer length = preBin.length();
    if (length < 8) {
        for (int i = 0; i < 8 - length; i++) {
            preBin = "0" + preBin;
        }
    }
    return preBin;
}

What is bootstrapping?

Alex, it's pretty much what your computer does when it boots up. ('Booting' a computer actually comes from the word bootstrapping)

Initially, the small program in your BIOS runs. That contains enough machine code to load and run a larger, more complex program.

That second program is probably something like NTLDR (in Windows) or LILO (in Linux), which then executes and is able to load, then run, the rest of the operating system.

Regex to match 2 digits, optional decimal, two digits

(?<![\d.])(\d{1,2}|\d{0,2}\.\d{1,2})?(?![\d.])

Matches:

  • Your examples
  • 33.

Does not match:

  • 333.33
  • 33.333

Use jQuery to get the file input's selected filename without the path

Get path work with all OS

var filename = $('input[type=file]').val().replace(/.*(\/|\\)/, '');

Example

C:\fakepath\filename.doc 
/var/fakepath/filename.doc

Both return

filename.doc
filename.doc

Example of multipart/form-data

EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245

To see exactly what is happening, use nc -l or an ECHO server and an user agent like a browser or cURL.

Save the form to an .html file:

<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
  <p><input type="text" name="text" value="text default">
  <p><input type="file" name="file1">
  <p><input type="file" name="file2">
  <p><button type="submit">Submit</button>
</form>

Create files to upload:

echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html

Run:

nc -l localhost 8000

Open the HTML on your browser, select the files and click on submit and check the terminal.

nc prints the request received. Firefox sent:

POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"

text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------9051914041544843365972754266--

Aternativelly, cURL should send the same POST request as your a browser form:

nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000

You can do multiple tests with:

while true; do printf '' | nc -l localhost 8000; done

How to filter a RecyclerView with a SearchView

Recyclerview with searchview and clicklistener

Add an interface in your adapter.

public interface SelectedUser{

    void selectedUser(UserModel userModel);

}

implement the interface in your mainactivity and override the method. @Override public void selectedUser(UserModel userModel) {

    startActivity(new Intent(MainActivity.this, SelectedUserActivity.class).putExtra("data",userModel));



}

Full tutorial and source code: Recyclerview with searchview and onclicklistener

Play local (hard-drive) video file with HTML5 video tag?

That will be possible only if the HTML file is also loaded with the file protocol from the local user's harddisk.

If the HTML page is served by HTTP from a server, you can't access any local files by specifying them in a src attribute with the file:// protocol as that would mean you could access any file on the users computer without the user knowing which would be a huge security risk.

As Dimitar Bonev said, you can access a file if the user selects it using a file selector on their own. Without that step, it's forbidden by all browsers for good reasons. Thus, while his answer might prove useful for many people, it loosens the requirement from the code in the original question.

How to implement __iter__(self) for a container object (Python)

One option that might work for some cases is to make your custom class inherit from dict. This seems like a logical choice if it acts like a dict; maybe it should be a dict. This way, you get dict-like iteration for free.

class MyDict(dict):
    def __init__(self, custom_attribute):
        self.bar = custom_attribute

mydict = MyDict('Some name')
mydict['a'] = 1
mydict['b'] = 2

print mydict.bar
for k, v in mydict.items():
    print k, '=>', v

Output:

Some name
a => 1
b => 2

Ignoring SSL certificate in Apache HttpClient 4.3

Here's a working distillation of the above techniques, equivalent to "curl --insecure":

HttpClient getInsecureHttpClient() throws GeneralSecurityException {
    TrustStrategy trustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) {
            return true;
        }
    };

    HostnameVerifier hostnameVerifier = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    return HttpClients.custom()
            .setSSLSocketFactory(new SSLConnectionSocketFactory(
                    new SSLContextBuilder().loadTrustMaterial(trustStrategy).build(),
                    hostnameVerifier))
            .build();
}

Reloading module giving NameError: name 'reload' is not defined

I recommend using the following snippet as it works in all python versions (requires six):

from six.moves import reload_module
reload_module(module)

403 - Forbidden: Access is denied. ASP.Net MVC

I just had this issue, it was because the IIS site was pointing at the wrong Application Pool.

python: restarting a loop

You may want to consider using a different type of loop where that logic is applicable, because it is the most obvious answer.

perhaps a:

i=2
while i < n:
    if something:
       do something
       i += 1
    else: 
       do something else  
       i = 2 #restart the loop  

What is the single most influential book every programmer should read?

I bough this when I was a complete newbie and took me from only knowing that Java existed to a reliable team member in a short time

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

Angular 2 Hover event

You can do it with a host:

import { Directive, ElementRef, Input } from '@angular/core';

@Directive({
  selector: '[myHighlight]',
  host: {
    '(mouseenter)': 'onMouseEnter()',
    '(mouseleave)': 'onMouseLeave()'
  }
})
export class HighlightDirective {
  private _defaultColor = 'blue';
  private el: HTMLElement;

  constructor(el: ElementRef) { this.el = el.nativeElement; }

  @Input('myHighlight') highlightColor: string;

  onMouseEnter() { this.highlight(this.highlightColor || this._defaultColor); }
  onMouseLeave() { this.highlight(null); }

   private highlight(color:string) {
    this.el.style.backgroundColor = color;
  }

}

Just adapt it to your code (found at: https://angular.io/docs/ts/latest/guide/attribute-directives.html )

ssh_exchange_identification: Connection closed by remote host under Git bash

For me this was caused by a limit on the number of concurrent ssh sessions. I added the two params below to /etc/ssh/sshd_config and then things worked.

echo 'MaxSessions 2000' >> /etc/ssh/sshd_config
echo 'MaxStartups 2000' >> /etc/ssh/sshd_config
service ssh restart

How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

The best way to solve this is to use Vanilla JS, but if you are already using jQuery, there´s a very easy solution:

<script type="text/javascript">
    function doOnClick() {
        $('#linkid').click();
    }
</script>
<a id="linkid" href="/testlocation" onclick="alert(this.href);">Testlink</a>

Tested in IE8-10, Chrome, Firefox.

how to convert date to a format `mm/dd/yyyy`

Use:

select convert(nvarchar(10), CREATED_TS, 101)

or

select format(cast(CREATED_TS as date), 'MM/dd/yyyy') -- MySQL 3.23 and above

How to get a random number between a float range?

if you want generate a random float with N digits to the right of point, you can make this :

round(random.uniform(1,2), N)

the second argument is the number of decimals.

How can I merge properties of two JavaScript objects dynamically?

jQuery also has a utility for this: http://api.jquery.com/jQuery.extend/.

Taken from the jQuery documentation:

// Merge options object into settings object
var settings = { validate: false, limit: 5, name: "foo" };
var options  = { validate: true, name: "bar" };
jQuery.extend(settings, options);

// Now the content of settings object is the following:
// { validate: true, limit: 5, name: "bar" }

The above code will mutate the existing object named settings.


If you want to create a new object without modifying either argument, use this:

var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };

/* Merge defaults and options, without modifying defaults */
var settings = $.extend({}, defaults, options);

// The content of settings variable is now the following:
// {validate: true, limit: 5, name: "bar"}
// The 'defaults' and 'options' variables remained the same.

Java - Search for files in a directory

I have used a different approach to search for a file using stack.. keeping in mind that there could be folders inside a folder. Though its not faster than windows search(and I was not expecting that though) but it definitely gives out correct result. Please modify the code as you wish to. This code was originally made to extract the file path of certain file extension :). Feel free to optimize.

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Deepankar Sinha
 */
public class GetList {
    public List<String> stack;
    static List<String> lnkFile;
    static List<String> progName;

    int index=-1;
    public static void main(String args[]) throws IOException
    {

        //var-- progFile:Location of the file to be search. 
        String progFile="C:\\";
        GetList obj=new GetList();
        String temp=progFile;
        int i;
        while(!"&%@#".equals(temp))
        {
            File dir=new File(temp);
            String[] directory=dir.list();
            if(directory!=null){
            for(String name: directory)
            {
                if(new File(temp+name).isDirectory())
                    obj.push(temp+name+"\\");
                else
                    if(new File(temp+name).isFile())
                    {
                        try{
                            //".exe can be replaced with file name to be searched. Just exclude name.substring()... you know what to do.:)
                        if(".exe".equals(name.substring(name.lastIndexOf('.'), name.length())))
                        {
                            //obj.addFile(temp+name,name);
                            System.out.println(temp+name);
                        }
                        }catch(StringIndexOutOfBoundsException e)
                        {
                            //debug purpose
                            System.out.println("ERROR******"+temp+name);
                        }

                    }
            }}
            temp=obj.pop();
        }
        obj.display();

//        for(int i=0;i<directory.length;i++)
//        System.out.println(directory[i]);
    }

    public GetList() {
        this.stack = new ArrayList<>();
        this.lnkFile=new ArrayList<>();
        this.progName=new ArrayList<>();
    }
    public void push(String dir)
    {
        index++;
        //System.out.println("PUSH : "+dir+" "+index);
        this.stack.add(index,dir);

    }
    public String pop()
    {
        String dir="";
        if(index==-1)
            return "&%@#";
        else
        {
            dir=this.stack.get(index);
            //System.out.println("POP : "+dir+" "+index);
            index--;

        }
        return dir;
    }

    public void addFile(String name,String name2)
    {
        lnkFile.add(name);
        progName.add(name2);
    }

    public void display()
    {
        GetList.lnkFile.stream().forEach((lnkFile1) -> {
            System.out.println(lnkFile1);
        });
    }

}

how do I join two lists using linq or lambda expressions

 public class State
        {
            public int SID { get; set; }
            public string SName { get; set; }
            public string SCode { get; set; }
            public string SAbbrevation { get; set; }
        }

        public class Country
        {
            public int CID { get; set; }
            public string CName { get; set; }
            public string CAbbrevation { get; set; }
        }


 List<State> states = new List<State>()
            {
               new  State{  SID=1,SName="Telangana",SCode="+91",SAbbrevation="TG"},
               new  State{  SID=2,SName="Texas",SCode="512",SAbbrevation="TS"},
            };

            List<Country> coutries = new List<Country>()
            {
               new Country{CID=1,CName="India",CAbbrevation="IND"},
               new Country{CID=2,CName="US of America",CAbbrevation="USA"},
            };

            var res = coutries.Join(states, a => a.CID, b => b.SID, (a, b) => new {a.CName,b.SName}).ToList();

PostgreSQL column 'foo' does not exist

the problem occurs because of the name of column is in camel case internally it wraps it in " "(double quotes) to solve this, at the time of inserting values in table use single quotes ('')

e.g. insert into schema_name.table_name values(' ',' ',' ');

How to connect to a remote Windows machine to execute commands using python?

You can connect one computer to another computer in a network by using these two methods:

  • Use WMI library.
  • Netuse method.

WMI

Here is the example to connect using wmi module:

ip = '192.168.1.13'
username = 'username'
password = 'password'
from socket import *
try:
    print("Establishing connection to %s" %ip)
    connection = wmi.WMI(ip, user=username, password=password)
    print("Connection established")
except wmi.x_wmi:
    print("Your Username and Password of "+getfqdn(ip)+" are wrong.")

netuse

The second method is to use netuse module.

By Netuse, you can connect to remote computer. And you can access all data of the remote computer. It is possible in the following two ways:

  1. Connect by virtual connection.

    import win32api
    import win32net
    ip = '192.168.1.18'
    username = 'ram'
    password = 'ram@123'
    
    use_dict={}
    use_dict['remote']=unicode('\\\\192.168.1.18\C$')
    use_dict['password']=unicode(password)
    use_dict['username']=unicode(username)
    win32net.NetUseAdd(None, 2, use_dict)
    

    To disconnect:

    import win32api
    import win32net
    win32net.NetUseDel('\\\\192.168.1.18',username,win32net.USE_FORCE)
    
  2. Mount remote computer drive in local system.

    import win32api
    import win32net
    import win32netcon,win32wnet
    
    username='user'
    password='psw'
    
    try:
        win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, 'Z:','\\\\192.168.1.18\\D$', None, username, password, 0)
        print('connection established successfully')
    except:
        print('connection not established')
    

    To unmount remote computer drive in local system:

    import win32api
    import win32net
    import win32netcon,win32wnet
    
    win32wnet.WNetCancelConnection2('\\\\192.168.1.4\\D$',1,1)
    

Before using netuse you should have pywin32 install in your system with python also.


Source: Connect remote system.

Can you blur the content beneath/behind a div?

If you want to enable unblur, you cannot just add the blur CSS to the body, you need to blur each visible child one level directly under the body and then remove the CSS to unblur. The reason is because of the "Cascade" in CSS, you cannot undo the cascading of the CSS blur effect for a child of the body. Also, to blur the body's background image you need to use the pseudo element :before

//HTML

<div id="fullscreen-popup" style="position:absolute;top:50%;left:50%;">
    <div class="morph-button morph-button-overlay morph-button-fixed">
        <button id="user-interface" type="button">MORE INFO</button>
        <!--a id="user-interface" href="javascript:void(0)">popup</a-->
        <div class="morph-content">
            <div>
                <div class="content-style-overlay">
                    <span class="icon icon-close">Close the overlay</span>
                    <h2>About Parsley</h2>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                </div>
            </div>
        </div>
    </div>
</div>

//CSS

/* Blur - doesn't work on IE */

.blur-on, .blur-element {
    -webkit-filter: blur(10px);
    -moz-filter: blur(10px);
    -o-filter: blur(10px);
    -ms-filter: blur(10px);
    filter: blur(10px);

    -webkit-transition: all 5s linear;
    transition        : all 5s linear;
    -moz-transition   : all 5s linear;
    -webkit-transition: all 5s linear;
    -o-transition     : all 5s linear;
}
.blur-off {
    -webkit-filter: blur(0px) !important;
    -moz-filter   : blur(0px) !important;
    -o-filter     : blur(0px) !important;
    -ms-filter    : blur(0px) !important;
    filter        : blur(0px) !important;
}
.blur-bgimage:before {
    content: "";
    position: absolute;
    height: 20%; width: 20%;
    background-size: cover;
    background: inherit;
    z-index: -1;

    transform: scale(5);
    transform-origin: top left;
    filter: blur(2px);       
    -moz-transform: scale(5);
    -moz-transform-origin: top left;
    -moz-filter: blur(2px);       
    -webkit-transform: scale(5);
    -webkit-transform-origin: top left;
    -webkit-filter: blur(2px);
    -o-transform: scale(5);
    -o-transform-origin: top left;
    -o-filter: blur(2px);       

    transition        : all 5s linear;
    -moz-transition   : all 5s linear;
    -webkit-transition: all 5s linear;
    -o-transition     : all 5s linear;
}


//Javascript

function blurBehindPopup() {
    if(blurredElements.length == 0) {
        for(var i=0; i < document.body.children.length; i++) {
            var element = document.body.children[i];
            if(element.id && element.id != 'fullscreen-popup' && element.isVisible == true) {
                classie.addClass( element, 'blur-element' );
                blurredElements.push(element);
            }
        }
    } else {
        for(var i=0; i < blurredElements.length; i++) {
            classie.addClass( blurredElements[i], 'blur-element' );
        }
    }
}
function unblurBehindPopup() {
    for(var i=0; i < blurredElements.length; i++) {
        classie.removeClass( blurredElements[i], 'blur-element' );
    }
}

Full Working Example Link

Getting Google+ profile picture url with user_id

If you want to show the profile picture for the currently logged in user, you do not even need to know the {user_id}. Simply using https://plus.google.com/s2/photos/profile/me will be enough.