Programs & Examples On #Throws

Excerpt from http://en.wikibooks.org/wiki/Java_Programming/Keywords/throws throws is a Java keyword. It is used in a method definition to declare the Exceptions to be thrown by the method.

When to use throws in a Java method declaration?

You're correct, in that example the throws is superfluous. It's possible that it was left there from some previous implementation - perhaps the exception was originally thrown instead of caught in the catch block.

Error message "unreported exception java.io.IOException; must be caught or declared to be thrown"

Exceptions bubble up the stack. If a caller calls a method that throws a checked exception, like IOException, it must also either catch the exception, or itself throw it.

In the case of the first block:

filecontent()
{
    setGUI();
    setRegister();
    showfile();
    setTitle("FileData");
    setVisible(true);
    setSize(300, 300);

    /*
        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent we)
            {
                System.exit(0);
            }
        });
    */
}

You would have to include a try catch block:

filecontent()
{
    setGUI();
    setRegister();
    try {
        showfile();
    }
    catch (IOException e) {
        // Do something here
    }
    setTitle("FileData");
    setVisible(true);
    setSize(300, 300);

    /*
        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent we)
            {
                System.exit(0);
            }
        });
    */
}

In the case of the second:

public void actionPerformed(ActionEvent ae)
{
    if (ae.getSource() == submit)
    {
        showfile();
    }
}

You cannot throw IOException from this method as its signature is determined by the interface, so you must catch the exception within:

public void actionPerformed(ActionEvent ae)
{
    if(ae.getSource()==submit)
    {
        try {
            showfile();
        }
        catch (IOException e) {
            // Do something here
        }
    }
}

Remember, the showFile() method is throwing the exception; that's what the "throws" keyword indicates that the method may throw that exception. If the showFile() method is throwing, then whatever code calls that method must catch, or themselves throw the exception explicitly by including the same throws IOException addition to the method signature, if it's permitted.

If the method is overriding a method signature defined in an interface or superclass that does not also declare that the method may throw that exception, you cannot declare it to throw an exception.

Why is "throws Exception" necessary when calling a function?

In Java, as you may know, exceptions can be categorized into two: One that needs the throws clause or must be handled if you don't specify one and another one that doesn't. Now, see the following figure:

enter image description here

In Java, you can throw anything that extends the Throwable class. However, you don't need to specify a throws clause for all classes. Specifically, classes that are either an Error or RuntimeException or any of the subclasses of these two. In your case Exception is not a subclass of an Error or RuntimeException. So, it is a checked exception and must be specified in the throws clause, if you don't handle that particular exception. That is why you needed the throws clause.


From Java Tutorial:

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

Now, as you know exceptions are classified into two: checked and unchecked. Why these classification?

Checked Exception: They are used to represent problems that can be recovered during the execution of the program. They usually are not the programmer's fault. For example, a file specified by user is not readable, or no network connection available, etc., In all these cases, our program doesn't need to exit, instead it can take actions like alerting the user, or go into a fallback mechanism(like offline working when network not available), etc.

Unchecked Exceptions: They again can be divided into two: Errors and RuntimeExceptions. One reason for them to be unchecked is that they are numerous in number, and required to handle all of them will clutter our program and reduce its clarity. The other reason is:

  • Runtime Exceptions: They usually happen due to a fault by the programmer. For example, if an ArithmeticException of division by zero occurs or an ArrayIndexOutOfBoundsException occurs, it is because we are not careful enough in our coding. They happen usually because some errors in our program logic. So, they must be cleared before our program enters into production mode. They are unchecked in the sense that, our program must fail when it occurs, so that we programmers can resolve it at the time of development and testing itself.

  • Errors: Errors are situations from which usually the program cannot recover. For example, if a StackOverflowError occurs, our program cannot do much, such as increase the size of program's function calling stack. Or if an OutOfMemoryError occurs, we cannot do much to increase the amount of RAM available to our program. In such cases, it is better to exit the program. That is why they are made unchecked.

For detailed information see:

Split pandas dataframe in two if it has more than 10 rows

There is no specific convenience function.

You'd have to do something like:

first_ten = pd.DataFrame()
rest = pd.DataFrame()

if df.shape[0] > 10: # len(df) > 10 would also work
    first_ten = df[:10]
    rest = df[10:]

Increment variable value by 1 ( shell programming)

There are more than one way to increment a variable in bash, but what you tried is not correct.

You can use for example arithmetic expansion:

i=$((i+1))

or only:

((i=i+1))

or:

((i+=1))

or even:

((i++))

Or you can use let:

let "i=i+1"

or only:

let "i+=1"

or even:

let "i++"

See also: http://tldp.org/LDP/abs/html/dblparens.html.

How can I test a change made to Jenkinsfile locally?

TL;DR

Long Version
Jenkins Pipeline testing becomes more and more of a pain. Unlike the classic declarative job configuration approach where the user was limited to what the UI exposed the new Jenkins Pipeline is a full fledged programming language for the build process where you mix the declarative part with your own code. As good developers we want to have some unit tests for this kind of code as well.

There are three steps you should follow when developing Jenkins Pipelines. The step 1. should cover 80% of the uses cases.

  1. Do as much as possible in build scripts (eg. Maven, Gradle, Gulp etc.). Then in your pipeline scripts just calls the build tasks in the right order. The build pipeline just orchestrates and executes the build tasks but does not have any major logic that needs a special testing.
  2. If the previous rule can't be fully applied then move over to Pipeline Shared libraries where you can develop and test custom logic on its own and integrate them into the pipeline.
  3. If all of the above fails you, you can try one of those libraries that came up recently (March-2017). Jenkins Pipeline Unit testing framework or pipelineUnit (examples). Since 2018 there is also Jenkinsfile Runner, a package to execution Jenkins pipelines from a command line tool.

Examples

The pipelineUnit GitHub repo contains some Spock examples on how to use Jenkins Pipeline Unit testing framework

How do you pass a function as a parameter in C?

Functions can be "passed" as function pointers, as per ISO C11 6.7.6.3p8: "A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1. ". For example, this:

void foo(int bar(int, int));

is equivalent to this:

void foo(int (*bar)(int, int));

how to increase java heap memory permanently?

This worked for me:

export _JAVA_OPTIONS="-Xmx1g"

It's important that you have no spaces because for me it did not work. I would suggest just copying and pasting. Then I ran:

java -XshowSettings:vm

and it will tell you:

Picked up _JAVA_OPTIONS: -Xmx1g

Max length UITextField

Im using this;

Limit 3 char

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        if let txt = textField.text {
            let currentText = txt + string
            if currentText.count > 3 {
                return false
            }
            return true
        }
        return true
    }

Use of Finalize/Dispose method in C#

1) WebClient is a managed type, so you don't need a finalizer. The finalizer is needed in the case your users don't Dispose() of your NoGateway class and the native type (which is not collected by the GC) needs to be cleaned up after. In this case, if the user doesn't call Dispose(), the contained WebClient will be disposed by the GC right after the NoGateway does.

2) Indirectly yes, but you shouldn't have to worry about it. Your code is correct as stands and you cannot prevent your users from forgetting to Dispose() very easily.

Load local JSON file into variable

A solution without require or fs:

var json = []
fetch('./content.json').then(response => json = response.json())

How can I get session id in php and show it?

if(isset($_POST['submit']))
   {  
 if(!empty($_POST['login_username']) && !empty($_POST['login_password']))
    {
     $uname = $_POST['login_username'];
     $pass = $_POST['login_password'];
     $res="SELECT count(*),uname,role FROM users WHERE uname='$uname' and  password='$pass' ";
$query=mysql_query($res)or die (mysql_error());  

list($result,$uname,$role) = mysql_fetch_row($query);   
$_SESSION['username'] = $uname;
$_SESSION['role'] = $role;
 if(isset($_SESSION['username']) && $_SESSION['role']=="admin")
 {
 if($result>0)
      {
       header ('Location:Dashboard.php');
      }
      else
      {
         header ('Location:loginform.php');
      }
 }

What happened to console.log in IE8?

I like this method (using jquery's doc ready)... it lets you use console even in ie... only catch is that you need to reload the page if you open ie's dev tools after the page loads...

it could be slicker by accounting for all the functions, but I only use log so this is what I do.

//one last double check against stray console.logs
$(document).ready(function (){
    try {
        console.log('testing for console in itcutils');
    } catch (e) {
        window.console = new (function (){ this.log = function (val) {
            //do nothing
        }})();
    }
});

Inline CSS styles in React: how to implement a:hover?

This is a universal wrapper for hover written in typescript. The component will apply style passed via props 'hoverStyle' on hover event.

import React, { useState } from 'react';

export const Hover: React.FC<{
  style?: React.CSSProperties;
  hoverStyle: React.CSSProperties;
}> = ({ style = {}, hoverStyle, children }) => {
  const [isHovered, setHovered] = useState(false);
  const calculatedStyle = { ...style, ...(isHovered ? hoverStyle : {}) };
  return (
    <div
      style={calculatedStyle}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      {children}
    </div>
  );
};    

Replace special characters in a string with _ (underscore)

string = string.replace(/[\W_]/g, "_");

Set value for particular cell in pandas DataFrame using index

I would suggest:

df.loc[index_position, "column_name"] = some_value

php: check if an array has duplicates

As you specifically said you didn't want to use array_unique I'm going to ignore the other answers despite the fact they're probably better.

Why don't you use array_count_values() and then check if the resulting array has any value greater than 1?

Loop timer in JavaScript

I believe you are looking for setInterval()

Flatten nested dictionaries, compressing keys

Not exactly what the OP asked, but lots of folks are coming here looking for ways to flatten real-world nested JSON data which can have nested key-value json objects and arrays and json objects inside the arrays and so on. JSON doesn't include tuples, so we don't have to fret over those.

I found an implementation of the list-inclusion comment by @roneo to the answer posted by @Imran :

https://github.com/ScriptSmith/socialreaper/blob/master/socialreaper/tools.py#L8

import collections
def flatten(dictionary, parent_key=False, separator='.'):
    """
    Turn a nested dictionary into a flattened dictionary
    :param dictionary: The dictionary to flatten
    :param parent_key: The string to prepend to dictionary's keys
    :param separator: The string used to separate flattened keys
    :return: A flattened dictionary
    """

    items = []
    for key, value in dictionary.items():
        new_key = str(parent_key) + separator + key if parent_key else key
        if isinstance(value, collections.MutableMapping):
            items.extend(flatten(value, new_key, separator).items())
        elif isinstance(value, list):
            for k, v in enumerate(value):
                items.extend(flatten({str(k): v}, new_key).items())
        else:
            items.append((new_key, value))
    return dict(items)

Test it:

flatten({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3] })

>> {'a': 1, 'c.a': 2, 'c.b.x': 5, 'c.b.y': 10, 'd.0': 1, 'd.1': 2, 'd.2': 3}

Annd that does the job I need done: I throw any complicated json at this and it flattens it out for me.

All credits to https://github.com/ScriptSmith .

How does facebook, gmail send the real time notification?

The way Facebook does this is pretty interesting.

A common method of doing such notifications is to poll a script on the server (using AJAX) on a given interval (perhaps every few seconds), to check if something has happened. However, this can be pretty network intensive, and you often make pointless requests, because nothing has happened.

The way Facebook does it is using the comet approach, rather than polling on an interval, as soon as one poll completes, it issues another one. However, each request to the script on the server has an extremely long timeout, and the server only responds to the request once something has happened. You can see this happening if you bring up Firebug's Console tab while on Facebook, with requests to a script possibly taking minutes. It is quite ingenious really, since this method cuts down immediately on both the number of requests, and how often you have to send them. You effectively now have an event framework that allows the server to 'fire' events.

Behind this, in terms of the actual content returned from those polls, it's a JSON response, with what appears to be a list of events, and info about them. It's minified though, so is a bit hard to read.

In terms of the actual technology, AJAX is the way to go here, because you can control request timeouts, and many other things. I'd recommend (Stack overflow cliche here) using jQuery to do the AJAX, it'll take a lot of the cross-compability problems away. In terms of PHP, you could simply poll an event log database table in your PHP script, and only return to the client when something happens? There are, I expect, many ways of implementing this.

Implementing:

Server Side:

There appear to be a few implementations of comet libraries in PHP, but to be honest, it really is very simple, something perhaps like the following pseudocode:

while(!has_event_happened()) {
   sleep(5);
}

echo json_encode(get_events());
  • The has_event_happened function would just check if anything had happened in an events table or something, and then the get_events function would return a list of the new rows in the table? Depends on the context of the problem really.

  • Don't forget to change your PHP max execution time, otherwise it will timeout early!

Client Side:

Take a look at the jQuery plugin for doing Comet interaction:

That said, the plugin seems to add a fair bit of complexity, it really is very simple on the client, perhaps (with jQuery) something like:

function doPoll() {
   $.get("events.php", {}, function(result) {
      $.each(result.events, function(event) { //iterate over the events
          //do something with your event
      });
      doPoll(); 
      //this effectively causes the poll to run again as
      //soon as the response comes back
   }, 'json'); 
}

$(document).ready(function() {
    $.ajaxSetup({
       timeout: 1000*60//set a global AJAX timeout of a minute
    });
    doPoll(); // do the first poll
});

The whole thing depends a lot on how your existing architecture is put together.

HTML select form with option to enter custom value

If the datalist option doesn't fulfill your requirements, take a look to the Select2 library and the "Dynamic option creation"

_x000D_
_x000D_
$(".js-example-tags").select2({_x000D_
  tags: true_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>_x000D_
_x000D_
_x000D_
<select class="form-control js-example-tags">_x000D_
  <option selected="selected">orange</option>_x000D_
  <option>white</option>_x000D_
  <option>purple</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

C# send a simple SSH command

I used SSH.Net in a project a while ago and was very happy with it. It also comes with a good documentation with lots of samples on how to use it.

The original package website can be still found here, including the documentation (which currently isn't available on GitHub).

For your case the code would be something like this.

using (var client = new SshClient("hostnameOrIp", "username", "password"))
{
    client.Connect();
    client.RunCommand("etc/init.d/networking restart");
    client.Disconnect();
}

Convert row to column header for Pandas DataFrame,

To rename the header without reassign df:

df.rename(columns=df.iloc[0], inplace = True)

To drop the row without reassign df:

df.drop(df.index[0], inplace = True)

Corrupt jar file

Also, make sure that the java version used at runtime is an equivalent or later version than the java used during compilation

How to execute shell command in Javascript

In IE, you can do this :

var shell = new ActiveXObject("WScript.Shell");
shell.run("cmd /c dir & pause");

Generating random integer from a range

If your compiler supports C++0x and using it is an option for you, then the new standard <random> header is likely to meet your needs. It has a high quality uniform_int_distribution which will accept minimum and maximum bounds (inclusive as you need), and you can choose among various random number generators to plug into that distribution.

Here is code that generates a million random ints uniformly distributed in [-57, 365]. I've used the new std <chrono> facilities to time it as you mentioned performance is a major concern for you.

#include <iostream>
#include <random>
#include <chrono>

int main()
{
    typedef std::chrono::high_resolution_clock Clock;
    typedef std::chrono::duration<double> sec;
    Clock::time_point t0 = Clock::now();
    const int N = 10000000;
    typedef std::minstd_rand G;
    G g;
    typedef std::uniform_int_distribution<> D;
    D d(-57, 365);
    int c = 0;
    for (int i = 0; i < N; ++i) 
        c += d(g);
    Clock::time_point t1 = Clock::now();
    std::cout << N/sec(t1-t0).count() << " random numbers per second.\n";
    return c;
}

For me (2.8 GHz Intel Core i5) this prints out:

2.10268e+07 random numbers per second.

You can seed the generator by passing in an int to its constructor:

    G g(seed);

If you later find that int doesn't cover the range you need for your distribution, this can be remedied by changing the uniform_int_distribution like so (e.g. to long long):

    typedef std::uniform_int_distribution<long long> D;

If you later find that the minstd_rand isn't a high enough quality generator, that can also easily be swapped out. E.g.:

    typedef std::mt19937 G;  // Now using mersenne_twister_engine

Having separate control over the random number generator, and the random distribution can be quite liberating.

I've also computed (not shown) the first 4 "moments" of this distribution (using minstd_rand) and compared them to the theoretical values in an attempt to quantify the quality of the distribution:

min = -57
max = 365
mean = 154.131
x_mean = 154
var = 14931.9
x_var = 14910.7
skew = -0.00197375
x_skew = 0
kurtosis = -1.20129
x_kurtosis = -1.20001

(The x_ prefix refers to "expected")

Center Oversized Image in Div

i'm a huge fan of making an image the background of a div/node -- then you can just use the background-position: center attribute to center it regardless of screen size

Output array to CSV in Ruby

Struggling with this myself. This is my take:

https://gist.github.com/2639448:

require 'csv'

class CSV
  def CSV.unparse array
    CSV.generate do |csv|
      array.each { |i| csv << i }
    end
  end
end

CSV.unparse [ %w(your array), %w(goes here) ]

How to handle iframe in Selenium WebDriver using java

WebDriver driver=new FirefoxDriver();
driver.get("http://www.java-examples.com/java-string-examples");
Thread.sleep(3000);
//Switch to nested frame
driver.switchTo().frame("aswift_2").switchTo().frame("google_ads_frame3");

How to solve could not create the virtual machine error of Java Virtual Machine Launcher?

I was also facing this issue when we upgraded from java 8 to java 10. I solved by removing -Djava.endorsed.dirs="C:\Program Files\Apache Software Foundation\Tomcat 8.5\endorsed" from the argument.

Android Studio emulator does not come with Play Store for API 23

Now there's no need to side load any packages of execute any scripts to get the Play Store on the emulator. Starting from Android Studio 2.4 now you can create an AVD that has Play Store pre-installed on it. Currently it is supported only on the AVDs running Android 7.0 (API 24) system images.

Official Source

AVD with Play Store

Note: Compatible devices are denoted by the new Play Store column.

How do you set the title color for the new Toolbar?

Very simple, this worked for me (title and icon white):

    <android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:background="@color/PrimaryColor"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    android:elevation="4dp" />

How do I prevent site scraping?

If you want to see a great example, check out http://www.bkstr.com/. They use a j/s algorithm to set a cookie, then reloads the page so it can use the cookie to validate that the request is being run within a browser. A desktop app built to scrape could definitely get by this, but it would stop most cURL type scraping.

Can constructors throw exceptions in Java?

Yes, constructors can throw exceptions. Usually this means that the new object is immediately eligible for garbage collection (although it may not be collected for some time, of course). It's possible for the "half-constructed" object to stick around though, if it's made itself visible earlier in the constructor (e.g. by assigning a static field, or adding itself to a collection).

One thing to be careful of about throwing exceptions in the constructor: because the caller (usually) will have no way of using the new object, the constructor ought to be careful to avoid acquiring unmanaged resources (file handles etc) and then throwing an exception without releasing them. For example, if the constructor tries to open a FileInputStream and a FileOutputStream, and the first succeeds but the second fails, you should try to close the first stream. This becomes harder if it's a subclass constructor which throws the exception, of course... it all becomes a bit tricky. It's not a problem very often, but it's worth considering.

What are file descriptors, explained in simple terms?

As an addition to other answers, unix considers everything as a file system. Your keyboard is a file that is read only from the perspective of the kernel. The screen is a write only file. Similarly, folders, input-output devices etc are also considered to be files. Whenever a file is opened, say when the device drivers[for device files] requests an open(), or a process opens an user file the kernel allocates a file descriptor, an integer that specifies the access to that file such it being read only, write only etc. [for reference : https://en.wikipedia.org/wiki/Everything_is_a_file ]

repaint() in Java

If you added JComponent to already visible Container, then you have call

frame.getContentPane().validate();
frame.getContentPane().repaint();

for example

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class Main {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(460, 500);
        frame.setTitle("Circles generator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
              frame.setVisible(true);
           }
        });

        String input = JOptionPane.showInputDialog("Enter n:");
        CustomComponents0 component = new CustomComponents0();
        frame.add(component);
        frame.getContentPane().validate();
        frame.getContentPane().repaint();
    }

    static class CustomComponents0 extends JLabel {

        private static final long serialVersionUID = 1L;

        @Override
        public Dimension getMinimumSize() {
            return new Dimension(200, 100);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(300, 200);
        }

        @Override
        public void paintComponent(Graphics g) {
            int margin = 10;
            Dimension dim = getSize();
            super.paintComponent(g);
            g.setColor(Color.red);
            g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
        }
    }
}

java.io.FileNotFoundException: (Access is denied)

Here's a gotcha that I just discovered - perhaps it might help someone else. If using windows the classes folder must not have encryption enabled! Tomcat doesn't seem to like that. Right click on the classes folder, select "Properties" and then click the "Advanced..." button. Make sure the "Encrypt contents to secure data" checkbox is cleared. Restart Tomcat.

It worked for me so here's hoping it helps someone else, too.

How to round up value C# to the nearest integer?

Use Math.Ceiling to round up

Math.Ceiling(0.5); // 1

Use Math.Round to just round

Math.Round(0.5, MidpointRounding.AwayFromZero); // 1

And Math.Floor to round down

Math.Floor(0.5); // 0

R * not meaningful for factors ERROR

new[,2] is a factor, not a numeric vector. Transform it first

new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5

How to apply box-shadow on all four sides?

It's because of x and y offset. Try this:

-webkit-box-shadow: 0 0 10px #fff;
        box-shadow: 0 0 10px #fff;

edit (year later..): Made the answer more cross-browser, as requested in comments :)

btw: there are many css3 generator nowadays.. css3.me, css3maker, css3generator etc...

Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet."

Late to the party, but grappelli was the reason for my error as well. I looked up the compatible version on pypi and that fixed it for me.

Plotting a 3d cube, a sphere and a vector in Matplotlib

It is a little complicated, but you can draw all the objects by the following code:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations


fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

# draw cube
r = [-1, 1]
for s, e in combinations(np.array(list(product(r, r, r))), 2):
    if np.sum(np.abs(s-e)) == r[1]-r[0]:
        ax.plot3D(*zip(s, e), color="b")

# draw sphere
u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
ax.plot_wireframe(x, y, z, color="r")

# draw a point
ax.scatter([0], [0], [0], color="g", s=100)

# draw a vector
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d


class Arrow3D(FancyArrowPatch):

    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
        self._verts3d = xs, ys, zs

    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
        FancyArrowPatch.draw(self, renderer)

a = Arrow3D([0, 1], [0, 1], [0, 1], mutation_scale=20,
            lw=1, arrowstyle="-|>", color="k")
ax.add_artist(a)
plt.show()

output_figure

Start thread with member function

Some users have already given their answer and explained it very well.

I would like to add few more things related to thread.

  1. How to work with functor and thread. Please refer to below example.

  2. The thread will make its own copy of the object while passing the object.

    #include<thread>
    #include<Windows.h>
    #include<iostream>
    
    using namespace std;
    
    class CB
    {
    
    public:
        CB()
        {
            cout << "this=" << this << endl;
        }
        void operator()();
    };
    
    void CB::operator()()
    {
        cout << "this=" << this << endl;
        for (int i = 0; i < 5; i++)
        {
            cout << "CB()=" << i << endl;
            Sleep(1000);
        }
    }
    
    void main()
    {
        CB obj;     // please note the address of obj.
    
        thread t(obj); // here obj will be passed by value 
                       //i.e. thread will make it own local copy of it.
                        // we can confirm it by matching the address of
                        //object printed in the constructor
                        // and address of the obj printed in the function
    
        t.join();
    }
    

Another way of achieving the same thing is like:

void main()
{
    thread t((CB()));

    t.join();
}

But if you want to pass the object by reference then use the below syntax:

void main()
{
    CB obj;
    //thread t(obj);
    thread t(std::ref(obj));
    t.join();
}

Visual Studio 2015 is very slow

My Visual Studio 2015 RTM was also very slow using ReSharper 9.1.2, but it has worked fine since I upgraded to 9.1.3 (see ReSharper 9.1.3 to the Rescue). Perhaps a cue.

One more cue. A ReSharper 9.2 version was made available to:

refines integration with Visual Studio 2015 RTM, addressing issues discovered in versions 9.1.2 and 9.1.3

How to change MySQL data directory?

If you want to do this programmatically (no manual text entry with gedit) here's a version for a Dockerfile based on user1341296's answer above:

FROM spittet/ruby-mysql
MAINTAINER [email protected]

RUN cp -R -p /var/lib/mysql /dev/shm && \
    rm -rf /var/lib/mysql && \
    sed -i -e 's,/var/lib/mysql,/dev/shm/mysql,g' /etc/mysql/my.cnf && \
    /etc/init.d/mysql restart

Available on Docker hub here: https://hub.docker.com/r/richardjecooke/ruby-mysql-in-memory/

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

The onbeforeunload Microsoft-ism is the closest thing we have to a standard solution, but be aware that browser support is uneven; e.g. for Opera it only works in version 12 and later (still in beta as of this writing).

Also, for maximum compatibility, you need to do more than simply return a string, as explained on the Mozilla Developer Network.

Example: Define the following two functions for enabling/disabling the navigation prompt (cf. the MDN example):

function enableBeforeUnload() {
    window.onbeforeunload = function (e) {
        return "Discard changes?";
    };
}
function disableBeforeUnload() {
    window.onbeforeunload = null;
}

Then define a form like this:

<form method="POST" action="" onsubmit="disableBeforeUnload();">
    <textarea name="text"
              onchange="enableBeforeUnload();"
              onkeyup="enableBeforeUnload();">
    </textarea>
    <button type="submit">Save</button>
</form>

This way, the user will only be warned about navigating away if he has changed the text area, and will not be prompted when he's actually submitting the form.

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

If you're not sure what you're doing, use the '=='. If you have a little more knowledge about it you can use 'is' for known objects like 'None'.

Otherwise you'll end up wondering why things doesn't work and why this happens:

>>> a = 1
>>> b = 1
>>> b is a
True
>>> a = 6000
>>> b = 6000
>>> b is a
False

I'm not even sure if some things are guaranteed to stay the same between different python versions/implementations.

What's the difference setting Embed Interop Types true and false in Visual Studio?

I noticed that when it's set to false, I'm able to see the value of an item using the debugger. When it was set to true, I was getting an error - item.FullName.GetValue The embedded interop type 'FullName' does not contain a definition for 'QBFC11Lib.IItemInventoryRet' since it was not used in the compiled assembly. Consider casting to object or changing the 'Embed Interop Types' property to true.

Call a "local" function within module.exports from another function in module.exports?

Another option, and closer to the original style of the OP, is to put the object you want to export into a variable and reference that variable to make calls to other methods in the object. You can then export that variable and you're good to go.

var self = {
  foo: function (req, res, next) {
    return ('foo');
  },
  bar: function (req, res, next) {
    return self.foo();
  }
};
module.exports = self;

Setup a Git server with msysgit on Windows

I just wanted to add my experiences with the PATH setup that Steve and timc mentions above: I got permission problems using shell tools (like mv and cp) having Git's shell executables first in the path.

Appending them after the existing PATH instead this solved my problems. Example:

GITPATH='/cygdrive/c/Program Files (x86)/Git/bin' GITCOREPATH='/cygdrive/c/Program Files (x86)/Git/libexec/git-core' PATH=${PATH}:${GITPATH}:${GITCOREPATH}

I guess CopSSH doesn't go along well with all of msysgit's shell executables...

New self vs. new static

will I get the same results?

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

What is the difference between new self and new static?

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

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

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

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

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

class B extends A {}

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

How to process POST data in Node.js?

You can use the express middleware, which now has body-parser built into it. This means all you need to do is the following:

import express from 'express'

const app = express()

app.use(express.json())

app.post('/thing', (req, res) => {
  console.log(req.body) // <-- this will access the body of the post
  res.sendStatus(200)
})

That code example is ES6 with Express 4.16.x

Convert System.Drawing.Color to RGB and Hex Value

I'm failing to see the problem here. The code looks good to me.

The only thing I can think of is that the try/catch blocks are redundant -- Color is a struct and R, G, and B are bytes, so c can't be null and c.R.ToString(), c.G.ToString(), and c.B.ToString() can't actually fail (the only way I can see them failing is with a NullReferenceException, and none of them can actually be null).

You could clean the whole thing up using the following:

private static String HexConverter(System.Drawing.Color c)
{
    return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}

private static String RGBConverter(System.Drawing.Color c)
{
    return "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")";
}

Can I store images in MySQL

You will need to store the image in the database as a BLOB.

you will want to create a column called PHOTO in your table and set it as a mediumblob.

Then you will want to get it from the form like so:

    $data = file_get_contents($_FILES['photo']['tmp_name']);

and then set the column to the value in $data.

Of course, this is bad practice and you would probably want to store the file on the system with a name that corresponds to the users account.

jQuery - select all text from a textarea

Slightly shorter jQuery version:

$('your-element').focus(function(e) {
  e.target.select();
  jQuery(e.target).one('mouseup', function(e) {
    e.preventDefault();
  });
});

It handles the Chrome corner case correctly. See http://jsfiddle.net/Ztyx/XMkwm/ for an example.

android download pdf from url then open it with a pdf reader

This is the best method to download and view PDF file.You can just call it from anywhere as like

PDFTools.showPDFUrl(context, url);

here below put the code. It will works fine

public class PDFTools {
private static final String TAG = "PDFTools";
private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url=";
private static final String PDF_MIME_TYPE = "application/pdf";
private static final String HTML_MIME_TYPE = "text/html";


public static void showPDFUrl(final Context context, final String pdfUrl ) {
    if ( isPDFSupported( context ) ) {
        downloadAndOpenPDF(context, pdfUrl);
    } else {
        askToOpenPDFThroughGoogleDrive( context, pdfUrl );
    }
}


@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
    // Get filename
    //final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
    String filename = "";
    try {
        filename = new GetFileInfo().execute(pdfUrl).get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    // The place where the downloaded PDF file will be put
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
    Log.e(TAG,"File Path:"+tempFile);
    if ( tempFile.exists() ) {
        // If we have downloaded the file before, just go ahead and show it.
        openPDF( context, Uri.fromFile( tempFile ) );
        return;
    }

    // Show progress dialog while downloading
    final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ), context.getString( R.string.pdf_show_local_progress_content ), true );

    // Create the download request
    DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
    r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
    final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
    BroadcastReceiver onComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ( !progress.isShowing() ) {
                return;
            }
            context.unregisterReceiver( this );

            progress.dismiss();
            long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
            Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

            if ( c.moveToFirst() ) {
                int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                    openPDF( context, Uri.fromFile( tempFile ) );
                }
            }
            c.close();
        }
    };
    context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

    // Enqueue the request
    dm.enqueue( r );
}


public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
    new AlertDialog.Builder( context )
            .setTitle( R.string.pdf_show_online_dialog_title )
            .setMessage( R.string.pdf_show_online_dialog_question )
            .setNegativeButton( R.string.pdf_show_online_dialog_button_no, null )
            .setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    openPDFThroughGoogleDrive(context, pdfUrl);
                }
            })
            .show();
}

public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
    context.startActivity( i );
}

public static final void openPDF(Context context, Uri localUri ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType( localUri, PDF_MIME_TYPE );
    context.startActivity( i );
}

public static boolean isPDFSupported( Context context ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
    i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
    return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
}

// get File name from url
static class GetFileInfo extends AsyncTask<String, Integer, String>
{
    protected String doInBackground(String... urls)
    {
        URL url;
        String filename = null;
        try {
            url = new URL(urls[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            conn.setInstanceFollowRedirects(false);
            if(conn.getHeaderField("Content-Disposition")!=null){
                String depo = conn.getHeaderField("Content-Disposition");

                String depoSplit[] = depo.split("filename=");
                filename = depoSplit[1].replace("filename=", "").replace("\"", "").trim();
            }else{
                filename = "download.pdf";
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
        }
        return filename;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // use result as file name
    }
}

}

try it. it will works, enjoy

Check whether variable is number or string in JavaScript

function IsNumeric(num) {
    return ((num >=0 || num < 0)&& (parseInt(num)==num) );
}

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

This error is usually observed when your machine is low on disk space. Steps to be followed to avoid this error message

  1. Resetting the read-only index block on the index:

    $ curl -X PUT -H "Content-Type: application/json" http://127.0.0.1:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'
    
    Response
    ${"acknowledged":true}
    
  2. Updating the low watermark to at least 50 gigabytes free, a high watermark of at least 20 gigabytes free, and a flood stage watermark of 10 gigabytes free, and updating the information about the cluster every minute

     Request
     $curl -X PUT "http://127.0.0.1:9200/_cluster/settings?pretty" -H 'Content-Type: application/json' -d' { "transient": { "cluster.routing.allocation.disk.watermark.low": "50gb", "cluster.routing.allocation.disk.watermark.high": "20gb", "cluster.routing.allocation.disk.watermark.flood_stage": "10gb", "cluster.info.update.interval": "1m"}}'
    
      Response
      ${
       "acknowledged" : true,
       "persistent" : { },
       "transient" : {
       "cluster" : {
       "routing" : {
       "allocation" : {
       "disk" : {
         "watermark" : {
           "low" : "50gb",
           "flood_stage" : "10gb",
           "high" : "20gb"
         }
       }
     }
    }, 
    "info" : {"update" : {"interval" : "1m"}}}}}
    

After running these two commands, you must run the first command again so that the index does not go again into read-only mode

Space between two divs

Why not use margin? you can apply all kinds off margins to an element. Not just the whole margin around it.

You should use css classes since this is referencing more than one element and you can use id's for those that you want to be different specifically

i.e:

<style>
.box { height: 50px; background: #0F0; width: 100%; margin-top: 10px; }
#first { margin-top: 20px; }
#second { background: #00F; }
h1.box { background: #F00; margin-bottom: 50px;  }
</style>

<h1 class="box">Hello World</h1>
<div class="box" id="first"></div>
<div class="box" id="second"></div>?

Here is a jsfiddle example:

REFERENCE:

How to enable Ad Hoc Distributed Queries

If ad hoc updates to system catalog is "not supported", or if you get a "Msg 5808" then you will need to configure with override like this:

EXEC sp_configure 'show advanced options', 1
RECONFIGURE with override
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE with override
GO

Dynamic instantiation from string name of a class in dynamically imported module?

tl;dr

Import the root module with importlib.import_module and load the class by its name using getattr function:

# Standard import
import importlib
# Load "module.submodule.MyClass"
MyClass = getattr(importlib.import_module("module.submodule"), "MyClass")
# Instantiate the class (pass arguments to the constructor, if needed)
instance = MyClass()

explanations

You probably don't want to use __import__ to dynamically import a module by name, as it does not allow you to import submodules:

>>> mod = __import__("os.path")
>>> mod.join
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'join'

Here is what the python doc says about __import__:

Note: This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module().

Instead, use the standard importlib module to dynamically import a module by name. With getattr you can then instantiate a class by its name:

import importlib
my_module = importlib.import_module("module.submodule")
MyClass = getattr(my_module, "MyClass")
instance = MyClass()

You could also write:

import importlib
module_name, class_name = "module.submodule.MyClass".rsplit(".", 1)
MyClass = getattr(importlib.import_module(module_name), class_name)
instance = MyClass()

This code is valid in python = 2.7 (including python 3).

Deserialize json object into dynamic object using Json.net

I know this is old post but JsonConvert actually has a different method so it would be

var product = new { Name = "", Price = 0 };
var jsonResponse = JsonConvert.DeserializeAnonymousType(json, product);

How to read integer values from text file

You can use a Scanner and its nextInt() method.
Scanner also has nextLong() for larger integers, if needed.

How to check if array is not empty?

I can't comment yet, but it should be mentioned that if you use numpy array with more than one element this will fail:

if l:
    print "list has items"

elif not l:
    print "list is empty"

the error will be:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?

Kotlin:

var list=ArrayList<Your class name>()
val listresult: Array<YOUR CLASS NAME> = Gson().fromJson(
                YOUR JSON RESPONSE IN STRING,
                Array<Your class name>:: class.java)

list.addAll(listresult)

How to Join to first row

,Another aproach using common table expression:

with firstOnly as (
    select Orders.OrderNumber, LineItems.Quantity, LineItems.Description, ROW_NUMBER() over (partiton by Orders.OrderID order by Orders.OrderID) lp
    FROM Orders
        join LineItems on Orders.OrderID = LineItems.OrderID
) select *
  from firstOnly
  where lp = 1

or, in the end maybe you would like to show all rows joined?

comma separated version here:

  select *
  from Orders o
    cross apply (
        select CAST((select l.Description + ','
        from LineItems l
        where l.OrderID = s.OrderID
        for xml path('')) as nvarchar(max)) l
    ) lines

Find a value in DataTable

AFAIK, there is nothing built in for searching all columns. You can use Find only against the primary key. Select needs specified columns. You can perhaps use LINQ, but ultimately this just does the same looping. Perhaps just unroll it yourself? It'll be readable, at least.

How to call execl() in C with the proper arguments?

If you need just to execute your VLC playback process and only give control back to your application process when it is done and nothing more complex, then i suppose you can use just:

system("The same thing you type into console");

Float to String format specifier

Use ToString() with this format:

12345.678901.ToString("0.0000"); // outputs 12345.6789
12345.0.ToString("0.0000"); // outputs 12345.0000

Put as much zero as necessary at the end of the format.

How to auto-scroll to end of div when data is added?

If you don't know when data will be added to #data, you could set an interval to update the element's scrollTop to its scrollHeight every couple of seconds. If you are controlling when data is added, just call the internal of the following function after the data has been added.

window.setInterval(function() {
  var elem = document.getElementById('data');
  elem.scrollTop = elem.scrollHeight;
}, 5000);

Why use prefixes on member variables in C++ classes

You have to be careful with using a leading underscore. A leading underscore before a capital letter in a word is reserved. For example:

_Foo

_L

are all reserved words while

_foo

_l

are not. There are other situations where leading underscores before lowercase letters are not allowed. In my specific case, I found the _L happened to be reserved by Visual C++ 2005 and the clash created some unexpected results.

I am on the fence about how useful it is to mark up local variables.

Here is a link about which identifiers are reserved: What are the rules about using an underscore in a C++ identifier?

Error: Uncaught (in promise): Error: Cannot match any routes Angular 2

I am using angular 4 and faced the same issue apply, all possible solution but finally, this solve my problem

export class AppRoutingModule {
constructor(private router: Router) {
    this.router.errorHandler = (error: any) => {
        this.router.navigate(['404']); // or redirect to default route
    }
  }
}

Hope this will help you.

C subscripted value is neither array nor pointer nor vector when assigning an array element value

The problem is that arr is not (declared as) a 2D array, and you are treating it as if it were 2D.

calling a function from class in python - different way

Your methods don't refer to an object (that is, self), so you should use the @staticmethod decorator:

class MathsOperations:
    @staticmethod
    def testAddition (x, y):
        return x + y

    @staticmethod
    def testMultiplication (a, b):
        return a * b

What's the equivalent of Java's Thread.sleep() in JavaScript?

Try with this code. I hope it's useful for you.

function sleep(seconds) 
{
  var e = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= e) {}
}

How to use gitignore command in git

So based on what you said, these files are libraries/documentation you don't want to delete but also don't want to push to github. Let say you have your project in folder your_project and a doc directory: your_project/doc.

  1. Remove it from the project directory (without actually deleting it): git rm --cached doc/*
  2. If you don't already have a .gitignore, you can make one right inside of your project folder: project/.gitignore.
  3. Put doc/* in the .gitignore
  4. Stage the file to commit: git add project/.gitignore
  5. Commit: git commit -m "message".
  6. Push your change to github.

How to vertically center an image inside of a div element in HTML using CSS?

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
(function ($) {

$.fn.verticalAlign = function() {
    return this.each(function(i){
    var ah = $(this).height();
    var ph = $(this).parent().height();
    var mh = Math.ceil((ph-ah)/2);
    $(this).css('margin-top', mh);
    });
};
})(jQuery);

$(document).ready(function(e) {


$('.in').verticalAlign();


});

</script>

<style type="text/css">
body { margin:0; padding:0;}
.divWrap { width:100%;}
.out { width:500px; height:500px; background:#000; text-align:center; padding:1px; }
.in { width:100px; height:100px; background:#CCC; margin:0 auto; }
</style>
</head>

<body>
<div class="divWrap">
<div class="out">
<div class="in">
</div>
</div>
</div>

</body>
</html>

Fixed page header overlaps in-page anchors

The best way that I found to handle this issue is (replace 65px with your fixed element height):

div:target {
  padding-top: 65px; 
  margin-top: -65px;
}

If you do not like to use the target selector you can also do it in this way:

.my-target {
    padding-top: 65px;
    margin-top: -65px;
}

Note: this example will not work if the target element have a backgound color that differant from his parent. for example:

<div style="background-color:red;height:100px;"></div>
<div class="my-target" style="background-color:green;height:100px;"></div>

in this case the green color of my-target element will overwrite his parent red element in 65px. I did not find any pure CSS solution to handle this issue but if you do not have another background color this solution is the best.

How to drop all tables in a SQL Server database?

The fasted way is:

  1. New Database Diagrams
  2. Add all table
  3. Ctrl + A to select all
  4. Right Click "Remove from Database"
  5. Ctrl + S to save
  6. Enjoy

What is a segmentation fault?

Wikipedia's Segmentation_fault page has a very nice description about it, just pointing out the causes and reasons. Have a look into the wiki for a detailed description.

In computing, a segmentation fault (often shortened to segfault) or access violation is a fault raised by hardware with memory protection, notifying an operating system (OS) about a memory access violation.

The following are some typical causes of a segmentation fault:

  • Dereferencing NULL pointers – this is special-cased by memory management hardware
  • Attempting to access a nonexistent memory address (outside process's address space)
  • Attempting to access memory the program does not have rights to (such as kernel structures in process context)
  • Attempting to write read-only memory (such as code segment)

These in turn are often caused by programming errors that result in invalid memory access:

  • Dereferencing or assigning to an uninitialized pointer (wild pointer, which points to a random memory address)

  • Dereferencing or assigning to a freed pointer (dangling pointer, which points to memory that has been freed/deallocated/deleted)

  • A buffer overflow.

  • A stack overflow.

  • Attempting to execute a program that does not compile correctly. (Some compilers will output an executable file despite the presence of compile-time errors.)

Why is the Android emulator so slow? How can we speed up the Android emulator?

For fast testing (<1 second) use buildroid with VirtualBox's first network card set to “host only network” and then run

C:\Program Files (x86)\Android\android-sdk\platform-tools>adb connect *.*.*.*:5555
connected to *.*.*.*:5555

(^) DOS / bash (v)

# adb connect *.*.*.*:5555
connected to *.*.*.*:5555

where *. *. * .* is the buildroid IP address you get by clicking the buildroid app in buildroid main screen.

How to check if a date is in a given range?

Convert both dates to timestamps then do

pseudocode:

if date_from_user > start_date && date_from_user < end_date
    return true

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

In my case, in the initializer from the class I was using in the database's table, I wasn't setting any default value to my DateTime property, therefore resulting in the problem explained in @Andrew Orsich' answer. So I just made the property nullable. Or I could also have given it DateTime.Now in the constructor. Hope it helps someone.

Oracle SQL escape character (for a '&')

SELECT 'Free &' || ' Clear' FROM DUAL;

Passing a Bundle on startActivity()?

Passing data from one Activity to Activity in android

An intent contains the action and optionally additional data. The data can be passed to other activity using intent putExtra() method. Data is passed as extras and are key/value pairs. The key is always a String. As value you can use the primitive data types int, float, chars, etc. We can also pass Parceable and Serializable objects from one activity to other.

Intent intent = new Intent(context, YourActivity.class);
intent.putExtra(KEY, <your value here>);
startActivity(intent);

Retrieving bundle data from android activity

You can retrieve the information using getData() methods on the Intent object. The Intent object can be retrieved via the getIntent() method.

 Intent intent = getIntent();
  if (null != intent) { //Null Checking
    String StrData= intent.getStringExtra(KEY);
    int NoOfData = intent.getIntExtra(KEY, defaultValue);
    boolean booleanData = intent.getBooleanExtra(KEY, defaultValue);
    char charData = intent.getCharExtra(KEY, defaultValue); 
  }

Does Enter key trigger a click event?

For angular 6 there is a new way of doing it. On your input tag add

(keyup.enter)="keyUpFunction($event)"

Where keyUpFunction($event) is your function.

Decoding UTF-8 strings in Python

You need to properly decode the source text. Most likely the source text is in UTF-8 format, not ASCII.

Because you do not provide any context or code for your question it is not possible to give a direct answer.

I suggest you study how unicode and character encoding is done in Python:

http://docs.python.org/2/howto/unicode.html

Vuejs and Vue.set(), update array

VueJS can't pickup your changes to the state if you manipulate arrays like this.

As explained in Common Beginner Gotchas, you should use array methods like push, splice or whatever and never modify the indexes like this a[2] = 2 nor the .length property of an array.

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    f: 'DD-MM-YYYY',_x000D_
    items: [_x000D_
      "10-03-2017",_x000D_
      "12-03-2017"_x000D_
    ]_x000D_
  },_x000D_
  methods: {_x000D_
_x000D_
    cha: function(index, item, what, count) {_x000D_
      console.log(item + " index > " + index);_x000D_
      val = moment(this.items[index], this.f).add(count, what).format(this.f);_x000D_
_x000D_
      this.items.$set(index, val)_x000D_
      console.log("arr length:  " + this.items.length);_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
ul {_x000D_
  list-style-type: none;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.11/vue.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>_x000D_
<div id="app">_x000D_
  <ul>_x000D_
    <li v-for="(index, item) in items">_x000D_
      <br><br>_x000D_
      <button v-on:click="cha(index, item, 'day', -1)">_x000D_
      - day</button> {{ item }}_x000D_
      <button v-on:click="cha(index, item, 'day', 1)">_x000D_
      + day</button>_x000D_
      <br><br>_x000D_
    </li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

AWK: Access captured group from line pattern

This is something I need all the time so I created a bash function for it. It's based on glenn jackman's answer.

Definition

Add this to your .bash_profile etc.

function regex { gawk 'match($0,/'$1'/, ary) {print ary['${2:-'0'}']}'; }

Usage

Capture regex for each line in file

$ cat filename | regex '.*'

Capture 1st regex capture group for each line in file

$ cat filename | regex '(.*)' 1

Android Layout Weight

i would suppose to set the EditTexts width to wrap_content and put the two buttons into a LinearLayout whose width is fill_parent and weight set to 1.

What's the difference between a proxy server and a reverse proxy server?

The difference is primarily in deployment. Web forward and reverse proxies all have the same underlying features. They accept requests for HTTP requests in various formats and provide a response, usually by accessing the origin or contact server.

Fully featured servers usually have access control, caching, and some link-mapping features.

A forward proxy is a proxy that is accessed by configuring the client machine. The client needs protocol support for proxy features (redirection, proxy authentication, etc.). The proxy is transparent to the user experience, but not to the application.

A reverse proxy is a proxy that is deployed as a web server and behaves like a web server, with the exception that instead of locally composing the content from programs and disk, it forwards the request to an origin server. From the client perspective it is a web server, so the user experience is completely transparent.

In fact, a single proxy instance can run as a forward and reverse proxy at the same time for different client populations.

How do I use a regular expression to match any string, but at least 3 characters?

I tried find similiar as topic first post.

For my needs I find this

http://answers.oreilly.com/topic/217-how-to-match-whole-words-with-a-regular-expression/

"\b[a-zA-Z0-9]{3}\b"

3 char words only "iokldöajf asd alkjwnkmd asd kja wwda da aij ednm <.jkakla "

Send json post using php

use CURL luke :) seriously, thats one of the best ways to do it AND you get the response.

Laravel Eloquent "WHERE NOT IN"

I had problems making a sub query until I added the method ->toArray() to the result, I hope it helps more than one since I had a good time looking for the solution.

Example

DB::table('user')                 
  ->select('id','name')
  ->whereNotIn('id', DB::table('curses')->select('id_user')->where('id_user', '=', $id)->get()->toArray())
  ->get();

Java Error: illegal start of expression

Remove the public keyword from int[] locations={1,2,3};. An access modifier isn't allowed inside a method, as its accessbility is defined by its method scope.

If your goal is to use this reference in many a method, you might want to move the declaration outside the method.

Custom alert and confirm box in jquery

Check the jsfiddle http://jsfiddle.net/CdwB9/3/ and click on delete

function yesnodialog(button1, button2, element){
  var btns = {};
  btns[button1] = function(){ 
      element.parents('li').hide();
      $(this).dialog("close");
  };
  btns[button2] = function(){ 
      // Do nothing
      $(this).dialog("close");
  };
  $("<div></div>").dialog({
    autoOpen: true,
    title: 'Condition',
    modal:true,
    buttons:btns
  });
}
$('.delete').click(function(){
    yesnodialog('Yes', 'No', $(this));
})

This should help you

return error message with actionResult

Inside Controller Action you can access HttpContext.Response. There you can set the response status as in the following listing.

[HttpPost]
public ActionResult PostViaAjax()
{
    var body = Request.BinaryRead(Request.TotalBytes);

    var result = Content(JsonError(new Dictionary<string, string>()
    {
        {"err", "Some error!"}
    }), "application/json; charset=utf-8");
    HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
    return result;
}

Uint8Array to string in Javascript

I was frustrated to see that people were not showing how to go both ways or showing that things work on none trivial UTF8 strings. I found a post on codereview.stackexchange.com that has some code that works well. I used it to turn ancient runes into bytes, to test some crypo on the bytes, then convert things back into a string. The working code is on github here. I renamed the methods for clarity:

// https://codereview.stackexchange.com/a/3589/75693
function bytesToSring(bytes) {
    var chars = [];
    for(var i = 0, n = bytes.length; i < n;) {
        chars.push(((bytes[i++] & 0xff) << 8) | (bytes[i++] & 0xff));
    }
    return String.fromCharCode.apply(null, chars);
}

// https://codereview.stackexchange.com/a/3589/75693
function stringToBytes(str) {
    var bytes = [];
    for(var i = 0, n = str.length; i < n; i++) {
        var char = str.charCodeAt(i);
        bytes.push(char >>> 8, char & 0xFF);
    }
    return bytes;
}

The unit test uses this UTF-8 string:

    // http://kermitproject.org/utf8.html
    // From the Anglo-Saxon Rune Poem (Rune version) 
    const secretUtf8 = `?????????????????????????????
?????????????????????????????????????????
?????????????????????????????????????`;

Note that the string length is only 117 characters but the byte length, when encoded, is 234.

If I uncomment the console.log lines I can see that the string that is decoded is the same string that was encoded (with the bytes passed through Shamir's secret sharing algorithm!):

unit test that demos encoding and decoding

Find running median from a stream of integers

The most efficient way to calculate a percentile of a stream that I have found is the P² algorithm: Raj Jain, Imrich Chlamtac: The P² Algorithm for Dynamic Calculation of Quantiiles and Histograms Without Storing Observations. Commun. ACM 28(10): 1076-1085 (1985)

The algorithm is straight forward to implement and works extremely well. It is an estimate, however, so keep that in mind. From the abstract:

A heuristic algorithm is proposed for dynamic calculation qf the median and other quantiles. The estimates are produced dynamically as the observations are generated. The observations are not stored; therefore, the algorithm has a very small and fixed storage requirement regardless of the number of observations. This makes it ideal for implementing in a quantile chip that can be used in industrial controllers and recorders. The algorithm is further extended to histogram plotting. The accuracy of the algorithm is analyzed.

CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

For Ubuntu, please install the below things:

sudo apt-get update && sudo apt-get install build-essential

How to detect the currently pressed key?

The code below is how to detect almost all currently pressed keys, not just the Shift key.

private KeyMessageFilter m_filter = new KeyMessageFilter();

private void Form1_Load(object sender, EventArgs e)
{
    Application.AddMessageFilter(m_filter);
}


public class KeyMessageFilter : IMessageFilter
{
    private const int WM_KEYDOWN = 0x0100;
    private const int WM_KEYUP = 0x0101;
    private bool m_keyPressed = false;

    private Dictionary<Keys, bool> m_keyTable = new Dictionary<Keys, bool>();

    public Dictionary<Keys, bool> KeyTable
    {
        get { return m_keyTable; }
        private set { m_keyTable = value; }
    }

    public bool IsKeyPressed()
    {
        return m_keyPressed;
    }

    public bool IsKeyPressed(Keys k)
    {
        bool pressed = false;

        if (KeyTable.TryGetValue(k, out pressed))
        {
            return pressed;
        }

        return false;
    }

    public bool PreFilterMessage(ref Message m)
    {
        if (m.Msg == WM_KEYDOWN)
        {
            KeyTable[(Keys)m.WParam] = true;

            m_keyPressed = true;
        }

        if (m.Msg == WM_KEYUP)
        {
            KeyTable[(Keys)m.WParam] = false;

            m_keyPressed = false;
        }

        return false;
    }
}

Format an Integer using Java String Format

String.format("%03d", 1)  // => "001"
//              ¦¦¦   +-- print the number one
//              ¦¦+------ ... as a decimal integer
//              ¦+------- ... minimum of 3 characters wide
//              +-------- ... pad with zeroes instead of spaces

See java.util.Formatter for more information.

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

Code for WebTestPlugIn

public class Protocols : WebTestPlugin
{

    public override void PreRequest(object sender, PreRequestEventArgs e)
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

    }

}

Read a Csv file with powershell and capture corresponding data

What you should be looking at is Import-Csv

Once you import the CSV you can use the column header as the variable.

Example CSV:

Name  | Phone Number | Email
Elvis | 867.5309     | [email protected]
Sammy | 555.1234     | [email protected]

Now we will import the CSV, and loop through the list to add to an array. We can then compare the value input to the array:

$Name = @()
$Phone = @()

Import-Csv H:\Programs\scripts\SomeText.csv |`
    ForEach-Object {
        $Name += $_.Name
        $Phone += $_."Phone Number"
    }

$inputNumber = Read-Host -Prompt "Phone Number"

if ($Phone -contains $inputNumber)
    {
    Write-Host "Customer Exists!"
    $Where = [array]::IndexOf($Phone, $inputNumber)
    Write-Host "Customer Name: " $Name[$Where]
    }

And here is the output:

I Found Sammy

Get encoding of a file in Windows

Install git ( on Windows you have to use git bash console). Type:

file *   

for all files in the current directory , or

file */*   

for the files in all subdirectories

MVC pattern on Android

There is no universally unique MVC pattern. MVC is a concept rather than a solid programming framework. You can implement your own MVC on any platform. As long as you stick to the following basic idea, you are implementing MVC:

  • Model: What to render
  • View: How to render
  • Controller: Events, user input

Also think about it this way: When you program your model, the model should not need to worry about the rendering (or platform specific code). The model would say to the view, I don't care if your rendering is Android or iOS or Windows Phone, this is what I need you to render. The view would only handle the platform-specific rendering code.

This is particularly useful when you use Mono to share the model in order to develop cross-platform applications.

Plotting of 1-dimensional Gaussian distribution function

you can read this tutorial for how to use functions of statistical distributions in python. http://docs.scipy.org/doc/scipy/reference/tutorial/stats.html

from scipy.stats import norm
import matplotlib.pyplot as plt
import numpy as np 

#initialize a normal distribution with frozen in mean=-1, std. dev.= 1
rv = norm(loc = -1., scale = 1.0)
rv1 = norm(loc = 0., scale = 2.0)
rv2 = norm(loc = 2., scale = 3.0)

x = np.arange(-10, 10, .1)

#plot the pdfs of these normal distributions 
plt.plot(x, rv.pdf(x), x, rv1.pdf(x), x, rv2.pdf(x))

Check if a div exists with jquery

As karim79 mentioned, the first is the most concise. However I could argue that the second is more understandable as it is not obvious/known to some Javascript/jQuery programmers that non-zero/false values are evaluated to true in if-statements. And because of that, the third method is incorrect.

Google Play error "Error while retrieving information from server [DF-DFERH-01]"

Issue resolved after installing Google Play Services (NEVER needed them until now, removed because used too many resources on my Android 2.3), and do the following steps:

From Ryan Lestage on Google+:

  1. Clear data for the following apps:

    • Play Store
    • Download Manager
    • Google Services Framework
  2. Restart your phone.

  3. Fire up the Play Store app.
  4. Wait for the device to show again on the web Play Store. It will appear under Settings > Devices. It may take a half-hour to several hours to appear.

When your phone has shown up in the Play Store with the date registered as today's date, proceed with the next steps, but not before.

  1. Open Google Settings from your device's apps menu.
  2. Touch Android Device Manager.
  3. Uncheck Allow remote factory reset.
  4. Go to your device's main Settings menu, then touch Apps > All > Google Play services.
  5. Touch Clear Data. Note that this action doesn't remove personal data.
  6. Go back to Google Settings and select Allow remote factory reset.
  7. Restart your device.

Scrollview can host only one direct child

Wrap all the children inside of another LinearLayout with wrap_content for both the width and the height as well as the vertical orientation.

Fastest JSON reader/writer for C++

http://lloyd.github.com/yajl/

http://www.digip.org/jansson/

Don't really know how they compare for speed, but the first one looks like the right idea for scaling to really big JSON data, since it parses only a small chunk at a time so they don't need to hold all the data in memory at once (This can be faster or slower depending on the library/use case)

Curl to return http status code along with the response

My way to achieve this:

To get both (header and body), I usually perform a curl -D- <url> as in:

$ curl -D- http://localhost:1234/foo
HTTP/1.1 200 OK
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/json
Date: Wed, 29 Jul 2020 20:59:21 GMT

{"data":["out.csv"]}

This will dump headers (-D) to stdout (-) (Look for --dump-header in man curl).

IMHO also very handy in this context:

I often use jq to get that json data (eg from some rest APIs) formatted. But as jq doesn't expect a HTTP header, the trick is to print headers to stderr using -D/dev/stderr. Note that this time we also use -sS (--silent, --show-errors) to suppress the progress meter (because we write to a pipe).

$ curl -sSD/dev/stderr http://localhost:1231/foo | jq .
HTTP/1.1 200 OK
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/json
Date: Wed, 29 Jul 2020 21:08:22 GMT

{
  "data": [
    "out.csv"
  ]
}

I guess this also can be handy if you'd like to print headers (for quick inspection) to console but redirect body to a file (eg when its some kind of binary to not mess up your terminal):

$ curl -sSD/dev/stderr http://localhost:1231 > /dev/null
HTTP/1.1 200 OK
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/json
Date: Wed, 29 Jul 2020 21:20:02 GMT

Be aware: This is NOT the same as curl -I <url>! As -I will perform a HEAD request and not a GET request (Look for --head in man curl. Yes: For most HTTP servers this will yield same result. But I know a lot of business applications which don't implement HEAD request at all ;-P

Sorting rows in a data table

Or, if you can use a DataGridView, you could just call Sort(column, direction):

namespace Sorter
{
    using System;
    using System.ComponentModel;
    using System.Windows.Forms;

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.dataGridView1.Rows.Add("Abc", 5);
            this.dataGridView1.Rows.Add("Def", 8);
            this.dataGridView1.Rows.Add("Ghi", 3);
            this.dataGridView1.Sort(this.dataGridView1.Columns[1], 
                                    ListSortDirection.Ascending);
        }
    }
}

Which would give you the desired result:

Debugger view

Turning off eslint rule for a specific file

You can turn off specific rule for a file by using /*eslint [<rule: "off"], >]*/

/* eslint no-console: "off", no-mixed-operators: "off" */

Version: [email protected]

How to write to Console.Out during execution of an MSTest test

The Console output is not appearing is because the backend code is not running in the context of the test.

You're probably better off using Trace.WriteLine (In System.Diagnostics) and then adding a trace listener which writes to a file.

This topic from MSDN shows a way of doing this.


According to Marty Neal's and Dave Anderson's comments:

using System;
using System.Diagnostics;

...

Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
// or Trace.Listeners.Add(new ConsoleTraceListener());
Trace.WriteLine("Hello World");

Syntax for async arrow function

Immediately Invoked Async Arrow Function:

(async () => {
    console.log(await asyncFunction());
})();

Immediately Invoked Async Function Expression:

(async function () {
    console.log(await asyncFunction());
})();

How to edit a JavaScript alert box title?

I had a similar issue when I wanted to change the box title and button title of the default confirm box. I have gone for the Jquery Ui dialog plugin http://jqueryui.com/dialog/#modal-confirmation

When I had the following:

function testConfirm() {
  if (confirm("Are you sure you want to delete?")) {
    //some stuff
  }
}

I have changed it to:

function testConfirm() {

  var $dialog = $('<div></div>')
    .html("Are you sure you want to delete?")
    .dialog({
      resizable: false,
      title: "Confirm Deletion",
      modal: true,
      buttons: {
        Cancel: function() {
          $(this).dialog("close");
        },
        "Delete": function() {
          //some stuff
          $(this).dialog("close");
        }
      }
    });

  $dialog.dialog('open');
}

Can be seen working here https://jsfiddle.net/5aua4wss/2/

Hope that helps.

How to get the fragment instance from the FragmentActivity?

To get the fragment instance in a class that extends FragmentActivity:

MyclassFragment instanceFragment=
    (MyclassFragment)getSupportFragmentManager().findFragmentById(R.id.idFragment);

To get the fragment instance in a class that extends Fragment:

MyclassFragment instanceFragment =  
    (MyclassFragment)getFragmentManager().findFragmentById(R.id.idFragment);

Remove privileges from MySQL database

As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost'; does not work is quite simple : There is no grant called USAGE.

The actual named grants are in the MySQL Documentation

The grant USAGE is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE. Running DROP USER 'phpmyadmin'@'localhost'; should work just fine. Under the hood, it's really doing this:

DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db   WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;

Therefore, the removal of a row from mysql.user constitutes running REVOKE USAGE, even though REVOKE USAGE cannot literally be executed.

How to get response using cURL in PHP

The crux of the solution is setting

CURLOPT_RETURNTRANSFER => true

then

$response = curl_exec($ch);

CURLOPT_RETURNTRANSFER tells PHP to store the response in a variable instead of printing it to the page, so $response will contain your response. Here's your most basic working code (I think, didn't test it):

// init curl object        
$ch = curl_init();

// define options
$optArray = array(
    CURLOPT_URL => 'http://www.google.com',
    CURLOPT_RETURNTRANSFER => true
);

// apply those options
curl_setopt_array($ch, $optArray);

// execute request and get response
$result = curl_exec($ch);

How to enter special characters like "&" in oracle database?

There are 3 ways to do so :

1) Simply do SET DEFINE OFF; and then execute the insert stmt.

2) Simply by concatenating reserved word within single quotes and concatenating it. E.g. Select 'Java_22 ' || '& '|| ':' || ' Oracle_14' from dual --(:) is an optional.

3) By using CHR function along with concatenation. E.g. Select 'Java_22 ' || chr(38)||' Oracle_14' from dual

Hope this help !!!

How to update Pandas from Anaconda and is it possible to use eclipse with this last

The answer above did not work for me (python 3.6, Anaconda, pandas 0.20.3). It worked with

conda install -c anaconda pandas 

Unfortunately I do not know how to help with Eclipse.

Why are C# 4 optional parameters defined on interface not enforced on implementing class?

Just want to add my take here, as the other answers do provide reasonable explanations, but not ones that fully satisfy me.

Optional parameters are syntactic sugar for compile-time injection of the default value at the call site. This doesn't have anything to do with interfaces/implementations, and it can be seen as purely a side-effect of methods with optional parameters. So, when you call the method,

public void TestMethod(bool value = false) { /*...*/ }

like SomeClass.TestMethod(), it is actually SomeClass.TestMethod(false). If you call this method on an interface, from static type-checking, the method signature has the optional parameter. If you call this method on a deriving class's instance that doesn't have the optional parameter, from static type-checking, the method signature does not have the optional parameter, and must be called with full arguments.

Due to how optional parameters are implemented, this is the natural design result.

Windows Batch: How to add Host-Entries?

I am adding this answer in case someone else would like to store the host entry set in a txt file formatted like the normal host file. This looks for a TAB delimiter. This is based off of the answers from @Rashy and @that0n3guy. The differences can be noticed around the FOR command.

@echo off
TITLE Modifying your HOSTS file
ECHO.

:: BatchGotAdmin
:-------------------------------------
REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set params = %*:"="
    echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B

:gotAdmin
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------

:LOOP
SET Choice=
SET /P Choice="Do you want to modify HOSTS file ? (Y/N)"

IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%

ECHO.
IF /I '%Choice%'=='Y' GOTO ACCEPTED
IF /I '%Choice%'=='N' GOTO REJECTED
ECHO Please type Y (for Yes) or N (for No) to proceed!
ECHO.
GOTO Loop


:REJECTED
ECHO Your HOSTS file was left unchanged.
ECHO Finished.
GOTO END


:ACCEPTED
setlocal enabledelayedexpansion
::Create your list of host domains
for /F "tokens=1,2 delims=  " %%A in (%WINDIR%\System32\drivers\etc\storedhosts.txt) do (
    SET _host=%%B
    SET _ip=%%A
    SET NEWLINE=^& echo.
    ECHO Adding !_ip!       !_host!
    REM REM ::strip out this specific line and store in tmp file
    type %WINDIR%\System32\drivers\etc\hosts | findstr /v !_host! > tmp.txt
    REM REM ::re-add the line to it
    ECHO %NEWLINE%^!_ip!        !_host! >> tmp.txt
    REM ::overwrite host file
    copy /b/v/y tmp.txt %WINDIR%\System32\drivers\etc\hosts
    del tmp.txt 
)

ipconfig /flushdns
ECHO.
ECHO.
ECHO Finished, you may close this window now.
GOTO END

:END
ECHO.
PAUSE
EXIT

Example "storedhosts.txt" (tab delimited)

127.0.0.1   mysite.com
168.1.64.2  yoursite.com
192.1.0.1   internalsite.com

Get rid of "The value for annotation attribute must be a constant expression" message

This is what a constant expression in Java looks like:

package com.mycompany.mypackage;

public class MyLinks {
  // constant expression
  public static final String GUESTBOOK_URL = "/guestbook";
}

You can use it with annotations as following:

import com.mycompany.mypackage.MyLinks;

@WebServlet(urlPatterns = {MyLinks.GUESTBOOK_URL})
public class GuestbookServlet extends HttpServlet {
  // ...
}

Float a div above page content

Use

position: absolute;
top: ...px;
left: ...px;

To position the div. Make sure it doesn't have a parent tag with position: relative;

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

This error is often caused by incompatible jQuery versions. I encountered the same error with a foundation 6 repository. My repository was using jQuery 3, but foundation requires an earlier version. I then changed it and it worked.

If you look at the version of jQuery required by the foundation 5 dependencies it states "jquery": "~2.1.0".

Can you confirm that you are loading the correct version of jQuery?

I hope this helps.

Hash table runtime complexity (insert, search and delete)

Depends on the how you implement hashing, in the worst case it can go to O(n), in best case it is 0(1) (generally you can achieve if your DS is not that big easily)

Is it possible to refresh a single UITableViewCell in a UITableView?

Just to update these answers slightly with the new literal syntax in iOS 6--you can use Paths = @[indexPath] for a single object, or Paths = @[indexPath1, indexPath2,...] for multiple objects.

Personally, I've found the literal syntax for arrays and dictionaries to be immensely useful and big time savers. It's just easier to read, for one thing. And it removes the need for a nil at the end of any multi-object list, which has always been a personal bugaboo. We all have our windmills to tilt with, yes? ;-)

Just thought I'd throw this into the mix. Hope it helps.

Using union and count(*) together in SQL query

If you have supporting indexes, and relatively high counts, something like this may be considerably faster than the solutions suggested:

SELECT name, MAX(Rcount) + MAX(Acount) AS TotalCount
FROM (
  SELECT name, COUNT(*) AS Rcount, 0 AS Acount
  FROM Results GROUP BY name
  UNION ALL
  SELECT name, 0, count(*)
  FROM Archive_Results
  GROUP BY name
) AS Both
GROUP BY name
ORDER BY name;

how to sort an ArrayList in ascending order using Collections and Comparator

Just throwing this out there...Can't you just do:

Collections.sort(myarrayList);

It's been awhile though...

show more/Less text with just HTML and JavaScript

 <script type="text/javascript">
     function showml(divId,inhtmText) 
     {  
        var x = document.getElementById(divId).style.display; 

        if(x=="block")
        {
          document.getElementById(divId).style.display = "none";
          document.getElementById(inhtmText).innerHTML="Show More...";
        }
       if(x=="none")
       {
          document.getElementById(divId).style.display = "block";
          document.getElementById(inhtmText).innerHTML="Show Less";
        }
     }
</script>

 <p id="show_more1" onclick="showml('content1','show_more1')" onmouseover="this.style.cursor='pointer'">Show More...</p>

 <div id="content1" style="display: none; padding: 16px 20px 4px; margin-bottom: 15px; background-color: rgb(239, 239, 239);">
 </div>

if more div use like this change only 1 to 2

<p id="show_more2" onclick="showml('content2','show_more2')" onmouseover="this.style.cursor='pointer'">Show More...</p>

 <div id="content2" style="display: none; padding: 16px 20px 4px; margin-bottom: 15px; background-color: rgb(239, 239, 239);">
 </div>

demo jsfiddle

Show a div with Fancybox

You just use this and it will be helpful for you

$("#btnForm").click(function (){

$.fancybox({
    'padding':  0,
    'width':    1087,
    'height':   610,
    'type':     'iframe',
    content:   $('#divForm').show();
        });

});

How to change a string into uppercase

For questions on simple string manipulation the dir built-in function comes in handy. It gives you, among others, a list of methods of the argument, e.g., dir(s) returns a list containing upper.

How can I specify the required Node.js version in package.json?

.nvmrc

If you are using NVM like this, which you likely should, then you can indicate the nodejs version required for given project in a git-tracked .nvmrc file:

echo v10.15.1 > .nvmrc

This does not take effect automatically on cd, which is sane: the user must then do a:

nvm use

and now that version of node will be used for the current shell.

You can list the versions of node that you have with:

nvm list

.nvmrc is documented at: https://github.com/creationix/nvm/tree/02997b0753f66c9790c6016ed022ed2072c22603#nvmrc

How to automatically select that node version on cd was asked at: Automatically switch to correct version of Node based on project

Tested with NVM 0.33.11.

How do I check if a cookie exists?

function hasCookie(cookieName){
return document.cookie.split(';')
.map(entry => entry.split('='))
.some(([name, value]) => (name.trim() === cookieName) && !!value);
}

Note: The author wanted the function to return false if the cookie is empty i.e. cookie=; this is achieved with the && !!value condition. Remove it if you consider an empty cookie is still an existing cookie…

How do I enter a multi-line comment in Perl?

POD is the official way to do multi line comments in Perl,

From faq.perl.org[perlfaq7]

The quick-and-dirty way to comment out more than one line of Perl is to surround those lines with Pod directives. You have to put these directives at the beginning of the line and somewhere where Perl expects a new statement (so not in the middle of statements like the # comments). You end the comment with =cut, ending the Pod section:

=pod

my $object = NotGonnaHappen->new();

ignored_sub();

$wont_be_assigned = 37;

=cut

The quick-and-dirty method only works well when you don't plan to leave the commented code in the source. If a Pod parser comes along, your multiline comment is going to show up in the Pod translation. A better way hides it from Pod parsers as well.

The =begin directive can mark a section for a particular purpose. If the Pod parser doesn't want to handle it, it just ignores it. Label the comments with comment. End the comment using =end with the same label. You still need the =cut to go back to Perl code from the Pod comment:

=begin comment

my $object = NotGonnaHappen->new();

ignored_sub();

$wont_be_assigned = 37;

=end comment

=cut

How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?

One really easy option which is often overlooked is to create a .rdlc report using Microsoft Reporting and export it to excel format. You can design it in visual studio and generate the file using:

localReport.Render("EXCELOPENXML", null, ((name, ext, encoding, mimeType, willSeek) => stream = new FileStream(name, FileMode.CreateNew)), out warnings);

You can also export it do .doc or .pdf, using "WORDOPENXML" and "PDF" respectively, and it's supported on many different platforms such as ASP.NET and SSRS.

It's much easier to make changes in a visual designer where you can see the results, and trust me, once you start grouping data, formatting group headers, adding new sections, you don't want to mess with dozens of XML nodes.

Count work days between two dates

In Calculating Work Days you can find a good article about this subject, but as you can see it is not that advanced.

--Changing current database to the Master database allows function to be shared by everyone.
USE MASTER
GO
--If the function already exists, drop it.
IF EXISTS
(
    SELECT *
    FROM dbo.SYSOBJECTS
    WHERE ID = OBJECT_ID(N'[dbo].[fn_WorkDays]')
    AND XType IN (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_WorkDays]
GO
 CREATE FUNCTION dbo.fn_WorkDays
--Presets
--Define the input parameters (OK if reversed by mistake).
(
    @StartDate DATETIME,
    @EndDate   DATETIME = NULL --@EndDate replaced by @StartDate when DEFAULTed
)

--Define the output data type.
RETURNS INT

AS
--Calculate the RETURN of the function.
BEGIN
    --Declare local variables
    --Temporarily holds @EndDate during date reversal.
    DECLARE @Swap DATETIME

    --If the Start Date is null, return a NULL and exit.
    IF @StartDate IS NULL
        RETURN NULL

    --If the End Date is null, populate with Start Date value so will have two dates (required by DATEDIFF below).
     IF @EndDate IS NULL
        SELECT @EndDate = @StartDate

    --Strip the time element from both dates (just to be safe) by converting to whole days and back to a date.
    --Usually faster than CONVERT.
    --0 is a date (01/01/1900 00:00:00.000)
     SELECT @StartDate = DATEADD(dd,DATEDIFF(dd,0,@StartDate), 0),
            @EndDate   = DATEADD(dd,DATEDIFF(dd,0,@EndDate)  , 0)

    --If the inputs are in the wrong order, reverse them.
     IF @StartDate > @EndDate
        SELECT @Swap      = @EndDate,
               @EndDate   = @StartDate,
               @StartDate = @Swap

    --Calculate and return the number of workdays using the input parameters.
    --This is the meat of the function.
    --This is really just one formula with a couple of parts that are listed on separate lines for documentation purposes.
     RETURN (
        SELECT
        --Start with total number of days including weekends
        (DATEDIFF(dd,@StartDate, @EndDate)+1)
        --Subtact 2 days for each full weekend
        -(DATEDIFF(wk,@StartDate, @EndDate)*2)
        --If StartDate is a Sunday, Subtract 1
        -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday'
            THEN 1
            ELSE 0
        END)
        --If EndDate is a Saturday, Subtract 1
        -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday'
            THEN 1
            ELSE 0
        END)
        )
    END
GO

If you need to use a custom calendar, you might need to add some checks and some parameters. Hopefully it will provide a good starting point.

SQL Server Pivot Table with multiple column aggregates

The least complicated, most straight-forward way of doing this is by simply wrapping your main query with the pivot in a common table expression, then grouping/aggregating.

WITH PivotCTE AS
(
    select * from  mytransactions
    pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
)
SELECT
    numericmonth,
    chardate,
    SUM(totalamount) AS totalamount,
    SUM(ISNULL(Australia, 0)) AS Australia,
    SUM(ISNULL(Austria, 0)) Austria
FROM PivotCTE
GROUP BY numericmonth, chardate

The ISNULL is to stop a NULL value from nullifying the sum (because NULL + any value = NULL)

How to change folder with git bash?

The command is:

cd  /c/project/

Tip:
Use the pwd command to see which path you are currently in, handy when you did a right-click "Git Bash here..."

Where can I download IntelliJ IDEA Color Schemes?

Please note there are two very nice color schemes by default in IDEA 10.

The one that is included is named Railcasts. It is included with the Ruby plugin (free official plugin, install via plugin manager).

Railcasts IDEA 10 color scheme

How to call stopservice() method of Service class from the calling activity class

@Juri

If you add IntentFilters for your service, you are saying you want to expose your service to other applications, then it may be stopped unexpectedly by other applications.

What to use instead of "addPreferencesFromResource" in a PreferenceActivity?

Instead of exceptions, just use:

if (Build.VERSION.SDK_INT >= 11)

and use

@SuppressLint("NewApi")

to suppress the warnings.

Make DateTimePicker work as TimePicker only in WinForms

The best way to do this is this:

datetimepicker.Format = DatetimePickerFormat.Custom;
datetimepicker.CustomFormat = "HH:mm tt";
datetimepicker.ShowUpDowm = true;

How to make the Facebook Like Box responsive?

As of August 4 2015, the native facebook like box have a responsive code snippet available at Facebook Developers page.

You can generate your responsive Facebook likebox here

https://developers.facebook.com/docs/plugins/page-plugin

This is the best solution ever rather than hacking CSS.

Javascript select onchange='this.form.submit()'

There are a few ways this can be completed.

Elements know which form they belong to, so you don't need to wrap this in jquery, you can just call this.form which returns the form element. Then you can call submit() on a form element to submit it.

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

documentation: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement

Simpler way to check if variable is not equal to multiple string values?

For your first code, you can use a short alteration of the answer given by @ShankarDamodaran using in_array():

if ( !in_array($some_variable, array('uk','in'), true ) ) {

or even shorter with [] notation available since php 5.4 as pointed out by @Forty in the comments

if ( !in_array($some_variable, ['uk','in'], true ) ) {

is the same as:

if ( $some_variable !== 'uk' && $some_variable !== 'in' ) {

... but shorter. Especially if you compare more than just 'uk' and 'in'. I do not use an additional variable (Shankar used $os) but instead define the array in the if statement. Some might find that dirty, i find it quick and neat :D

The problem with your second code is that it can easily be exchanged with just TRUE since:

if (true) {

equals

if ( $some_variable !== 'uk' || $some_variable !== 'in' ) {

You are asking if the value of a string is not A or Not B. If it is A, it is definitely not also B and if it is B it is definitely not A. And if it is C or literally anything else, it is also not A and not B. So that statement always (not taking into account schrödingers law here) returns true.

Add Foreign Key relationship between two Databases

As the error message says, this is not supported on sql server. The only way to ensure refrerential integrity is to work with triggers.

How to create an empty array in Swift?

Here are some common tasks in Swift 4 you can use as a reference until you get used to things.

    let emptyArray = [String]()
    let emptyDouble: [Double] = []

    let preLoadArray = Array(repeating: 0, count: 10) // initializes array with 10 default values of the number 0

    let arrayMix = [1, "two", 3] as [Any]
    var arrayNum = [1, 2, 3]
    var array = ["1", "two", "3"]
    array[1] = "2"
    array.append("4")
    array += ["5", "6"]
    array.insert("0", at: 0)
    array[0] = "Zero"
    array.insert(contentsOf: ["-3", "-2", "-1"], at: 0)
    array.remove(at: 0)
    array.removeLast()
    array = ["Replaces all indexes with this"]
    array.removeAll()

    for item in arrayMix {
        print(item)
    }

    for (index, element) in array.enumerated() {
        print(index)
        print(element)
    }

    for (index, _) in arrayNum.enumerated().reversed() {
        arrayNum.remove(at: index)
    }

    let words = "these words will be objects in an array".components(separatedBy: " ")
    print(words[1])

    var names = ["Jemima", "Peter", "David", "Kelly", "Isabella", "Adam"]
    names.sort() // sorts names in alphabetical order

    let nums = [1, 1234, 12, 123, 0, 999]
    print(nums.sorted()) // sorts numbers from lowest to highest

Facebook API: Get fans of / people who like a page

Facebook's FQL documentation here tells you how to do it. Run the example SELECT name, fan_count FROM page WHERE page_id = 19292868552 and replace the page_id number with your page's id number and it will return the page name and the fan count.

How to read a large file line by line?

You can use the fgets() function to read the file line by line:

$handle = fopen("inputfile.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        // process the line read.
    }

    fclose($handle);
} else {
    // error opening the file.
} 

show validation error messages on submit in angularjs

Since I'm using Bootstrap 3, I use a directive: (see plunkr)

    var ValidSubmit = ['$parse', function ($parse) {
        return {
            compile: function compile(tElement, tAttrs, transclude) {
                return {
                    post: function postLink(scope, element, iAttrs, controller) {
                        var form = element.controller('form');
                        form.$submitted = false;
                        var fn = $parse(iAttrs.validSubmit);
                        element.on('submit', function(event) {
                            scope.$apply(function() {
                                element.addClass('ng-submitted');
                                form.$submitted = true;
                                if(form.$valid) {
                                    fn(scope, {$event:event});
                                }
                            });
                        });
                        scope.$watch(function() { return form.$valid}, function(isValid) {
                            if(form.$submitted == false) return;
                            if(isValid) {
                                element.removeClass('has-error').addClass('has-success');
                            } else {
                                element.removeClass('has-success');
                                element.addClass('has-error');
                            }
                        });
                    }
                }
            }
        }
    }]

    app.directive('validSubmit', ValidSubmit);

and then in my HTML:

<form class="form-horizontal" role="form" name="form" novalidate valid-submit="connect()">
  <div class="form-group">
    <div class="input-group col col-sm-11 col-sm-offset-1">
      <span class="input-group-addon input-large"><i class="glyphicon glyphicon-envelope"></i></span>
      <input class="input-large form-control" type="email" id="email" placeholder="Email" name="email" ng-model="email" required="required">
    </div>
    <p class="col-sm-offset-3 help-block error" ng-show="form.$submitted && form.email.$error.required">please enter your email</p>
    <p class="col-sm-offset-3 help-block error" ng-show="form.$submitted && form.email.$error.email">please enter a valid email</p>
  </div>
</form>

UPDATED

In my latest project, I use Ionic so I have the following, which automatically puts .valid or .invalid on the input-item's:

.directive('input', ['$timeout', function ($timeout) {
  function findParent(element, selector) {
    selector = selector || 'item';
    var parent = element.parent();
    while (parent && parent.length) {
      parent = angular.element(parent);
      if (parent.hasClass(selector)) {
        break;
      }
      parent = parent && parent.parent && parent.parent();
    }
    return parent;
  }

  return {
    restrict: 'E',
    require: ['?^ngModel', '^form'],
    priority: 1,
    link: function (scope, element, attrs, ctrls) {
      var ngModelCtrl = ctrls[0];
      var form = ctrls[1];

      if (!ngModelCtrl || form.$name !== 'form' || attrs.type === 'radio' || attrs.type === 'checkbox') {
        return;
      }

      function setValidClass() {
        var parent = findParent(element);
        if (parent && parent.toggleClass) {
          parent.addClass('validated');
          parent.toggleClass('valid', ngModelCtrl.$valid && (ngModelCtrl.$dirty || form.$submitted));
          parent.toggleClass('invalid', ngModelCtrl.$invalid && (ngModelCtrl.$dirty || form.$submitted));
          $timeout(angular.noop);
        }
      }

      scope.$watch(function () {
        return form.$submitted;
      }, function (b, a) {
        setValidClass();
      });


      var before = void 0;
      var update = function () {
        before = element.val().trim();
        ngModelCtrl.$setViewValue(before);
        ngModelCtrl.$render();
        setValidClass();
      };
      element
        .on('focus', function (e) {
          if (ngModelCtrl.$pristine) {
            element.removeClass('$blurred');
          }

        })
        .on('blur', function (e) {
          if (ngModelCtrl.$dirty) {
            setValidClass();
            element.addClass('$blurred');
          }
        }).on('change', function (e) {
          if (form.$submitted || element.hasClass('$blurred')) {
            setValidClass();
          }
        }).on('paste', function (e) {
          if (form.$submitted || element.hasClass('$blurred')) {
            setValidClass();
          }
        })
      ;

    }
  };
}])

and then in the HTML:

    <form name='form' novalidate="novalidate" ng-submit="auth.signin(form, vm)">
          <label class="item item-input item-floating-label">
            <span class="input-label">Email</span>
            <input type="email" placeholder="Email" ng-model="vm.email" autofocus="true" required
              >
          </label>
          <button ng-if="!posting" type="submit" class="item button-block item-balanced item-icon-right  call-to-action">Login<i class="icon ion-chevron-right"></i>
          </button>

and in the controller:

  self.signin = function (form, data) {
    if (!form.$valid) return;

    Authentication.emailLogin(data)
    //...

so, now, in the CSS, you can do stuff like:

.item.valid::before{
    float: right;
    font-family: "Ionicons";
    font-style: normal;
    font-weight: normal;
    font-variant: normal;
    text-transform: none;
    text-rendering: auto;
    line-height: 1;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    color: #66cc33;
    margin-right: 8px;
    font-size: 24px;
    content: "\f122";
}

.item.invalid::before{
    float: right;
    font-family: "Ionicons";
    font-style: normal;
    font-weight: normal;
    font-variant: normal;
    text-transform: none;
    text-rendering: auto;
    line-height: 1;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    color: #ef4e3a;
    margin-right: 8px;
    font-size: 24px;
    content: "\f12a";

/*
    border-left: solid 2px #ef4e3a !important;
    border-right: solid 2px #ef4e3a !important;
*/
}

MUCH SIMPLER!

How to write to file in Ruby?

Are you looking for the following?

File.open(yourfile, 'w') { |file| file.write("your text") }

How do I read a specified line in a text file?

Tried and tested. It's as simple as follows:

string line = File.ReadLines(filePath).ElementAt(actualLineNumber - 1);

As long as you have a text file, this should work. Later, depending upon what data you expect to read, you can cast the string accordingly and use it.

Inner join of DataTables in C#

This is my code. Not perfect, but working good. I hope it helps somebody:

    static System.Data.DataTable DtTbl (System.Data.DataTable[] dtToJoin)
    {
        System.Data.DataTable dtJoined = new System.Data.DataTable();

        foreach (System.Data.DataColumn dc in dtToJoin[0].Columns)
            dtJoined.Columns.Add(dc.ColumnName);

        foreach (System.Data.DataTable dt in dtToJoin)
            foreach (System.Data.DataRow dr1 in dt.Rows)
            {
                System.Data.DataRow dr = dtJoined.NewRow();
                foreach (System.Data.DataColumn dc in dtToJoin[0].Columns)
                    dr[dc.ColumnName] = dr1[dc.ColumnName];

                dtJoined.Rows.Add(dr);
            }

        return dtJoined;
    }

How to map a composite key with JPA and Hibernate?

To map a composite key, you can use the EmbeddedId or the IdClass annotations. I know this question is not strictly about JPA but the rules defined by the specification also applies. So here they are:

2.1.4 Primary Keys and Entity Identity

...

A composite primary key must correspond to either a single persistent field or property or to a set of such fields or properties as described below. A primary key class must be defined to represent a composite primary key. Composite primary keys typically arise when mapping from legacy databases when the database key is comprised of several columns. The EmbeddedId and IdClass annotations are used to denote composite primary keys. See sections 9.1.14 and 9.1.15.

...

The following rules apply for composite primary keys:

  • The primary key class must be public and must have a public no-arg constructor.
  • If property-based access is used, the properties of the primary key class must be public or protected.
  • The primary key class must be serializable.
  • The primary key class must define equals and hashCode methods. The semantics of value equality for these methods must be consistent with the database equality for the database types to which the key is mapped.
  • A composite primary key must either be represented and mapped as an embeddable class (see Section 9.1.14, “EmbeddedId Annotation”) or must be represented and mapped to multiple fields or properties of the entity class (see Section 9.1.15, “IdClass Annotation”).
  • If the composite primary key class is mapped to multiple fields or properties of the entity class, the names of primary key fields or properties in the primary key class and those of the entity class must correspond and their types must be the same.

With an IdClass

The class for the composite primary key could look like (could be a static inner class):

public class TimePK implements Serializable {
    protected Integer levelStation;
    protected Integer confPathID;

    public TimePK() {}

    public TimePK(Integer levelStation, Integer confPathID) {
        this.levelStation = levelStation;
        this.confPathID = confPathID;
    }
    // equals, hashCode
}

And the entity:

@Entity
@IdClass(TimePK.class)
class Time implements Serializable {
    @Id
    private Integer levelStation;
    @Id
    private Integer confPathID;

    private String src;
    private String dst;
    private Integer distance;
    private Integer price;

    // getters, setters
}

The IdClass annotation maps multiple fields to the table PK.

With EmbeddedId

The class for the composite primary key could look like (could be a static inner class):

@Embeddable
public class TimePK implements Serializable {
    protected Integer levelStation;
    protected Integer confPathID;

    public TimePK() {}

    public TimePK(Integer levelStation, Integer confPathID) {
        this.levelStation = levelStation;
        this.confPathID = confPathID;
    }
    // equals, hashCode
}

And the entity:

@Entity
class Time implements Serializable {
    @EmbeddedId
    private TimePK timePK;

    private String src;
    private String dst;
    private Integer distance;
    private Integer price;

    //...
}

The @EmbeddedId annotation maps a PK class to table PK.

Differences:

  • From the physical model point of view, there are no differences
  • @EmbeddedId somehow communicates more clearly that the key is a composite key and IMO makes sense when the combined pk is either a meaningful entity itself or it reused in your code.
  • @IdClass is useful to specify that some combination of fields is unique but these do not have a special meaning.

They also affect the way you write queries (making them more or less verbose):

  • with IdClass

    select t.levelStation from Time t
    
  • with EmbeddedId

    select t.timePK.levelStation from Time t
    

References

  • JPA 1.0 specification
    • Section 2.1.4 "Primary Keys and Entity Identity"
    • Section 9.1.14 "EmbeddedId Annotation"
    • Section 9.1.15 "IdClass Annotation"

jquery onclick change css background image

You need to use background-image instead of backgroundImage. For example:

$(function() {
  $('.home').click(function() {
    $(this).css('background-image', 'url(images/tabs3.png)');
  });
}):

How to set image for bar button with swift?

An easy solution may be the following

barButtonItem.image = UIImage(named: "image")

then go to your Assets.xcassets select the image and go to the Attribute Inspector and select "Original Image" in Reder as option.

How to center and crop an image to always appear in square shape with CSS?

<div>
    <img class="crop" src="http://lorempixel.com/500/200"/>
</div>

<img src="http://lorempixel.com/500/200"/>




div {
    width: 200px;
    height: 200px;
    overflow: hidden;
    margin: 10px;
    position: relative;
}
.crop {
    position: absolute;
    left: -100%;
    right: -100%;
    top: -100%;
    bottom: -100%;
    margin: auto; 
    height: auto;
    width: auto;
}

http://jsfiddle.net/J7a5R/56/

How to build a query string for a URL in C#?

With the inspiration from Roy Tinker's comment, I ended up using a simple extension method on the Uri class that keeps my code concise and clean:

using System.Web;

public static class HttpExtensions
{
    public static Uri AddQuery(this Uri uri, string name, string value)
    {
        var httpValueCollection = HttpUtility.ParseQueryString(uri.Query);

        httpValueCollection.Remove(name);
        httpValueCollection.Add(name, value);

        var ub = new UriBuilder(uri);
        ub.Query = httpValueCollection.ToString();

        return ub.Uri;
    }
}

Usage:

Uri url = new Uri("http://localhost/rest/something/browse").
          AddQuery("page", "0").
          AddQuery("pageSize", "200");

Edit - Standards compliant variant

As several people pointed out, httpValueCollection.ToString() encodes Unicode characters in a non-standards-compliant way. This is a variant of the same extension method that handles such characters by invoking HttpUtility.UrlEncode method instead of the deprecated HttpUtility.UrlEncodeUnicode method.

using System.Web;

public static Uri AddQuery(this Uri uri, string name, string value)
{
    var httpValueCollection = HttpUtility.ParseQueryString(uri.Query);

    httpValueCollection.Remove(name);
    httpValueCollection.Add(name, value);

    var ub = new UriBuilder(uri);

    // this code block is taken from httpValueCollection.ToString() method
    // and modified so it encodes strings with HttpUtility.UrlEncode
    if (httpValueCollection.Count == 0)
        ub.Query = String.Empty;
    else
    {
        var sb = new StringBuilder();

        for (int i = 0; i < httpValueCollection.Count; i++)
        {
            string text = httpValueCollection.GetKey(i);
            {
                text = HttpUtility.UrlEncode(text);

                string val = (text != null) ? (text + "=") : string.Empty;
                string[] vals = httpValueCollection.GetValues(i);

                if (sb.Length > 0)
                    sb.Append('&');

                if (vals == null || vals.Length == 0)
                    sb.Append(val);
                else
                {
                    if (vals.Length == 1)
                    {
                        sb.Append(val);
                        sb.Append(HttpUtility.UrlEncode(vals[0]));
                    }
                    else
                    {
                        for (int j = 0; j < vals.Length; j++)
                        {
                            if (j > 0)
                                sb.Append('&');

                            sb.Append(val);
                            sb.Append(HttpUtility.UrlEncode(vals[j]));
                        }
                    }
                }
            }
        }

        ub.Query = sb.ToString();
    }

    return ub.Uri;
}

Append an array to another array in JavaScript

If you want to modify the original array instead of returning a new array, use .push()...

array1.push.apply(array1, array2);
array1.push.apply(array1, array3);

I used .apply to push the individual members of arrays 2 and 3 at once.

or...

array1.push.apply(array1, array2.concat(array3));

To deal with large arrays, you can do this in batches.

for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
    array1.push.apply(array1, to_add.slice(n, n+300));
}

If you do this a lot, create a method or function to handle it.

var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);

Object.defineProperty(Array.prototype, "pushArrayMembers", {
    value: function() {
        for (var i = 0; i < arguments.length; i++) {
            var to_add = arguments[i];
            for (var n = 0; n < to_add.length; n+=300) {
                push_apply(this, slice_call(to_add, n, n+300));
            }
        }
    }
});

and use it like this:

array1.pushArrayMembers(array2, array3);

_x000D_
_x000D_
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
    value: function() {_x000D_
        for (var i = 0; i < arguments.length; i++) {_x000D_
            var to_add = arguments[i];_x000D_
            for (var n = 0; n < to_add.length; n+=300) {_x000D_
                push_apply(this, slice_call(to_add, n, n+300));_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
_x000D_
_x000D_

How to find available directory objects on Oracle 11g system?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

How to use Tomcat 8 in Eclipse?

UPDATE: Eclipse Mars EE and later have native support for Tomcat8. Use this only if you have an earlier version of eclipse.


The latest version of Eclipse still does not support Tomcat 8, but you can add the new version of WTP and Tomcat 8 support will be added natively. To do this:

  • Download the latest version of Eclipse for Java EE
  • Go to the WTP downloads page, select the latest version (currently 3.6), and download the zip (under Traditional Zip Files...Web App Developers). Here's the current link.
  • Copy the all of the files in features and plugins directories of the downloaded WTP into the corresponding Eclipse directories in your Eclipse folder (overwriting the existing files).

Start Eclipse and you should have a Tomcat 8 option available when you go to deploy. enter image description here

Error: Could not find or load main class

Problem is not about your main function. Check out for

javac -d . -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel.java     VensimHelper.java VensimException.java VensimContextRepository.java

output and run it.

sys.path different in Jupyter and Python - how to import own modules in Jupyter?

You can use absolute imports:

/root
    /app
      /config
        config.py
      /source
        file.ipynb

# In the file.ipynb importing the config.py file
from root.app.config import config

Forbidden: You don't have permission to access / on this server, WAMP Error

I find the best (and least frustrating) path is to start with Allow from All, then, when you know it will work that way, scale it back to the more secure Allow from 127.0.0.1 or Allow from ::1 (localhost).

As long as your firewall is configured properly, Allow from all shouldn't cause any problems, but it is better to only allow from localhost if you don't need other computers to be able to access your site.

Don't forget to restart Apache whenever you make changes to httpd.conf. They will not take effect until the next start.

Hopefully this is enough to get you started, there is lots of documentation available online.

AngularJS is rendering <br> as text not as a newline

I could be wrong because I've never used Angular, but I believe you are probably using ng-bind, which will create just a TextNode.

You will want to use ng-bind-html instead.

http://docs.angularjs.org/api/ngSanitize.directive:ngBindHtml

Update: It looks like you'll need to use ng-bind-html-unsafe='q.category'

http://docs.angularjs.org/api/ng.directive:ngBindHtmlUnsafe

Here's a demo:

http://jsfiddle.net/VFVMv/

show/hide html table columns using css

No, that's pretty much it. In theory you could use visibility: collapse on some <col>?s to do it, but browser support isn't all there.

To improve what you've got slightly, you could use table-layout: fixed on the <table> to allow the browser to use the simpler, faster and more predictable fixed-table-layout algorithm. You could also drop the .show rules as when a cell isn't made display: none by a .hide rule it will automatically be display: table-cell. Allowing table display to revert to default rather than setting it explicitly avoids problems in IE<8, where the table display values are not supported.

allowing only alphabets in text box using java script

You can try:

 function onlyAlphabets(e, t) {
        return (e.charCode > 64 && e.charCode < 91) || (e.charCode > 96 && e.charCode < 123) || e.charCode == 32;   
    }

Query to convert from datetime to date mysql

Use the DATE function:

SELECT DATE(orders.date_purchased) AS date

The Eclipse executable launcher was unable to locate its companion launcher jar windows

Edit the eclipse.ini file and remove these two lines:

-startup
plugins\org.eclipse.equinox.launcher_1.0.100.v20080509-1800.jar 

Opening port 80 EC2 Amazon web services

For those of you using Centos (and perhaps other linux distibutions), you need to make sure that its FW (iptables) allows for port 80 or any other port you want.

See here on how to completely disable it (for testing purposes only!). And here for specific rules

How to change XML Attribute

Mike; Everytime I need to modify an XML document I work it this way:

//Here is the variable with which you assign a new value to the attribute
string newValue = string.Empty;
XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load(xmlFile);

XmlNode node = xmlDoc.SelectSingleNode("Root/Node/Element");
node.Attributes[0].Value = newValue;

xmlDoc.Save(xmlFile);

//xmlFile is the path of your file to be modified

I hope you find it useful

Search an array for matching attribute

you can use ES5 some. Its pretty first by using callback

function findRestaurent(foodType) {
    var restaurant;
    restaurants.some(function (r) {
        if (r.food === id) {
            restaurant = r;
            return true;
        }
   });
  return restaurant;
}

Browser Caching of CSS files

It does depend on the HTTP headers sent with the CSS files as both of the previous answers state - as long as you don't append any cachebusting stuff to the href. e.g.

<link href="/stylesheets/mycss.css?some_var_to_bust_cache=24312345" rel="stylesheet" type="text/css" />

Some frameworks (e.g. rails) put these in by default.

However If you get something like firebug or fiddler, you can see exactly what your browser is downloading on each request - which is expecially useful for finding out what your browser is doing, as opposed to just what it should be doing.

All browsers should respect the cache headers in the same way, unless configured to ignore them (but there are bound to be exceptions)

What does `dword ptr` mean?

Consider the figure enclosed in this other question. ebp-4 is your first local variable and, seen as a dword pointer, it is the address of a 32 bit integer that has to be cleared. Maybe your source starts with

Object x = null;

How do I get an animated gif to work in WPF?

I couldn't get the most popular answer to this question (above by Dario) to work properly. The result was weird, choppy animation with weird artifacts. Best solution I have found so far: https://github.com/XamlAnimatedGif/WpfAnimatedGif

You can install it with NuGet

PM> Install-Package WpfAnimatedGif

and to use it, at a new namespace to the Window where you want to add the gif image and use it as below

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:gif="http://wpfanimatedgif.codeplex.com" <!-- THIS NAMESPACE -->
    Title="MainWindow" Height="350" Width="525">

<Grid>
    <!-- EXAMPLE USAGE BELOW -->
    <Image gif:ImageBehavior.AnimatedSource="Images/animated.gif" />

The package is really neat, you can set some attributes like below

<Image gif:ImageBehavior.RepeatBehavior="3x"
       gif:ImageBehavior.AnimatedSource="Images/animated.gif" />

and you can use it in your code as well:

var image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(fileName);
image.EndInit();
ImageBehavior.SetAnimatedSource(img, image);

EDIT: Silverlight support

As per josh2112's comment if you want to add animated GIF support to your Silverlight project then use github.com/XamlAnimatedGif/XamlAnimatedGif

Check Postgres access for a user

For all users on a specific database, do the following:

# psql
\c your_database
select grantee, table_catalog, privilege_type, table_schema, table_name from information_schema.table_privileges order by grantee, table_schema, table_name;

Retrieving the COM class factory for component failed

I had the same error when I deployed my app. I've got solution from this site: Component with CLSID XXX failed due to the following error: 80070005 Access is denied

Here is this solution:

  1. In DCOMCNFG, right click on the My Computer and select properties.

  2. Choose the COM Securities tab.

  3. In Access Permissions, click Edit Defaults and add Network Service to it and give it Allow local access permission. Do the same for < Machine_name >\Users.

  4. In Launch and Activation Permissions, click Edit Defaults and add Network Service to it and give it Local launch and Local Activation permission. Do the same for < Machine_name >\Users.

*I used forms authentication.

How can I get npm start at a different directory?

I came here from google so it might be relevant to others: for yarn you could use:

yarn --cwd /path/to/your/app run start 

Python pandas insert list into a cell

As mentionned in this post pandas: how to store a list in a dataframe?; the dtypes in the dataframe may influence the results, as well as calling a dataframe or not to be assigned to.

How do I run a Python script from C#?

Execute Python script from C

Create a C# project and write the following code.

using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            run_cmd();
        }

        private void run_cmd()
        {

            string fileName = @"C:\sample_script.py";

            Process p = new Process();
            p.StartInfo = new ProcessStartInfo(@"C:\Python27\python.exe", fileName)
            {
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };
            p.Start();

            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();

            Console.WriteLine(output);

            Console.ReadLine();

        }
    }
}

Python sample_script

print "Python C# Test"

You will see the 'Python C# Test' in the console of C#.

Spring @ContextConfiguration how to put the right location for the xml

That's the reason not to put configuration into webapp.

As far as I know, there are no good ways to access files in webapp folder from the unit tests. You can put your configuration into src/main/resources instead, so that you can access it from your unit tests (as described in the docs), as well as from the webapp (using classpath: prefix in contextConfigLocation).

See also:

An error occurred while signing: SignTool.exe not found

You can fix this by clicking on installation application of VS. Then click Modify > Mark ClickOnce App and then upgrade your VS. Also i think @Alex Erygin is right. It is a bad solution to Click Once application --> Properties --> Signing -> Uncheck Sign the ClickOnce manifests. This is not a solution. It only circumambulated the problem.

JavaScript: how to change form action attribute value based on selection?

It's better to use

$('#search-form').setAttribute('action', '/controllerName/actionName');

rather than

$('#search-form').attr('action', '/controllerName/actionName');

So, based on trante's answer we have:

$('#search-form').submit(function() {
    var formAction = $("#selectsearch").val() == "people" ? "user" : "content";
    $("#search-form").setAttribute("action", "/search/" + formAction);
}); 

Using setAttribute can save you a lot of time potentially.

Working Copy Locked

Every time I get a Working copy locked error I run a "Clean up". After that everything is back to normal.

On the command line you can execute svn cleanup which also removes lock files.

Note: Perform this operation on one level up directory and that should resolve most of the times.

Is Tomcat running?

Are you trying to set up an alert system? For a simple "heartbeat", do a HTTP request to the Tomcat port.

For more elaborate monitoring, you can set up JMX and/or SNMP to view JVM stats. We run Nagios with the SNMP plugin (bridges to JMX) to check Tomcat memory usage and request thread pool size every 10-15 minutes.

http://tomcat.apache.org/tomcat-6.0-doc/monitoring.html

Update (2012):

We have upgraded our systems to use "monit" to check the tomcat process. I really like it. With very little configuration it automatically verifies the service is running, and automatically restarts if it is not. (sending an email alert). It can integrate with the /etc/init.d scripts or check by process name.

How can I dynamically add items to a Java array?

In Java size of array is fixed , but you can add elements dynamically to a fixed sized array using its index and for loop. Please find example below.

package simplejava;

import java.util.Arrays;

/**
 *
 * @author sashant
 */
public class SimpleJava {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        try{
            String[] transactions;
            transactions = new String[10];

            for(int i = 0; i < transactions.length; i++){
                transactions[i] = "transaction - "+Integer.toString(i);            
            }

            System.out.println(Arrays.toString(transactions));

        }catch(Exception exc){
            System.out.println(exc.getMessage());
            System.out.println(Arrays.toString(exc.getStackTrace()));
        }
    }

}

How to detect DIV's dimension changed?

You can try the code in the following snippet, it covers your needs using plain javascript. (run the code snippet and click full page link to trigger the alert that the div is resized if you want to test it.).

Based on the fact that this is a setInterval of 100 milliseconds, i would dare to say that my PC did not find it too much CPU hungry. (0.1% of CPU was used as total for all opened tabs in Chrome at the time tested.). But then again this is for just one div, if you would like to do this for a large amount of elements then yes it could be very CPU hungry.

You could always use a click event to stop the div-resize sniffing anyway.

_x000D_
_x000D_
var width = 0; 
var interval = setInterval(function(){
if(width <= 0){
width = document.getElementById("test_div").clientWidth;
} 
if(document.getElementById("test_div").clientWidth!==width) {   
  alert('resized div');
  width = document.getElementById("test_div").clientWidth;
}    

}, 100);
_x000D_
<div id="test_div" style="width: 100%; min-height: 30px; border: 1px dashed pink;">
        <input type="button" value="button 1" />
        <input type="button" value="button 2" />
        <input type="button" value="button 3" />
</div>
_x000D_
_x000D_
_x000D_

You can check the fiddle also

UPDATE

_x000D_
_x000D_
var width = 0; 
function myInterval() {
var interval = setInterval(function(){
if(width <= 0){
width = document.getElementById("test_div").clientWidth;
} 
if(document.getElementById("test_div").clientWidth!==width) {   
  alert('resized');
  width = document.getElementById("test_div").clientWidth;
}    

}, 100);
return interval;
}
var interval = myInterval();
document.getElementById("clickMe").addEventListener( "click" , function() {
if(typeof interval!=="undefined") {
clearInterval(interval);
alert("stopped div-resize sniffing");
}
});
document.getElementById("clickMeToo").addEventListener( "click" , function() {
myInterval();
alert("started div-resize sniffing");
});
_x000D_
<div id="test_div" style="width: 100%; min-height: 30px; border: 1px dashed pink;">
        <input type="button" value="button 1" id="clickMe" />
        <input type="button" value="button 2" id="clickMeToo" />
        <input type="button" value="button 3" />
</div>
_x000D_
_x000D_
_x000D_

Updated Fiddle

How do I write JSON data to a file?

The JSON data can be written to a file as follows

hist1 = [{'val_loss': [0.5139984398465246],
'val_acc': [0.8002029867684085],
'loss': [0.593220705309384],
'acc': [0.7687131817929321]},
{'val_loss': [0.46456472964199463],
'val_acc': [0.8173602046780344],
'loss': [0.4932038113037539],
'acc': [0.8063946213802453]}]

Write to a file:

with open('text1.json', 'w') as f:
     json.dump(hist1, f)

Data binding for TextBox

You need a bindingsource object to act as an intermediary and assist in the binding. Then instead of updating the user interface, update the underlining model.

var model = (Fruit) bindingSource1.DataSource;

model.FruitType = "oranges";

bindingSource.ResetBindings();

Read up on BindingSource and simple data binding for Windows Forms.

How to read from stdin with fgets()?

Exits the loop if the line is empty(Improving code).

#include <stdio.h>
#include <string.h>

// The value BUFFERSIZE can be changed to customer's taste . Changes the
// size of the base array (string buffer )    
#define BUFFERSIZE 10

int main(void)
{
    char buffer[BUFFERSIZE];
    char cChar;
    printf("Enter a message: \n");
    while(*(fgets(buffer, BUFFERSIZE, stdin)) != '\n')
    {
        // For concatenation
        // fgets reads and adds '\n' in the string , replace '\n' by '\0' to 
        // remove the line break .
/*      if(buffer[strlen(buffer) - 1] == '\n')
            buffer[strlen(buffer) - 1] = '\0'; */
        printf("%s", buffer);
        // Corrects the error mentioned by Alain BECKER.       
        // Checks if the string buffer is full to check and prevent the 
        // next character read by fgets is '\n' .
        if(strlen(buffer) == (BUFFERSIZE - 1) && (buffer[strlen(buffer) - 1] != '\n'))
        {
            // Prevents end of the line '\n' to be read in the first 
            // character (Loop Exit) in the next loop. Reads
            // the next char in stdin buffer , if '\n' is read and removed, if
            // different is returned to stdin 
            cChar = fgetc(stdin);
            if(cChar != '\n')
                ungetc(cChar, stdin);
            // To print correctly if '\n' is removed.
            else
                printf("\n");
        }
    }
    return 0;
}

Exit when Enter is pressed.

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>

#define BUFFERSIZE 16

int main(void)
{
    char buffer[BUFFERSIZE];
    printf("Enter a message: \n");
    while(true)
    {
        assert(fgets(buffer, BUFFERSIZE, stdin) != NULL);
        // Verifies that the previous character to the last character in the
        // buffer array is '\n' (The last character is '\0') if the
        // character is '\n' leaves loop.
        if(buffer[strlen(buffer) - 1] == '\n')
        {
            // fgets reads and adds '\n' in the string, replace '\n' by '\0' to 
            // remove the line break .
            buffer[strlen(buffer) - 1] = '\0';
            printf("%s", buffer);
            break;
        }
        printf("%s", buffer);   
    }
    return 0;
}

Concatenation and dinamic allocation(linked list) to a single string.

/* Autor : Tiago Portela
   Email : [email protected]
   Sobre : Compilado com TDM-GCC 5.10 64-bit e LCC-Win32 64-bit;
   Obs : Apenas tentando aprender algoritimos, sozinho, por hobby. */

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>

#define BUFFERSIZE 8

typedef struct _Node {
    char *lpBuffer;
    struct _Node *LpProxNode;
} Node_t, *LpNode_t;

int main(void)
{
    char acBuffer[BUFFERSIZE] = {0};
    LpNode_t lpNode = (LpNode_t)malloc(sizeof(Node_t));
    assert(lpNode!=NULL);
    LpNode_t lpHeadNode = lpNode;
    char* lpBuffer = (char*)calloc(1,sizeof(char));
    assert(lpBuffer!=NULL);
    char cChar;


    printf("Enter a message: \n");
    // Exit when Enter is pressed
/*  while(true)
    {
        assert(fgets(acBuffer, BUFFERSIZE, stdin)!=NULL);
        lpNode->lpBuffer = (char*)malloc((strlen(acBuffer) + 1) * sizeof(char));
        assert(lpNode->lpBuffer!=NULL);
        strcpy(lpNode->lpBuffer, acBuffer);
        if(lpNode->lpBuffer[strlen(acBuffer) - 1] == '\n')
        {
            lpNode->lpBuffer[strlen(acBuffer) - 1] = '\0';
            lpNode->LpProxNode = NULL;
            break;
        }
        lpNode->LpProxNode = (LpNode_t)malloc(sizeof(Node_t));
        lpNode = lpNode->LpProxNode;
        assert(lpNode!=NULL);
    }*/

    // Exits the loop if the line is empty(Improving code).
    while(true)
    {
        assert(fgets(acBuffer, BUFFERSIZE, stdin)!=NULL);
        lpNode->lpBuffer = (char*)malloc((strlen(acBuffer) + 1) * sizeof(char));
        assert(lpNode->lpBuffer!=NULL);
        strcpy(lpNode->lpBuffer, acBuffer);
        if(acBuffer[strlen(acBuffer) - 1] == '\n')
            lpNode->lpBuffer[strlen(acBuffer) - 1] = '\0';
        if(strlen(acBuffer) == (BUFFERSIZE - 1) && (acBuffer[strlen(acBuffer) - 1] != '\n'))
        {
            cChar = fgetc(stdin);
            if(cChar != '\n')
                ungetc(cChar, stdin);
        }
        if(acBuffer[0] == '\n')
        {
            lpNode->LpProxNode = NULL;
            break;
        }
        lpNode->LpProxNode = (LpNode_t)malloc(sizeof(Node_t));
        lpNode = lpNode->LpProxNode;
        assert(lpNode!=NULL);
    }


    printf("\nPseudo String :\n");
    lpNode = lpHeadNode;
    while(lpNode != NULL)
    {
        printf("%s", lpNode->lpBuffer);
        lpNode = lpNode->LpProxNode;
    }


    printf("\n\nMemory blocks:\n");
    lpNode = lpHeadNode;
    while(lpNode != NULL)
    {
        printf("Block \"%7s\" size = %lu\n", lpNode->lpBuffer, (long unsigned)(strlen(lpNode->lpBuffer) + 1));
        lpNode = lpNode->LpProxNode;
    }


    printf("\nConcatenated string:\n");
    lpNode = lpHeadNode;
    while(lpNode != NULL)
    {
        lpBuffer = (char*)realloc(lpBuffer, (strlen(lpBuffer) + strlen(lpNode->lpBuffer)) + 1);
        strcat(lpBuffer, lpNode->lpBuffer);
        lpNode = lpNode->LpProxNode;
    }
    printf("%s", lpBuffer);
    printf("\n\n");

    // Deallocate memory
    lpNode = lpHeadNode;
    while(lpNode != NULL)
    {
        lpHeadNode = lpNode->LpProxNode;
        free(lpNode->lpBuffer);
        free(lpNode);
        lpNode = lpHeadNode;
    }
    lpBuffer = (char*)realloc(lpBuffer, 0);
    lpBuffer = NULL;
    if((lpNode == NULL) && (lpBuffer == NULL))
    {

        printf("Deallocate memory = %s", (char*)lpNode);
    }
    printf("\n\n");

    return 0;
}

1052: Column 'id' in field list is ambiguous

The simplest solution is a join with USING instead of ON. That way, the database "knows" that both id columns are actually the same, and won't nitpick on that:

SELECT id, name, section
  FROM tbl_names
  JOIN tbl_section USING (id)

If id is the only common column name in tbl_names and tbl_section, you can even use a NATURAL JOIN:

SELECT id, name, section
  FROM tbl_names
  NATURAL JOIN tbl_section

See also: https://dev.mysql.com/doc/refman/5.7/en/join.html

Retrieve CPU usage and memory usage of a single process on Linux?

A variant of caf's answer: top -p <pid>

This auto-refreshes the CPU usage so it's good for monitoring.

How to set selected value of jquery select2?

$('#inputID').val("100").select2();

It would be more appropriate to apply select2 after choosing one of the current select.

Remove attribute "checked" of checkbox

Sorry, I solved my problem with the code above:

$("#captureImage").live("change", function() {
    if($("#captureImage:checked").val() !== undefined) {
        navigator.device.capture.captureImage(function(mediaFiles) {
            console.log("works");
        }, function(exception) {
            $("#captureImage").removeAttr('checked').checkboxradio('refresh');
            _callback.error(exception);
        }, {});
    }
});

Set a border around a StackPanel.

What about this one :

<DockPanel Margin="8">
    <Border CornerRadius="6" BorderBrush="Gray" Background="LightGray" BorderThickness="2" DockPanel.Dock="Top">
        <StackPanel Orientation="Horizontal">
            <TextBlock FontSize="14" Padding="0 0 8 0" HorizontalAlignment="Center" VerticalAlignment="Center">Search:</TextBlock>
            <TextBox x:Name="txtSearchTerm" HorizontalAlignment="Center" VerticalAlignment="Center" />
            <Image Source="lock.png" Width="32" Height="32" HorizontalAlignment="Center" VerticalAlignment="Center" />            
        </StackPanel>
    </Border>
    <StackPanel Orientation="Horizontal" DockPanel.Dock="Bottom" Height="25" />
</DockPanel>

Python style - line continuation with strings?

I've gotten around this with

mystr = ' '.join(
        ["Why, hello there",
         "wonderful stackoverflow people!"])

in the past. It's not perfect, but it works nicely for very long strings that need to not have line breaks in them.

How to get the file-path of the currently executing javascript code

All browsers except Internet Explorer (any version) have document.currentScript, which always works always (no matter how the file was included (async, bookmarklet etc)).

If you want to know the full URL of the JS file you're in right now:

var script = document.currentScript;
var fullUrl = script.src;

Tadaa.

Trim specific character from a string

To my knowledge, jQuery doesnt have a built in function the method your are asking about. With javascript however, you can just use replace to change the content of your string:

x.replace(/|/i, ""));

This will replace all occurences of | with nothing.

How do I implement JQuery.noConflict() ?

Today i have this issue because i have implemented "bootstrap menu" that uses a jQuery version along with "fancybox image gallery". Of course one plugin works and the other not due to jQuery conflict but i have overcome it as follow:

First i have added the "bootstrap menu" Js in the script footer as the menu is presented allover the website pages:

<!-- Top Menu Javascript -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript">
var jq171 = jQuery.noConflict(true);
</script>

And in the "fancybox" image gallery page as follow:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="fancybox/js/libs/jquery-1.7.1.min.js"><\/script>')</script>

And the good thing is both working like a charm :)

Give it a try :)

What are all codecs and formats supported by FFmpeg?

ffmpeg -codecs

should give you all the info about the codecs available.

You will see some letters next to the codecs:

Codecs:
 D..... = Decoding supported
 .E.... = Encoding supported
 ..V... = Video codec
 ..A... = Audio codec
 ..S... = Subtitle codec
 ...I.. = Intra frame-only codec
 ....L. = Lossy compression
 .....S = Lossless compression