Programs & Examples On #Network shares

How do I divide in the Linux console?

I still prefer using dc, which is an RPN calculator, so quick session to divide 67 by 18 with 4 digits precision would look like

>dc
4k
67
18/p
3.7222
q
>

Obviously, much more available: man dc

How to install Visual C++ Build tools?

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

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

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

Difference between r+ and w+ in fopen()

Both r+ and w+ can read and write to a file. However, r+ doesn't delete the content of the file and doesn't create a new file if such file doesn't exist, whereas w+ deletes the content of the file and creates it if it doesn't exist.

File size exceeds configured limit (2560000), code insight features not available

Go to IDE:

STEP 1: Open the menu item: click on Help then click on Edit Custom Properties

STEP 2: Set the parameter:

idea.max.intellisense.filesize= 999999999

Best way to style a TextBox in CSS

You Also wanna put some text (placeholder) in the empty input box for the

_x000D_
_x000D_
.myClass {_x000D_
   ::-webkit-input-placeholder {_x000D_
    color: #f00;_x000D_
  }_x000D_
   ::-moz-placeholder {_x000D_
    color: #f00;_x000D_
  }_x000D_
  /* firefox 19+ */_x000D_
   :-ms-input-placeholder {_x000D_
    color: #f00;_x000D_
  }_x000D_
  /* ie */_x000D_
  input:-moz-placeholder {_x000D_
    color: #f00;_x000D_
  }_x000D_
}
_x000D_
<input type="text" class="myClass" id="fname" placeholder="Enter First Name Here!">
_x000D_
_x000D_
_x000D_

user to understand what to type.

How to close IPython Notebook properly?

Option 1

Open a different console and run

jupyter notebook stop [PORT]

The default [PORT] is 8888, so, assuming that Jupyter Notebooks is running on port 8888, just run

jupyter notebook stop

If it is on port 9000, then

jupyter notebook stop 9000

Option 2 (Source)

  1. Check runtime folder location

    jupyter --paths
    
  2. Remove all files in the runtime folder

    rm -r [RUNTIME FOLDER PATH]/*
    
  3. Use top to find any Jupyter Notebook running processes left and if so kill their PID.

    top | grep jupyter &
    kill [PID]
    

One can boilt it down to

TARGET_PORT=8888
kill -9 $(lsof -n -i4TCP:$TARGET_PORT | cut -f 2 -d " ")

Note: If one wants to launch one's Notebook on a specific IP/Port

jupyter notebook --ip=[ADD_IP] --port=[ADD_PORT] --allow-root &

Error renaming a column in MySQL

Renaming a column in MySQL :

ALTER TABLE mytable CHANGE current_column_name new_column_name DATATYPE;

Long Press in JavaScript?

You can check the time to identify Click or Long Press [jQuery]

function AddButtonEventListener() {
try {
    var mousedowntime;
    var presstime;
    $("button[id$='" + buttonID + "']").mousedown(function() {
        var d = new Date();
        mousedowntime = d.getTime();
    });
    $("button[id$='" + buttonID + "']").mouseup(function() {
        var d = new Date();
        presstime = d.getTime() - mousedowntime;
        if (presstime > 999/*You can decide the time*/) {
            //Do_Action_Long_Press_Event();
        }
        else {
            //Do_Action_Click_Event();
        }
    });
}
catch (err) {
    alert(err.message);
}
} 

How to make a promise from setTimeout

Update (2017)

Here in 2017, Promises are built into JavaScript, they were added by the ES2015 spec (polyfills are available for outdated environments like IE8-IE11). The syntax they went with uses a callback you pass into the Promise constructor (the Promise executor) which receives the functions for resolving/rejecting the promise as arguments.

First, since async now has a meaning in JavaScript (even though it's only a keyword in certain contexts), I'm going to use later as the name of the function to avoid confusion.

Basic Delay

Using native promises (or a faithful polyfill) it would look like this:

function later(delay) {
    return new Promise(function(resolve) {
        setTimeout(resolve, delay);
    });
}

Note that that assumes a version of setTimeout that's compliant with the definition for browsers where setTimeout doesn't pass any arguments to the callback unless you give them after the interval (this may not be true in non-browser environments, and didn't used to be true on Firefox, but is now; it's true on Chrome and even back on IE8).

Basic Delay with Value

If you want your function to optionally pass a resolution value, on any vaguely-modern browser that allows you to give extra arguments to setTimeout after the delay and then passes those to the callback when called, you can do this (current Firefox and Chrome; IE11+, presumably Edge; not IE8 or IE9, no idea about IE10):

function later(delay, value) {
    return new Promise(function(resolve) {
        setTimeout(resolve, delay, value); // Note the order, `delay` before `value`
        /* Or for outdated browsers that don't support doing that:
        setTimeout(function() {
            resolve(value);
        }, delay);
        Or alternately:
        setTimeout(resolve.bind(null, value), delay);
        */
    });
}

If you're using ES2015+ arrow functions, that can be more concise:

function later(delay, value) {
    return new Promise(resolve => setTimeout(resolve, delay, value));
}

or even

const later = (delay, value) =>
    new Promise(resolve => setTimeout(resolve, delay, value));

Cancellable Delay with Value

If you want to make it possible to cancel the timeout, you can't just return a promise from later, because promises can't be cancelled.

But we can easily return an object with a cancel method and an accessor for the promise, and reject the promise on cancel:

const later = (delay, value) => {
    let timer = 0;
    let reject = null;
    const promise = new Promise((resolve, _reject) => {
        reject = _reject;
        timer = setTimeout(resolve, delay, value);
    });
    return {
        get promise() { return promise; },
        cancel() {
            if (timer) {
                clearTimeout(timer);
                timer = 0;
                reject();
                reject = null;
            }
        }
    };
};

Live Example:

_x000D_
_x000D_
const later = (delay, value) => {_x000D_
    let timer = 0;_x000D_
    let reject = null;_x000D_
    const promise = new Promise((resolve, _reject) => {_x000D_
        reject = _reject;_x000D_
        timer = setTimeout(resolve, delay, value);_x000D_
    });_x000D_
    return {_x000D_
        get promise() { return promise; },_x000D_
        cancel() {_x000D_
            if (timer) {_x000D_
                clearTimeout(timer);_x000D_
                timer = 0;_x000D_
                reject();_x000D_
                reject = null;_x000D_
            }_x000D_
        }_x000D_
    };_x000D_
};_x000D_
_x000D_
const l1 = later(100, "l1");_x000D_
l1.promise_x000D_
  .then(msg => { console.log(msg); })_x000D_
  .catch(() => { console.log("l1 cancelled"); });_x000D_
_x000D_
const l2 = later(200, "l2");_x000D_
l2.promise_x000D_
  .then(msg => { console.log(msg); })_x000D_
  .catch(() => { console.log("l2 cancelled"); });_x000D_
setTimeout(() => {_x000D_
  l2.cancel();_x000D_
}, 150);
_x000D_
_x000D_
_x000D_


Original Answer from 2014

Usually you'll have a promise library (one you write yourself, or one of the several out there). That library will usually have an object that you can create and later "resolve," and that object will have a "promise" you can get from it.

Then later would tend to look something like this:

function later() {
    var p = new PromiseThingy();
    setTimeout(function() {
        p.resolve();
    }, 2000);

    return p.promise(); // Note we're not returning `p` directly
}

In a comment on the question, I asked:

Are you trying to create your own promise library?

and you said

I wasn't but I guess now that's actually what I was trying to understand. That how a library would do it

To aid that understanding, here's a very very basic example, which isn't remotely Promises-A compliant: Live Copy

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Very basic promises</title>
</head>
<body>
  <script>
    (function() {

      // ==== Very basic promise implementation, not remotely Promises-A compliant, just a very basic example
      var PromiseThingy = (function() {

        // Internal - trigger a callback
        function triggerCallback(callback, promise) {
          try {
            callback(promise.resolvedValue);
          }
          catch (e) {
          }
        }

        // The internal promise constructor, we don't share this
        function Promise() {
          this.callbacks = [];
        }

        // Register a 'then' callback
        Promise.prototype.then = function(callback) {
          var thispromise = this;

          if (!this.resolved) {
            // Not resolved yet, remember the callback
            this.callbacks.push(callback);
          }
          else {
            // Resolved; trigger callback right away, but always async
            setTimeout(function() {
              triggerCallback(callback, thispromise);
            }, 0);
          }
          return this;
        };

        // Our public constructor for PromiseThingys
        function PromiseThingy() {
          this.p = new Promise();
        }

        // Resolve our underlying promise
        PromiseThingy.prototype.resolve = function(value) {
          var n;

          if (!this.p.resolved) {
            this.p.resolved = true;
            this.p.resolvedValue = value;
            for (n = 0; n < this.p.callbacks.length; ++n) {
              triggerCallback(this.p.callbacks[n], this.p);
            }
          }
        };

        // Get our underlying promise
        PromiseThingy.prototype.promise = function() {
          return this.p;
        };

        // Export public
        return PromiseThingy;
      })();

      // ==== Using it

      function later() {
        var p = new PromiseThingy();
        setTimeout(function() {
          p.resolve();
        }, 2000);

        return p.promise(); // Note we're not returning `p` directly
      }

      display("Start " + Date.now());
      later().then(function() {
        display("Done1 " + Date.now());
      }).then(function() {
        display("Done2 " + Date.now());
      });

      function display(msg) {
        var p = document.createElement('p');
        p.innerHTML = String(msg);
        document.body.appendChild(p);
      }
    })();
  </script>
</body>
</html>

How do I make a https post in Node Js without any third party module?

For example, like this:

const querystring = require('querystring');
const https = require('https');

var postData = querystring.stringify({
    'msg' : 'Hello World!'
});

var options = {
  hostname: 'posttestserver.com',
  port: 443,
  path: '/post.php',
  method: 'POST',
  headers: {
       'Content-Type': 'application/x-www-form-urlencoded',
       'Content-Length': postData.length
     }
};

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});

req.write(postData);
req.end();

How to fit a smooth curve to my data in R?

The other answers are all good approaches. However, there are a few other options in R that haven't been mentioned, including lowess and approx, which may give better fits or faster performance.

The advantages are more easily demonstrated with an alternate dataset:

sigmoid <- function(x)
{
  y<-1/(1+exp(-.15*(x-100)))
  return(y)
}

dat<-data.frame(x=rnorm(5000)*30+100)
dat$y<-as.numeric(as.logical(round(sigmoid(dat$x)+rnorm(5000)*.3,0)))

Here is the data overlaid with the sigmoid curve that generated it:

Data

This sort of data is common when looking at a binary behavior among a population. For example, this might be a plot of whether or not a customer purchased something (a binary 1/0 on the y-axis) versus the amount of time they spent on the site (x-axis).

A large number of points are used to better demonstrate the performance differences of these functions.

Smooth, spline, and smooth.spline all produce gibberish on a dataset like this with any set of parameters I have tried, perhaps due to their tendency to map to every point, which does not work for noisy data.

The loess, lowess, and approx functions all produce usable results, although just barely for approx. This is the code for each using lightly optimized parameters:

loessFit <- loess(y~x, dat, span = 0.6)
loessFit <- data.frame(x=loessFit$x,y=loessFit$fitted)
loessFit <- loessFit[order(loessFit$x),]

approxFit <- approx(dat,n = 15)

lowessFit <-data.frame(lowess(dat,f = .6,iter=1))

And the results:

plot(dat,col='gray')
curve(sigmoid,0,200,add=TRUE,col='blue',)
lines(lowessFit,col='red')
lines(loessFit,col='green')
lines(approxFit,col='purple')
legend(150,.6,
       legend=c("Sigmoid","Loess","Lowess",'Approx'),
       lty=c(1,1),
       lwd=c(2.5,2.5),col=c("blue","green","red","purple"))

Fits

As you can see, lowess produces a near perfect fit to the original generating curve. Loess is close, but experiences a strange deviation at both tails.

Although your dataset will be very different, I have found that other datasets perform similarly, with both loess and lowess capable of producing good results. The differences become more significant when you look at benchmarks:

> microbenchmark::microbenchmark(loess(y~x, dat, span = 0.6),approx(dat,n = 20),lowess(dat,f = .6,iter=1),times=20)
Unit: milliseconds
                           expr        min         lq       mean     median        uq        max neval cld
  loess(y ~ x, dat, span = 0.6) 153.034810 154.450750 156.794257 156.004357 159.23183 163.117746    20   c
            approx(dat, n = 20)   1.297685   1.346773   1.689133   1.441823   1.86018   4.281735    20 a  
 lowess(dat, f = 0.6, iter = 1)   9.637583  10.085613  11.270911  11.350722  12.33046  12.495343    20  b 

Loess is extremely slow, taking 100x as long as approx. Lowess produces better results than approx, while still running fairly quickly (15x faster than loess).

Loess also becomes increasingly bogged down as the number of points increases, becoming unusable around 50,000.

EDIT: Additional research shows that loess gives better fits for certain datasets. If you are dealing with a small dataset or performance is not a consideration, try both functions and compare the results.

Adding a regression line on a ggplot

The simple solution using geom_abline:

geom_abline(slope = coef(data.lm)[[2]], intercept = coef(data.lm)[[1]])

Where data.lm is an lm object, and coef(data.lm) looks something like this:

> coef(data.lm)
(Intercept)    DepDelay 
  -2.006045    1.025109 

The numeric indexing assumes that (Intercept) is listed first, which is the case if the model includes an intercept. If you have some other linear model object, just plug in the slope and intercept values similarly.

Reading from file using read() function

Read Byte by Byte and check that each byte against '\n' if it is not, then store it into buffer
if it is '\n' add '\0' to buffer and then use atoi()

You can read a single byte like this

char c;
read(fd,&c,1);

See read()

Can you do greater than comparison on a date in a Rails 3 search?

Rails 6.1 added a new 'syntax' for comparison operators in where conditions, for example:

Post.where('id >': 9)
Post.where('id >=': 9)
Post.where('id <': 3)
Post.where('id <=': 3)

So your query can be rewritten as follows:

Note
  .where(user_id: current_user.id, notetype: p[:note_type], 'date >', p[:date])
  .order(date: :asc, created_at: :asc)

Here is a link to PR where you can find more examples.

Constructor of an abstract class in C#

It's there to enforce some initialization logic required by all implementations of your abstract class, or any methods you have implemented on your abstract class (not all the methods on your abstract class have to be abstract, some can be implemented).

Any class which inherits from your abstract base class will be obliged to call the base constructor.

Way to get number of digits in an int?

Curious, I tried to benchmark it ...

import org.junit.Test;
import static org.junit.Assert.*;


public class TestStack1306727 {

    @Test
    public void bench(){
        int number=1000;
        int a= String.valueOf(number).length();
        int b= 1 + (int)Math.floor(Math.log10(number));

        assertEquals(a,b);
        int i=0;
        int s=0;
        long startTime = System.currentTimeMillis();
        for(i=0, s=0; i< 100000000; i++){
            a= String.valueOf(number).length();
            s+=a;
        }
        long stopTime = System.currentTimeMillis();
        long runTime = stopTime - startTime;
        System.out.println("Run time 1: " + runTime);
        System.out.println("s: "+s);
        startTime = System.currentTimeMillis();
        for(i=0,s=0; i< 100000000; i++){
            b= number==0?1:(1 + (int)Math.floor(Math.log10(Math.abs(number))));
            s+=b;
        }
        stopTime = System.currentTimeMillis();
        runTime = stopTime - startTime;
        System.out.println("Run time 2: " + runTime);
        System.out.println("s: "+s);
        assertEquals(a,b);


    }
}

the results are :

Run time 1: 6765
s: 400000000
Run time 2: 6000
s: 400000000

Now I am left to wonder if my benchmark actually means something but I do get consistent results (variations within a ms) over multiple runs of the benchmark itself ... :) It looks like it's useless to try and optimize this...


edit: following ptomli's comment, I replaced 'number' by 'i' in the code above and got the following results over 5 runs of the bench :

Run time 1: 11500
s: 788888890
Run time 2: 8547
s: 788888890

Run time 1: 11485
s: 788888890
Run time 2: 8547
s: 788888890

Run time 1: 11469
s: 788888890
Run time 2: 8547
s: 788888890

Run time 1: 11500
s: 788888890
Run time 2: 8547
s: 788888890

Run time 1: 11484
s: 788888890
Run time 2: 8547
s: 788888890

Android 5.0 - Add header/footer to a RecyclerView

my "keep it simple stupid" way ...it waste some resources , i know , but i dont care as my code keep simple so... First, add a footer with visibility GONE to your item_layout

<LinearLayout
        android:id="@+id/footer"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:orientation="vertical"
        android:visibility="gone">
</LinearLayout>

Then, set it visible on the last item

public void onBindViewHolder(ChannelAdapter.MyViewHolder holder, int position) {
        boolean last = position==data.size()-1;
        //....
        holder.footer.setVisibility(View.GONE);
        if (last && showFooter){
            holder.footer.setVisibility(View.VISIBLE);
        }
    }

do the opposite for header

error, string or binary data would be truncated when trying to insert

When I tried to execute my stored procedure I had the same problem because the size of the column that I need to add some data is shorter than the data I want to add.

You can increase the size of the column data type or reduce the length of your data.

Why can't overriding methods throw exceptions broader than the overridden method?

In my opinion, it is a fail in the Java syntax design. Polymorphism shouldn't limit the usage of exception handling. In fact, other computer languages don't do it (C#).

Moreover, a method is overriden in a more specialiced subclass so that it is more complex and, for this reason, more probable to throwing new exceptions.

How to run Conda?

To edit bashrc in Ubuntu

$ /usr/bin/vim ~/.bashrc

type PATH=$PATH:$HOME/anaconda3/bin Press Esc and :wq to save bashrc file and exit vim enter image description here

then

$ export PATH=~/anaconda3/bin:$PATH

and type $ source ~/.bashrc Now to confirm the installation of conda type

$ conda --version

Datatables - Setting column width

I set the column widths in the HTML markup like so:

    <thead>
        <tr>

            <th style='width: 5%;'>ProjectId</th>
            <th style='width: 15%;'>Title</th>
            <th style='width: 40%;'>Abstract</th>
            <th style='width: 20%;'>Keywords</th>
            <th style='width: 10%;'>PaperName</th>
            <th style='width: 10%;'>PaperURL</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr id="@item.ID">
                <td>@item.ProjectId</td>
                <td>@item.Title</td>
                <td>@item.Abstract</td>
                <td>@item.Keywords</td>
                <td>@item.PaperName</td>
                <td>@item.PaperURL</td>
            </tr>
        }
    </tbody>
</table>

How to run shell script file using nodejs?

you can go:

var cp = require('child_process');

and then:

cp.exec('./myScript.sh', function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a command in your $SHELL.
Or go

cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a file WITHOUT a shell.
Or go

cp.execFile();

which is the same as cp.exec() but doesn't look in the $PATH.

You can also go

cp.fork('myJS.js', function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a javascript file with node.js, but in a child process (for big programs).

EDIT

You might also have to access stdin and stdout with event listeners. e.g.:

var child = cp.spawn('./myScript.sh', [args]);
child.stdout.on('data', function(data) {
  // handle stdout as `data`
});

Last element in .each() set

For future Googlers i've a different approach to check if it's last element. It's similar to last lines in OP question.

This directly compares elements rather than just checking index numbers.

$yourset.each(function() {
    var $this = $(this);
    if($this[0] === $yourset.last()[0]) {
        //$this is the last one
    }
});

Set value to an entire column of a pandas dataframe

I had a similar issue before even with this approach df.loc[:,'industry'] = 'yyy', but once I refreshed the notebook, it ran well.

You may want to try refreshing the cells after you have df.loc[:,'industry'] = 'yyy'.

In Python, how do you convert seconds since epoch to a `datetime` object?

Seconds since epoch to datetime to strftime:

>>> ts_epoch = 1362301382
>>> ts = datetime.datetime.fromtimestamp(ts_epoch).strftime('%Y-%m-%d %H:%M:%S')
>>> ts
'2013-03-03 01:03:02'

Set JavaScript variable = null, or leave undefined?

Generally, I use null for values that I know can have a "null" state; for example

if(jane.isManager == false){
  jane.employees = null
}

Otherwise, if its a variable or function that's not defined yet (and thus, is not "usable" at the moment) but is supposed to be setup later, I usually leave it undefined.

Android error: Failed to install *.apk on device *: timeout

I used to have this problem sometimes, the solution was to change the USB cable to a new one

Persist javascript variables across pages?

Yes, using Cookies. But be careful, don't put too much in them (I think there is a limit at 4kb). But a few variables are ok.

If you need to store considerably more than that, check out @Annie's great tips in the other answer. For small time data storage, I would say Cookies are the easiest thing.

Note that cookies are stored client side.

remove borders around html input

It's simple

input {border:0;outline:0;}
input:focus {outline:none!important;}

What are the ascii values of up down left right?

The Ascii codes for arrow characters are the following: ? 24 ? 25 ? 26 ? 27

How can I use optional parameters in a T-SQL stored procedure?

Extend your WHERE condition:

WHERE
    (FirstName = ISNULL(@FirstName, FirstName)
    OR COALESCE(@FirstName, FirstName, '') = '')
AND (LastName = ISNULL(@LastName, LastName)
    OR COALESCE(@LastName, LastName, '') = '')
AND (Title = ISNULL(@Title, Title)
    OR COALESCE(@Title, Title, '') = '')

i. e. combine different cases with boolean conditions.

angular 4: *ngIf with multiple conditions

<div *ngIf="currentStatus !== ('status1' || 'status2' || 'status3' || 'status4')">

Jersey client: How to add a list as query parameter

If you are sending anything other than simple strings I would recommend using a POST with an appropriate request body, or passing the entire list as an appropriately encoded JSON string. However, with simple strings you just need to append each value to the request URL appropriately and Jersey will deserialize it for you. So given the following example endpoint:

@Path("/service/echo") public class MyServiceImpl {
    public MyServiceImpl() {
        super();
    }

    @GET
    @Path("/withlist")
    @Produces(MediaType.TEXT_PLAIN)
    public Response echoInputList(@QueryParam("list") final List<String> inputList) {
        return Response.ok(inputList).build();
    }
}

Your client would send a request corresponding to:

GET http://example.com/services/echo?list=Hello&list=Stay&list=Goodbye

Which would result in inputList being deserialized to contain the values 'Hello', 'Stay' and 'Goodbye'

Can't find/install libXtst.so.6?

This worked for me in Luna elementary OS

sudo apt-get install libxtst6:i386

How can I insert vertical blank space into an html document?

i always use this cheap word for vertical spaces.

    <p>Q1</p>
    <br>
    <p>Q2</p>

Remove an onclick listener

Just reinitializing item as below would do the trick. It would remove onclick,onlonglick,onitemclick,onitemlongclick based on item

mTitleView = findViewById(R.id.mTitleView);

PHP - Notice: Undefined index:

How are you loading this page? Is it getting anything on POST to load? If it's not, then the $name = $_POST['Name']; assignation doesn't have any 'Name' on POST.

What "wmic bios get serialnumber" actually retrieves?

wmic bios get serialnumber     

if run from a command line (start-run should also do the trick) prints out on screen the Serial Number of the product,
(for example in a toshiba laptop it would print out the serial number of the laptop.
with this serial number you can then identify your laptop model if you need ,from the makers service website-usually..:):)

I had to do exactly that.:):)

Setting state on componentDidMount()

The only reason that the linter complains about using setState({..}) in componentDidMount and componentDidUpdate is that when the component render the setState immediately causes the component to re-render. But the most important thing to note: using it inside these component's lifecycles is not an anti-pattern in React.

Please take a look at this issue. you will understand more about this topic. Thanks for reading my answer.

arranging div one below the other

The default behaviour of divs is to take the full width available in their parent container.
This is the same as if you'd give the inner divs a width of 100%.

By floating the divs, they ignore their default and size their width to fit the content. Everything behind it (in the HTML), is placed under the div (on the rendered page).
This is the reason that they align theirselves next to each other.

The float CSS property specifies that an element should be taken from the normal flow and placed along the left or right side of its container, where text and inline elements will wrap around it. A floating element is one where the computed value of float is not none.

Source: https://developer.mozilla.org/en-US/docs/Web/CSS/float

Get rid of the float, and the divs will be aligned under each other.
If this does not happen, you'll have some other css on divs or children of wrapper defining a floating behaviour or an inline display.

If you want to keep the float, for whatever reason, you can use clear on the 2nd div to reset the floating properties of elements before that element.
clear has 5 valid values: none | left | right | both | inherit. Clearing no floats (used to override inherited properties), left or right floats or both floats. Inherit means it'll inherit the behaviour of the parent element

Also, because of the default behaviour, you don't need to set the width and height on auto.
You only need this is you want to set a hardcoded height/width. E.g. 80% / 800px / 500em / ...

<div id="wrapper">
    <div id="inner1"></div>
    <div id="inner2"></div>
</div>

CSS is

#wrapper{
    margin-left:auto;
    margin-right:auto;
    height:auto; // this is not needed, as parent container, this div will size automaticly
    width:auto; // this is not needed, as parent container, this div will size automaticly
}

/*
You can get rid of the inner divs in the css, unless you want to style them.
If you want to style them identicly, you can use concatenation
*/
#inner1, #inner2 {
    border: 1px solid black;
}

Remove header and footer from window.print()

I am sure Adding this code on your css file will solve the problem

<style type="text/css" media="print">
    @page 
    {
        size: auto;   /* auto is the initial value */
        margin: 0mm;  /* this affects the margin in the printer settings */
    }
</style>

You may visit this to know more about this

substring of an entire column in pandas dataframe

case the column isn't string, use astype to convert:

df['col'] = df['col'].astype(str).str[:9]

Excel how to fill all selected blank cells with text

To put the same text in a certain number of cells do the following:

  1. Highlight the cells you want to put text into
  2. Type into the cell you're currently in the data you want to be repeated
  3. Hold Crtl and press 'return'

You will find that all the highlighted cells now have the same data in them. Have a nice day.

Tkinter example code for multiple windows, why won't buttons load correctly?

You need to specify the master for the second button. Otherwise it will get packed onto the first window. This is needed not only for Button, but also for other widgets and non-gui objects such as StringVar.

Quick fix: add the frame new as the first argument to your Button in Demo2.

Possibly better: Currently you have Demo2 inheriting from tk.Frame but I think this makes more sense if you change Demo2 to be something like this,

class Demo2(tk.Toplevel):     
    def __init__(self):
        tk.Toplevel.__init__(self)
        self.title("Demo 2")
        self.button = tk.Button(self, text="Button 2", # specified self as master
                                width=25, command=self.close_window)
        self.button.pack()

    def close_window(self):
        self.destroy()

Just as a suggestion, you should only import tkinter once. Pick one of your first two import statements.

Why is there no ForEach extension method on IEnumerable?

Is it me or is the List<T>.Foreach pretty much been made obsolete by Linq. Originally there was

foreach(X x in Y) 

where Y simply had to be IEnumerable (Pre 2.0), and implement a GetEnumerator(). If you look at the MSIL generated you can see that it is exactly the same as

IEnumerator<int> enumerator = list.GetEnumerator();
while (enumerator.MoveNext())
{
    int i = enumerator.Current;

    Console.WriteLine(i);
}

(See http://alski.net/post/0a-for-foreach-forFirst-forLast0a-0a-.aspx for the MSIL)

Then in DotNet2.0 Generics came along and the List. Foreach has always felt to me to be an implementation of the Vistor pattern, (see Design Patterns by Gamma, Helm, Johnson, Vlissides).

Now of course in 3.5 we can instead use a Lambda to the same effect, for an example try http://dotnet-developments.blogs.techtarget.com/2008/09/02/iterators-lambda-and-linq-oh-my/

find if an integer exists in a list of integers

You should be referencing Selected not ids.Contains as the last line.

I just realized this is a formatting issue, from the OP. Regardless you should be referencing the value in Selected. I recommend adding some Console.WriteLine calls to see exactly what is being printed out on each line and also what each value is.

After your update: ids is an empty list, how is this not throwing a NullReferenceException? As it was never initialized in that code block

When to use Comparable and Comparator

If you own the class better go with Comparable. Generally Comparator is used if you dont own the class but you have to use it a TreeSet or TreeMap because Comparator can be passed as a parameter in the conctructor of TreeSet or TreeMap. You can see how to use Comparator and Comparable in http://preciselyconcise.com/java/collections/g_comparator.php

How to set xlim and ylim for a subplot in matplotlib

You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.* function are thin wrappers that basically do gca().*.

plt.subplot returns an axes object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.

import matplotlib.pyplot as plt

ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])


ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])

and so on for as many axes as you want.

or better, wrap it all up in a loop:

import matplotlib.pyplot as plt

DATA_x = ([1, 2],
          [2, 3],
          [3, 4])

DATA_y = DATA_x[::-1]

XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3

for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
    ax = plt.subplot(1, 3, j + 1)
    ax.scatter(x, y)
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

Substring a string from the end of the string

C# 8 introduced indices and ranges which allow you to write

str[^2..]

This is equivalent to

str.Substring(str.Length - 2, str.Length)

In fact, this is almost exactly what the compiler will generate, so there's no overhead.

Note that you will get an ArgumentOutOfRangeException if the range isn't within the string.

How to get all key in JSON object (javascript)

var jsonData = { Name: "Ricardo Vasquez", age: "46", Email: "[email protected]" };

for (x in jsonData) {   
  console.log(x +" => "+ jsonData[x]);  
  alert(x +" => "+  jsonData[x]);  
  }

Atom menu is missing. How do I re-enable

Open atom editor and then press Alt and menu bar will appear. Now click on View tab and then click on Toggle Menu Bar as seen on this screenshot.

What are static factory methods?

If the constructor of a class is private then you cannot create an object for class from outside of it.

class Test{
 int x, y;
 private Test(){
  .......
  .......
  }
}

We cannot create an object for above class from outside of it. So you cannot access x, y from outside of the class. Then what is the use of this class?
Here is the Answer : FACTORY method.
Add the below method in above class

public static Test getObject(){
  return new Test();
}

So now you can create an object for this class from outside of it. Like the way...

Test t = Test.getObject();

Hence, a static method which returns the object of the class by executing its private constructor is called as FACTORY method
.

angular.js ng-repeat li items with html content

Note that ng-bind-html-unsafe is no longer suppported in rc 1.2. Use ng-bind-html instead. See: With ng-bind-html-unsafe removed, how do I inject HTML?

Laravel 5 Application Key

Just as another option if you want to print only the key (doesn't write the .env file) you can use:

php artisan key:generate --show

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

I had a similar issue:

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

But in my case, the cause was really silly. I copied the command from a Word document, and the problem was that an hyphen did not have the ASCII 2D code but the Unicode E28093.

Wrong way:

mysql -u root –pxxxx

Right way:

mysql -u root -pxxxx

Both look the same but aren't the same (try it, copy and paste replacing your password).

Faced with this type of error, the recommendation is to try typing the command instead of copying and pasting.

Change bullets color of an HTML list without using span

I managed this without adding markup, but instead using li:before. This obviously has all the limitations of :before (no old IE support), but it seems to work with IE8, Firefox and Chrome after some very limited testing. The bullet style is also limited by what's in unicode.

_x000D_
_x000D_
li {_x000D_
  list-style: none;_x000D_
}_x000D_
li:before {_x000D_
  /* For a round bullet */_x000D_
  content: '\2022';_x000D_
  /* For a square bullet */_x000D_
  /*content:'\25A0';*/_x000D_
  display: block;_x000D_
  position: relative;_x000D_
  max-width: 0;_x000D_
  max-height: 0;_x000D_
  left: -10px;_x000D_
  top: 0;_x000D_
  color: green;_x000D_
  font-size: 20px;_x000D_
}
_x000D_
<ul>_x000D_
  <li>foo</li>_x000D_
  <li>bar</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How do I determine if a checkbox is checked?

_x000D_
_x000D_
var elementCheckBox = document.getElementById("IdOfCheckBox");_x000D_
_x000D_
_x000D_
elementCheckBox[0].checked //return true if checked and false if not checked
_x000D_
_x000D_
_x000D_

thanks

IntelliJ - show where errors are

In my case, I unknowingly unchecked 'Error Stripe Mark' option (Idea 2018.2: Settings > Editor > Color Scheme > General and expand `Error and Warnings' & click 'Error').

Fix is to check 'Error Stripe Mark' option of 'Error' (as highlighted in the below image). Now you will see the error marks in scrollbar area.

enter image description here

Checking for a null int value from a Java ResultSet

Just check if the field is null or not using ResultSet#getObject(). Substitute -1 with whatever null-case value you want.

int foo = resultSet.getObject("foo") != null ? resultSet.getInt("foo") : -1;

Or, if you can guarantee that you use the right DB column type so that ResultSet#getObject() really returns an Integer (and thus not Long, Short or Byte), then you can also just typecast it to an Integer.

Integer foo = (Integer) resultSet.getObject("foo");

How to re-sync the Mysql DB if Master and slave have different database incase of Mysql replication?

Following up on David's answer...

Using SHOW SLAVE STATUS\G will give human-readable output.

How to sum all column values in multi-dimensional array?

$sumArray = array();
foreach ($myArray as $k => $subArray) {
    foreach ($subArray as $id => $value) {
        if (!isset($sumArray[$id])) {
            $sumArray[$id] = 0;
        }
        $sumArray[$id]+=$value;
    }
}

How to detect idle time in JavaScript elegantly?

Similar to Iconic's solution above (with jQuery custom event)...

// use jquery-idle-detect.js script below
$(window).on('idle:start', function(){
  //start your prefetch etc here...
});

$(window).on('idle:stop', function(){
  //stop your prefetch etc here...
});

//jquery-idle-detect.js
(function($,$w){
  // expose configuration option
  // idle is triggered when no events for 2 seconds
  $.idleTimeout = 2000;

  // currently in idle state
  var idle = false;

  // handle to idle timer for detection
  var idleTimer = null;

  //start idle timer and bind events on load (not dom-ready)
  $w.on('load', function(){
    startIdleTimer();
    $w.on('focus resize mousemove keyup', startIdleTimer)
      .on('blur',idleStart) //force idle when in a different tab/window
      ;
  ]);

  function startIdleTimer() {
    clearTimeout(idleTimer); //clear prior timer

    if (idle) $w.trigger('idle:stop'); //if idle, send stop event
    idle = false; //not idle

    var timeout = ~~$.idleTimeout; // option to integer
    if (timeout <= 100) timeout = 100; // min 100ms
    if (timeout > 300000) timeout = 300000; // max 5 minutes

    idleTimer = setTimeout(idleStart, timeout); //new timer
  }

  function idleStart() {
    if (!idle) $w.trigger('idle:start');
    idle = true;
  }

}(window.jQuery, window.jQuery(window)))

Excel VBA Run Time Error '424' object required

You have two options,

-If you want the value:

Dim MyValue as Variant ' or string/date/long/...
MyValue = ThisWorkbook.Sheets(1).Range("A1").Value

-if you want the cell object:

Dim oCell as Range  ' or object (but then you'll miss out on intellisense), and both can also contain more than one cell.
Set oCell = ThisWorkbook.Sheets(1).Range("A1")

Java NoSuchAlgorithmException - SunJSSE, sun.security.ssl.SSLContextImpl$DefaultSSLContext

Well after doing some more searching I discovered the error may be related to other issues as invalid keystores, passwords etc.

I then remembered that I had set two VM arguments for when I was testing SSL for my network connectivity.

I removed the following VM arguments to fix the problem:

-Djavax.net.ssl.keyStore=mySrvKeystore -Djavax.net.ssl.keyStorePassword=123456

Note: this keystore no longer exists so that's probably why the Exception.

SQL Server 2012 Install or add Full-text search

You can add full text to an existing instance by changing the SQL Server program in Programs and Features. Follow the steps below. You might need the original disk or ISO for the installation to complete. (Per HotN's comment: If you have SQL Server Express, make sure it is SQL Server Express With Advanced Services.)

Directions:

  1. Open the Programs and Features control panel.
  2. Select Microsoft SQL Server 2012 and click Change.
  3. When prompted to Add/Repair/Remove, select Add.
  4. Advance through the wizard until the Feature Selection screen. Then select Full-Text Search.

Step 1 Step 2

enter image description here

  1. On the Installation Type screen, select the appropriate SQL Server instance.

  2. Advance through the rest of the wizard.

Source (with screenshots): http://www.techrepublic.com/blog/networking/adding-sql-full-text-search-to-an-existing-sql-server/5546

Most concise way to convert a Set<T> to a List<T>

Considering that we have Set<String> stringSet we can use following:

Plain Java

List<String> strList = new ArrayList<>(stringSet);

Guava

List<String> strList = Lists.newArrayList(stringSet);

Apache Commons

List<String> strList = new ArrayList<>();
CollectionUtils.addAll(strList, stringSet);

Java 10 (Unmodifiable List)

List<String> strList = List.copyOf(stringSet);
List<String> strList = stringSet.stream().collect(Collectors.toUnmodifiableList());

Java 8 (Modifiable Lists)

import static java.util.stream.Collectors.*;
List<String> stringList1 = stringSet.stream().collect(toList());

As per the doc for the method toList()

There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; if more control over the returned List is required, use toCollection(Supplier).

So if we need a specific implementation e.g. ArrayList we can get it this way:

List<String> stringList2 = stringSet.stream().
                              collect(toCollection(ArrayList::new));

Java 8 (Unmodifiable Lists)

We can make use of Collections::unmodifiableList method and wrap the list returned in previous examples. We can also write our own custom method as:

class ImmutableCollector {
    public static <T> Collector<T, List<T>, List<T>> toImmutableList(Supplier<List<T>> supplier) {
            return Collector.of( supplier, List::add, (left, right) -> {
                        left.addAll(right);
                        return left;
                    }, Collections::unmodifiableList);
        }
}

And then use it as:

List<String> stringList3 = stringSet.stream()
             .collect(ImmutableCollector.toImmutableList(ArrayList::new)); 

Another possibility is to make use of collectingAndThen method which allows some final transformation to be done before returning result:

    List<String> stringList4 = stringSet.stream().collect(collectingAndThen(
      toCollection(ArrayList::new),Collections::unmodifiableList));

One point to note is that the method Collections::unmodifiableList returns an unmodifiable view of the specified list, as per doc. An unmodifiable view collection is a collection that is unmodifiable and is also a view onto a backing collection. Note that changes to the backing collection might still be possible, and if they occur, they are visible through the unmodifiable view. But the collector method Collectors.unmodifiableList returns truly immutable list in Java 10.

ssh: Could not resolve hostname github.com: Name or service not known; fatal: The remote end hung up unexpectedly

Recently, I have seen this problem too. Below, you have my solution:

  1. ping github.com, if ping failed. it is DNS error.
  2. sudo vim /etc/resolv.conf, the add: nameserver 8.8.8.8 nameserver 8.8.4.4

Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart or fix it up


I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):

ssh -T [email protected]

Upon receiving a successful response, I could fetch/push to the repo with ssh.

I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.

How is Docker different from a virtual machine?

I have used Docker in production environments and staging very much. When you get used to it you will find it very powerful for building a multi container and isolated environments.

Docker has been developed based on LXC (Linux Container) and works perfectly in many Linux distributions, especially Ubuntu.

Docker containers are isolated environments. You can see it when you issue the top command in a Docker container that has been created from a Docker image.

Besides that, they are very light-weight and flexible thanks to the dockerFile configuration.

For example, you can create a Docker image and configure a DockerFile and tell that for example when it is running then wget 'this', apt-get 'that', run 'some shell script', setting environment variables and so on.

In micro-services projects and architecture Docker is a very viable asset. You can achieve scalability, resiliency and elasticity with Docker, Docker swarm, Kubernetes and Docker Compose.

Another important issue regarding Docker is Docker Hub and its community. For example, I implemented an ecosystem for monitoring kafka using Prometheus, Grafana, Prometheus-JMX-Exporter, and Docker.

For doing that, I downloaded configured Docker containers for zookeeper, kafka, Prometheus, Grafana and jmx-collector then mounted my own configuration for some of them using YAML files, or for others, I changed some files and configuration in the Docker container and I build a whole system for monitoring kafka using multi-container Dockers on a single machine with isolation and scalability and resiliency that this architecture can be easily moved into multiple servers.

Besides the Docker Hub site there is another site called quay.io that you can use to have your own Docker images dashboard there and pull/push to/from it. You can even import Docker images from Docker Hub to quay then running them from quay on your own machine.

Note: Learning Docker in the first place seems complex and hard, but when you get used to it then you can not work without it.

I remember the first days of working with Docker when I issued the wrong commands or removing my containers and all of data and configurations mistakenly.

How do I extract data from a DataTable?

Please, note that Open and Close the connection is not necessary when using DataAdapter.

So I suggest please update this code and remove the open and close of the connection:

        SqlDataAdapter adapt = new SqlDataAdapter(cmd);

conn.Open(); // this line of code is uncessessary

        Console.WriteLine("connection opened successfuly");
        adapt.Fill(table);

conn.Close(); // this line of code is uncessessary

        Console.WriteLine("connection closed successfuly");

Reference Documentation

The code shown in this example does not explicitly open and close the Connection. The Fill method implicitly opens the Connection that the DataAdapter is using if it finds that the connection is not already open. If Fill opened the connection, it also closes the connection when Fill is finished. This can simplify your code when you deal with a single operation such as a Fill or an Update. However, if you are performing multiple operations that require an open connection, you can improve the performance of your application by explicitly calling the Open method of the Connection, performing the operations against the data source, and then calling the Close method of the Connection. You should try to keep connections to the data source open as briefly as possible to free resources for use by other client applications.

How to set the maximum memory usage for JVM?

The NativeHeap can be increasded by -XX:MaxDirectMemorySize=256M (default is 128)

I've never used it. Maybe you'll find it useful.

Java: Simplest way to get last word in a string

You can do that with StringUtils (from Apache Commons Lang). It avoids index-magic, so it's easier to understand. Unfortunately substringAfterLast returns empty string when there is no separator in the input string so we need the if statement for that case.

public static String getLastWord(String input) {
    String wordSeparator = " ";
    boolean inputIsOnlyOneWord = !StringUtils.contains(input, wordSeparator);
    if (inputIsOnlyOneWord) {
        return input;
    }
    return StringUtils.substringAfterLast(input, wordSeparator);
}

Fixed positioned div within a relative parent div

Gavin,

The issue you are having is a misunderstanding of positioning. If you want it to be "fixed" relative to the parent, then you really want your #fixed to be position:absolute which will update its position relative to the parent.

This question fully describes positioning types and how to use them effectively.

In summary, your CSS should be

#wrap{ 
    position:relative;
}
#fixed{ 
    position:absolute;
    top:30px;
    left:40px;
}

SQL Query to add a new column after an existing column in SQL Server 2005

Microsoft SQL (AFAIK) does not allow you to alter the table and add a column after a specific column. Your best bet is using Sql Server Management Studio, or play around with either dropping and re-adding the table, or creating a new table and moving the data over manually. neither are very graceful.

MySQL does however:

ALTER TABLE mytable
ADD COLUMN  new_column <type>
AFTER       existing_column

load csv into 2D matrix with numpy for plotting

You can read a CSV file with headers into a NumPy structured array with np.genfromtxt. For example:

import numpy as np

csv_fname = 'file.csv'
with open(csv_fname, 'w') as fp:
    fp.write("""\
"A","B","C","D","E","F","timestamp"
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291111964948E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291113113366E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291120650486E12
""")

# Read the CSV file into a Numpy record array
r = np.genfromtxt(csv_fname, delimiter=',', names=True, case_sensitive=True)
print(repr(r))

which looks like this:

array([(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111196e+12),
       (611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111311e+12),
       (611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29112065e+12)],
      dtype=[('A', '<f8'), ('B', '<f8'), ('C', '<f8'), ('D', '<f8'), ('E', '<f8'), ('F', '<f8'), ('timestamp', '<f8')])

You can access a named column like this r['E']:

array([1715.37476, 1715.37476, 1715.37476])

Note: this answer previously used np.recfromcsv to read the data into a NumPy record array. While there was nothing wrong with that method, structured arrays are generally better than record arrays for speed and compatibility.

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

You can flip it around and list the dependencies in setup.py and have a single character — a dot . — in requirements.txt instead.


Alternatively, even if not advised, it is still possible to parse the requirements.txt file (if it doesn't refer any external requirements by URL) with the following hack (tested with pip 9.0.1):

install_reqs = parse_requirements('requirements.txt', session='hack')

This doesn't filter environment markers though.


In old versions of pip, more specifically older than 6.0, there is a public API that can be used to achieve this. A requirement file can contain comments (#) and can include some other files (--requirement or -r). Thus, if you really want to parse a requirements.txt you can use the pip parser:

from pip.req import parse_requirements

# parse_requirements() returns generator of pip.req.InstallRequirement objects
install_reqs = parse_requirements(<requirements_path>)

# reqs is a list of requirement
# e.g. ['django==1.5.1', 'mezzanine==1.4.6']
reqs = [str(ir.req) for ir in install_reqs]

setup(
    ...
    install_requires=reqs
)

Relay access denied on sending mail, Other domain outside of network

If it is giving you relay access denied when you are trying to send an email from outside your network to a domain that your server is not authoritative for then it means your receive connector does not grant you the permissions for sending/relaying. Most likely what you need to do is to authenticate to the server to be granted the permissions for relaying but that does depend upon the configuration of your receive connector. In Exchange 2007/2010/2013 you would need to enable ExchangeUsers permission group as well as an authentication mechanism such as Basic authentication.

Once you're sure your receive connector is configured make sure your email client is configured for authentication as well for the SMTP server. It depends upon your server setup but normally for Exchange you would configure the username by itself, no need for the domain to appended or prefixed to it.

To test things out with authentication via telnet you can go over my post here for directions: https://jefferyland.wordpress.com/2013/05/28/essential-exchange-troubleshooting-send-email-via-telnet/

Given URL is not allowed by the Application configuration

The other answers here are excellent and accurate. In the interest of adding to the list of things to try:

Double and triple-check that your app is using the right application ID and secret key. In my case, after trying many other things, I checked the application ID and secret key and found that I was using our production settings on our development system. Doh!

Using the correct application ID and secret key fixed the problem.

How to pass a value from one jsp to another jsp page?

Suppose we want to pass three values(u1,u2,u3) from say 'show.jsp' to another page say 'display.jsp' Make three hidden text boxes and a button that is click automatically(using javascript). //Code to written in 'show.jsp'

<body>
<form action="display.jsp" method="post">
 <input type="hidden" name="u1" value="<%=u1%>"/>
 <input type="hidden" name="u2" value="<%=u2%>" />
 <input type="hidden" name="u3" value="<%=u3%>" />
 <button type="hidden" id="qq" value="Login" style="display: none;"></button>
</form>
  <script type="text/javascript">
     document.getElementById("qq").click();
  </script>
</body>

// Code to be written in 'display.jsp'

 <% String u1 = request.getParameter("u1").toString();
    String u2 = request.getParameter("u2").toString();
    String u3 = request.getParameter("u3").toString();
 %>

If you want to use these variables of servlets in javascript then simply write

<script type="text/javascript">
 var a=<%=u1%>;
</script>

Hope it helps :)

Creating a copy of an object in C#

The easiest way to do this is writing a copy constructor in the MyClass class.

Something like this:

namespace Example
{
    class MyClass
    {
        public int val;

        public MyClass()
        {
        }

        public MyClass(MyClass other)
        {
            val = other.val;
        }
    }
}

The second constructor simply accepts a parameter of his own type (the one you want to copy) and creates a new object assigned with the same value

class Program
{
    static void Main(string[] args)
    {
        MyClass objectA = new MyClass();
        MyClass objectB = new MyClass(objectA);
        objectA.val = 10;
        objectB.val = 20;
        Console.WriteLine("objectA.val = {0}", objectA.val);
        Console.WriteLine("objectB.val = {0}", objectB.val);
        Console.ReadKey();
    }
}

output:

objectA.val = 10

objectB.val = 20               

How to 'grep' a continuous stream?

you certainly won't succeed with

tail -f /var/log/foo.log |grep --line-buffered string2search

when you use "colortail" as an alias for tail, eg. in bash

alias tail='colortail -n 30'

you can check by type alias if this outputs something like tail isan alias of colortail -n 30. then you have your culprit :)

Solution:

remove the alias with

unalias tail

ensure that you're using the 'real' tail binary by this command

type tail

which should output something like:

tail is /usr/bin/tail

and then you can run your command

tail -f foo.log |grep --line-buffered something

Good luck.

What is the best workaround for the WCF client `using` block issue?

Given a choice between the solution advocated by IServiceOriented.com and the solution advocated by David Barret's blog, I prefer the simplicity offered by overriding the client's Dispose() method. This allows me to continue to use the using() statement as one would expect with a disposable object. However, as @Brian pointed out, this solution contains a race condition in that the State might not be faulted when it is checked but could be by the time Close() is called, in which case the CommunicationException still occurs.

So, to get around this, I've employed a solution that mixes the best of both worlds.

void IDisposable.Dispose()
{
    bool success = false;
    try 
    {
        if (State != CommunicationState.Faulted) 
        {
            Close();
            success = true;
        }
    } 
    finally 
    {
        if (!success) 
            Abort();
    }
}

How to keep environment variables when using sudo

First you need to export HTTP_PROXY. Second, you need to read man sudo carefully, and pay attention to the -E flag. This works:

$ export HTTP_PROXY=foof
$ sudo -E bash -c 'echo $HTTP_PROXY'

Here is the quote from the man page:

-E, --preserve-env
             Indicates to the security policy that the user wishes to preserve their
             existing environment variables.  The security policy may return an error
             if the user does not have permission to preserve the environment.

Exit while loop by user hitting ENTER key

The exact thing you want ;)

https://stackoverflow.com/a/22391379/3394391

import sys, select, os

i = 0
while True:
    os.system('cls' if os.name == 'nt' else 'clear')
    print "I'm doing stuff. Press Enter to stop me!"
    print i
    if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
        line = raw_input()
        break
    i += 1

How to re import an updated package while in Python Interpreter?

So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me.

Yes, just saying import again gives you the existing copy of the module from sys.modules.

You can say reload(module) to update sys.modules and get a new copy of that single module, but if any other modules have a reference to the original module or any object from the original module, they will keep their old references and Very Confusing Things will happen.

So if you've got a module a, which depends on module b, and b changes, you have to ‘reload b’ followed by ‘reload a’. If you've got two modules which depend on each other, which is extremely common when those modules are part of the same package, you can't reload them both: if you reload p.a it'll get a reference to the old p.b, and vice versa. The only way to do it is to unload them both at once by deleting their items from sys.modules, before importing them again. This is icky and has some practical pitfalls to do with modules entries being None as a failed-relative-import marker.

And if you've got a module which passes references to its objects to system modules — for example it registers a codec, or adds a warnings handler — you're stuck; you can't reload the system module without confusing the rest of the Python environment.

In summary: for all but the simplest case of one self-contained module being loaded by one standalone script, reload() is very tricky to get right; if, as you imply, you are using a ‘package’, you will probably be better off continuing to cycle the interpreter.

WPF Check box: Check changed handling

Im putting this in an answer because it's too long for a comment:

If you need the VM to be aware when the CheckBox is changed, you should really bind the CheckBox to the VM, and not a static value:

public class ViewModel
{
    private bool _caseSensitive;
    public bool CaseSensitive
    {
        get { return _caseSensitive; }
        set
        {
            _caseSensitive = value;
            NotifyPropertyChange(() => CaseSensitive);

            Settings.Default.bSearchCaseSensitive = value;
        }
    }
}

XAML:

<CheckBox Content="Case Sensitive" IsChecked="{Binding CaseSensitive}"/>

pinpointing "conditional jump or move depends on uninitialized value(s)" valgrind message

What this means is that you are trying to print out/output a value which is at least partially uninitialized. Can you narrow it down so that you know exactly what value that is? After that, trace through your code to see where it is being initialized. Chances are, you will see that it is not being fully initialized.

If you need more help, posting the relevant sections of source code might allow someone to offer more guidance.

EDIT

I see you've found the problem. Note that valgrind watches for Conditional jump or move based on unitialized variables. What that means is that it will only give out a warning if the execution of the program is altered due to the uninitialized value (ie. the program takes a different branch in an if statement, for example). Since the actual arithmetic did not involve a conditional jump or move, valgrind did not warn you of that. Instead, it propagated the "uninitialized" status to the result of the statement that used it.

It may seem counterintuitive that it does not warn you immediately, but as mark4o pointed out, it does this because uninitialized values get used in C all the time (examples: padding in structures, the realloc() call, etc.) so those warnings would not be very useful due to the false positive frequency.

Can we update primary key values of a table?

From a relational database theory point of view, there should be absolutely no problem on updating the primary key of a table, provided that there are no duplicates among the primary keys and that you do not try to put a NULL value in any of the primary key columns.

What is the recommended way to make a numeric TextField in JavaFX?

Here is a simple class that handles some basic validations on TextField, using TextFormatter introduced in JavaFX 8u40

EDIT:

(Code added regarding Floern's comment)

import java.text.DecimalFormatSymbols;
import java.util.regex.Pattern;

import javafx.beans.NamedArg;
import javafx.scene.control.TextFormatter;
import javafx.scene.control.TextFormatter.Change;

public class TextFieldValidator {

    private static final String CURRENCY_SYMBOL   = DecimalFormatSymbols.getInstance().getCurrencySymbol();
    private static final char   DECIMAL_SEPARATOR = DecimalFormatSymbols.getInstance().getDecimalSeparator();

    private final Pattern       INPUT_PATTERN;

    public TextFieldValidator(@NamedArg("modus") ValidationModus modus, @NamedArg("countOf") int countOf) {
        this(modus.createPattern(countOf));
    }

    public TextFieldValidator(@NamedArg("regex") String regex) {
        this(Pattern.compile(regex));
    }

    public TextFieldValidator(Pattern inputPattern) {
        INPUT_PATTERN = inputPattern;
    }

    public static TextFieldValidator maxFractionDigits(int countOf) {
        return new TextFieldValidator(maxFractionPattern(countOf));
    }

    public static TextFieldValidator maxIntegers(int countOf) {
        return new TextFieldValidator(maxIntegerPattern(countOf));
    }

    public static TextFieldValidator integersOnly() {
        return new TextFieldValidator(integersOnlyPattern());
    }

    public TextFormatter<Object> getFormatter() {
        return new TextFormatter<>(this::validateChange);
    }

    private Change validateChange(Change c) {
        if (validate(c.getControlNewText())) {
            return c;
        }
        return null;
    }

    public boolean validate(String input) {
        return INPUT_PATTERN.matcher(input).matches();
    }

    private static Pattern maxFractionPattern(int countOf) {
        return Pattern.compile("\\d*(\\" + DECIMAL_SEPARATOR + "\\d{0," + countOf + "})?");
    }

    private static Pattern maxCurrencyFractionPattern(int countOf) {
        return Pattern.compile("^\\" + CURRENCY_SYMBOL + "?\\s?\\d*(\\" + DECIMAL_SEPARATOR + "\\d{0," + countOf + "})?\\s?\\" +
                CURRENCY_SYMBOL + "?");
    }

    private static Pattern maxIntegerPattern(int countOf) {
        return Pattern.compile("\\d{0," + countOf + "}");
    }

    private static Pattern integersOnlyPattern() {
        return Pattern.compile("\\d*");
    }

    public enum ValidationModus {

        MAX_CURRENCY_FRACTION_DIGITS {
            @Override
            public Pattern createPattern(int countOf) {
                return maxCurrencyFractionPattern(countOf);
            }
        },

        MAX_FRACTION_DIGITS {
            @Override
            public Pattern createPattern(int countOf) {
                return maxFractionPattern(countOf);
            }
        },
        MAX_INTEGERS {
            @Override
            public Pattern createPattern(int countOf) {
                return maxIntegerPattern(countOf);
            }
        },

        INTEGERS_ONLY {
            @Override
            public Pattern createPattern(int countOf) {
                return integersOnlyPattern();
            }
        };

        public abstract Pattern createPattern(int countOf);
    }

}

You can use it like this:

textField.setTextFormatter(new TextFieldValidator(ValidationModus.INTEGERS_ONLY).getFormatter());

or you can instantiate it in a fxml file, and apply it to a customTextField with the according properties.

app.fxml:

<fx:define>
    <TextFieldValidator fx:id="validator" modus="INTEGERS_ONLY"/>
</fx:define>

CustomTextField.class:

public class CustomTextField {

private TextField textField;

public CustomTextField(@NamedArg("validator") TextFieldValidator validator) {
        this();
        textField.setTextFormatter(validator.getFormatter());
    }
}

Code on github

Converting UTF-8 to ISO-8859-1 in Java - how to keep it as single byte

This is what I needed:

public static byte[] encode(byte[] arr, String fromCharsetName) {
    return encode(arr, Charset.forName(fromCharsetName), Charset.forName("UTF-8"));
}

public static byte[] encode(byte[] arr, String fromCharsetName, String targetCharsetName) {
    return encode(arr, Charset.forName(fromCharsetName), Charset.forName(targetCharsetName));
}

public static byte[] encode(byte[] arr, Charset sourceCharset, Charset targetCharset) {

    ByteBuffer inputBuffer = ByteBuffer.wrap( arr );

    CharBuffer data = sourceCharset.decode(inputBuffer);

    ByteBuffer outputBuffer = targetCharset.encode(data);
    byte[] outputData = outputBuffer.array();

    return outputData;
}

Case vs If Else If: Which is more efficient?

It seems that the compiler is better in optimizing a switch-statement than an if-statement.

The compiler doesn't know if the order of evaluating the if-statements is important to you, and can't perform any optimizations there. You could be calling methods in the if-statements, influencing variables. With the switch-statement it knows that all clauses can be evaluated at the same time and can put them in whatever order is most efficient.

Here's a small comparison:
http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx

Stopping fixed position scrolling at a certain point?

I wrote a blog post about this that featured this function:

$.fn.myFixture = function (settings) {
  return this.each(function () {

    // default css declaration 
    var elem = $(this).css('position', 'fixed');

    var setPosition = function () {         
      var top = 0;
      // get no of pixels hidden above the the window     
      var scrollTop = $(window).scrollTop();    
      // get elements distance from top of window
      var topBuffer = ((settings.topBoundary || 0) - scrollTop);
      // update position if required
      if (topBuffer >= 0) { top += topBuffer }
      elem.css('top', top);      
    };

    $(window).bind('scroll', setPosition);
    setPosition();
  });
};

Converting double to integer in Java

Double perValue = 96.57;
int roundVal= (int) Math.round(perValue);

Solved my purpose.

Iframe transparent background

Set the background color of the src to none and allow transparencey.

[WITHIN SCR PAGE STYLE]
<style type="text/css">
    body
    {
        background:none transparent;
    }
</style>

[IFRAME]
<iframe src="#" allowtransparency="true">Error, iFrame failed to load.</iframe>

NOTE: I code my CSS a little different to how everyone else does.

How do I change TextView Value inside Java Code?

First we need to find a Button:

Button mButton = (Button) findViewById(R.id.my_button);

After that, you must implement View.OnClickListener and there you should find the TextView and execute the method setText:

mButton.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
        final TextView mTextView = (TextView) findViewById(R.id.my_text_view);
        mTextView.setText("Some Text");
    }
});

JPA: JOIN in JPQL

Join on one-to-many relation in JPQL looks as follows:

select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName 

When several properties are specified in select clause, result is returned as Object[]:

Object[] temp = (Object[]) em.createNamedQuery("...")
    .setParameter("groupName", groupName)
    .getSingleResult(); 
String fname = (String) temp[0];
String lname = (String) temp[1];

By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

@Entity @Table(name = "Users")     
public class User implements Serializable { ... } 

How to resolve git status "Unmerged paths:"?

All you should need to do is:

# if the file in the right place isn't already committed:
git add <path to desired file>

# remove the "both deleted" file from the index:
git rm --cached ../public/images/originals/dog.ai

# commit the merge:
git commit

Is it possible to get element from HashMap by its position?

Use LinkedHashMap:

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries.

How do I tidy up an HTML file's indentation in VI?

I use this script: https://github.com/maksimr/vim-jsbeautify

In the above link you have all the info:

  1. Install
  2. Configure (copy from the first example)
  3. Run :call HtmlBeautify()

Does the job beautifully!

PLS-00103: Encountered the symbol "CREATE"

For me / had to be in a new line.

For example

create type emp_t;/

didn't work

but

create type emp_t;

/

worked.

$_POST Array from html form

You should get the array like in $_POST['id']. So you should be able to do this:

foreach ($_POST['id'] as $key => $value) {
    echo $value . "<br />";
}

Input names should be same:

<input name='id[]' type='checkbox' value='1'>
<input name='id[]' type='checkbox' value='2'>
...

How do I get the classes of all columns in a data frame?

One option is to use lapply and class. For example:

> foo <- data.frame(c("a", "b"), c(1, 2))
> names(foo) <- c("SomeFactor", "SomeNumeric")
> lapply(foo, class)
$SomeFactor
[1] "factor"

$SomeNumeric
[1] "numeric"

Another option is str:

> str(foo)
'data.frame':   2 obs. of  2 variables:
 $ SomeFactor : Factor w/ 2 levels "a","b": 1 2
 $ SomeNumeric: num  1 2

Get timezone from users browser using moment(timezone).js

var timedifference = new Date().getTimezoneOffset();

This returns the difference from the clients timezone from UTC time. You can then play around with it as you like.

JavaScript load a page on button click

Simple code to redirect page

<!-- html button designing and calling the event in javascript -->
<input id="btntest" type="button" value="Check" 
       onclick="window.location.href = 'http://www.google.com'" />

Oracle: If Table Exists

I prefer to specify the table and the schema owner.

Watch out for case sensitivity as well. (see "upper" clause below).

I threw a couple of different objects in to show that is can be used in places besides TABLEs.

.............

declare
   v_counter int;
begin
 select count(*) into v_counter from dba_users where upper(username)=upper('UserSchema01');
   if v_counter > 0 then
      execute immediate 'DROP USER UserSchema01 CASCADE';
   end if; 
end;
/



CREATE USER UserSchema01 IDENTIFIED BY pa$$word
  DEFAULT TABLESPACE users
  TEMPORARY TABLESPACE temp
  QUOTA UNLIMITED ON users;

grant create session to UserSchema01;  

And a TABLE example:

declare
   v_counter int;
begin
 select count(*) into v_counter from all_tables where upper(TABLE_NAME)=upper('ORDERS') and upper(OWNER)=upper('UserSchema01');
   if v_counter > 0 then
      execute immediate 'DROP TABLE UserSchema01.ORDERS';
   end if; 
end;
/   

How to annotate MYSQL autoincrement field with JPA annotations

Using MySQL, only this approach was working for me:

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;

The other 2 approaches stated by Pascal in his answer were not working for me.

Split data frame string column into multiple columns

base but probably slow:

n <- 1
for(i in strsplit(as.character(before$type),'_and_')){
     before[n, 'type_1'] <- i[[1]]
     before[n, 'type_2'] <- i[[2]]
     n <- n + 1
}

##   attr          type type_1 type_2
## 1    1   foo_and_bar    foo    bar
## 2   30 foo_and_bar_2    foo  bar_2
## 3    4   foo_and_bar    foo    bar
## 4    6 foo_and_bar_2    foo  bar_2

Access parent URL from iframe

The following line will work: document.location.ancestorOrigins[0] this one returns the ancestor domain name.

How to use Visual Studio C++ Compiler?

You may be forgetting something. Before #include <iostream>, write #include <stdafx.h> and maybe that will help. Then, when you are done writing, click test, than click output from build, then when it is done processing/compiling, press Ctrl+F5 to open the Command Prompt and it should have the output and "press any key to continue."

How to do IF NOT EXISTS in SQLite

If you want to ignore the insertion of existing value, there must be a Key field in your Table. Just create a table With Primary Key Field Like:

CREATE TABLE IF NOT EXISTS TblUsers (UserId INTEGER PRIMARY KEY, UserName varchar(100), ContactName varchar(100),Password varchar(100));

And Then Insert Or Replace / Insert Or Ignore Query on the Table Like:

INSERT OR REPLACE INTO TblUsers (UserId, UserName, ContactName ,Password) VALUES('1','UserName','ContactName','Password');

It Will Not Let it Re-Enter The Existing Primary key Value... This Is how you can Check Whether a Value exists in the table or not.

Google Maps: How to create a custom InfoWindow?

I think the best answer I've come up with is here: https://codepen.io/sentrathis96/pen/yJPZGx

I can't take credit for this, I forked this from another codepen user to fix the google maps dependency to actually load

Make note of the call to:

InfoWindow() // constructor

How to get the sign, mantissa and exponent of a floating point number

My advice is to stick to rule 0 and not redo what standard libraries already do, if this is enough. Look at math.h (cmath in standard C++) and functions frexp, frexpf, frexpl, that break a floating point value (double, float, or long double) in its significand and exponent part. To extract the sign from the significand you can use signbit, also in math.h / cmath, or copysign (only C++11). Some alternatives, with slighter different semantics, are modf and ilogb/scalbn, available in C++11; http://en.cppreference.com/w/cpp/numeric/math/logb compares them, but I didn't find in the documentation how all these functions behave with +/-inf and NaNs. Finally, if you really want to use bitmasks (e.g., you desperately need to know the exact bits, and your program may have different NaNs with different representations, and you don't trust the above functions), at least make everything platform-independent by using the macros in float.h/cfloat.

Difference between signed / unsigned char

There's no dedicated "character type" in C language. char is an integer type, same (in that regard) as int, short and other integer types. char just happens to be the smallest integer type. So, just like any other integer type, it can be signed or unsigned.

It is true that (as the name suggests) char is mostly intended to be used to represent characters. But characters in C are represented by their integer "codes", so there's nothing unusual in the fact that an integer type char is used to serve that purpose.

The only general difference between char and other integer types is that plain char is not synonymous with signed char, while with other integer types the signed modifier is optional/implied.

Max tcp/ip connections on Windows Server 2008

There is a limit on the number of half-open connections, but afaik not for active connections. Although it appears to depend on the type of Windows 2008 server, at least according to this MSFT employee:

It depends on the edition, Web and Foundation editions have connection limits while Standard, Enterprise, and Datacenter do not.

How to keep onItemSelected from firing off on a newly instantiated Spinner?

Since nothing worked for me, and I have more than 1 spinner in my view (and IMHO holding a bool map is an overkill) I use the tag to count the clicks :

spinner.setTag(0);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Integer selections = (Integer) parent.getTag();
            if (selections > 0) {
                // real selection
            }
            parent.setTag(++selections); // (or even just '1')
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

org.json.simple cannot be resolved

The jar file is missing. You can download the jar file and add it as external libraries in your project . You can download this from

http://www.findjar.com/jar/com/googlecode/json-simple/json-simple/1.1/json-simple-1.1.jar.html

vuetify center items into v-flex

wrap button inside <div class="text-xs-center">

<div class="text-xs-center">
  <v-btn primary>
    Signup
  </v-btn>
</div>

Dev uses it in his examples.


For centering buttons in v-card-actions we can add class="justify-center" (note in v2 class is text-center (so without xs):

<v-card-actions class="justify-center">
  <v-btn>
    Signup
  </v-btn>
</v-card-actions>

Codepen


For more examples with regards to centering see here

Simulating ENTER keypress in bash script

You might find the yes command useful.

See man yes

How do I plot only a table in Matplotlib?

This is another option to write a pandas dataframe directly into a matplotlib table:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# hide axes
fig.patch.set_visible(False)
ax.axis('off')
ax.axis('tight')

df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))

ax.table(cellText=df.values, colLabels=df.columns, loc='center')

fig.tight_layout()

plt.show()

enter image description here

Text overflow ellipsis on two lines

Base on an answer I saw in stackoveflow, I created this LESS mixin (use this link to generate the CSS code):

.max-lines(@lines: 3; @line-height: 1.2) {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: @lines;
  line-height: @line-height;
  max-height: @line-height * @lines;
}

Usage

.example-1 {
    .max-lines();
}

.example-2 {
    .max-lines(3);
}

.example-3 {
    .max-lines(3, 1.5);
}

WCF vs ASP.NET Web API

The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.


For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here


ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.


In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

How to set selected item of Spinner by value, not by position?

You can use this way, just make your code more simple and more clear.

ArrayAdapter<String> adapter = (ArrayAdapter<String>) spinnerCountry.getAdapter();
int position = adapter.getPosition(obj.getCountry());
spinnerCountry.setSelection(position);

Hope it helps.

Split comma-separated input box values into array in jquery, and loop through it

var array = $('#searchKeywords').val().split(",");

then

$.each(array,function(i){
   alert(array[i]);
});

OR

for (i=0;i<array.length;i++){
     alert(array[i]);
}

Prevent Default on Form Submit jQuery

Well I encountered a similar problem. The problem for me is that the JS file get loaded before the DOM render happens. So move your <script> to the end of <body> tag.

or use defer.

<script defer src="">

so rest assured e.preventDefault() should work.

The application has stopped unexpectedly: How to Debug?

If you use the Logcat display inside the 'debug' perspective in Eclipse the lines are colour-coded. It's pretty easy to find what made your app crash because it's usually in red.

The Java (or Dalvik) virtual machine should never crash, but if your program throws an exception and does not catch it the VM will terminate your program, which is the 'crash' you are seeing.

Error while trying to retrieve text for error ORA-01019

Well,

Just worked it out. While having both installations we have two ORACLE_HOME directories and both have SQAORA32.dll files. While looking up for ORACLE_HOMe my app was getting confused..I just removed the Client oracle home entry as oracle client is by default present in oracle DB Now its working...Thanks!!

How to get distinct values for non-key column fields in Laravel?

$users = User::all();
foreach($users->unique('column_name') as $user){
    code here..
}

Install a Windows service using a Windows command prompt?

Open command prompt as administrator, go to your Folder where your .exe resides. To Install Exe as service

D:\YourFolderName\YourExeName /i

To uninstall use /u.

In PHP with PDO, how to check the final SQL parametrized query?

I think easiest way to see final query text when you use pdo is to make special error and look error message. I don't know how to do that, but when i make sql error in yii framework that use pdo i could see query text

ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead

Got a similar error from CircleCi's error log.

"ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.3.0 but 3.3.3333 was found instead."

Just so you know this did not affect the Angular application, but the CircleCi error was becoming annoying. I am running Angular 7.1

I ran: $ npm i [email protected] --save-dev --save-exact to update the package-lock.json file.

Then I ran: $ npm i

After that I ran: $ npm audit fix

"This CircleCi error message" went away. So it works

Accessing @attribute from SimpleXML

I used before so many times for getting @attributes like below and it was a little bit longer.

$att = $xml->attributes();
echo $att['field'];

It should be more easy and you can get attributes following format only at once:

Standard Way - Array-Access Attributes (AAA)

$xml['field'];

Other alternatives are:

Right & Quick Format

$xml->attributes()->{'field'};

Wrong Formats

$xml->attributes()->field;
$xml->{"@attributes"}->field;
$xml->attributes('field');
$xml->attributes()['field'];
$xml->attributes->['field'];

How do I get the directory that a program is running from?

If you want a standard way without libraries: No. The whole concept of a directory is not included in the standard.

If you agree that some (portable) dependency on a near-standard lib is okay: Use Boost's filesystem library and ask for the initial_path().

IMHO that's as close as you can get, with good karma (Boost is a well-established high quality set of libraries)

Obtain form input fields using jQuery?

Hope this helps somebody. :)

// This html:
// <form id="someCoolForm">
// <input type="text" class="form-control" name="username" value="...." />
// 
// <input type="text" class="form-control" name="profile.first_name" value="...." />
// <input type="text" class="form-control" name="profile.last_name" value="...." />
// 
// <input type="text" class="form-control" name="emails[]" value="..." />
// <input type="text" class="form-control" name="emails[]" value=".." />
// <input type="text" class="form-control" name="emails[]" value="." />
// </form>
// 
// With this js:
// 
// var form1 = parseForm($('#someCoolForm'));
// console.log(form1);
// 
// Will output something like:
// {
// username: "test2"
// emails:
//   0: "[email protected]"
//   1: "[email protected]"
// profile: Object
//   first_name: "..."
//   last_name: "..."
// }
// 
// So, function below:

var parseForm = function (form) {

    var formdata = form.serializeArray();

    var data = {};

    _.each(formdata, function (element) {

        var value = _.values(element);

        // Parsing field arrays.
        if (value[0].indexOf('[]') > 0) {
            var key = value[0].replace('[]', '');

            if (!data[key])
                data[key] = [];

            data[value[0].replace('[]', '')].push(value[1]);
        } else

        // Parsing nested objects.
        if (value[0].indexOf('.') > 0) {

            var parent = value[0].substring(0, value[0].indexOf("."));
            var child = value[0].substring(value[0].lastIndexOf(".") + 1);

            if (!data[parent])
                data[parent] = {};

            data[parent][child] = value[1];
        } else {
            data[value[0]] = value[1];
        }
    });

    return data;
};

git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054

This happens when you push first time without net connection or poor net connection.But when you try again using good connection 2,3 times problem will be solved.

C Linking Error: undefined reference to 'main'

You are overwriting your object file runexp.o by running this command :

 gcc -o runexp.o scd.o data_proc.o -lm -fopenmp

In fact, the -o is for the output file. You need to run :

gcc -o runexp.out runexp.o scd.o data_proc.o -lm -fopenmp

runexp.out will be you binary file.

What does "Table does not support optimize, doing recreate + analyze instead" mean?

Best option is create new table with same properties

CREATE TABLE <NEW.NAME.TABLE> LIKE <TABLE.CRASHED>;
INSERT INTO <NEW.NAME.TABLE> SELECT * FROM <TABLE.CRASHED>;

Rename NEW.NAME.TABLE and TABLE.CRASH

RENAME TABLE <TABLE.CRASHED> TO <TABLE.CRASHED.BACKUP>;
RENAME TABLE <NEW.NAME.TABLE> TO <TABLE.CRASHED>;

After work well, delete

DROP TABLE <TABLE.CRASHED.BACKUP>;

Remove CSS from a Div using JQuery

I used the second solution of user147767

However, there is a typo here. It should be

curCssName.toUpperCase().indexOf(cssName.toUpperCase() + ':') < 0

not <= 0

I also changed this condition for:

!curCssName.match(new RegExp(cssName + "(-.+)?:"), "mi")

as sometimes we add a css property over jQuery, and it's added in a different way for different browsers (i.e. the border property will be added as "border" for Firefox, and "border-top", "border-bottom" etc for IE).

Select default option value from typescript angular 6

In addition to what mentioned before, you can use [attr.selected] directive to select a specific option, as follows:

<select>
    <option *ngFor="let program of programs" [attr.selected]="(member.programID == program.id)">
        {{ program.name }}
    </option>
</select>

Javascript Click on Element by Class

If you want to click on all elements selected by some class, you can use this example (used on last.fm on the Loved tracks page to Unlove all).

var divs = document.querySelectorAll('.love-button.love-button--loved'); 

for (i = 0; i < divs.length; ++i) {
  divs[i].click();
};

With ES6 and Babel (cannot be run in the browser console directly)

[...document.querySelectorAll('.love-button.love-button--loved')]
   .forEach(div => { div.click(); })

React - uncaught TypeError: Cannot read property 'setState' of undefined

Arrow function could have make your life more easier to avoid binding this keyword. Like so:

 delta = () => {
       this.setState({
           count : this.state.count++
      });
   }

How to find difference between two columns data?

IF the table is alias t

SELECT t.Present , t.previous, t.previous- t.Present AS Difference
FROM   temp1 as t

How to get these two divs side-by-side?

Using flexbox it is super simple!

#parent_div_1, #parent_div_2, #parent_div_3 {
    display: flex;
}

Fiddle example

Javascript get the text value of a column from a particular row of an html table

document.getElementById("tblBlah").rows[i].columns[j].innerHTML;

Should be:

document.getElementById("tblBlah").rows[i].cells[j].innerHTML;

But I get the distinct impression that the row/cell you need is the one clicked by the user. If so, the simplest way to achieve this would be attaching an event to the cells in your table:

function alertInnerHTML(e)
{
    e = e || window.event;//IE
    alert(this.innerHTML);
}

var theTbl = document.getElementById('tblBlah');
for(var i=0;i<theTbl.length;i++)
{
    for(var j=0;j<theTbl.rows[i].cells.length;j++)
    {
        theTbl.rows[i].cells[j].onclick = alertInnerHTML;
    }
}

That makes all table cells clickable, and alert it's innerHTML. The event object will be passed to the alertInnerHTML function, in which the this object will be a reference to the cell that was clicked. The event object offers you tons of neat tricks on how you want the click event to behave if, say, there's a link in the cell that was clicked, but I suggest checking the MDN and MSDN (for the window.event object)

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

If you are using ASP.NET Core with the Startup.cs convention, you can access and set the query command timeout option like this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContextPool<MyDbContext>(_ =>
    {
        _.UseSqlServer(Configuration.GetConnectionString("MyConnectionString"), options => 
        {
            options.CommandTimeout(180); // 3 minutes
        });
    });
}

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

How do I show the schema of a table in a MySQL database?

describe [db_name.]table_name;

for formatted output, or

show create table [db_name.]table_name;

for the SQL statement that can be used to create a table.

Trying to use Spring Boot REST to Read JSON String from POST

I think the simplest/handy way to consuming JSON is using a Java class that resembles your JSON: https://stackoverflow.com/a/6019761

But if you can't use a Java class you can use one of these two solutions.

Solution 1: you can do it receiving a Map<String, Object> from your controller:

@RequestMapping(
    value = "/process", 
    method = RequestMethod.POST)
public void process(@RequestBody Map<String, Object> payload) 
    throws Exception {

  System.out.println(payload);

}

Using your request:

curl -H "Accept: application/json" -H "Content-type: application/json" \
-X POST -d '{"name":"value"}' http://localhost:8080/myservice/process

Solution 2: otherwise you can get the POST payload as a String:

@RequestMapping(
    value = "/process", 
    method = RequestMethod.POST,
    consumes = "text/plain")
public void process(@RequestBody String payload) throws Exception {

  System.out.println(payload);

}

Then parse the string as you want. Note that must be specified consumes = "text/plain" on your controller. In this case you must change your request with Content-type: text/plain:

curl -H "Accept: application/json" -H "Content-type: text/plain" -X POST \
-d '{"name":"value"}' http://localhost:8080/myservice/process

How can I troubleshoot Python "Could not find platform independent libraries <prefix>"

I had this problem and spent a few hours trying to fix it. I fixed the prefix error by changing the path but I still had an encoding import error. This was fixed by restarting my computer.

How do I concatenate two lists in Python?

You can use sets to obtain merged list of unique values

mergedlist = list(set(listone + listtwo))

Decreasing height of bootstrap 3.0 navbar

I got the same problem, the height of my menu bar provided by bootstrap was too big, actually i downloaded some wrong bootstrap, finally get rid of it by downloading the orignal bootstrap from this site.. http://getbootstrap.com/2.3.2/ want to use bootstrap in yii( netbeans) follow this tutorial, https://www.youtube.com/watch?v=XH_qG8gphaw... The voice is not present but the steps are slow you can easily understand and implement them. Thanks

Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate)

Most programs will check the $EDITOR environment variable, so you can set that to the path of TextEdit in your bashrc. Git will use this as well.

How to do this:

  • Add the following to your ~/.bashrc file:
    export EDITOR="/Applications/TextEdit.app/Contents/MacOS/TextEdit"
  • or just type the following command into your Terminal:
    echo "export EDITOR=\"/Applications/TextEdit.app/Contents/MacOS/TextEdit\"" >> ~/.bashrc

If you are using zsh, use ~/.zshrc instead of ~/.bashrc.

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

I had a similar issue with 50,000 rdf/xml files in 5,000 directories (the Project Gutenberg catalog file). I solved it with riot (in the jena distribution)

the directory is cache/epub/NN/nn.rdf (where NN is a number)

in the directory above the directory where all the files are, i.e. in cache

riot epub/*/*.rdf --output=turtle > allTurtle.ttl

This produces possibly many warnings but the result is in a format which can be loaded into jena (using the fuseki web interface).

surprisingly simple (at least in this case).

Count number of cells with any value (string or number) in a column in Google Docs Spreadsheet

The SUBTOTAL function can be used if you want to get the count respecting any filters you use on the page.

=SUBTOTAL(103, A1:A200)

will help you get count of non-empty rows, respecting filters.

103 - is similar to COUNTA, but ignores empty rows and also respects filters.

Reference : SUBTOTAL function

Ignoring upper case and lower case in Java

You ignore case when you treat the data, not when you retrieve/store it. If you want to store everything in lowercase use String#toLowerCase, in uppercase use String#toUpperCase.

Then when you have to actually treat it, you may use out of the bow methods, like String#equalsIgnoreCase(java.lang.String). If nothing exists in the Java API that fulfill your needs, then you'll have to write your own logic.

List of IP Space used by Facebook

Updated list as of 6/11/2013

204.15.20.0/22
69.63.176.0/20

66.220.144.0/20
66.220.144.0/21
69.63.184.0/21
69.63.176.0/21
74.119.76.0/22
69.171.255.0/24
173.252.64.0/18
69.171.224.0/19
69.171.224.0/20
103.4.96.0/22
69.63.176.0/24
173.252.64.0/19
173.252.70.0/24
31.13.64.0/18
31.13.24.0/21
66.220.152.0/21
66.220.159.0/24
69.171.239.0/24
69.171.240.0/20
31.13.64.0/19
31.13.64.0/24
31.13.65.0/24
31.13.67.0/24
31.13.68.0/24
31.13.69.0/24
31.13.70.0/24
31.13.71.0/24
31.13.72.0/24
31.13.73.0/24
31.13.74.0/24
31.13.75.0/24
31.13.76.0/24
31.13.77.0/24
31.13.96.0/19
31.13.66.0/24
173.252.96.0/19
69.63.178.0/24
31.13.78.0/24
31.13.79.0/24
31.13.80.0/24
31.13.82.0/24
31.13.83.0/24
31.13.84.0/24
31.13.85.0/24
31.13.87.0/24
31.13.88.0/24
31.13.89.0/24
31.13.90.0/24
31.13.91.0/24
31.13.92.0/24
31.13.93.0/24
31.13.94.0/24
31.13.95.0/24
69.171.253.0/24
69.63.186.0/24
204.15.20.0/22
69.63.176.0/20
69.63.176.0/21
69.63.184.0/21
66.220.144.0/20
69.63.176.0/20

SQL Server : error converting data type varchar to numeric

If you are running SQL Server 2012 or newer you can also use the new TRY_PARSE() function:

Returns the result of an expression, translated to the requested data type, or null if the cast fails in SQL Server. Use TRY_PARSE only for converting from string to date/time and number types.

Or TRY_CONVERT/TRY_CAST:

Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.

iOS Launching Settings -> Restrictions URL Scheme

As of iOS10 you can use

UIApplication.sharedApplication().openURL(NSURL(string:"App-Prefs:root")!) 

to open general settings.

also you can add known urls(you can see them in the most upvoted answer) to it to open specific settings. For example the below one opens touchID and passcode.

UIApplication.sharedApplication().openURL(NSURL(string:"App-Prefs:root=TOUCHID_PASSCODE")!)

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

Group dataframe and get sum AND count?

df.groupby('Company Name').agg({'Organisation name':'count','Amount':'sum'})\
    .apply(lambda x: x.sort_values(['count','sum'], ascending=False))

Release generating .pdb files, why?

PDB can be generated for Release as well as for Debug. This is set at (in VS2010 but in VS2005 must be similar):

Project ? Properties ? Build ? Advanced ? Debug Info

Just change it to None.

CSS flexbox not working in IE10

As Ennui mentioned, IE 10 supports the -ms prefixed version of Flexbox (IE 11 supports it unprefixed). The errors I can see in your code are:

  • You should have display: -ms-flexbox instead of display: -ms-flex
  • I think you should specify all 3 flex values, like flex: 0 1 auto to avoid ambiguity

So the final updated code is...

.flexbox form {
    display: -webkit-flex;
    display: -moz-flex;
    display: -ms-flexbox;
    display: -o-flex;
    display: flex;

    /* Direction defaults to 'row', so not really necessary to specify */
    -webkit-flex-direction: row;
    -moz-flex-direction: row;
    -ms-flex-direction: row;
    -o-flex-direction: row;
    flex-direction: row;
}

.flexbox form input[type=submit] {
    width: 31px;
}

.flexbox form input[type=text] {
    width: auto;

    /* Flex should have 3 values which is shorthand for 
       <flex-grow> <flex-shrink> <flex-basis> */
    -webkit-flex: 1 1 auto;
    -moz-flex: 1 1 auto;
    -ms-flex: 1 1 auto;
    -o-flex: 1 1 auto;
    flex: 1 1 auto;

    /* I don't think you need 'display: flex' on child elements * /
    display: -webkit-flex;
    display: -moz-flex;
    display: -ms-flex;
    display: -o-flex;
    display: flex;
    /**/
}

Base64 length calculation?

Simple implementantion in javascript

function sizeOfBase64String(base64String) {
    if (!base64String) return 0;
    const padding = (base64String.match(/(=*)$/) || [])[1].length;
    return 4 * Math.ceil((base64String.length / 3)) - padding;
}

Questions every good Database/SQL developer should be able to answer

At our company, instead of asking a lot of SQL questions that anyone with a good memory can answer, we created a SQL Developers test. The test is designed to have the candidate put together a solid schema with normalization and RI considerations, check constraints etc. And then be able to create some queries to produce results sets we're looking for. They create all this against a brief design specification we give them. They are allowed to do this at home, and take as much time as they need (within reason).

Regex: Use start of line/end of line signs (^ or $) in different context

Just use look-arounds to solve this:

(?<=^|,)garp(?=$|,)

The difference with look-arounds and just regular groups are that with regular groups the comma would be part of the match, and with look-arounds it wouldn't. In this case it doesn't make a difference though.

Change font color and background in html on mouseover

Either do it with CSS like the other answers did or change the text style color directly via the onMouseOver and onMouseOut event:

onmouseover="this.bgColor='white'; this.style.color='black'"

onmouseout="this.bgColor='black'; this.style.color='white'"

Default values in a C Struct

How about something like:

struct foo bar;
update(init_id(42, init_dont_care(&bar)));

with:

struct foo* init_dont_care(struct foo* bar) {
  bar->id = dont_care;
  bar->route = dont_care;
  bar->backup_route = dont_care;
  bar->current_route = dont_care;
  return bar;
}

and:

struct foo* init_id(int id, struct foo* bar) {
  bar->id = id;
  return bar;
}

and correspondingly:

struct foo* init_route(int route, struct foo* bar);
struct foo* init_backup_route(int backup_route, struct foo* bar);
struct foo* init_current_route(int current_route, struct foo* bar);

In C++, a similar pattern has a name which I don't remember just now.

EDIT: It's called the Named Parameter Idiom.

Java : Comparable vs Comparator

Comparator provides a way for you to provide custom comparison logic for types that you have no control over.

Comparable allows you to specify how objects that you are implementing get compared.

Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator.

Otherwise you can use Comparable.

Collection was modified; enumeration operation may not execute

This way should cover a situation of concurrency when the function is called again while is still executing (and items need used only once):

 while (list.Count > 0)
 {
    string Item = list[0];
    list.RemoveAt(0);
 
    // do here what you need to do with item
 
 } 
 

If the function get called while is still executing items will not reiterate from the first again as they get deleted as soon as they get used. Should not affect performance much for small lists.

Switch to another Git tag

Clone the repository as normal:

git clone git://github.com/rspec/rspec-tmbundle.git RSpec.tmbundle

Then checkout the tag you want like so:

git checkout tags/1.1.4

This will checkout out the tag in a 'detached HEAD' state. In this state, "you can look around, make experimental changes and commit them, and [discard those commits] without impacting any branches by performing another checkout".

To retain any changes made, move them to a new branch:

git checkout -b 1.1.4-jspooner

You can get back to the master branch by using:

git checkout master

Note, as was mentioned in the first revision of this answer, there is another way to checkout a tag:

git checkout 1.1.4

But as was mentioned in a comment, if you have a branch by that same name, this will result in git warning you that the refname is ambiguous and checking out the branch by default:

warning: refname 'test' is ambiguous.
Switched to branch '1.1.4'

The shorthand can be safely used if the repository does not share names between branches and tags.

UTF-8 all the way through

I recently discovered that using strtolower() can cause issues where the data is truncated after a special character.

The solution was to use

mb_strtolower($string, 'UTF-8');

mb_ uses MultiByte. It supports more characters but in general is a little slower.

How to read a PEM RSA private key from .NET

ok, Im using mac to generate my self signed keys. Here is the working method I used.

I created a shell script to speed up my key generation.

genkey.sh

#/bin/sh

ssh-keygen -f host.key
openssl req -new -key host.key -out request.csr
openssl x509 -req -days 99999 -in request.csr -signkey host.key -out server.crt
openssl pkcs12 -export -inkey host.key -in server.crt -out private_public.p12 -name "SslCert"
openssl base64 -in private_public.p12 -out Base64.key

add the +x execute flag to the script

chmod +x genkey.sh

then call genkey.sh

./genkey.sh

I enter a password (important to include a password at least for the export at the end)

Enter pass phrase for host.key:
Enter Export Password:   {Important to enter a password here}
Verifying - Enter Export Password: { Same password here }

I then take everything in Base64.Key and put it into a string named sslKey

private string sslKey = "MIIJiAIBA...................................." +
                        "......................ETC...................." +
                        "......................ETC...................." +
                        "......................ETC...................." +
                        ".............ugICCAA=";

I then used a lazy load Property getter to get my X509 Cert with a private key.

X509Certificate2 _serverCertificate = null;
X509Certificate2 serverCertificate{
    get
    {
        if (_serverCertificate == null){
            string pass = "Your Export Password Here";
            _serverCertificate = new X509Certificate(Convert.FromBase64String(sslKey), pass, X509KeyStorageFlags.Exportable);
        }
        return _serverCertificate;
    }
}

I wanted to go this route because I am using .net 2.0 and Mono on mac and I wanted to use vanilla Framework code with no compiled libraries or dependencies.

My final use for this was the SslStream to secure TCP communication to my app

SslStream sslStream = new SslStream(serverCertificate, false, SslProtocols.Tls, true);

I hope this helps other people.

NOTE

Without a password I was unable to correctly unlock the private key for export.

Improve INSERT-per-second performance of SQLite

Use ContentProvider for inserting the bulk data in db. The below method used for inserting bulk data in to database. This should Improve INSERT-per-second performance of SQLite.

private SQLiteDatabase database;
database = dbHelper.getWritableDatabase();

public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {

database.beginTransaction();

for (ContentValues value : values)
 db.insert("TABLE_NAME", null, value);

database.setTransactionSuccessful();
database.endTransaction();

}

Call bulkInsert method :

App.getAppContext().getContentResolver().bulkInsert(contentUriTable,
            contentValuesArray);

Link: https://www.vogella.com/tutorials/AndroidSQLite/article.html check Using ContentProvider Section for more details

How can I programmatically freeze the top row of an Excel worksheet in Excel 2007 VBA?

Rows("2:2").Select
ActiveWindow.FreezePanes = True

Select a different range for a different effect, much the same way you would do manually. The "Freeze Top Row" really just is a shortcut new in Excel 2007 (and up), it contains no added functionality compared to earlier versions of Excel.

Self-references in object literals / initializers

The key to all this is SCOPE.

You need to encapsulate the "parent" (parent object) of the property you want to define as it's own instantiated object, and then you can make references to sibling properties using the key word this

It's very, very important to remember that if you refer to this without first so doing, then this will refer to the outer scope... which will be the window object.

var x = 9   //this is really window.x
var bar = {
  x: 1,
  y: 2,
  foo: new function(){
    this.a = 5, //assign value
    this.b = 6,
    this.c = this.a + this.b;  // 11
  },
  z: this.x   // 9 (not 1 as you might expect, b/c *this* refers `window` object)
};

C# generic list <T> how to get the type of T?

Type type = pi.PropertyType;
if(type.IsGenericType && type.GetGenericTypeDefinition()
        == typeof(List<>))
{
    Type itemType = type.GetGenericArguments()[0]; // use this...
}

More generally, to support any IList<T>, you need to check the interfaces:

foreach (Type interfaceType in type.GetInterfaces())
{
    if (interfaceType.IsGenericType &&
        interfaceType.GetGenericTypeDefinition()
        == typeof(IList<>))
    {
        Type itemType = type.GetGenericArguments()[0];
        // do something...
        break;
    }
}

run program in Python shell

From the same folder, you can do:

import test

How to find the parent element using javascript

Use the change event of the select:

$('#my_select').change(function()
{
   $(this).parents('td').css('background', '#000000');
});

'tsc command not found' in compiling typescript

After finding all solutions for this small issue for macOS only.
Finally, I got my TSC works on my MacBook pro.

This might be the best solution I found out.

For all macOS users, instead of installing TypeScript using NPM, you can install TypeScript using homebrew.

brew install typescript

Please see attached screencap for reference. enter image description here

What are the best PHP input sanitizing functions?

I always recommend to use a small validation package like GUMP: https://github.com/Wixel/GUMP

Build all you basic functions arround a library like this and is is nearly impossible to forget sanitation. "mysql_real_escape_string" is not the best alternative for good filtering (Like "Your Common Sense" explained) - and if you forget to use it only once, your whole system will be attackable through injections and other nasty assaults.

How to import existing Git repository into another?

If you want to retain the exact commit history of the second repository and therefore also retain the ability to easily merge upstream changes in the future then here is the method you want. It results in unmodified history of the subtree being imported into your repo plus one merge commit to move the merged repository to the subdirectory.

git remote add XXX_remote <path-or-url-to-XXX-repo>
git fetch XXX_remote
git merge -s ours --no-commit --allow-unrelated-histories XXX_remote/master
git read-tree --prefix=ZZZ/ -u XXX_remote/master
git commit -m "Imported XXX as a subtree."

You can track upstream changes like so:

git pull -s subtree XXX_remote master

Git figures out on its own where the roots are before doing the merge, so you don't need to specify the prefix on subsequent merges.

The downside is that in the merged history the files are unprefixed (not in a subdirectory). As a result git log ZZZ/a will show you all the changes (if any) except those in the merged history. You can do:

git log --follow -- a

but that won't show the changes other then in the merged history.

In other words, if you don't change ZZZ's files in repository XXX, then you need to specify --follow and an unprefixed path. If you change them in both repositories, then you have 2 commands, none of which shows all the changes.

Git versions before 2.9: You don’t need to pass the --allow-unrelated-histories option to git merge.

The method in the other answer that uses read-tree and skips the merge -s ours step is effectively no different than copying the files with cp and committing the result.

Original source was from github's "Subtree Merge" help article. And another useful link.

reading from app.config file

Also add the key "StartingMonthColumn" in App.config that you run application from, for example in the App.config of the test project.

creating Hashmap from a JSON String

Here is an example of an easy and simple way to create a Hashmap from a JSON string by only using the JSON simple library:

{"Collection":{"Item_Type":"Any","Name":"A","Item_ID":"000014"},"Object_Name":"System"}

import java.io.FileReader;
import java.util.HashMap;
import java.util.Iterator; 
import java.util.Map;  
import org.json.simple.JSONObject; 
import org.json.simple.parser.*;

public class JSONRead {

public static void main(String[] args) throws Exception {
    
    Object obj = new JSONParser().parse(new FileReader("D:\\other.json"));
    
    HashMap<String,String> map =new HashMap<String,String>();
    
    // typecasting obj to JSONObject 
    JSONObject jo = (JSONObject) obj;
    
    Map Item_Id = ((Map)jo.get("Collection"));
            
    Iterator<Map.Entry> itr1 = Item_Id.entrySet().iterator(); 
    while (itr1.hasNext()) { 
        Map.Entry pair = itr1.next(); 
        String key = (String) pair.getKey();
        String value = (String) pair.getValue();
        System.out.println( pair.getKey() + " : " + pair.getValue()); 
        map.put(key, value);
    }
    
    System.out.println(map)
    System.out.println(map.get("Item"));        
}

How to remove margin space around body or clear default css styles

That's the default margin/padding of the body element.

Some browsers have a default margin, some a default padding, and both are applied as a padding in the body element.

Add this to your CSS:

body { margin: 0; padding: 0; }

Pandas - How to flatten a hierarchical index in columns

All of the current answers on this thread must have been a bit dated. As of pandas version 0.24.0, the .to_flat_index() does what you need.

From panda's own documentation:

MultiIndex.to_flat_index()

Convert a MultiIndex to an Index of Tuples containing the level values.

A simple example from its documentation:

import pandas as pd
print(pd.__version__) # '0.23.4'
index = pd.MultiIndex.from_product(
        [['foo', 'bar'], ['baz', 'qux']],
        names=['a', 'b'])

print(index)
# MultiIndex(levels=[['bar', 'foo'], ['baz', 'qux']],
#           codes=[[1, 1, 0, 0], [0, 1, 0, 1]],
#           names=['a', 'b'])

Applying to_flat_index():

index.to_flat_index()
# Index([('foo', 'baz'), ('foo', 'qux'), ('bar', 'baz'), ('bar', 'qux')], dtype='object')

Using it to replace existing pandas column

An example of how you'd use it on dat, which is a DataFrame with a MultiIndex column:

dat = df.loc[:,['name','workshop_period','class_size']].groupby(['name','workshop_period']).describe()
print(dat.columns)
# MultiIndex(levels=[['class_size'], ['count', 'mean', 'std', 'min', '25%', '50%', '75%', 'max']],
#            codes=[[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5, 6, 7]])

dat.columns = dat.columns.to_flat_index()
print(dat.columns)
# Index([('class_size', 'count'),  ('class_size', 'mean'),
#     ('class_size', 'std'),   ('class_size', 'min'),
#     ('class_size', '25%'),   ('class_size', '50%'),
#     ('class_size', '75%'),   ('class_size', 'max')],
#  dtype='object')

How can I loop through all rows of a table? (MySQL)

You should really use a set based solution involving two queries (basic insert):

INSERT INTO TableB (Id2Column, Column33, Column44)
SELECT id, column1, column2 FROM TableA

UPDATE TableA SET column1 = column2 * column3

And for your transform:

INSERT INTO TableB (Id2Column, Column33, Column44)
SELECT 
    id, 
    column1 * column4 * 100, 
    (column2 / column12) 
FROM TableA

UPDATE TableA SET column1 = column2 * column3

Now if your transform is more complicated than that and involved multiple tables, post another question with the details.

convert a char* to std::string

Pass it in through the constructor:

const char* dat = "my string!";
std::string my_string( dat );

You can use the function string.c_str() to go the other way:

std::string my_string("testing!");
const char* dat = my_string.c_str();

Gradle project refresh failed after Android Studio update

Check the Gradle home path after the update to version 1.5. It should be ../gradle-2.8.

enter image description here

How to remove all ListBox items?

while (listBox1.Items.Count > 0){ 
    listBox1.Items.Remove(0);
}

Select parent element of known element in Selenium

Little more about XPath axes

Lets say we have below HTML structure:

<div class="third_level_ancestor">
    <nav class="second_level_ancestor">
        <div class="parent">
            <span>Child</span>
        </div>
    </nav>
</div>
  1. //span/parent::* - returns any element which is direct parent.

In this case output is <div class="parent">

  1. //span/parent::div[@class="parent"] - returns parent element only of exact node type and only if specified predicate is True.

Output: <div class="parent">

  1. //span/ancestor::* - returns all ancestors (including parent).

Output: <div class="parent">, <nav class="second_level_ancestor">, <div class="third_level_ancestor">...

  1. //span/ancestor-or-self::* - returns all ancestors and current element itself.

Output: <span>Child</span>, <div class="parent">, <nav class="second_level_ancestor">, <div class="third_level_ancestor">...

  1. //span/ancestor::div[2] - returns second ancestor (starting from parent) of type div.

Output: <div class="third_level_ancestor">

Angular bootstrap datepicker date format does not format ng-model value

All proposed solutions didn't work for me but the closest one was from @Rishii.

I'm using AngularJS 1.4.4 and UI Bootstrap 0.13.3.

.directive('jsr310Compatible', ['dateFilter', 'dateParser', function(dateFilter, dateParser) {
  return {
    restrict: 'EAC',
    require: 'ngModel',
    priority: 1,
    link: function(scope, element, attrs, ngModel) {
      var dateFormat = 'yyyy-MM-dd';

      ngModel.$parsers.push(function(viewValue) {
        return dateFilter(viewValue, dateFormat);
      });

      ngModel.$validators.date = function (modelValue, viewValue) {
        var value = modelValue || viewValue;

        if (!attrs.ngRequired && !value) {
          return true;
        }

        if (angular.isNumber(value)) {
          value = new Date(value);
        }

        if (!value) {
          return true;
        }
        else if (angular.isDate(value) && !isNaN(value)) {
          return true;
        }
        else if (angular.isString(value)) {
          var date = dateParser.parse(value, dateFormat);
          return !isNaN(date);
        }
        else {
          return false;
        }
      };
    }
  };
}])

Change language for bootstrap DateTimePicker

1.you will use different locale array element in datepicker.js from following link https://github.com/smalot/bootstrap-datetimepicker/tree/master/js/locales

2.add array in datepicker.js like this:

_x000D_
_x000D_
$.fn.datepicker.Constructor = Datepicker;_x000D_
    var dates = $.fn.datepicker.dates = {_x000D_
        en: {_x000D_
            days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],_x000D_
            daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],_x000D_
            daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],_x000D_
            months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],_x000D_
            monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],_x000D_
            today: "Today"_x000D_
        },_x000D_
        CN:{_x000D_
        days: ["???", "???", "???", "???", "???", "???", "???", "???"],_x000D_
        daysShort: ["??", "??", "??", "??", "??", "??", "??", "??"],_x000D_
    daysMin: ["?", "?", "?", "?", "?", "?", "?", "?"],_x000D_
    months: ["??", "??", "??", "??", "??", "??", "??", "??", "??", "??", "???", "???"],_x000D_
    monthsShort: ["??", "??", "??", "??", "??", "??", "??", "??", "??", "??", "???", "???"],_x000D_
    today: "??",_x000D_
    suffix: [],_x000D_
    meridiem: ["??", "??"]_x000D_
}_x000D_
 };
_x000D_
_x000D_
_x000D_

Meaning of Open hashing and Closed hashing

The name open addressing refers to the fact that the location ("address") of the element is not determined by its hash value. (This method is also called closed hashing).

In separate chaining, each bucket is independent, and has some sort of ADT (list, binary search trees, etc) of entries with the same index. In a good hash table, each bucket has zero or one entries, because we need operations of order O(1) for insert, search, etc.

This is a example of separate chaining using C++ with a simple hash function using mod operator (clearly, a bad hash function)

How do I sort a VARCHAR column in SQL server that contains numbers?

I solved it in a very simple way writing this in the "order" part

ORDER BY (
sr.codice +0
)
ASC

This seems to work very well, in fact I had the following sorting:

16079   Customer X 
016082  Customer Y
16413   Customer Z

So the 0 in front of 16082 is considered correctly.

Where could I buy a valid SSL certificate?

Let's Encrypt is a free, automated, and open certificate authority made by the Internet Security Research Group (ISRG). It is sponsored by well-known organisations such as Mozilla, Cisco or Google Chrome. All modern browsers are compatible and trust Let's Encrypt.

All certificates are free (even wildcard certificates)! For security reasons, the certificates expire pretty fast (after 90 days). For this reason, it is recommended to install an ACME client, which will handle automatic certificate renewal.

There are many clients you can use to install a Let's Encrypt certificate:

Let’s Encrypt uses the ACME protocol to verify that you control a given domain name and to issue you a certificate. To get a Let’s Encrypt certificate, you’ll need to choose a piece of ACME client software to use. - https://letsencrypt.org/docs/client-options/

how to display data values on Chart.js

This animation option works for 2.1.3 on a bar chart.

Slightly modified @Ross answer

animation: {
duration: 0,
onComplete: function () {
    // render the value of the chart above the bar
    var ctx = this.chart.ctx;
    ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily);
    ctx.fillStyle = this.chart.config.options.defaultFontColor;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'bottom';
    this.data.datasets.forEach(function (dataset) {
        for (var i = 0; i < dataset.data.length; i++) {
            var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
            ctx.fillText(dataset.data[i], model.x, model.y - 5);
        }
    });
}}

HTML text input field with currency symbol

I ended up needing the type to still remain as a number, so used CSS to push the dollar sign into the input field using an absolute position.

_x000D_
_x000D_
<div>_x000D_
   <span style="position: absolute; margin-left: 1px; margin-top: 1px;">$</span>_x000D_
   <input type="number" style="padding-left: 8px;">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Gradle sync failed: failed to find Build Tools revision 24.0.0 rc1

I ran into this problem after a fresh install of Android Studio (in GNU/Linux). I also used the installation wizard for Android SDK, and the Build Tools 28.0.3 were installed, although Android Studio tried to use 28.0.2 instead.

But the problem was not the build tools version but the license. I had not accepted the Android SDK license (the wizard does not ask for it), and Android Studio refused to use the build tools; the error message just is wrong.

In order to solve the problem, I manually accepted the license. In a terminal, I launched $ANDROID_SDK/tools/bin/sdkmanager --licenses and answered "Yes" for the SDK license. The other ones can be refused.