Programs & Examples On #Yfrog

Spring - download response as a file

You can't download a file through an XHR request (which is how Angular makes it's requests). See Why threre is no way to download file using ajax request? You either need to go to the URL via $window.open or do the iframe trick shown here: JavaScript/jQuery to download file via POST with JSON data

SQL - How do I get only the numbers after the decimal?

You can use FLOOR:

select x, ABS(x) - FLOOR(ABS(x))
from (
    select 2.938 as x
) a

Output:

x                                       
-------- ----------
2.938    0.938

Or you can use SUBSTRING:

select x, SUBSTRING(cast(x as varchar(max)), charindex(cast(x as varchar(max)), '.') + 3, len(cast(x as varchar(max))))
from (
    select 2.938 as x
) a

axios post request to send form data

2020 ES6 way of doing

Having the form in html I binded in data like so:

DATA:

form: {
   name: 'Joan Cap de porc',
   email: '[email protected]',
   phone: 2323,
   query: 'cap d\ou'
   file: null,
   legal: false
},

onSubmit:

async submitForm() {
  const formData = new FormData()
  Object.keys(this.form).forEach((key) => {
    formData.append(key, this.form[key])
  })

  try {
    await this.$axios.post('/ajax/contact/contact-us', formData)
    this.$emit('formSent')
  } catch (err) {
    this.errors.push('form_error')
  }
}

how to print a string to console in c++

yes it's possible to print a string to the console.

#include "stdafx.h"
#include <string>
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    string strMytestString("hello world");
    cout << strMytestString;
    return 0;
}

stdafx.h isn't pertinent to the solution, everything else is.

How to get the string size in bytes?

While sizeof works for this specific type of string:

char str[] = "content";
int charcount = sizeof str - 1; // -1 to exclude terminating '\0'

It does not work if str is pointer (sizeof returns size of pointer, usually 4 or 8) or array with specified length (sizeof will return the byte count matching specified length, which for char type are same).

Just use strlen().

how to "execute" make file

As paxdiablo said make -f pax.mk would execute the pax.mk makefile, if you directly execute it by typing ./pax.mk, then you would get syntax error.

Also you can just type make if your file name is makefile/Makefile.

Suppose you have two files named makefile and Makefile in the same directory then makefile is executed if make alone is given. You can even pass arguments to makefile.

Check out more about makefile at this Tutorial : Basic understanding of Makefile

Android Canvas: drawing too large bitmap

For this error was like others said a big image(1800px X 900px) which was in drawable directory, I edited the image and reduced the size proportionally using photoshop and it worked...!!

Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)

Your path only lists Visual Studio 11 and 12, it wants 14, which is Visual Studio 2015. If you install that, and remember to tick the box for Languages->C++ then it should work.

On my Python 3.5 install, the error message was a little more useful, and included the URL to get it from

 error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

Edit: New working link

Edit: As suggested by Lightfire228, you may also need to upgrade setuptools package for the error to disappear:

pip install --upgrade setuptools

Generate an HTML Response in a Java Servlet

Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:

public void doGet(HttpServletRequest request,
       HttpServletResponse response)
       throws IOException, ServletException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   out.println("HTML from an external file:");     
   request.getRequestDispatcher("/pathToFile/fragment.html")
          .include(request, response); 
   out.close();
}

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

Concatenating strings doesn't work as expected

I would do this:

std::string a("Hello ");
std::string b("World");
std::string c = a + b;

Which compiles in VS2008.

Enter key in textarea

You could do something like this:

<body>

<textarea id="txtArea" onkeypress="onTestChange();"></textarea>

<script>
function onTestChange() {
    var key = window.event.keyCode;

    // If the user has pressed enter
    if (key === 13) {
        document.getElementById("txtArea").value = document.getElementById("txtArea").value + "\n*";
        return false;
    }
    else {
        return true;
    }
}
</script>

</body>

Although the new line character feed from pressing enter will still be there, but its a start to getting what you want.

Get connection string from App.config

string str = Properties.Settings.Default.myConnectionString; 

NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle

I had renamed a xib and had this problem, the solution for me was to edit the main window.xib manually and change the offending text

search for the offending xib name in the relevant xib ( view as source code)

changed

<viewController nibName="OldNibName" id="116" customClass="SomeViewController">

with

<viewController nibName="NewNibName" id="116" customClass="SomeViewController">

and it worked

UTF-8: General? Bin? Unicode?

Accepted answer is outdated.

If you use MySQL 5.5.3+, use utf8mb4_unicode_ci instead of utf8_unicode_ci to ensure the characters typed by your users won't give you errors.

utf8mb4 supports emojis for example, whereas utf8 might give you hundreds of encoding-related bugs like:

Incorrect string value: ‘\xF0\x9F\x98\x81…’ for column ‘data’ at row 1

Not able to start Genymotion device

In my case, I restart the computer and enable the virtualization technology in BIOS. Then start up computer, open VM Virtual Box, choose a virtual device, go to Settings-General-Basic-Version, choose ubuntu(64 bit), save the settings then start virtual device from genymotion, everything is ok now.

How to Display Selected Item in Bootstrap Button Dropdown Title

you need to use add class open in <div class="btn-group open">

and in li add class="active"

Variable might not have been initialized error

You declared them, but not initialized.

int a; // declaration, unknown value
a = 0; // initialization
int a = 0; // declaration with initialization

Get all inherited classes of an abstract class

It may not be the elegant way but you can iterate all classes in the assembly and invoke Type.IsSubclassOf(AbstractDataExport) for each one.

sql like operator to get the numbers only

what might get you where you want in plain SQL92:

select * from tbl where lower(answer) = upper(answer)

or, if you also want to be robust for leading/trailing spaces:

select * from tbl where lower(answer) = trim(upper(answer))

How to manually trigger click event in ReactJS?

In a functional component this principle also works, it's just a slightly different syntax and way of thinking.

const UploadsWindow = () => {
  // will hold a reference for our real input file
  let inputFile = '';

  // function to trigger our input file click
  const uploadClick = e => {
    e.preventDefault();
    inputFile.click();
    return false;
  };

  return (
    <>
      <input
        type="file"
        name="fileUpload"
        ref={input => {
          // assigns a reference so we can trigger it later
          inputFile = input;
        }}
        multiple
      />

      <a href="#" className="btn" onClick={uploadClick}>
        Add or Drag Attachments Here
      </a>
    </>
  )

}

How do I declare a namespace in JavaScript?

I think you all use too much code for such a simple problem. No need to make a repo for that. Here's a single line function.

namespace => namespace.split(".").reduce((last, next) => (last[next] = (last[next] || {})), window);

Try it :

_x000D_
_x000D_
// --- definition ---
const namespace = name => name.split(".").reduce((last, next) => (last[next] = (last[next] || {})), window);

// --- Use ----
const c = namespace("a.b.c");
c.MyClass = class MyClass {};

// --- see ----
console.log("a : ", a);
_x000D_
_x000D_
_x000D_

Directory Chooser in HTML page

If you do not have too many folders then I suggest you use if statements to choose an upload folder depending on the user input details. E.g.

String user= request.getParameter("username");
if (user=="Alfred"){
//Path A;
}
if (user=="other"){
//Path B;
}

How do I delete virtual interface in Linux?

You can use sudo ip link delete to remove the interface.

Ruby on Rails: How do I add placeholder text to a f.text_field?

I tried the solutions above and it looks like on rails 5.* the second agument by default is the value of the input form, what worked for me was:

text_field_tag :attr, "", placeholder: "placeholder text"

How do I change screen orientation in the Android emulator?

Num 7 on keypad does it for me. Remember it works only when Num Lock is off.

Controlling a USB power supply (on/off) with Linux

I wanted to do this, and with my USB hardware I couldn't. I wrote a hacky way how to do it here:

http://pintant.cat/2012/05/12/power-off-usb-device/ .

In a short way: I used a USB relay to open/close the VCC of another USB cable...

Executing JavaScript after X seconds

I believe you are looking for the setTimeout function.

To make your code a little neater, define a separate function for onclick in a <script> block:

function myClick() {
  setTimeout(
    function() {
      document.getElementById('div1').style.display='none';
      document.getElementById('div2').style.display='none';
    }, 5000);
}

then call your function from onclick

onclick="myClick();"

Provide static IP to docker containers via docker-compose

I was facing some difficulties with an environment variable that is with custom name (not with container name /port convention for KAPACITOR_BASE_URL and KAPACITOR_ALERTS_ENDPOINT). If we give service name in this case it wouldn't resolve the ip as

KAPACITOR_BASE_URL:  http://kapacitor:9092

In above http://[**kapacitor**]:9092 would not resolve to http://172.20.0.2:9092

I resolved the static IPs issues using subnetting configurations.

version: "3.3"

networks:
  frontend:
    ipam:
      config:
        - subnet: 172.20.0.0/24
services:
    db:
        image: postgres:9.4.4
        networks:
            frontend:
                ipv4_address: 172.20.0.5
        ports:
            - "5432:5432"
        volumes:
            - postgres_data:/var/lib/postgresql/data

    redis:
        image: redis:latest
        networks:
            frontend:
                ipv4_address: 172.20.0.6
        ports:
            - "6379"

    influxdb:
        image: influxdb:latest
        ports:
            - "8086:8086"
            - "8083:8083"
        volumes:
            - ../influxdb/influxdb.conf:/etc/influxdb/influxdb.conf
            - ../influxdb/inxdb:/var/lib/influxdb
        networks:
            frontend:
                ipv4_address: 172.20.0.4
        environment:
          INFLUXDB_HTTP_AUTH_ENABLED: "false"
          INFLUXDB_ADMIN_ENABLED: "true"
          INFLUXDB_USERNAME: "db_username"
          INFLUXDB_PASSWORD: "12345678"
          INFLUXDB_DB: db_customers

    kapacitor:
        image: kapacitor:latest
        ports: 
            - "9092:9092"
        networks:
            frontend:
                ipv4_address: 172.20.0.2
        depends_on:
            - influxdb
        volumes:
            - ../kapacitor/kapacitor.conf:/etc/kapacitor/kapacitor.conf
            - ../kapacitor/kapdb:/var/lib/kapacitor
        environment:
          KAPACITOR_INFLUXDB_0_URLS_0: http://influxdb:8086

    web:
        build: .
        environment:
          RAILS_ENV: $RAILS_ENV
        command: bundle exec rails s -b 0.0.0.0
        ports:
            - "3000:3000"
        networks:
            frontend:
                ipv4_address: 172.20.0.3
        links:
            - db
            - kapacitor
        depends_on:
            - db
        volumes:
            - .:/var/app/current
        environment:
          DATABASE_URL: postgres://postgres@db
          DATABASE_USERNAME: postgres
          DATABASE_PASSWORD: postgres
          INFLUX_URL: http://influxdb:8086
          INFLUX_USER: db_username
          INFLUX_PWD: 12345678
          KAPACITOR_BASE_URL:  http://172.20.0.2:9092
          KAPACITOR_ALERTS_ENDPOINT: http://172.20.0.3:3000

volumes:
  postgres_data:

Command to run a .bat file

There are many possibilities to solve this task.

1. RUN the batch file with full path

The easiest solution is running the batch file with full path.

"F:\- Big Packets -\kitterengine\Common\Template.bat"

Once end of batch file Template.bat is reached, there is no return to previous script in case of the command line above is within a *.bat or *.cmd file.

The current directory for the batch file Template.bat is the current directory of the current process. In case of Template.bat requires that the directory of this batch file is the current directory, the batch file Template.bat should contain after @echo off as second line the following command line:

cd /D "%~dp0"

Run in a command prompt window cd /? for getting displayed the help of this command explaining parameter /D ... change to specified directory also on a different drive.

Run in a command prompt window call /? for getting displayed the help of this command used also in 2., 4. and 5. solution and explaining also %~dp0 ... drive and path of argument 0 which is the name of the batch file.

2. CALL the batch file with full path

Another solution is calling the batch file with full path.

call "F:\- Big Packets -\kitterengine\Common\Template.bat"

The difference to first solution is that after end of batch file Template.bat is reached the batch processing continues in batch script containing this command line.

For the current directory read above.

3. Change directory and RUN batch file with one command line

There are 3 operators for running multiple commands on one command line: &, && and ||.
For details see answer on Single line with multiple commands using Windows batch file

I suggest for this task the && operator.

cd /D "F:\- Big Packets -\kitterengine\Common" && Template.bat

As on first solution there is no return to current script if this is a *.bat or *.cmd file and changing the directory and continuation of batch processing on Template.bat is successful.

4. Change directory and CALL batch file with one command line

This command line changes the directory and on success calls the batch file.

cd /D "F:\- Big Packets -\kitterengine\Common" && call Template.bat

The difference to third solution is the return to current batch script on exiting processing of Template.bat.

5. Change directory and CALL batch file with keeping current environment with one command line

The four solutions above change the current directory and it is unknown what Template.bat does regarding

  1. current directory
  2. environment variables
  3. command extensions state
  4. delayed expansion state

In case of it is important to keep the environment of current *.bat or *.cmd script unmodified by whatever Template.bat changes on environment for itself, it is advisable to use setlocal and endlocal.

Run in a command prompt window setlocal /? and endlocal /? for getting displayed the help of these two commands. And read answer on change directory command cd ..not working in batch file after npm install explaining more detailed what these two commands do.

setlocal & cd /D "F:\- Big Packets -\kitterengine\Common" & call Template.bat & endlocal

Now there is only & instead of && used as it is important here that after setlocal is executed the command endlocal is finally also executed.


ONE MORE NOTE

If batch file Template.bat contains the command exit without parameter /B and this command is really executed, the command process is always exited independent on calling hierarchy. So make sure Template.bat contains exit /B or goto :EOF instead of just exit if there is exit used at all in this batch file.

How do format a phone number as a String in Java?

The easiest way to do this is by using the built in MaskFormatter in the javax.swing.text library.

You can do something like this :

import javax.swing.text.MaskFormatter;

String phoneMask= "###-###-####";
String phoneNumber= "123423452345";

MaskFormatter maskFormatter= new MaskFormatter(phoneMask);
maskFormatter.setValueContainsLiteralCharacters(false);
maskFormatter.valueToString(phoneNumber) ;

Sprintf equivalent in Java

Since Java 13 you have formatted 1 method on String, which was added along with text blocks as a preview feature 2. You can use it instead of String.format()

Assertions.assertEquals(
   "%s %d %.3f".formatted("foo", 123, 7.89),
   "foo 123 7.890"
);

Javascript Print iframe contents only

I had issues with all of the above solutions in IE8, have found a decent workaround that is tested in IE 8+9, Chrome, Safari and Firefox. For my situation i needed to print a report that was generated dynamically:

// create content of iframe
var content = '<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">'+
'<head><link href="/css/print.css" media="all" rel="stylesheet" type="text/css"></head>'+
'<body>(rest of body content)'+
'<script type="text/javascript">function printPage() { window.focus(); window.print();return; }</script>'+
'</body></html>';

Note the printPage() javascript method before the body close tag.

Next create the iframe and append it to the parent body so its contentWindow is available:

var newIframe = document.createElement('iframe');
newIframe.width = '0';
newIframe.height = '0';
newIframe.src = 'about:blank';
document.body.appendChild(newIframe);

Next set the content:

newIframe.contentWindow.contents = content;
newIframe.src = 'javascript:window["contents"]';

Here we are setting the dynamic content variable to the iframe's window object then invoking it via the javascript: scheme.

Finally to print; focus the iframe and call the javascript printPage() function within the iframe content:

newIframe.focus();
setTimeout(function() {
  newIframe.contentWindow.printPage();
}, 200);
return;

The setTimeout is not necessarily needed, however if you're loading large amounts of content i found Chrome occasionally failed to print without it so this step is recommended. The alternative is to wrap 'newIframe.contentWindow.printPage();' in a try catch and place the setTimeout wrapped version in the catch block.

Hope this helps someone as i spent a lot of time finding a solution that worked well across multiple browsers. Thanks to SpareCycles.

EDIT:

Instead of using setTimeout to call the printPage function use the following:

newIframe.onload = function() {
    newIframe.contentWindow.printPage();
}

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

What went wrong?

When you include jQuery the first time:

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>

The second script plugs itself into jQuery, and "adds" $(...).datepicker.

But then you are including jQuery once again:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

It undoes the plugging in and therefore $(...).datepicker becomes undefined.

Although the first $(document).ready block appears before that, the anonymous callback function body is not executed until all scripts are loaded, and by then $(...) (window.$ to be precise) is referring to the most recently loaded jQuery.

You would not run into this if you called $('.dateinput').datepicker immediately rather than in $(document).ready callback, but then you'd need to make sure that the target element (with class dateinput) is already in the document before the script, and it's generally advised to use the ready callback.

Solution

If you want to use datepicker from jquery-ui, it would probably make most sense to include the jquery-ui script after bootstrap. jquery-ui 1.11.4 is compatible with jquery 1.6+ so it will work fine.

Alternatively (in particular if you are not using jquery-ui for anything else), you could try bootstrap-datepicker.

Angular 2: How to access an HTTP response body?

This is work for me 100% :

let data:Observable<any> = this.http.post(url, postData);
  data.subscribe((data) => {

  let d = data.json();
  console.log(d);
  console.log("result = " + d.result);
  console.log("url = " + d.image_url);      
  loader.dismiss();
});

Laravel requires the Mcrypt PHP extension

For php-fpm installations on Ubuntu 14.04, the following worked for me :

sudo apt-get install php5-mcrypt

This will create mcrypt.ini file inside /etc/php5/mods-available/

Then

sudo php5enmod mcrypt

will create a symlink in: /etc/php5/fpm/conf.d/

Just restart php-fpm services sudo service php5-fpm restart

In MySQL, can I copy one row to insert into the same table?

This is an additional solution to the answer by "Grim..." There have been some comments on it having a primary key as null. Some comments about it not working. And some comments on solutions. None of the solutions worked for us. We have MariaDB with the InnoDB table.

We could not set the primary key to allow null. Using 0 instead of NULL led to duplicate value error for the primary key. SET SQL_SAFE_UPDATES = 0; Did not work either.

The solution from "Grim..." did work IF we changed our PRIMARY KEY to UNIQUE instead

What is the LD_PRELOAD trick?

As many people mentioned, using LD_PRELOAD to preload library. BTW, you can CHECK if the setting is available by ldd command.

Example: suppose you need to preload your own libselinux.so.1.

> ldd /bin/ls
    ...
    libselinux.so.1 => /lib/x86_64-linux-gnu/libselinux.so.1 (0x00007f3927b1d000)
    libacl.so.1 => /lib/x86_64-linux-gnu/libacl.so.1 (0x00007f3927914000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f392754f000)
    libpcre.so.3 => /lib/x86_64-linux-gnu/libpcre.so.3 (0x00007f3927311000)
    libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f392710c000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f3927d65000)
    libattr.so.1 => /lib/x86_64-linux-gnu/libattr.so.1 (0x00007f3926f07000)

Thus, set your preload environment:

  export LD_PRELOAD=/home/patric/libselinux.so.1

Check your library again:

>ldd /bin/ls
    ...
    libselinux.so.1 =>
    /home/patric/libselinux.so.1 (0x00007fb9245d8000)
    ...

How to order a data frame by one descending and one ascending column?

I'm afraid Roman Luštrik's answer is wrong. It works on this input by chance. Consider for example its output on a very similar input (with an additional line similar to the original line 3 with "c" in the I2 column):

rum <- read.table(textConnection("P1  P2  P3  T1  T2  T3  I1  I2
2   3   5   52  43  61  6   b
6   4   3   72  NA  59  1   a
1   5   6   55  48  60  6   f
2   4   4   65  64  58  2   b
1   5   6   55  48  60  6   c"), header = TRUE)

rum$I2 <- as.character(rum$I2)
rum[order(rum$I1, rev(rum$I2), decreasing = TRUE), ]

  P1 P2 P3 T1 T2 T3 I1 I2
3  1  5  6 55 48 60  6  f
1  2  3  5 52 43 61  6  b
5  1  5  6 55 48 60  6  c
4  2  4  4 65 64 58  2  b
2  6  4  3 72 NA 59  1  a

This is not the desired result: the first three values of I2 are f b c instead of b c f, which would be expected since the secondary sort is I2 in ascending order.

To get the reverse order of I2, you want the large values to be small and vice versa. For numeric values multiplying by -1 will do it, but for characters its a bit more tricky. A general solution for characters/strings would be to go through factors, reverse the levels (to make large values small and small values large) and change the factor back to characters:

rum <- read.table(textConnection("P1  P2  P3  T1  T2  T3  I1  I2
2   3   5   52  43  61  6   b
6   4   3   72  NA  59  1   a
1   5   6   55  48  60  6   f
2   4   4   65  64  58  2   b
1   5   6   55  48  60  6   c"), header = TRUE)

f=factor(rum$I2)
levels(f) = rev(levels(f))
rum[order(rum$I1, as.character(f), decreasing = TRUE), ]

  P1 P2 P3 T1 T2 T3 I1 I2
1  2  3  5 52 43 61  6  b
5  1  5  6 55 48 60  6  c
3  1  5  6 55 48 60  6  f
4  2  4  4 65 64 58  2  b
2  6  4  3 72 NA 59  1  a

Best way to handle list.index(might-not-exist) in python?

What about this :

li = [1,2,3,4,5] # create list 

li = dict(zip(li,range(len(li)))) # convert List To Dict 
print( li ) # {1: 0, 2: 1, 3: 2, 4:3 , 5: 4}
li.get(20) # None 
li.get(1)  # 0 

How can the Euclidean distance be calculated with NumPy?

Calculate the Euclidean distance for multidimensional space:

 import math

 x = [1, 2, 6] 
 y = [-2, 3, 2]

 dist = math.sqrt(sum([(xi-yi)**2 for xi,yi in zip(x, y)]))
 5.0990195135927845

jquery validate check at least one checkbox

The validate plugin will only validate the current/focused element.Therefore you will need to add a custom rule to the validator to validate all the checkboxes. Similar to the answer above.

$.validator.addMethod("roles", function(value, elem, param) {
   return $(".roles:checkbox:checked").length > 0;
},"You must select at least one!");

And on the element:

<input class='{roles: true}' name='roles' type='checkbox' value='1' />

In addition, you will likely find the error message display, not quite sufficient. Only 1 checkbox is highlighted and only 1 message displayed. If you click another separate checkbox, which then returns a valid for the second checkbox, the original one is still marked as invalid, and the error message is still displayed, despite the form being valid. I have always resorted to just displaying and hiding the errors myself in this case.The validator then only takes care of not submitting the form.

The other option you have is to write a function that will change the value of a hidden input to be "valid" on the click of a checkbox and then attach the validation rule to the hidden element. This will only validate in the onSubmit event though, but will display and hide messages at the appropriate times. Those are about the only options that you can use with the validate plugin.

Hope that helps!

C++ Fatal Error LNK1120: 1 unresolved externals

I have faced this particular error when I didn't defined the main() function. Check if the main() function exists or check the name of the function letter by letter as Timothy described above or check if the file where the main function is located is included to your project.

What is the difference between fastcgi and fpm?

What Anthony says is absolutely correct, but I'd like to add that your experience will likely show a lot better performance and efficiency (due not to fpm-vs-fcgi but more to the implementation of your httpd).

For example, I had a quad-core machine running lighttpd + fcgi humming along nicely. I upgraded to a 16-core machine to cope with growth, and two things exploded: RAM usage, and segfaults. I found myself restarting lighttpd every 30 minutes to keep the website up.

I switched to php-fpm and nginx, and RAM usage dropped from >20GB to 2GB. Segfaults disappeared as well. After doing some research, I learned that lighttpd and fcgi don't get along well on multi-core machines under load, and also have memory leak issues in certain instances.

Is this due to php-fpm being better than fcgi? Not entirely, but how you hook into php-fpm seems to be a whole heckuva lot more efficient than how you serve via fcgi.

HTML anchor link - href and onclick both?

Just return true instead?

The return value from the onClick code is what determines whether the link's inherent clicked action is processed or not - returning false means that it isn't processed, but if you return true then the browser will proceed to process it after your function returns and go to the proper anchor.

Origin is not allowed by Access-Control-Allow-Origin

You may make it work without modifiying the server by making the broswer including the header Access-Control-Allow-Origin: * in the HTTP OPTIONS' responses.

In Chrome, use this extension. If you are on Mozilla check this answer.

Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

I was getting this exception every time I created a "new" project.

My solution was:

  • Go menu Tools ? Extensions and Updates
  • Not check the "Updates" link...search "asp.net". There was an update to Microsoft ASP.NET and Web Tools. Get it as AspNetWebFrameworksTools2015_KB3137909.exe and install it.

That fixed it for me.


Unfortunately, I ran into another exception:

"Exception has been thrown by the target of an invocation"

I disabled the FIPS setting Enabled DWORD value to zero.

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\FipsAlgorithmPolicy]
Enabled=dword:00000000 And All fixed.

MS Access - execute a saved query by name in VBA

Thre are 2 ways to run Action Query in MS Access VBA:


  1. You can use DoCmd.OpenQuery statement. This allows you to control these warnings:

Action Query Warning Example

BUT! Keep in mind that DoCmd.SetWarnings will remain set even after the function completes. This means that you need to make sure that you leave it in a condition that suits your needs

Function RunActionQuery(QueryName As String)
    On Error GoTo Hell              'Set Error Hanlder
    DoCmd.SetWarnings True          'Turn On Warnings
    DoCmd.OpenQuery QueryName       'Execute Action Query
    DoCmd.SetWarnings False         'Turn On Warnings
    Exit Function
Hell:
    If Err.Number = 2501 Then       'If Query Was Canceled
        MsgBox Err.Description, vbInformation
    Else                            'Everything else
        MsgBox Err.Description, vbCritical
    End If
End Function

  1. You can use CurrentDb.Execute method. This alows you to keep Action Query failures under control. The SetWarnings flag does not affect it. Query is executed always without warnings.
Function RunActionQuery()
    'To Catch the Query Error use dbFailOnError option
    On Error GoTo Hell
    CurrentDb.Execute "Query1", dbFailOnError
    Exit Function
Hell:
    Debug.Print Err.Description
End Function

It is worth noting that the dbFailOnError option responds only to data processing failures. If the Query contains an error (such as a typo), then a runtime error is generated, even if this option is not specified


In addition, you can use DoCmd.Hourglass True and DoCmd.Hourglass False to control the mouse pointer if your Query takes longer

How to receive serial data using android bluetooth

I tried this out for transmitting continuous data (float values converted to string) from my PC (MATLAB) to my phone. But, still my App misreads the delimiter '\n' and still data gets garbled. So, I took the character 'N' as the delimiter rather than '\n' (it could be any character that doesn't occur as part of your data) and I've achieved better transmission speed - I gave just 0.1 seconds delay between transmitting successive samples - with more than 99% data integrity at the receiver i.e. out of 2000 samples (float values) that I transmitted, only 10 were not decoded properly in my application.

My answer in short is: Choose a delimiter other than '\r' or '\n' as these create more problems for real-time data transmission when compared to other characters like the one I've used. If we work more, may be we can increase the transmission rate even more. I hope my answer helps someone!

Import error No module named skimage

For OSX: pip install scikit-image

and then run python to try following

from skimage.feature import corner_harris, corner_peaks

What is the difference between concurrent programming and parallel programming?

Different people talk about different kinds of concurrency and parallelism in many different specific cases, so some abstractions to cover their common nature are needed.

The basic abstraction is done in computer science, where both concurrency and parallelism are attributed to the properties of programs. Here, programs are formalized descriptions of computing. Such programs need not to be in any particular language or encoding, which is implementation-specific. The existence of API/ABI/ISA/OS is irrelevant to such level of abstraction. Surely one will need more detailed implementation-specific knowledge (like threading model) to do concrete programming works, the spirit behind the basic abstraction is not changed.

A second important fact is, as general properties, concurrency and parallelism can coexist in many different abstractions.

For the general distinction, see the relevant answer for the basic view of concurrency v. parallelism. (There are also some links containing some additional sources.)

Concurrent programming and parallel programming are techniques to implement such general properties with some systems which expose programmability. The systems are usually programming languages and their implementations.

A programming language may expose the intended properties by built-in semantic rules. In most cases, such rules specify the evaluations of specific language structures (e.g. expressions) making the computation involved effectively concurrent or parallel. (More specifically, the computational effects implied by the evaluations can perfectly reflect these properties.) However, concurrent/parallel language semantics are essentially complex and they are not necessary to practical works (to implement efficient concurrent/parallel algorithms as the solutions of realistic problems). So, most traditional languages take a more conservative and simpler approach: assuming the semantics of evaluation totally sequential and serial, then providing optional primitives to allow some of the computations being concurrent and parallel. These primitives can be keywords or procedural constructs ("functions") supported by the language. They are implemented based on the interaction with hosted environments (OS, or "bare metal" hardware interface), usually opaque (not able to be derived using the language portably) to the language. Thus, in this particular kind of high-level abstractions seen by the programmers, nothing is concurrent/parallel besides these "magic" primitives and programs relying on these primitives; the programmers can then enjoy less error-prone experience of programming when concurrency/parallelism properties are not so interested.

Although primitives abstract the complex away in the most high-level abstractions, the implementations still have the extra complexity not exposed by the language feature. So, some mid-level abstractions are needed. One typical example is threading. Threading allows one or more thread of execution (or simply thread; sometimes it is also called a process, which is not necessarily the concept of a task scheduled in an OS) supported by the language implementation (the runtime). Threads are usually preemptively scheduled by the runtime, so a thread needs to know nothing about other threads. Thus, threads are natural to implement parallelism as long as they share nothing (the critical resources): just decompose computations in different threads, once the underlying implementation allows the overlapping of the computation resources during the execution, it works. Threads are also subject to concurrent accesses of shared resources: just access resources in any order meets the minimal constraints required by the algorithm, and the implementation will eventually determine when to access. In such cases, some synchronization operations may be necessary. Some languages treat threading and synchronization operations as parts of the high-level abstraction and expose them as primitives, while some other languages encourage only relatively more high-level primitives (like futures/promises) instead.

Under the level of language-specific threads, there come multitasking of the underlying hosting environment (typically, an OS). OS-level preemptive multitasking are used to implement (preemptive) multithreading. In some environments like Windows NT, the basic scheduling units (the tasks) are also "threads". To differentiate them with userspace implementation of threads mentioned above, they are called kernel threads, where "kernel" means the kernel of the OS (however, strictly speaking, this is not quite true for Windows NT; the "real" kernel is the NT executive). Kernel threads are not always 1:1 mapped to the userspace threads, although 1:1 mapping often reduces most overhead of mapping. Since kernel threads are heavyweight (involving system calls) to create/destroy/communicate, there are non 1:1 green threads in the userspace to overcome the overhead problems at the cost of the mapping overhead. The choice of mapping depending on the programming paradigm expected in the high-level abstraction. For example, when a huge number of userspace threads expected being concurrently executed (like Erlang), 1:1 mapping is never feasible.

The underlying of OS multitasking is ISA-level multitasking provided by the logical core of the processor. This is usually the most low-level public interface for programmers. Beneath this level, there may exist SMT. This is a form of more low-level multithreading implemented by the hardware, but arguably, still somewhat programmable - though it is usually only accessible by the processor manufacturer. Note the hardware design is apparently reflecting parallelism, but there is also concurrent scheduling mechanism to make the internal hardware resources being efficiently used.

In each level of "threading" mentioned above, both concurrency and parallelism are involved. Although the programming interfaces vary dramatically, all of them are subject to the properties revealed by the basic abstraction at the very beginning.

process.waitFor() never returns

Also from Java doc:

java.lang

Class Process

Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

Fail to clear the buffer of input stream (which pipes to the output stream of subprocess) from Process may lead to a subprocess blocking.

Try this:

Process process = Runtime.getRuntime().exec("tasklist");
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((reader.readLine()) != null) {}
process.waitFor();

Seeing the underlying SQL in the Spring JdbcTemplate?

Try adding in log4j.xml

<!--  enable query logging -->
<category name="org.springframework.jdbc.core.JdbcTemplate">
    <priority value="DEBUG" />
</category>

<!-- enable query logging for SQL statement parameter value -->
<category name="org.springframework.jdbc.core.StatementCreatorUtils">
    <priority value="TRACE" />
</category>

your logs looks like:

DEBUG JdbcTemplate:682 - Executing prepared SQL query
DEBUG JdbcTemplate:616 - Executing prepared SQL statement [your sql query]
TRACE StatementCreatorUtils:228 - Setting SQL statement parameter value: column index 1, parameter value [param], value class [java.lang.String], SQL type unknown

Error in file(file, "rt") : cannot open the connection

Error in file(file, "rt") :

I just faced the same error and resolved by removing spacing in address using paste0 instead of paste

filepath=paste0(directory,"/",filename[1],sep="")

Static methods in Python?

You don't really need to use the @staticmethod decorator. Just declaring a method (that doesn't expect the self parameter) and call it from the class. The decorator is only there in case you want to be able to call it from an instance as well (which was not what you wanted to do)

Mostly, you just use functions though...

Where is GACUTIL for .net Framework 4.0 in windows 7?

VS 2012/13 Win 7 64 bit gacutil.exe is located in

C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools

querySelectorAll with multiple conditions

Is it possible to make a search by querySelectorAll using multiple unrelated conditions?

Yes, because querySelectorAll accepts full CSS selectors, and CSS has the concept of selector groups, which lets you specify more than one unrelated selector. For instance:

var list = document.querySelectorAll("form, p, legend");

...will return a list containing any element that is a form or p or legend.

CSS also has the other concept: Restricting based on more criteria. You just combine multiple aspects of a selector. For instance:

var list = document.querySelectorAll("div.foo");

...will return a list of all div elements that also (and) have the class foo, ignoring other div elements.

You can, of course, combine them:

var list = document.querySelectorAll("div.foo, p.bar, div legend");

...which means "Include any div element that also has the foo class, any p element that also has the bar class, and any legend element that's also inside a div."

How do I run a simple bit of code in a new thread?

I'd recommend looking at Jeff Richter's Power Threading Library and specifically the IAsyncEnumerator. Take a look at the video on Charlie Calvert's blog where Richter goes over it for a good overview.

Don't be put off by the name because it makes asynchronous programming tasks easier to code.

How can I suppress the newline after a print statement?

print didn't transition from statement to function until Python 3.0. If you're using older Python then you can suppress the newline with a trailing comma like so:

print "Foo %10s bar" % baz,

Importing Excel files into R, xlsx or xls

If you are running into the same problem and R is giving you an error -- could not find function ".jnew" -- Just install the library rJava. Or if you have it already just run the line library(rJava). That should be the problem.

Also, it should be clear to everybody that csv and txt files are easier to work with, but life is not easy and sometimes you just have to open an xlsx.

Convert a String to int?

With a recent nightly, you can do this:

let my_int = from_str::<int>(&*my_string);

What's happening here is that String can now be dereferenced into a str. However, the function wants an &str, so we have to borrow again. For reference, I believe this particular pattern (&*) is called "cross-borrowing".

Copy tables from one database to another in SQL Server

You may go with this way: ( a general example )

insert into QualityAssuranceDB.dbo.Customers (columnA, ColumnB)
Select columnA, columnB from DeveloperDB.dbo.Customers

Also if you need to generate the column names as well to put in insert clause, use:

    select (name + ',') as TableColumns from sys.columns 
where object_id = object_id('YourTableName')

Copy the result and paste into query window to represent your table column names and even this will exclude the identity column as well:

    select (name + ',') as TableColumns from sys.columns 
where object_id = object_id('YourTableName') and is_identity = 0

Remember the script to copy rows will work if the databases belongs to the same location.


You can Try This.

select * into <Destination_table> from <Servername>.<DatabaseName>.dbo.<sourceTable>

Server name is optional if both DB is in same server.

Class vs. static method in JavaScript

When i faced such a situation, i have done something like this:

Logger = {
    info: function (message, tag) {
        var fullMessage = '';        
        fullMessage = this._getFormatedMessage(message, tag);
        if (loggerEnabled) {
            console.log(fullMessage);
        }
    },
    warning: function (message, tag) {
        var fullMessage = '';
        fullMessage = this._getFormatedMessage(message, tag);
        if (loggerEnabled) {
            console.warn(fullMessage);`enter code here`
        }
    },
    _getFormatedMessage: function () {}
};

so now i can call the info method as Logger.info("my Msg", "Tag");

Entity framework code-first null foreign key

I recommend to read Microsoft guide for use Relationships, Navigation Properties and Foreign Keys in EF Code First, like this picture.

enter image description here

Guide link below:

https://docs.microsoft.com/en-gb/ef/ef6/fundamentals/relationships?redirectedfrom=MSDN

How to generate and manually insert a uniqueidentifier in sql server?

Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .

*Your parameter order is passed wrongly , Parameter @id should be passed as first argument, but in your script it is placed in second argument..*

So error is raised..

Please refere sample script:

DECLARE @id uniqueidentifier
SET @id = NEWID()
Create Table #temp1(AppId uniqueidentifier)

insert into #temp1 values(@id)

Select * from #temp1

Drop Table #temp1

How to use cookies in Python Requests

From the documentation:

  1. get cookie from response

    url = 'http://example.com/some/cookie/setting/url'
    r = requests.get(url)
    r.cookies
    

    {'example_cookie_name': 'example_cookie_value'}

  2. give cookie back to server on subsequent request

    url = 'http://httpbin.org/cookies'
    cookies = dict(cookies_are='working')
    r = requests.get(url, cookies=cookies)`
    

Sass calculate percent minus px

Sorry for reviving old thread - Compass' stretch with an :after pseudo-selector might suit your purpose - eg. if you want a div to fill width from left to (50% + 10px) of screen you could use (in SASS indented syntax):

.example
    background: red
    +stretch(0, -10px, 0, 0)
    &:after
        +stretch(0, 0, 0, 50%)
        content: ' '
        background: blue

The :after element fills 50% to the right of .example (leaving 50% available for .example's width), then .example is stretched to that width plus 10px.

ImportError: cannot import name

The problem is that you have a circular import: in app.py

from mod_login import mod_login

in mod_login.py

from app import app

This is not permitted in Python. See Circular import dependency in Python for more info. In short, the solution are

  • either gather everything in one big file
  • delay one of the import using local import

Indentation shortcuts in Visual Studio

Just hit Tab to push it over or on the menu bar Edit --> Advanced --> Format Selection and that will auto indent, the keyboard shortcut is also shown in the menu.

How do I access (read, write) Google Sheets spreadsheets with Python?

The latest google api docs document how to write to a spreadsheet with python but it's a little difficult to navigate to. Here is a link to an example of how to append.

The following code is my first successful attempt at appending to a google spreadsheet.

import httplib2
import os

from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'


def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'mail_to_g_app.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def add_todo():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                    'version=v4')
    service = discovery.build('sheets', 'v4', http=http,
                              discoveryServiceUrl=discoveryUrl)

    spreadsheetId = 'PUT YOUR SPREADSHEET ID HERE'
    rangeName = 'A1:A'

    # https://developers.google.com/sheets/guides/values#appending_values
    values = {'values':[['Hello Saturn',],]}
    result = service.spreadsheets().values().append(
        spreadsheetId=spreadsheetId, range=rangeName,
        valueInputOption='RAW',
        body=values).execute()

if __name__ == '__main__':
    add_todo()

Commenting multiple lines in DOS batch file

break||(
 code that cannot contain non paired closing bracket
)

While the goto solution is a good option it will not work within brackets (including FOR and IF commands).But this will. Though you should be careful about closing brackets and invalid syntax for FOR and IF commands because they will be parsed.

Update

The update in the dbenham's answer gave me some ideas. First - there are two different cases where we can need multi line comments - in a bracket's context where GOTO cannot be used and outside it. Inside brackets context we can use another brackets if there's a condition which prevents the code to be executed.Though the code thede will still be parsed and some syntax errors will be detected (FOR,IF ,improperly closed brackets, wrong parameter expansion ..).So if it is possible it's better to use GOTO.

Though it is not possible to create a macro/variable used as a label - but is possible to use macros for bracket's comments.Still two tricks can be used make the GOTO comments more symetrical and more pleasing (at least for me). For this I'll use two tricks - 1) you can put a single symbol in front of a label and goto will still able to find it (I have no idea why is this.My guues it is searching for a drive). 2) you can put a single : at the end of a variable name and a replacement/subtring feature will be not triggered (even under enabled extensions). Wich combined with the macros for brackets comments can make the both cases to look almost the same.

So here are the examples (in the order I like them most):

With rectangular brackets:

@echo off

::GOTO comment macro
set "[:=goto :]%%"
::brackets comment macros
set "[=rem/||(" & set "]=)"

::testing
echo not commented 1

%[:%
  multi 
  line
  comment outside of brackets
%:]%

echo not commented 2

%[:%
  second multi 
  line
  comment outside of brackets
%:]%

::GOTO macro cannot be used inside for
for %%a in (first second) do (
    echo first not commented line of the %%a execution
    %[%
        multi line
        comment
    %]%
    echo second not commented line of the %%a execution
)

With curly brackets:

@echo off

::GOTO comment macro
set "{:=goto :}%%"
::brackets comment macros
set "{=rem/||(" & set "}=)"

::testing
echo not commented 1

%{:%
  multi 
  line
  comment outside of brackets
%:}%

echo not commented 2

%{:%
  second multi 
  line
  comment outside of brackets
%:}%

::GOTO macro cannot be used inside for loop
for %%a in (first second) do (
    echo first not commented line of the %%a execution
    %{%
        multi line
        comment
    %}%
    echo second not commented line of the %%a execution
)

With parentheses:

@echo off

::GOTO comment macro
set "(:=goto :)%%"
::brackets comment macros
set "(=rem/||(" & set ")=)"

::testing
echo not commented 1

%(:%
  multi 
  line
  comment outside of brackets
%:)%

echo not commented 2

%(:%
  second multi 
  line
  comment outside of brackets
%:)%

::GOTO macro cannot be used inside for loop
for %%a in (first second) do (
    echo first not commented line of the %%a execution
    %(%
        multi line
        comment
    %)%
    echo second not commented line of the %%a execution
)

Mixture between powershell and C styles (< cannot be used because the redirection is with higher prio.* cannot be used because of the %*) :

@echo off

::GOTO comment macro
set "/#:=goto :#/%%"
::brackets comment macros
set "/#=rem/||(" & set "#/=)"

::testing
echo not commented 1

%/#:%
  multi 
  line
  comment outside of brackets
%:#/%

echo not commented 2

%/#:%
  second multi 
  line
  comment outside of brackets
%:#/%

::GOTO macro cannot be used inside for loop
for %%a in (first second) do (
    echo first not commented line of the %%a execution
    %/#%
        multi line
        comment
    %#/%
    echo second not commented line of the %%a execution
)

To emphase that's a comment (thought it is not so short):

@echo off

::GOTO comment macro
set "REM{:=goto :}REM%%"
::brackets comment macros
set "REM{=rem/||(" & set "}REM=)"

::testing
echo not commented 1

%REM{:%
  multi 
  line
  comment outside of brackets
%:}REM%

echo not commented 2

%REM{:%
  second multi 
  line
  comment outside of brackets
%:}REM%

::GOTO macro cannot be used inside for
for %%a in (first second) do (
    echo first not commented line of the %%a execution
    %REM{%
        multi line
        comment
    %}REM%
    echo second not commented line of the %%a execution
)

Jquery Validate custom error message location

HTML

<form ... id ="GoogleMapsApiKeyForm">
    ...
    <input name="GoogleMapsAPIKey" type="text" class="form-control" placeholder="Enter Google maps API key" />
    ....
    <span class="text-danger" id="GoogleMapsAPIKey-errorMsg"></span>'
    ...
    <button type="submit" class="btn btn-primary">Save</button>
</form>

Javascript

$(function () {
    $("#GoogleMapsApiKeyForm").validate({
      rules: {
          GoogleMapsAPIKey: {
              required: true
          }
        },
        messages: {
            GoogleMapsAPIKey: 'Google maps api key is required',
        },
        errorPlacement: function (error, element) {
            if (element.attr("name") == "GoogleMapsAPIKey")
                $("#GoogleMapsAPIKey-errorMsg").html(error);
        },
        submitHandler: function (form) {
           // form.submit(); //if you need Ajax submit follow for rest of code below
        }
    });

    //If you want to use ajax
    $("#GoogleMapsApiKeyForm").submit(function (e) {
        e.preventDefault();
        if (!$("#GoogleMapsApiKeyForm").valid())
            return;

       //Put your ajax call here
    });
});

How can I get the current date and time in UTC or GMT in Java?

Converting Current DateTime in UTC:

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

DateTimeZone dateTimeZone = DateTimeZone.getDefault(); //Default Time Zone

DateTime currDateTime = new DateTime(); //Current DateTime

long utcTime = dateTimeZone.convertLocalToUTC(currDateTime .getMillis(), false);

String currTime = formatter.print(utcTime); //UTC time converted to string from long in format of formatter

currDateTime = formatter.parseDateTime(currTime); //Converted to DateTime in UTC

Html/PHP - Form - Input as array

Simply add [] to those names like

 <input type="text" class="form-control" placeholder="Titel" name="levels[level][]">
 <input type="text" class="form-control" placeholder="Titel" name="levels[build_time][]">

Take that template and then you can add those even using a loop.

Then you can add those dynamically as much as you want, without having to provide an index. PHP will pick them up just like your expected scenario example.

Edit

Sorry I had braces in the wrong place, which would make every new value as a new array element. Use the updated code now and this will give you the following array structure

levels > level (Array)
levels > build_time (Array)

Same index on both sub arrays will give you your pair. For example

echo $levels["level"][5];
echo $levels["build_time"][5];

Selecting an element in iFrame jQuery

when your document is ready that doesn't mean that your iframe is ready too,
so you should listen to the iframe load event then access your contents:

$(function() {
    $("#my-iframe").bind("load",function(){
        $(this).contents().find("[tokenid=" + token + "]").html();
    });
});

What does numpy.random.seed(0) do?

If you set the np.random.seed(a_fixed_number) every time you call the numpy's other random function, the result will be the same:

>>> import numpy as np
>>> np.random.seed(0) 
>>> perm = np.random.permutation(10) 
>>> print perm 
[2 8 4 9 1 6 7 3 0 5]
>>> np.random.seed(0) 
>>> print np.random.permutation(10) 
[2 8 4 9 1 6 7 3 0 5]
>>> np.random.seed(0) 
>>> print np.random.permutation(10) 
[2 8 4 9 1 6 7 3 0 5]
>>> np.random.seed(0) 
>>> print np.random.permutation(10) 
[2 8 4 9 1 6 7 3 0 5]
>>> np.random.seed(0) 
>>> print np.random.rand(4) 
[0.5488135  0.71518937 0.60276338 0.54488318]
>>> np.random.seed(0) 
>>> print np.random.rand(4) 
[0.5488135  0.71518937 0.60276338 0.54488318]

However, if you just call it once and use various random functions, the results will still be different:

>>> import numpy as np
>>> np.random.seed(0) 
>>> perm = np.random.permutation(10)
>>> print perm 
[2 8 4 9 1 6 7 3 0 5]
>>> np.random.seed(0) 
>>> print np.random.permutation(10)
[2 8 4 9 1 6 7 3 0 5]
>>> print np.random.permutation(10) 
[3 5 1 2 9 8 0 6 7 4]
>>> print np.random.permutation(10) 
[2 3 8 4 5 1 0 6 9 7]
>>> print np.random.rand(4) 
[0.64817187 0.36824154 0.95715516 0.14035078]
>>> print np.random.rand(4) 
[0.87008726 0.47360805 0.80091075 0.52047748]

How to read a single character from the user?

An alternative method:

import os
import sys    
import termios
import fcntl

def getch():
  fd = sys.stdin.fileno()

  oldterm = termios.tcgetattr(fd)
  newattr = termios.tcgetattr(fd)
  newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
  termios.tcsetattr(fd, termios.TCSANOW, newattr)

  oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
  fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

  try:        
    while 1:            
      try:
        c = sys.stdin.read(1)
        break
      except IOError: pass
  finally:
    termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
  return c

From this blog post.

How can I represent an 'Enum' in Python?

Another, very simple, implementation of an enum in Python, using namedtuple:

from collections import namedtuple

def enum(*keys):
    return namedtuple('Enum', keys)(*keys)

MyEnum = enum('FOO', 'BAR', 'BAZ')

or, alternatively,

# With sequential number values
def enum(*keys):
    return namedtuple('Enum', keys)(*range(len(keys)))

# From a dict / keyword args
def enum(**kwargs):
    return namedtuple('Enum', kwargs.keys())(*kwargs.values())




# Example for dictionary param:
values = {"Salad": 20, "Carrot": 99, "Tomato": "No i'm not"} 
Vegetables= enum(**values)

# >>> print(Vegetables.Tomato)        'No i'm not'


# Example for keyworded params: 
Fruits = enum(Apple="Steve Jobs", Peach=1, Banana=2)

# >>> print(Fruits.Apple)             'Steve Jobs'

Like the method above that subclasses set, this allows:

'FOO' in MyEnum
other = MyEnum.FOO
assert other == MyEnum.FOO

But has more flexibility as it can have different keys and values. This allows

MyEnum.FOO < MyEnum.BAR

to act as is expected if you use the version that fills in sequential number values.

ESLint not working in VS Code?

General issues

Open the terminal Ctrl+`

Under output ESLint dropdown, you find useful debugging data (Errors, warnings, info).

enter image description here

For example, missing .eslintrc-.json throw this error: enter image description here

Error: ENOENT: no such file or directory, realpath

Next, check if the plugin enabled: enter image description here

Last, Since v 2.0.4 - eslint.validate in normal cases not necessary anymore (old legacy setting):

eslint.probe = an array for language identifiers for which the ESLint extension should be activated and should try to validate the file. If validation fails for probed languages the extension says silent. Defaults to [javascript, javascriptreact, typescript, typescriptreact, html, vue, markdown].

Specific Issue - First-time plugin instalation

My issue was related to the ESLint plugin "currently block" status bar enter image description here on New/First instalation (v2.1.14).

Since ESLint plugin Version 2.1.10 (08/10/2020)

no modal dialog is shown when the ESLint extension tries to load an ESLint library for the first time and an approval is necessary. Instead the ESLint status bar item changes to ESLint status icon indicating that the execution is currently block.

Click on the status-bar (Right-Bottom corner): enter image description here

Opens this popup:

enter image description here

Approve ==> Allows Everywhere

enter image description here

-or- by commands:

ctrl + Shift + p -- ESLint: Manage Library Execution

enter image description here

Read more here under "Release Notes":

https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint

Git copy file preserving history

All you have to do is:

  1. move the file to two different locations,
  2. merge the two commits that do the above, and
  3. move one copy back to the original location.

You will be able to see historical attributions (using git blame) and full history of changes (using git log) for both files.

Suppose you want to create a copy of file foo called bar. In that case the workflow you'd use would look like this:

git mv foo bar
git commit

SAVED=`git rev-parse HEAD`
git reset --hard HEAD^
git mv foo copy
git commit

git merge $SAVED     # This will generate conflicts
git commit -a        # Trivially resolved like this

git mv copy foo
git commit

Why this works

After you execute the above commands, you end up with a revision history that looks like this:

( revision history )            ( files )

    ORIG_HEAD                      foo
     /     \                      /   \
SAVED       ALTERNATE          bar     copy
     \     /                      \   /
      MERGED                     bar,copy
        |                           |
     RESTORED                    bar,foo

When you ask Git about the history of foo, it will:

  1. detect the rename from copy between MERGED and RESTORED,
  2. detect that copy came from the ALTERNATE parent of MERGED, and
  3. detect the rename from foo between ORIG_HEAD and ALTERNATE.

From there it will dig into the history of foo.

When you ask Git about the history of bar, it will:

  1. notice no change between MERGED and RESTORED,
  2. detect that bar came from the SAVED parent of MERGED, and
  3. detect the rename from foo between ORIG_HEAD and SAVED.

From there it will dig into the history of foo.

It's that simple. :)

You just need to force Git into a merge situation where you can accept two traceable copies of the file(s), and we do this with a parallel move of the original (which we soon revert).

How to output messages to the Eclipse console when developing for Android

System.out.println() also outputs to LogCat. The benefit of using good old System.out.println() is that you can print an object like System.out.println(object) to the console if you need to check if a variable is initialized or not.

Log.d, Log.v, Log.w etc methods only allow you to print strings to the console and not objects. To circumvent this (if you desire), you must use String.format.

Center image in div horizontally

text-align: center will only work for horizontal centering. For it to be in the complete center, vertical and horizontal you can do the following :

div
{
    position: relative;
}
div img
{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: [-50% of your image's width];
    margin-top: [-50% of your image's height];
}

Getting a list of files in a directory with a glob

stringWithFileSystemRepresentation doesn't appear to be available in iOS.

Load local javascript file in chrome for testing?

Running a simple local HTTP server

To test such examples, one needs a local webserver. One of the easiest ways to do this for our purposes is to use Python's SimpleHTTPServer (or http.server, depending on the version of Python installed.)

# Install Python & try one of the following depending on your python version. if the version is 3.X
python3 -m http.server
# On windows try "python" instead of "python3", or "py -3"
# If Python version is 2.X
python -m SimpleHTTPServer

How to loop through all enum values in C#?

foreach(Foos foo in Enum.GetValues(typeof(Foos)))

Test for multiple cases in a switch, like an OR (||)

You can use fall-through:

switch (pageid)
{
    case "listing-page":
    case "home-page":
        alert("hello");
        break;
    case "details-page":
        alert("goodbye");
        break;
}

How to detect a loop in a linked list?

boolean hasCycle(Node head) {

    boolean dec = false;
    Node first = head;
    Node sec = head;
    while(first != null && sec != null)
    {
        first = first.next;
        sec = sec.next.next;
        if(first == sec )
        {
            dec = true;
            break;
        }

    }
        return dec;
}

Use above function to detect a loop in linkedlist in java.

Pass object to javascript function

function myFunction(arg) {
    alert(arg.var1 + ' ' + arg.var2 + ' ' + arg.var3);
}

myFunction ({ var1: "Option 1", var2: "Option 2", var3: "Option 3" });

C++ performance vs. Java/C#

Actually, C# does not really run in a virtual machine like Java does. IL is compiled into assembly language, which is entirely native code and runs at the same speed as native code. You can pre-JIT an .NET application which entirely removes the JIT cost and then you are running entirely native code.

The slowdown with .NET will come not because .NET code is slower, but because it does a lot more behind the scenes to do things like garbage collect, check references, store complete stack frames, etc. This can be quite powerful and helpful when building applications, but also comes at a cost. Note that you could do all these things in a C++ program as well (much of the core .NET functionality is actually .NET code which you can view in ROTOR). However, if you hand wrote the same functionality you would probably end up with a much slower program since the .NET runtime has been optimized and finely tuned.

That said, one of the strengths of managed code is that it can be fully verifiable, ie. you can verify that the code will never access another processes's memory or do unsage things before you execute it. Microsoft has a research prototype of a fully managed operating system that has suprisingly shown that a 100% managed environment can actually perform significantly faster than any modern operating system by taking advantage of this verification to turn off security features that are no longer needed by managed programs (we are talking like 10x in some cases). SE radio has a great episode talking about this project.

Concept behind putting wait(),notify() methods in Object class

These methods works on the locks and locks are associated with Object and not Threads. Hence, it is in Object class.

The methods wait(), notify() and notifyAll() are not only just methods, these are synchronization utility and used in communication mechanism among threads in Java.

For more detailed explanation, please visit : http://parameshk.blogspot.in/2013/11/why-wait-notify-and-notifyall-methods.html

VS 2017 Metadata file '.dll could not be found

Check all the projects are loaded. In my case one of the project was unloaded and reloading the project clears the errors.

Splitting a list into N parts of approximately equal length

Have a look at numpy.split:

>>> a = numpy.array([1,2,3,4])
>>> numpy.split(a, 2)
[array([1, 2]), array([3, 4])]

Placeholder in IE9

I searched on the internet and found a simple jquery code to handle this problem. In my side, it was solved and worked on ie 9.

$("input[placeholder]").each(function () {
        var $this = $(this);
        if($this.val() == ""){
            $this.val($this.attr("placeholder")).focus(function(){
                if($this.val() == $this.attr("placeholder")) {
                    $this.val("");
                }
            }).blur(function(){
                if($this.val() == "") {
                    $this.val($this.attr("placeholder"));
                }
            });
        }
    });

Java POI : How to read Excel cell value and not the formula computing it?

For formula cells, excel stores two things. One is the Formula itself, the other is the "cached" value (the last value that the forumla was evaluated as)

If you want to get the last cached value (which may no longer be correct, but as long as Excel saved the file and you haven't changed it it should be), you'll want something like:

 for(Cell cell : row) {
     if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
        System.out.println("Formula is " + cell.getCellFormula());
        switch(cell.getCachedFormulaResultType()) {
            case Cell.CELL_TYPE_NUMERIC:
                System.out.println("Last evaluated as: " + cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_STRING:
                System.out.println("Last evaluated as \"" + cell.getRichStringCellValue() + "\"");
                break;
        }
     }
 }

What is the point of the diamond operator (<>) in Java 7?

The point for diamond operator is simply to reduce typing of code when declaring generic types. It doesn't have any effect on runtime whatsoever.

The only difference if you specify in Java 5 and 6,

List<String> list = new ArrayList();

is that you have to specify @SuppressWarnings("unchecked") to the list (otherwise you will get an unchecked cast warning). My understanding is that diamond operator is trying to make development easier. It's got nothing to do on runtime execution of generics at all.

Should I use != or <> for not equal in T-SQL?

One alternative would be to use the NULLIF operator other than <> or != which returns NULL if the two arguments are equal NULLIF in Microsoft Docs. So I believe WHERE clause can be modified for <> and != as follows:

NULLIF(arg1, arg2) IS NOT NULL

As I found that, using <> and != doesn't work for date in some cases. Hence using the above expression does the needful.

How to view hierarchical package structure in Eclipse package explorer

For Eclipse in Macbook it is just 2 click process:

  • Click on view menu (3 dot symbol) in package explorer -> hover over package presentation -> Click on Hierarchical

enter image description here

What is the difference between MVC and MVVM?

Simple Difference: (Inspired by Yaakov's Coursera AngularJS course)

enter image description here

MVC (Model View Controller)

  1. Models: Models contain data information. Does not call or use Controller and View. Contains the business logic and ways to represent data. Some of this data, in some form, may be displayed in the view. It can also contain logic to retrieve the data from some source.
  2. Controller: Acts as the connection between view and model. View calls Controller and Controller calls the model. It basically informs the model and/or the view to change as appropriate.
  3. View: Deals with UI part. Interacts with the user.

MVVM (Model View View Model)

ViewModel:

  1. It is the representation of the state of the view.
  2. It holds the data that’s displayed in the view.
  3. Responds to view events, aka presentation logic.
  4. Calls other functionalities for business logic processing.
  5. Never directly asks the view to display anything.

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

java_home environment variable should point to the location of the proper version of java installation directory, so that tomcat starts with the right version. for example it you built the project with java 1.7 , then make sure that JAVA_HOME environment variable points to the jdk 1.7 installation directory in your machine.

I had same problem , when i deploy the war in tomcat and run, the link throws the error. But pointing the variable - JAVA_HOME to jdk 1.7 resolved the issue, as my war file was built in java 1.7 environment.

Official reasons for "Software caused connection abort: socket write error"

This error can occur when the local network system aborts a connection, such as when WinSock closes an established connection after data retransmission fails (receiver never acknowledges data sent on a datastream socket).

See this MSDN article. See also Some information about 'Software caused connection abort'.

How to escape comma and double quote at same time for CSV file?

Thanks to both Tony and Paul for the quick feedback, its very helpful. I actually figure out a solution through POJO. Here it is:

if (cell_value.indexOf("\"") != -1 || cell_value.indexOf(",") != -1) {
    cell_value = cell_value.replaceAll("\"", "\"\"");
    row.append("\"");
    row.append(cell_value);
    row.append("\"");
} else {
    row.append(cell_value);
}

in short if there is special character like comma or double quote within the string in side the cell, then first escape the double quote("\"") by adding additional double quote (like "\"\""), then put the whole thing into a double quote (like "\""+theWholeThing+"\"" )

How to take a screenshot programmatically on iOS

Below method works for OPENGL objects also

//iOS7 or above
- (UIImage *) screenshot {

    CGSize size = CGSizeMake(your_width, your_height);

    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);

    CGRect rec = CGRectMake(0, 0, your_width, your_height);
    [_viewController.view drawViewHierarchyInRect:rec afterScreenUpdates:YES];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

What is a semaphore?

A hardware or software flag. In multi tasking systems , a semaphore is as variable with a value that indicates the status of a common resource.A process needing the resource checks the semaphore to determine the resources status and then decides how to proceed.

What is the difference between POST and GET?

GET and POST are two different types of HTTP requests.

According to Wikipedia:

GET requests a representation of the specified resource. Note that GET should not be used for operations that cause side-effects, such as using it for taking actions in web applications. One reason for this is that GET may be used arbitrarily by robots or crawlers, which should not need to consider the side effects that a request should cause.

and

POST submits data to be processed (e.g., from an HTML form) to the identified resource. The data is included in the body of the request. This may result in the creation of a new resource or the updates of existing resources or both.

So essentially GET is used to retrieve remote data, and POST is used to insert/update remote data.


HTTP/1.1 specification (RFC 2616) section 9 Method Definitions contains more information on GET and POST as well as the other HTTP methods, if you are interested.

In addition to explaining the intended uses of each method, the spec also provides at least one practical reason for why GET should only be used to retrieve data:

Authors of services which use the HTTP protocol SHOULD NOT use GET based forms for the submission of sensitive data, because this will cause this data to be encoded in the Request-URI. Many existing servers, proxies, and user agents will log the request URI in some place where it might be visible to third parties. Servers can use POST-based form submission instead


Finally, an important consideration when using GET for AJAX requests is that some browsers - IE in particular - will cache the results of a GET request. So if you, for example, poll using the same GET request you will always get back the same results, even if the data you are querying is being updated server-side. One way to alleviate this problem is to make the URL unique for each request by appending a timestamp.

JavaScript check if variable exists (is defined/initialized)

Attention :: people who don't understand the difference between a proposition let, a constant const and a variable var should refrain themselves from commenting.

These answers (aside from the Fred Gandt solution ) are all either incorrect or incomplete.

Suppose I need my variableName; to carry an undefined value, and therefore it has been declared in a manner such as var variableName; which means it's already initialized; - How do I check if it's already declared?

Or even better - how do I immediately check if "Book1.chapter22.paragraph37" exists with a single call, but not rise a reference error?

We do it by using the most powerful JasvaScript operator, the in operator.:

"[variable||property]" in [context||root] 
>> true||false

In times of AJAX peaking popularity I've written a method (later named) isNS() which is capable of determining if the namespace exists including deep tests for property names such as "Book1.chapter22.paragraph37" and a lot more.

But since it has been previously published and because of its great importance it deserves to be published in a separate thread I will not post it here but will provide keywords (javascript + isNS ) which will help you locate the source code, backed with all the necessary explanations.

Getting the IP Address of a Remote Socket Endpoint

string ip = ((IPEndPoint)(testsocket.RemoteEndPoint)).Address.ToString();

Export html table data to Excel using JavaScript / JQuery is not working properly in chrome browser

Excel export script works on IE7+, Firefox and Chrome.

function fnExcelReport()
{
    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j=0;
    tab = document.getElementById('headerTable'); // id of table

    for(j = 0 ; j < tab.rows.length ; j++) 
    {     
        tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
        //tab_text=tab_text+"</tr>";
    }

    tab_text=tab_text+"</table>";
    tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
    tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
    tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE "); 

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
    {
        txtArea1.document.open("txt/html","replace");
        txtArea1.document.write(tab_text);
        txtArea1.document.close();
        txtArea1.focus(); 
        sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
    }  
    else                 //other browser not tested on IE 11
        sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

    return (sa);
}

Just create a blank iframe:

<iframe id="txtArea1" style="display:none"></iframe>

Call this function on:

<button id="btnExport" onclick="fnExcelReport();"> EXPORT </button>

How to deserialize JS date using Jackson?

@JsonFormat only work for standard format supported by the jackson version that you are using.

Ex :- compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd")) for jackson 2.8.6

SQL RANK() over PARTITION on joined tables

SELECT a.C_ID,a.QRY_ID,a.RES_ID,b.SCORE,ROW_NUMBER() OVER (ORDER BY SCORE DESC) AS [RANK]
FROM CONTACTS a JOIN RSLTS b ON a.QRY_ID=b.QRY_ID AND a.RES_ID=b.RES_ID
ORDER BY a.C_ID

Android difference between Two Dates

I use this: send start and end date in millisecond

public int GetDifference(long start,long end){
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(start);
    int hour = cal.get(Calendar.HOUR_OF_DAY);
    int min = cal.get(Calendar.MINUTE);
    long t=(23-hour)*3600000+(59-min)*60000;

    t=start+t;

    int diff=0;
    if(end>t){
        diff=(int)((end-t)/ TimeUnit.DAYS.toMillis(1))+1;
    }

    return  diff;
}

How to correctly assign a new string value?

The first example doesn't work because you can't assign values to arrays - arrays work (sort of) like const pointers in this respect. What you can do though is copy a new value into the array:

strcpy(p.name, "Jane");

Char arrays are fine to use if you know the maximum size of the string in advance, e.g. in the first example you are 100% sure that the name will fit into 19 characters (not 20 because one character is always needed to store the terminating zero value).

Conversely, pointers are better if you don't know the possible maximum size of your string, and/or you want to optimize your memory usage, e.g. avoid reserving 512 characters for the name "John". However, with pointers you need to dynamically allocate the buffer they point to, and free it when not needed anymore, to avoid memory leaks.

Update: example of dynamically allocated buffers (using the struct definition in your 2nd example):

char* firstName = "Johnnie";
char* surname = "B. Goode";
person p;

p.name = malloc(strlen(firstName) + 1);
p.surname = malloc(strlen(surname) + 1);

p.age = 25;
strcpy(p.name, firstName);
strcpy(p.surname, surname);

printf("Name: %s; Age: %d\n",p.name,p.age);

free(p.surname);
free(p.name);

Python: import module from another directory at the same level in project hierarchy

If I move CreateUser.py to the main user_management directory, I can easily use: import Modules.LDAPManager to import LDAPManager.py --- this works.

Please, don't. In this way the LDAPManager module used by CreateUser will not be the same as the one imported via other imports. This can create problems when you have some global state in the module or during pickling/unpickling. Avoid imports that work only because the module happens to be in the same directory.

When you have a package structure you should either:

  • Use relative imports, i.e if the CreateUser.py is in Scripts/:

     from ..Modules import LDAPManager
    

    Note that this was (note the past tense) discouraged by PEP 8 only because old versions of python didn't support them very well, but this problem was solved years ago. The current version of PEP 8 does suggest them as an acceptable alternative to absolute imports. I actually like them inside packages.

  • Use absolute imports using the whole package name(CreateUser.py in Scripts/):

     from user_management.Modules import LDAPManager
    

In order for the second one to work the package user_management should be installed inside the PYTHONPATH. During development you can configure the IDE so that this happens, without having to manually add calls to sys.path.append anywhere.

Also I find it odd that Scripts/ is a subpackage. Because in a real installation the user_management module would be installed under the site-packages found in the lib/ directory (whichever directory is used to install libraries in your OS), while the scripts should be installed under a bin/ directory (whichever contains executables for your OS).

In fact I believe Script/ shouldn't even be under user_management. It should be at the same level of user_management. In this way you do not have to use -m, but you simply have to make sure the package can be found (this again is a matter of configuring the IDE, installing the package correctly or using PYTHONPATH=. python Scripts/CreateUser.py to launch the scripts with the correct path).


In summary, the hierarchy I would use is:

user_management  (package)
        |
        |------- __init__.py
        |
        |------- Modules/
        |           |
        |           |----- __init__.py
        |           |----- LDAPManager.py
        |           |----- PasswordManager.py
        |

 Scripts/  (*not* a package)
        |  
        |----- CreateUser.py
        |----- FindUser.py

Then the code of CreateUser.py and FindUser.py should use absolute imports to import the modules:

from user_management.Modules import LDAPManager

During installation you make sure that user_management ends up somewhere in the PYTHONPATH, and the scripts inside the directory for executables so that they are able to find the modules. During development you either rely on IDE configuration, or you launch CreateUser.py adding the Scripts/ parent directory to the PYTHONPATH (I mean the directory that contains both user_management and Scripts):

PYTHONPATH=/the/parent/directory python Scripts/CreateUser.py

Or you can modify the PYTHONPATH globally so that you don't have to specify this each time. On unix OSes (linux, Mac OS X etc.) you can modify one of the shell scripts to define the PYTHONPATH external variable, on Windows you have to change the environmental variables settings.


Addendum I believe, if you are using python2, it's better to make sure to avoid implicit relative imports by putting:

from __future__ import absolute_import

at the top of your modules. In this way import X always means to import the toplevel module X and will never try to import the X.py file that's in the same directory (if that directory isn't in the PYTHONPATH). In this way the only way to do a relative import is to use the explicit syntax (the from . import X), which is better (explicit is better than implicit).

This will make sure you never happen to use the "bogus" implicit relative imports, since these would raise an ImportError clearly signalling that something is wrong. Otherwise you could use a module that's not what you think it is.

Find unused code

Resharper is good for this like others have stated. Be careful though, these tools don't find you code that is used by reflection, e.g. cannot know if some code is NOT used by reflection.

Where is the documentation for the values() method of Enum?

You can't see this method in javadoc because it's added by the compiler.

Documented in three places :

The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type.

  • Enum.valueOf class
    (The special implicit values method is mentioned in description of valueOf method)

All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type.

The values function simply list all values of the enumeration.

remove attribute display:none; so the item will be visible

If you are planning to hide show some span based on click event which is initially hidden with style="display:none" then .toggle() is best option to go with.

$("span").toggle();

Reasons : Each time you don't need to check whether the style is already there or not. .toggle() will take care of that automatically and hide/show span based on current state.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="button" value="Toggle" onclick="$('#hiddenSpan').toggle();"/>_x000D_
<br/>_x000D_
<br/>_x000D_
<span id="hiddenSpan" style="display:none">Just toggle me</span>
_x000D_
_x000D_
_x000D_

Find the number of columns in a table

Or use the sys.columns

--SQL 2005
SELECT  *
FROM    sys.columns
WHERE   OBJECT_NAME(object_id) = 'spt_values'
-- returns 6 rows = 6 columns

--SQL 2000
SELECT  *
FROM    syscolumns
WHERE   OBJECT_NAME(id) = 'spt_values'
-- returns 6 rows = 6 columns

SELECT  *
FROM    dbo.spt_values
    -- 6 columns indeed

return results from a function (javascript, nodejs)

You are trying to execute an asynchronous function in a synchronous way, which is unfortunately not possible in Javascript.

As you guessed correctly, the roomId=results.... is executed when the loading from the DB completes, which is done asynchronously, so AFTER the resto of your code is completed.

Look at this article, it talks about .insert and not .find, but the idea is the same : http://metaduck.com/01-asynchronous-iteration-patterns.html

SQL update query using joins

UPDATE im
SET mf_item_number = gm.SKU --etc
FROM item_master im
JOIN group_master gm
    ON im.sku = gm.sku 
JOIN Manufacturer_Master mm
    ON gm.ManufacturerID = mm.ManufacturerID
WHERE im.mf_item_number like 'STA%' AND
      gm.manufacturerID = 34

To make it clear... The UPDATE clause can refer to an table alias specified in the FROM clause. So im in this case is valid

Generic example

UPDATE A
SET foo = B.bar
FROM TableA A
JOIN TableB B
    ON A.col1 = B.colx
WHERE ...

Cursor adapter and sqlite example

CursorAdapter Example with Sqlite

...
DatabaseHelper helper = new DatabaseHelper(this);
aListView = (ListView) findViewById(R.id.aListView);
Cursor c = helper.getAllContacts();
CustomAdapter adapter = new CustomAdapter(this, c);
aListView.setAdapter(adapter);
...

class CustomAdapter extends CursorAdapter {
    // CursorAdapter will handle all the moveToFirst(), getCount() logic for you :)

    public CustomAdapter(Context context, Cursor c) {
        super(context, c);
    }

    public void bindView(View view, Context context, Cursor cursor) {
        String id = cursor.getString(0);
        String name = cursor.getString(1);
        // Get all the values
        // Use it however you need to
        TextView textView = (TextView) view;
        textView.setText(name);
    }

    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        // Inflate your view here.
        TextView view = new TextView(context);
        return view;
    }
}

private final class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "db_name";
    private static final int DATABASE_VERSION = 1;
    private static final String CREATE_TABLE_TIMELINE = "CREATE TABLE IF NOT EXISTS table_name (_id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar);";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_TIMELINE);
        db.execSQL("INSERT INTO ddd (name) VALUES ('One')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Two')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Three')");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public Cursor getAllContacts() {
        String selectQuery = "SELECT  * FROM table_name;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        return cursor;
    }
}

Getting last day of the month in a given string date

This looks like your needs:

http://obscuredclarity.blogspot.de/2010/08/get-last-day-of-month-date-object-in.html

code:

import java.text.DateFormat;  
import java.text.DateFormat;  
import java.text.SimpleDateFormat;  
import java.util.Calendar;  
import java.util.Date;  

//Java 1.4+ Compatible  
//  
// The following example code demonstrates how to get  
// a Date object representing the last day of the month  
// relative to a given Date object.  

public class GetLastDayOfMonth {  

    public static void main(String[] args) {  

        Date today = new Date();  

        Calendar calendar = Calendar.getInstance();  
        calendar.setTime(today);  

        calendar.add(Calendar.MONTH, 1);  
        calendar.set(Calendar.DAY_OF_MONTH, 1);  
        calendar.add(Calendar.DATE, -1);  

        Date lastDayOfMonth = calendar.getTime();  

        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
        System.out.println("Today            : " + sdf.format(today));  
        System.out.println("Last Day of Month: " + sdf.format(lastDayOfMonth));  
    }  

} 

Output:

Today            : 2010-08-03  
Last Day of Month: 2010-08-31  

openssl s_client -cert: Proving a client certificate was sent to the server

I know this is an old question but it does not yet appear to have an answer. I've duplicated this situation, but I'm writing the server app, so I've been able to establish what happens on the server side as well. The client sends the certificate when the server asks for it and if it has a reference to a real certificate in the s_client command line. My server application is set up to ask for a client certificate and to fail if one is not presented. Here is the command line I issue:

Yourhostname here -vvvvvvvvvv s_client -connect <hostname>:443 -cert client.pem -key cckey.pem -CAfile rootcert.pem -cipher ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH -tls1 -state

When I leave out the "-cert client.pem" part of the command the handshake fails on the server side and the s_client command fails with an error reported. I still get the report "No client certificate CA names sent" but I think that has been answered here above.

The short answer then is that the server determines whether a certificate will be sent by the client under normal operating conditions (s_client is not normal) and the failure is due to the server not recognizing the CA in the certificate presented. I'm not familiar with many situations in which two-way authentication is done although it is required for my project.

You are clearly sending a certificate. The server is clearly rejecting it.

The missing information here is the exact manner in which the certs were created and the way in which the provider loaded the cert, but that is probably all wrapped up by now.

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

I ran into this error because I was attempting to write a string to a cell which started with an "=".

The solution was to put an "'" (apostrophe) before the equals sign, which is a way to tell excel that you're not, in fact, trying to write a formula, and just want to print the equals sign.

Rolling back local and remote git repository by 1 commit

For Windows Machines, use:

git reset HEAD~1  #Remove Commit Locally

Error in plot.window(...) : need finite 'xlim' values

The problem is that you're (probably) trying to plot a vector that consists exclusively of missing (NA) values. Here's an example:

> x=rep(NA,100)
> y=rnorm(100)
> plot(x,y)
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf

In your example this means that in your line plot(costs,pseudor2,type="l"), costs is completely NA. You have to figure out why this is, but that's the explanation of your error.


From comments:

Scott C Wilson: Another possible cause of this message (not in this case, but in others) is attempting to use character values as X or Y data. You can use the class function to check your x and Y values to be sure if you think this might be your issue.

stevec: Here is a quick and easy solution to that problem (basically wrap x in as.factor(x))

android fragment- How to save states of views in a fragment when another fragment is pushed on top of it

A simple way of keeping the values of fields in different fragments in an activity

Create the Instances of fragments and add instead of replace and remove

    FragA  fa= new FragA();
    FragB  fb= new FragB();
    FragC  fc= new FragB();
    fragmentManager = getSupportFragmentManager();
    fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(R.id.fragmnt_container, fa);
    fragmentTransaction.add(R.id.fragmnt_container, fb);
    fragmentTransaction.add(R.id.fragmnt_container, fc);
    fragmentTransaction.show(fa);
    fragmentTransaction.hide(fb);
    fragmentTransaction.hide(fc);
    fragmentTransaction.commit();

Then just show and hide the fragments instead of adding and removing those again

    fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.hide(fa);
    fragmentTransaction.show(fb);
    fragmentTransaction.hide(fc);
    fragmentTransaction.commit()

;

How to create a new file in unix?

The command is lowercase: touch filename.

Keep in mind that touch will only create a new file if it does not exist! Here's some docs for good measure: http://unixhelp.ed.ac.uk/CGI/man-cgi?touch

If you always want an empty file, one way to do so would be to use:

echo "" > filename

open the file upload dialogue box onclick the image

Also, You can write all inline, direct at html code:

<input type="file" id="imgupload">
<a href="#" onclick="$('#imgupload').trigger('click'); return false;">Upload file</a>

return false; - will be useful to decline anchor action after link was clicked.

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

In windows 10, period is first parameter

docker build . -t docker-whale

How can I delete one element from an array by value

A .delete_at(3) 3 here being the position.

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

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

SELECT owner, directory_name, directory_path
  FROM all_directories

What is `related_name` used for in Django?

To add to existing answer - related name is a must in case there 2 FKs in the model that point to the same table. For example in case of Bill of material

@with_author 
class BOM(models.Model): 
    name = models.CharField(max_length=200,null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    tomaterial =  models.ForeignKey(Material, related_name = 'tomaterial')
    frommaterial =  models.ForeignKey(Material, related_name = 'frommaterial')
    creation_time = models.DateTimeField(auto_now_add=True, blank=True)
    quantity = models.DecimalField(max_digits=19, decimal_places=10)

So when you will have to access this data you only can use related name

 bom = material.tomaterial.all().order_by('-creation_time')

It is not working otherwise (at least I was not able to skip the usage of related name in case of 2 FK's to the same table.)

./xx.py: line 1: import: command not found

It's about Shebang

#!usr/bin/python

This will tell which interpreter to wake up to run the code written in file.

What regex will match every character except comma ',' or semi-colon ';'?

[^,;]+         

You haven't specified the regex implementation you are using. Most of them have a Split method that takes delimiters and split by them. You might want to use that one with a "normal" (without ^) character class:

[,;]+

getting the index of a row in a pandas apply function

To answer the original question: yes, you can access the index value of a row in apply(). It is available under the key name and requires that you specify axis=1 (because the lambda processes the columns of a row and not the rows of a column).

Working example (pandas 0.23.4):

>>> import pandas as pd
>>> df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df.set_index('a', inplace=True)
>>> df
   b  c
a      
1  2  3
4  5  6
>>> df['index_x10'] = df.apply(lambda row: 10*row.name, axis=1)
>>> df
   b  c  index_x10
a                 
1  2  3         10
4  5  6         40

What's the difference between emulation and simulation?

I was confused between the two processes. I found this simple explaination about the difference between Emulators and Simulators

  1. Simulator:
    Suppose you have written assembly program in a file and corresponding exe file is ready. The simulator is the pc software which reads the instructions from the exe and 'minmics' the operation of the processor.

  2. Emulator:
    Emulator is a (PC software + a processor). The Processor can be plugged into the TARGET BOARD when you want to test the developed software in real time to check run time bugs. When not in use it can be unplugged. The Processor will have a parallel or JTAG interface with the PC for downloading the exe file for execution.

Hence, whereas the Simulator is slow in execution, Emulator will be able to give real time verification of the developed code. Generally you will test your developed code on simulator first and then go for checking on emulator.

source : http://www.dsprelated.com/groups/c6x/show/148.php

Detect URLs in text with JavaScript

tmp.innerText is undefined. You should use tmp.innerHTML

function strip(html) 
    {  
        var tmp = document.createElement("DIV"); 
        tmp.innerHTML = html; 
        var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;   
        return tmp.innerHTML .replace(urlRegex, function(url) {     
        return '\n' + url 
    })

How to run Node.js as a background process and never die?

Apart from cool solutions above I'd mention also about supervisord and monit tools which allow to start process, monitor its presence and start it if it died. With 'monit' you can also run some active checks like check if process responds for http request

Capturing a single image from my webcam in Java or Python

Some time ago I wrote simple Webcam Capture API which can be used for that. The project is available on Github.

Example code:

Webcam webcam = Webcam.getDefault();
webcam.open();
try {
  ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));
} catch (IOException e) {
  e.printStackTrace();
} finally {
  webcam.close();
}

How to check if a windows form is already open, and close it if it is?

This is what I used to close all open forms (except for the main form)

    private void CloseOpenForms()
    {

           // Close all open forms - except for the main form.  (This is usually OpenForms[0].
           // Closing a form decrmements the OpenForms count
           while (Application.OpenForms.Count > 1)
           {
               Application.OpenForms[Application.OpenForms.Count-1].Close();
           }
    }

How do I negate a test with regular expressions in a bash script?

You had it right, just put a space between the ! and the [[ like if ! [[

What is a vertical tab?

I believe it's still being used, not sure exactly. There might be even a key combination of it.

As English is written Left to Right, Arabic Right to Left, there are languages in world that are also written top to bottom. In that case a vertical tab might be useful same as the horizontal tab is used for English text.

I tried searching, but couldn't find anything useful yet.

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

PowerShell Remoting giving "Access is Denied" error

Had similar problems recently. Would suggest you carefully check if the user you're connecting with has proper authorizations on the remote machine.

You can review permissions using the following command.

Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell

Found this tip here (updated link, thanks "unbob"):

https://devblogs.microsoft.com/scripting/configure-remote-security-settings-for-windows-powershell/

It fixed it for me.

Way to run Excel macros from command line or batch file?

The method shown below allows to run defined Excel macro from batch file, it uses environment variable to pass macro name from batch to Excel.

Put this code to the batch file (use your paths to EXCEL.EXE and to the workbook):

Set MacroName=MyMacro
"C:\Program Files\Microsoft Office\Office15\EXCEL.EXE" "C:\MyWorkbook.xlsm"

Put this code to Excel VBA ThisWorkBook Object:

Private Sub Workbook_Open()
    Dim strMacroName As String
    strMacroName = CreateObject("WScript.Shell").Environment("process").Item("MacroName")
    If strMacroName <> "" Then Run strMacroName
End Sub

And put your code to Excel VBA Module, like as follows:

Sub MyMacro()
    MsgBox "MyMacro is running..."
End Sub

Launch the batch file and get the result:

macro's dialog

For the case when you don't intend to run any macro just put empty value Set MacroName= to the batch.

How to save an image to localStorage and display it on the next page?

You could serialize the image into a Data URI. There's a tutorial in this blog post. That will produce a string you can store in local storage. Then on the next page, use the data uri as the source of the image.

Can we execute a java program without a main() method?

You should also be able to accomplish a similar thing using the premain method of a Java agent.

The manifest of the agent JAR file must contain the attribute Premain-Class. The value of this attribute is the name of the agent class. The agent class must implement a public static premain method similar in principle to the main application entry point. After the Java Virtual Machine (JVM) has initialized, each premain method will be called in the order the agents were specified, then the real application main method will be called. Each premain method must return in order for the startup sequence to proceed.

Google Authenticator available as a public service?

The project is open source. I have not used it. But it's using a documented algorithm (noted in the RFC listed on the open source project page), and the authenticator implementations support multiple accounts.

The actual process is straightforward. The one time code is, essentially, a pseudo random number generator. A random number generator is a formula that once given a seed, or starting number, continues to create a stream of random numbers. Given a seed, while the numbers may be random to each other, the sequence itself is deterministic. So, once you have your device and the server "in sync" then the random numbers that the device creates, each time you hit the "next number button", will be the same, random, numbers the server expects.

A secure one time password system is more sophisticated than a random number generator, but the concept is similar. There are also other details to help keep the device and server in sync.

So, there's no need for someone else to host the authentication, like, say OAuth. Instead you need to implement that algorithm that is compatible with the apps that Google provides for the mobile devices. That software is (should be) available on the open source project.

Depending on your sophistication, you should have all you need to implement the server side of this process give the OSS project and the RFC. I do not know if there is a specific implementation for your server software (PHP, Java, .NET, etc.)

But, specifically, you don't need an offsite service to handle this.

AngularJs ReferenceError: angular is not defined

I think this will happen if you'll use 'async defer' for (the file that contains the filter) while working with angularjs:

<script src="js/filter.js" type="text/javascript" async defer></script>

if you do, just remove 'async defer'.

finding multiples of a number in Python

For the first ten multiples of 5, say

>>> [5*n for n in range(1,10+1)]
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

Rails formatting date

Since I18n is the Rails core feature starting from version 2.2 you can use its localize-method. By applying the forementioned strftime %-variables you can specify the desired format under config/locales/en.yml (or whatever language), in your case like this:

time:
  formats:
    default: '%FT%T'

Or if you want to use this kind of format in a few specific places you can refer it as a variable like this

time:
  formats:
    specific_format: '%FT%T'

After that you can use it in your views like this:

l(Mode.last.created_at, format: :specific_format)  

With Twitter Bootstrap, how can I customize the h1 text color of one page and leave the other pages to be default?

in bootstrap 3 here are the classes to change the text color:

<p class="text-muted">...</p> //grey
<p class="text-primary">...</p> //light blue
<p class="text-success">...</p> //green
<p class="text-info">...</p> //blue
<p class="text-warning">...</p> //orangish,yellow
<p class="text-danger">...</p> //red

Documentation under Helper classes - Contextual colors.

Difference between Xms and Xmx and XX:MaxPermSize

Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.

The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.

-Xmssize Specifies the initial heap size.

-Xmxsize Specifies the maximum heap size.

-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

Sizes are expressed in bytes. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes.

References:

How is the java memory pool divided?

What is perm space?

Java (JVM) Memory Model – Memory Management in Java

Java 7 SE Command Line Options

Java 7 HotSpot VM Options

Add a background image to shape in XML Android

I used the following for a drawable image with a border.

First make a .xml file with this code in drawable folder:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape android:shape="oval">
        <solid android:color="@color/orange"/>
    </shape>
</item>
<item
    android:top="2dp"
    android:bottom="2dp"
    android:left="2dp"
    android:right="2dp">
    <shape android:shape="oval">
        <solid android:color="@color/white"/>
    </shape>
</item>
<item
    android:drawable="@drawable/messages" //here messages is my image name, please give here your image name.
    android:bottom="15dp"
    android:left="15dp"
    android:right="15dp"
    android:top="15dp"/>

Second make a view .xml file in layout folder and call the above .xml file with this way

<ImageView
   android:id="@+id/imageView2"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:src="@drawable/merchant_circle" />  // here merchant_circle will be your first .xml file name

Catching KeyboardInterrupt in Python during program shutdown

You could ignore SIGINTs after shutdown starts by calling signal.signal(signal.SIGINT, signal.SIG_IGN) before you start your cleanup code.

Understanding `scale` in R

This is a late addition but I was looking for information on the scale function myself and though it might help somebody else as well.

To modify the response from Ricardo Saporta a little bit.
Scaling is not done using standard deviation, at least not in version 3.6.1 of R, I base this on "Becker, R. (2018). The new S language. CRC Press." and my own experimentation.

X.man.scaled <- X/sqrt(sum(X^2)/(length(X)-1))
X.aut.scaled <- scale(X, center = F)

The result of these rows are exactly the same, I show it without centering because of simplicity.

I would respond in a comment but did not have enough reputation.

How do I tell Maven to use the latest version of a dependency?

NOTE:

The mentioned LATEST and RELEASE metaversions have been dropped for plugin dependencies in Maven 3 "for the sake of reproducible builds", over 6 years ago. (They still work perfectly fine for regular dependencies.) For plugin dependencies please refer to this Maven 3 compliant solution.


If you always want to use the newest version, Maven has two keywords you can use as an alternative to version ranges. You should use these options with care as you are no longer in control of the plugins/dependencies you are using.

When you depend on a plugin or a dependency, you can use the a version value of LATEST or RELEASE. LATEST refers to the latest released or snapshot version of a particular artifact, the most recently deployed artifact in a particular repository. RELEASE refers to the last non-snapshot release in the repository. In general, it is not a best practice to design software which depends on a non-specific version of an artifact. If you are developing software, you might want to use RELEASE or LATEST as a convenience so that you don't have to update version numbers when a new release of a third-party library is released. When you release software, you should always make sure that your project depends on specific versions to reduce the chances of your build or your project being affected by a software release not under your control. Use LATEST and RELEASE with caution, if at all.

See the POM Syntax section of the Maven book for more details. Or see this doc on Dependency Version Ranges, where:

  • A square bracket ( [ & ] ) means "closed" (inclusive).
  • A parenthesis ( ( & ) ) means "open" (exclusive).

Here's an example illustrating the various options. In the Maven repository, com.foo:my-foo has the following metadata:

<?xml version="1.0" encoding="UTF-8"?><metadata>
  <groupId>com.foo</groupId>
  <artifactId>my-foo</artifactId>
  <version>2.0.0</version>
  <versioning>
    <release>1.1.1</release>
    <versions>
      <version>1.0</version>
      <version>1.0.1</version>
      <version>1.1</version>
      <version>1.1.1</version>
      <version>2.0.0</version>
    </versions>
    <lastUpdated>20090722140000</lastUpdated>
  </versioning>
</metadata>

If a dependency on that artifact is required, you have the following options (other version ranges can be specified of course, just showing the relevant ones here):

Declare an exact version (will always resolve to 1.0.1):

<version>[1.0.1]</version>

Declare an explicit version (will always resolve to 1.0.1 unless a collision occurs, when Maven will select a matching version):

<version>1.0.1</version>

Declare a version range for all 1.x (will currently resolve to 1.1.1):

<version>[1.0.0,2.0.0)</version>

Declare an open-ended version range (will resolve to 2.0.0):

<version>[1.0.0,)</version>

Declare the version as LATEST (will resolve to 2.0.0) (removed from maven 3.x)

<version>LATEST</version>

Declare the version as RELEASE (will resolve to 1.1.1) (removed from maven 3.x):

<version>RELEASE</version>

Note that by default your own deployments will update the "latest" entry in the Maven metadata, but to update the "release" entry, you need to activate the "release-profile" from the Maven super POM. You can do this with either "-Prelease-profile" or "-DperformRelease=true"


It's worth emphasising that any approach that allows Maven to pick the dependency versions (LATEST, RELEASE, and version ranges) can leave you open to build time issues, as later versions can have different behaviour (for example the dependency plugin has previously switched a default value from true to false, with confusing results).

It is therefore generally a good idea to define exact versions in releases. As Tim's answer points out, the maven-versions-plugin is a handy tool for updating dependency versions, particularly the versions:use-latest-versions and versions:use-latest-releases goals.

Enable & Disable a Div and its elements in Javascript

You should be able to set these via the attr() or prop() functions in jQuery as shown below:

jQuery (< 1.7):

// This will disable just the div
$("#dcacl").attr('disabled','disabled');

or

// This will disable everything contained in the div
$("#dcacl").children().attr("disabled","disabled");

jQuery (>= 1.7):

// This will disable just the div
$("#dcacl").prop('disabled',true);

or

// This will disable everything contained in the div
$("#dcacl").children().prop('disabled',true);

or

//  disable ALL descendants of the DIV
$("#dcacl *").prop('disabled',true);

Javascript:

// This will disable just the div
document.getElementById("dcalc").disabled = true;

or

// This will disable all the children of the div
var nodes = document.getElementById("dcalc").getElementsByTagName('*');
for(var i = 0; i < nodes.length; i++){
     nodes[i].disabled = true;
}

JDBC ODBC Driver Connection

As mentioned in the comments to the question, the JDBC-ODBC Bridge is - as the name indicates - only a mechanism for the JDBC layer to "talk to" the ODBC layer. Even if you had a JDBC-ODBC Bridge on your Mac you would also need to have

  • an implementation of ODBC itself, and
  • an appropriate ODBC driver for the target database (ACE/Jet, a.k.a. "Access")

So, for most people, using JDBC-ODBC Bridge technology to manipulate ACE/Jet ("Access") databases is really a practical option only under Windows. It is also important to note that the JDBC-ODBC Bridge will be has been removed in Java 8 (ref: here).

There are other ways of manipulating ACE/Jet databases from Java, such as UCanAccess and Jackcess. Both of these are pure Java implementations so they work on non-Windows platforms. For details on how to use UCanAccess see

Manipulating an Access database from Java without ODBC

Section vs Article HTML5

I like to stick with the standard meaning of the words used: An article would apply to, well, articles. I would define blog posts, documents, and news articles as articles. Sections on the other hand, would refer to layout/ux items: sidebar, header, footer would be sections. However this is all my own personal interpretation -- as you pointed out, the specification for these elements are not well defined.

Supporting this, the w3c defines an article element as a section of content that can independently stand on its own. A blog post could stand on it's own as a valuable and consumable item of content. However, a header would not.

Here is an interesting article about one mans madness in trying to differenciate between the two new elements. The basic point of the article, that I also feel is correct, is to try and use what ever element you feel best actually represents what it contains.

What’s more problematic is that article and section are so very similar. All that separates them is the word “self-contained”. Deciding which element to use would be easy if there were some hard and fast rules. Instead, it’s a matter of interpretation. You can have multiple articles within a section, you can have multiple sections within and article, you can nest sections within sections and articles within sections. It’s up to you to decide which element is the most semantically appropriate in any given situation.

Here is a very good answer to the same question here on SO

Symfony - generate url with parameter in controller

It's pretty simple :

public function myAction()
{
    $url = $this->generateUrl('blog_show', array('slug' => 'my-blog-post'));
}

Inside an action, $this->generateUrl is an alias that will use the router to get the wanted route, also you could do this that is the same :

$this->get('router')->generate('blog_show', array('slug' => 'my-blog-post'));

I want to show all tables that have specified column name

Pretty simple on a per database level

Use DatabaseName
Select * From INFORMATION_SCHEMA.COLUMNS Where column_name = 'ColName'

Multi-key dictionary in c#?

I use a Tuple as the keys in a Dictionary.

public class Tuple<T1, T2> {
    public T1 Item1 { get; private set; }
    public T2 Item2 { get; private set; }

    // implementation details
}

Be sure to override Equals and GetHashCode and define operator!= and operator== as appropriate. You can expand the Tuple to hold more items as needed. .NET 4.0 will include a built-in Tuple.

How to vertically center a "div" element for all browsers using CSS?

The easiest solution is below:

_x000D_
_x000D_
.outer-div{_x000D_
  width: 100%;_x000D_
  height: 200px;_x000D_
  display: flex;_x000D_
  border:1px solid #000;_x000D_
}_x000D_
.inner-div{_x000D_
  margin: auto;_x000D_
  text-align:center;_x000D_
  border:1px solid red;_x000D_
}
_x000D_
<div class="outer-div">_x000D_
  <div class="inner-div">_x000D_
    Hey there!_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

To delay JavaScript function call using jQuery

Since you declare sample inside the anonymous function you pass to ready, it is scoped to that function.

You then pass a string to setTimeout which is evaled after 2 seconds. This takes place outside the current scope, so it can't find the function.

Only pass functions to setTimeout, using eval is inefficient and hard to debug.

setTimeout(sample,2000)

Is there a reason for C#'s reuse of the variable in a foreach?

Having been bitten by this, I have a habit of including locally defined variables in the innermost scope which I use to transfer to any closure. In your example:

foreach (var s in strings)
    query = query.Where(i => i.Prop == s); // access to modified closure

I do:

foreach (var s in strings)
{
    string search = s;
    query = query.Where(i => i.Prop == search); // New definition ensures unique per iteration.
}        

Once you have that habit, you can avoid it in the very rare case you actually intended to bind to the outer scopes. To be honest, I don't think I have ever done so.

Excel - Combine multiple columns into one column

Try this. Click anywhere in your range of data and then use this macro:

Sub CombineColumns()
Dim rng As Range
Dim iCol As Integer
Dim lastCell As Integer

Set rng = ActiveCell.CurrentRegion
lastCell = rng.Columns(1).Rows.Count + 1

For iCol = 2 To rng.Columns.Count
    Range(Cells(1, iCol), Cells(rng.Columns(iCol).Rows.Count, iCol)).Cut
    ActiveSheet.Paste Destination:=Cells(lastCell, 1)
    lastCell = lastCell + rng.Columns(iCol).Rows.Count
Next iCol
End Sub

Skip a submodule during a Maven build

there is now (from 1.1.1 version) a 'skip' flag in pit.

So you can do things like :

    <profile>
        <id>pit</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.pitest</groupId>
                    <artifactId>pitest-maven</artifactId>
                    <configuration>
                        <skip>true</skip>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>

in your module, and pit will skip

[INFO] --- pitest-maven:1.1.3:mutationCoverage (default-cli) @ module-selenium --- [INFO] Skipping project

How to rotate x-axis tick labels in Pandas barplot

You can use set_xticklabels()

ax.set_xticklabels(df['Names'], rotation=90, ha='right')

Is it still valid to use IE=edge,chrome=1?

<head>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>

worked for me, to force IE to "snap out of compatibility mode" (so to speak), BUT that meta statement must appear IMMEDIATELY after the <head>, or it won't work!

wget/curl large file from google drive

The easy way:

(if you just need it for a one-off download)

  1. Go to the Google Drive webpage that has the download link
  2. Open your browser console and go to the "network" tab
  3. Click the download link
  4. Wait for it the file to start downloading, and find the corresponding request (should be the last one in the list), then you can cancel the download
  5. Right click on the request and click "Copy as cURL" (or similar)

You should end up with something like:

curl 'https://doc-0s-80-docs.googleusercontent.com/docs/securesc/aa51s66fhf9273i....................blah blah blah...............gEIqZ3KAQ==' --compressed

Past it in your console, add > my-file-name.extension to the end (otherwise it will write the file into your console), then press enter :)

Mouseover or hover vue.js

Though I would give an update using the new composition api.

Component

<template>
  <div @mouseenter="hovering = true" @mouseleave="hovering = false">
    {{ hovering }}
  </div>
</template>

<script>
  import { ref } from '@vue/compsosition-api'

  export default {
    setup() {
      const hovering = ref(false)
      return { hovering }
    }
  })
</script>

Reusable Composition Function

Creating a useHover function will allow you to reuse in any components.

export function useHover(target: Ref<HTMLElement | null>) {
  const hovering = ref(false)

  const enterHandler = () => (hovering.value = true)
  const leaveHandler = () => (hovering.value = false)

  onMounted(() => {
    if (!target.value) return
    target.value.addEventListener('mouseenter', enterHandler)
    target.value.addEventListener('mouseleave', leaveHandler)
  })

  onUnmounted(() => {
    if (!target.value) return
    target.value.removeEventListener('mouseenter', enterHandler)
    target.value.removeEventListener('mouseleave', leaveHandler)
  })

  return hovering
}

Here's a quick example calling the function inside a Vue component.

<template>
  <div ref="hoverRef">
    {{ hovering }}
  </div>
</template>

<script lang="ts">
  import { ref } from '@vue/compsosition-api'
  import { useHover } from './useHover'

  export default {
    setup() {
      const hoverRef = ref(null)
      const hovering = useHover(hoverRef)
      return { hovering, hoverRef }
    }
  })
</script>

You can also use a library such as @vuehooks/core which comes with many useful functions including useHover.

How to use "like" and "not like" in SQL MSAccess for the same field?

What I found out is that MS Access will reject --Not Like "BB*"-- if not enclosed in PARENTHESES, unlike --Like "BB*"-- which is ok without parentheses.

I tested these on MS Access 2010 and are all valid:

  1. Like "BB"

  2. (Like "BB")

  3. (Not Like "BB")

how to open a url in python

Here is another way to do it.

import webbrowser

webbrowser.open("foobar.com")

AngularJS ng-click stopPropagation

An addition to Stewie's answer. In case when your callback decides whether the propagation should be stopped or not, I found it useful to pass the $event object to the callback:

<div ng-click="parentHandler($event)">
  <div ng-click="childHandler($event)">
  </div>
</div>

And then in the callback itself, you can decide whether the propagation of the event should be stopped:

$scope.childHandler = function ($event) {
  if (wanna_stop_it()) {
    $event.stopPropagation();
  }
  ...
};

How can foreign key constraints be temporarily disabled using T-SQL?

Find the constraint

SELECT * 
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('TABLE_NAME')

Execute the SQL generated by this SQL

SELECT 
    'ALTER TABLE ' +  OBJECT_SCHEMA_NAME(parent_object_id) +
    '.[' + OBJECT_NAME(parent_object_id) + 
    '] DROP CONSTRAINT ' + name
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('TABLE_NAME')

Safeway.

Note: Added solution for droping the constraint so that table can be dropped or modified without any constraint error.

R plot: size and resolution

A reproducible example:

the_plot <- function()
{
  x <- seq(0, 1, length.out = 100)
  y <- pbeta(x, 1, 10)
  plot(
    x,
    y,
    xlab = "False Positive Rate",
    ylab = "Average true positive rate",
    type = "l"
  )
}

James's suggestion of using pointsize, in combination with the various cex parameters, can produce reasonable results.

png(
  "test.png",
  width     = 3.25,
  height    = 3.25,
  units     = "in",
  res       = 1200,
  pointsize = 4
)
par(
  mar      = c(5, 5, 2, 2),
  xaxs     = "i",
  yaxs     = "i",
  cex.axis = 2,
  cex.lab  = 2
)
the_plot()
dev.off()

Of course the better solution is to abandon this fiddling with base graphics and use a system that will handle the resolution scaling for you. For example,

library(ggplot2)

ggplot_alternative <- function()
{
  the_data <- data.frame(
    x <- seq(0, 1, length.out = 100),
    y = pbeta(x, 1, 10)
  )

ggplot(the_data, aes(x, y)) +
    geom_line() +
    xlab("False Positive Rate") +
    ylab("Average true positive rate") +
    coord_cartesian(0:1, 0:1)
}

ggsave(
  "ggtest.png",
  ggplot_alternative(),
  width = 3.25,
  height = 3.25,
  dpi = 1200
)

How to enable core dump in my Linux C++ program

You need to set ulimit -c. If you have 0 for this parameter a coredump file is not created. So do this: ulimit -c unlimited and check if everything is correct ulimit -a. The coredump file is created when an application has done for example something inappropriate. The name of the file on my system is core.<process-pid-here>.

How to style the option of an html "select" element?

Leaving here a quick alternative, using class toggle on a table. The behavior is very similar than a select, but can be styled with transition, filters and colors, each children individually.

_x000D_
_x000D_
function toggleSelect(){ _x000D_
 if (store.classList[0] === "hidden"){_x000D_
    store.classList = "viewfull"_x000D_
  }_x000D_
  else {_x000D_
    store.classList = "hidden"_x000D_
  }_x000D_
}
_x000D_
#store {_x000D_
  overflow-y: scroll;_x000D_
  max-height: 110px;_x000D_
  max-width: 50%_x000D_
 }_x000D_
 _x000D_
.hidden {_x000D_
  display: none_x000D_
 }_x000D_
 _x000D_
.viewfull {_x000D_
  display: block_x000D_
}_x000D_
_x000D_
#store :nth-child(4) {_x000D_
  background-color: lime;_x000D_
}_x000D_
_x000D_
span {font-size:2rem;cursor:pointer}
_x000D_
<span onclick="toggleSelect()">?</span>_x000D_
 <div id="store" class="hidden">_x000D_
 _x000D_
<ul><li><a href="#keylogger">keylogger</a></li><li><a href="#1526269343113">1526269343113</a></li><li><a href="#slow">slow</a></li><li><a href="#slow2">slow2</a></li><li><a href="#Benchmark">Benchmark</a></li><li><a href="#modal">modal</a></li><li><a href="#buma">buma</a></li><li><a href="#1526099371108">1526099371108</a></li><a href="#1526099371108o">1526099371108o</a></li><li><a href="#pwnClrB">pwnClrB</a></li><li><a href="#stars%20u">stars%20u</a></li><li><a href="#pwnClrC">pwnClrC</a></li><li><a href="#stars ">stars </a></li><li><a href="#wello">wello</a></li><li><a href="#equalizer">equalizer</a></li><li><a href="#pwnClrA">pwnClrA</a></li></ul>_x000D_
 _x000D_
 </div>
_x000D_
_x000D_
_x000D_

How do I merge a git tag onto a branch

You mean this?

git checkout destination_branch
git merge tag_name

Perform .join on value in array of objects

try this

var x= [
  {name: "Joe", age: 22},
  {name: "Kevin", age: 24},
  {name: "Peter", age: 21}
]

function joinObj(a, attr) {
  var out = []; 
  for (var i=0; i<a.length; i++) {  
    out.push(a[i][attr]); 
  } 
 return out.join(", ");
}

var z = joinObj(x,'name');
z > "Joe, Kevin, Peter"
var y = joinObj(x,'age');
y > "22, 24, 21"

C# adding a character in a string

You can use this:

string alpha = "abcdefghijklmnopqrstuvwxyz";
int length = alpha.Length;

for (int i = length - ((length - 1) % 5 + 1); i > 0; i -= 5)
{
    alpha = alpha.Insert(i, "-");
}

Works perfectly with any string. As always, the size doesn't matter. ;)

Checking for NULL pointer in C/C++

I'll start off with this: consistency is king, the decision is less important than the consistency in your code base.

In C++

NULL is defined as 0 or 0L in C++.

If you've read The C++ Programming Language Bjarne Stroustrup suggests using 0 explicitly to avoid the NULL macro when doing assignment, I'm not sure if he did the same with comparisons, it's been a while since I read the book, I think he just did if(some_ptr) without an explicit comparison but I am fuzzy on that.

The reason for this is that the NULL macro is deceptive (as nearly all macros are) it is actually 0 literal, not a unique type as the name suggests it might be. Avoiding macros is one of the general guidelines in C++. On the other hand, 0 looks like an integer and it is not when compared to or assigned to pointers. Personally I could go either way, but typically I skip the explicit comparison (though some people dislike this which is probably why you have a contributor suggesting a change anyway).

Regardless of personal feelings this is largely a choice of least evil as there isn't one right method.

This is clear and a common idiom and I prefer it, there is no chance of accidentally assigning a value during the comparison and it reads clearly:

if (some_ptr) {}

This is clear if you know that some_ptr is a pointer type, but it may also look like an integer comparison:

if (some_ptr != 0) {}

This is clear-ish, in common cases it makes sense... But it's a leaky abstraction, NULL is actually 0 literal and could end up being misused easily:

if (some_ptr != NULL) {}

C++11 has nullptr which is now the preferred method as it is explicit and accurate, just be careful about accidental assignment:

if (some_ptr != nullptr) {}

Until you are able to migrate to C++0x I would argue it's a waste of time worrying about which of these methods you use, they are all insufficient which is why nullptr was invented (along with generic programming issues which came up with perfect forwarding.) The most important thing is to maintain consistency.

In C

C is a different beast.

In C NULL can be defined as 0 or as ((void *)0), C99 allows for implementation defined null pointer constants. So it actually comes down to the implementation's definition of NULL and you will have to inspect it in your standard library.

Macros are very common and in general they are used a lot to make up for deficiencies in generic programming support in the language and other things as well. The language is much simpler and reliance on the preprocessor more common.

From this perspective I'd probably recommend using the NULL macro definition in C.

Unique on a dataframe with only selected columns

Using unique():

dat <- data.frame(id=c(1,1,3),id2=c(1,1,4),somevalue=c("x","y","z"))    
dat[row.names(unique(dat[,c("id", "id2")])),]

convert nan value to zero

A code example for drake's answer to use nan_to_num:

>>> import numpy as np
>>> A = np.array([[1, 2, 3], [0, 3, np.NaN]])
>>> A = np.nan_to_num(A)
>>> A
array([[ 1.,  2.,  3.],
       [ 0.,  3.,  0.]])

How to use a TRIM function in SQL Server

TRIM all SPACE's TAB's and ENTER's:

DECLARE @Str VARCHAR(MAX) = '      
          [         Foo    ]       
          '

DECLARE @NewStr VARCHAR(MAX) = ''
DECLARE @WhiteChars VARCHAR(4) =
      CHAR(13) + CHAR(10) -- ENTER
    + CHAR(9) -- TAB
    + ' ' -- SPACE

;WITH Split(Chr, Pos) AS (
    SELECT
          SUBSTRING(@Str, 1, 1) AS Chr
        , 1 AS Pos
    UNION ALL
    SELECT
          SUBSTRING(@Str, Pos, 1) AS Chr
        , Pos + 1 AS Pos
    FROM Split
    WHERE Pos <= LEN(@Str)
)
SELECT @NewStr = @NewStr + Chr
FROM Split
WHERE
    Pos >= (
        SELECT MIN(Pos)
        FROM Split
        WHERE CHARINDEX(Chr, @WhiteChars) = 0
    )
    AND Pos <= (
        SELECT MAX(Pos)
        FROM Split
        WHERE CHARINDEX(Chr, @WhiteChars) = 0
    )

SELECT '"' + @NewStr + '"'

As Function

CREATE FUNCTION StrTrim(@Str VARCHAR(MAX)) RETURNS VARCHAR(MAX) BEGIN
    DECLARE @NewStr VARCHAR(MAX) = NULL

    IF (@Str IS NOT NULL) BEGIN
        SET @NewStr = ''

        DECLARE @WhiteChars VARCHAR(4) =
              CHAR(13) + CHAR(10) -- ENTER
            + CHAR(9) -- TAB
            + ' ' -- SPACE

        IF (@Str LIKE ('%[' + @WhiteChars + ']%')) BEGIN

            ;WITH Split(Chr, Pos) AS (
                SELECT
                      SUBSTRING(@Str, 1, 1) AS Chr
                    , 1 AS Pos
                UNION ALL
                SELECT
                      SUBSTRING(@Str, Pos, 1) AS Chr
                    , Pos + 1 AS Pos
                FROM Split
                WHERE Pos <= LEN(@Str)
            )
            SELECT @NewStr = @NewStr + Chr
            FROM Split
            WHERE
                Pos >= (
                    SELECT MIN(Pos)
                    FROM Split
                    WHERE CHARINDEX(Chr, @WhiteChars) = 0
                )
                AND Pos <= (
                    SELECT MAX(Pos)
                    FROM Split
                    WHERE CHARINDEX(Chr, @WhiteChars) = 0
                )
        END
    END

    RETURN @NewStr
END

Example

-- Test
DECLARE @Str VARCHAR(MAX) = '      
          [         Foo    ]       
              '

SELECT 'Str', '"' + dbo.StrTrim(@Str) + '"'
UNION SELECT 'EMPTY', '"' + dbo.StrTrim('') + '"'
UNION SELECT 'EMTPY', '"' + dbo.StrTrim('      ') + '"'
UNION SELECT 'NULL', '"' + dbo.StrTrim(NULL) + '"'

Result

+-------+----------------+
| Test  | Result         |
+-------+----------------+
| EMPTY | ""             |
| EMTPY | ""             |
| NULL  | NULL           |
| Str   | "[   Foo    ]" |
+-------+----------------+

mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in

That query is failing and returning false.

Put this after mysqli_query() to see what's going on.

if (!$check1_res) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

For more information:

http://www.php.net/manual/en/mysqli.error.php

Getting an element from a Set

Convert set to list, and then use get method of list

Set<Foo> set = ...;
List<Foo> list = new ArrayList<Foo>(set);
Foo obj = list.get(0);

SVN Repository on Google Drive or DropBox

While possible, it's potentially very risky - if you attempt to commit changes to the repository from 2 different locations simultaneously, you'll get a giant mess due to the file conflicts. Get a free private SVN host somewhere, or set up a repository on a server you have access to.

Edit based on a recent experience: If you have files open that are managed by Dropbox and your computer crashes, your files may be truncated to 0 bytes. If this happens to the files which manage your repository, your repository will be corrupted. If you discover this soon enough, you can use Dropbox's "recover old version" feature but you're still taking a risk.

onclick or inline script isn't working in extension

I decide to publish my example that I used in my case. I tried to replace content in div using a script. My problem was that Chrome did not recognized / did not run that script.

In more detail What I wanted to do: To click on a link, and that link to "read" an external html file, that it will be loaded in a div section.

  • I found out that by placing the script before the DIV with ID that was called, the script did not work.
  • If the script was in another DIV, also it does not work
  • The script must be coded using document.addEventListener('DOMContentLoaded', function() as it was told

        <body>
        <a id=id_page href ="#loving"   onclick="load_services()"> loving   </a>
    
            <script>
                    // This script MUST BE under the "ID" that is calling
                    // Do not transfer it to a differ DIV than the caller "ID"
                    document.getElementById("id_page").addEventListener("click", function(){
                    document.getElementById("mainbody").innerHTML = '<object data="Services.html" class="loving_css_edit"; ></object>'; });
                </script>
        </body>
    
      <div id="mainbody" class="main_body">
            "here is loaded the external html file when the loving link will 
             be  clicked. "
      </div>
    

Extract column values of Dataframe as List in Apache Spark

sqlContext.sql(" select filename from tempTable").rdd.map(r => r(0)).collect.toList.foreach(out_streamfn.println) //remove brackets

it works perfectly

android View not attached to window manager

After a fight with this issue, I finally end up with this workaround:

/**
 * Dismiss {@link ProgressDialog} with check for nullability and SDK version
 *
 * @param dialog instance of {@link ProgressDialog} to dismiss
 */
public void dismissProgressDialog(ProgressDialog dialog) {
    if (dialog != null && dialog.isShowing()) {

            //get the Context object that was used to great the dialog
            Context context = ((ContextWrapper) dialog.getContext()).getBaseContext();

            // if the Context used here was an activity AND it hasn't been finished or destroyed
            // then dismiss it
            if (context instanceof Activity) {

                // Api >=17
                if (!((Activity) context).isFinishing() {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                        if (!((Activity) context).isDestroyed()) {
                            dismissWithExceptionHandling(dialog);
                        }
                    } else { 
                        // Api < 17. Unfortunately cannot check for isDestroyed()
                        dismissWithExceptionHandling(dialog);
                    }
                }
            } else
                // if the Context used wasn't an Activity, then dismiss it too
                dismissWithExceptionHandling(dialog);
        }
        dialog = null;
    }
}

/**
 * Dismiss {@link ProgressDialog} with try catch
 *
 * @param dialog instance of {@link ProgressDialog} to dismiss
 */
public void dismissWithExceptionHandling(ProgressDialog dialog) {
    try {
        dialog.dismiss();
    } catch (final IllegalArgumentException e) {
        // Do nothing.
    } catch (final Exception e) {
        // Do nothing.
    } finally {
        dialog = null;
    }
}

Sometimes, good exception handling works well if there wasn't a better solution for this issue.

How to download a file using a Java REST service and a data stream

Refer this:

@RequestMapping(value="download", method=RequestMethod.GET)
public void getDownload(HttpServletResponse response) {

// Get your file stream from wherever.
InputStream myStream = someClass.returnFile();

// Set the content type and attachment header.
response.addHeader("Content-disposition", "attachment;filename=myfilename.txt");
response.setContentType("txt/plain");

// Copy the stream to the response's output stream.
IOUtils.copy(myStream, response.getOutputStream());
response.flushBuffer();
}

Details at: https://twilblog.github.io/java/spring/rest/file/stream/2015/08/14/return-a-file-stream-from-spring-rest.html

How to parse a date?

The problem is that you have a date formatted like this:

Thu Jun 18 20:56:02 EDT 2009

But are using a SimpleDateFormat that is:

yyyy-MM-dd

The two formats don't agree. You need to construct a SimpleDateFormat that matches the layout of the string you're trying to parse into a Date. Lining things up to make it easy to see, you want a SimpleDateFormat like this:

EEE MMM dd HH:mm:ss zzz yyyy
Thu Jun 18 20:56:02 EDT 2009

Check the JavaDoc page I linked to and see how the characters are used.

Removing unwanted table cell borders with CSS

Try assigning the style of border: 0px; border-collapse: collapse; to the table element.