text:
Q: Is there a faster way to find any name in namesArray? Can I find a required name without loop through each array item?
Is there any faster way to do the same assuming that I have a very big array length, because if I have an array of 10000 items and the name doesn't exist in it, it will be a waste of time and assuming that we don't have inclouds function

$(document).ready(function() {
  function binarySearch(names, requiredName) {
    for (var i = 0; i < names.length; i++) {
      if (names[i] === requiredName) {
        return true;
      }
    }
    return false;
  }
  console.log(binarySearch(['ola', 'amer', 'anwar', 'mamon'], 'hadeel'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

A: You can use the Array#includes function like this.
names.includes(requiredName)

If you want to know exactly WHERE the item is located you need to iterate like you already did.

A: You can use

var array = ["foo", "bar", "baz"];
var search = "foo";

// using the ES6 some function
var includes = array.some(val => val == search);
console.log(includes);

// using the find function
var found = array.find(val => val == search);
console.log(!!found); // or found != null

but the simplest way is indexOf or includes (but doens't have full browser support yet)


text:
Q: Tailwind CSS Scrollbar only appearing on hover I don't understand why my scrollbar is only appearing when I hover over it, otherwise it doesn't show meaning if you didn't know it was there it could be very difficult to navigate. The code where I'm using the scrollbar is shown below.
import FormInputField from "./FormInputField";
import { useState } from "react";
import FormDropdown from "./FormDropdown";

const CoreDetailsForm = () => {
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [dateOfBirth, setDateOfBirth] = useState('');
  const [height, setHeight] = useState('');
  const [weight, setWeight] = useState('');
  const [gender, setGender] = useState('');
  const [wingspan, setWingspan] = useState('');

  return (

My Details

        <FormInputField title="First Name" name="first-name" type="text" changeHandler={setFirstName} />
        <FormInputField title="Surname" name="surname" type="text" changeHandler={setLastName} />
        <FormInputField title="Date of Birth" name="dob" type="text" placeholder="DD/MM/YYYY" changeHandler={setDateOfBirth} />
        <FormDropdown />
        <FormInputField title="Height (cm)" name="height" type="number" min={0} max={999} changeHandler={setHeight} />
        <FormInputField title="Weight (kg)" name="weight" type="number" min={0} max={999} changeHandler={setWeight} />
        <FormInputField title="Wingspan (cm)" name="wingspan" type="number" min={0} max={999} changeHandler={setWingspan} />
        <FormInputField title="Weight (kg)" name="weight" type="number" min={0} max={999} changeHandler={setWeight} />
        <FormInputField title="Wingspan (cm)" name="wingspan" type="number" min={0} max={999} changeHandler={setWingspan} />

  )
}

export default CoreDetailsForm;

I'm  using React with TypeScript and Tailwind CSS. I've tried using overflow-auto as well.

A: try adding
 .scrollbar { display: block; }
to your css file

redpajama_set_name: RedPajamaStackExchange


text:
Q: COPY 0 when copying table with data in PostgreSQL to CSV I have a table under a schema, table_schema, that has data in it:
\c data_store
select count(*) from table_schema.mytable;
9898123 rows

But when I try to copy this data to a CSV file, I get COPY 0:
copy table_schema.mytable to '/tmp/mytable.csv' with (format csv, header);
COPY 0

but if use a select instead, the file is created correctly:
copy (select * from table_schema.mytable) to '/tmp/mytable.csv' with (format csv, header)
COPY 9898123

Any ideas on what's going on here? PostgreSQL version is 9.6.


text:
Q: Centralized backup method recommendation for SMEs with various OSes Hi I was wondering what in your opinion is the "best" method for having "everything" backed-up in the following situation.

*

*We are a SMEs with 10 computers in total.

*

*Three of those computers are MACs

*The rest are windows (1 vista, 4 win7 and 2 XPs)

I'm very open to what the method should be but you should also consider the follwing:

*

*Very limited resources

*Quite "small" bandwidth (4 MBs for all (download) 0.4 MBs (upload, yep, thats it)- though this might get, a little bit better)

One of the main thing to back up would be the mails, considerations:

*

*All windows computers use outlook, mainly 2003

*There is one mac that uses outlook too (for mac of course - not 2011 yet)

We also have to backup the files:

*

*Not a huge amount

*Very few very big files

*Very organizes (by machine)

What I would like is to hear your opinions as to which would be the best method (or combination of methods - preferably one of course) considering.
We are not sure what do we need and I'm open to suggestions, though an online (cloud based applications) would be great, remember the the bandwidth is unbearable.
Last think to consider, it that we would like to do weekly updates (unless the method is very easy of course).
Thanks in advance!! I tried to be as specific as possible, but if anything is needed I'll gladly update, please ask for any clarification needed!

Please avoid any answers like upgrade all to windows 7 and throw away your macs :) our's may not be an ideal situation, but it is what it is, and right now, it would be impossible for us to change it for a lot of circumstances.

A: BackupPC - install it on a Linux box, no need to install software on workstations.
for Windows machines need a share to be created (for example c:\documents and settings)
for Linux and macs - export directories via NFS or via ssh
has web based interface for administering and with detailed statistics/ log files

A: I'd probably suggest you look at CrashPlan Pro.  Ten licenses costs $686 a year (looking at their store right now) but it supports all your platforms and provides unlimited cloud based storage, or you can use it to back up locally - or both.  You're not supposed to use the consumer version ($12 a month or less for 10 computers) for business backups.
They also offer a service where they post you a 1TB drive for you to back up on to and ship to them, kick starting your cloud backup.
As for your bandwidth - consider performing the remote backups out of hours - it does mean leaving the computers on overnight but it also gives you a good time to schedule full AV scans and other such tasks.
I use their consumer version and I'm very happy with it.

A: Check out an online solution like Mozy.


text:
Q: My images won't show My images won't show up when I am trying to load up this page! I am trying to make a traffic light sequence (UK) that shows up with all the colours when the change lights button is pressed!
<!DOCTYPE html>

Changing Traffic Lights

<button type="button" onClick="changeLights()"> Change Lights </button>

A: Your code works. But you must have a problem with your image source paths. Because this works correctly when I change the images to something remote like lorempixel.
Working jsfiddle here.
Try to fix the image paths in your JS. Good luck.
var trafficlights = ["http://lorempixel.com/100/100","http://lorempixel.com/100/90","http://lorempixel.com/100/100","http://lorempixel.com/100/110"]


text:
Q: What will happen if an attribute is used in program without enabled and binding a buffer? Recently, when I reading the webgl spec. I have a question about below, since my program has randomly error on chrome browser due to it:
What will happen if an attribute is used in program without binding a buffer and enabled during a call to drawArrays or drawElements?
The spec only says that:

If a vertex attribute is enabled as an array, a buffer is bound to
  that attribute, but the attribute is not consumed by the current
  program, then regardless of the size of the bound buffer, it will not
  cause any error to be generated during a call to drawArrays or
  drawElements.
If a vertex attribute is enabled as an array via
  enableVertexAttribArray but no buffer is bound to that attribute via
  bindBuffer and vertexAttribPointer, then calls to drawArrays or
  drawElements will generate an INVALID_OPERATION error

Can anyone help me on this??

A: The second paragraph says you'll get an error, always, if you enable an attribute but don't bind a buffer.
There's 4 possibilities

*

*You have an attribute enabled with a buffer bound and that attribute is used by the current shader program.
In this case the buffer must be large enough to handle whatever you try to draw. In other words if you have a buffer with 3 vertices but you ask WebGL to draw 4 vertices you'll get an error. Or if you call gl.drawElements and one of your indices is greater than 2 you'll get an error.

*You have an attribute enabled with a buffer bound and that attribute is NOT used by the current shader program.
In this case there will be no error even if the buffer is not large enough because the buffer is not used.

*You have an attribute enabled with NO BUFFER bound.
In this case you'll get an error, always.

*You have an attribute disabled
In this case it will use the value supplied by calling gl.vertexAttrib4f or one of its variants.
The 2 paragraphs you quoted from the spec cover cases 2 and 3 above.


text:
Q: set tinymce in " javascript, $(document).ready...", my solution is not working i use javascript made a function that every time i click button "add one more" button, html page will add another group of html elements, which i need to includes tinymce text area, but I cannot manage to do it.
here is part of my code,
<script>
$(document).ready(function (e) {
var html = '<textarea class="tinymce" name="CCV_product_full_description[]" id="childccv-product-full-description" />';
...

I defined tinymce in another js file and included in this html file, but it not works some how, i need some help :)
in another js file
tinymce.init({
selector:"textarea.tinymce"
});

here is the function for add another group of html elements
$("#add").click(function (e) {
        $("#container").append(html);

    });

A: It looks like you are trying to initialize the editor on DOM elements that don't yet exist.
Also, if you are trying to dynamically add several instances of TinyMCE, you need to remove TinyMCE first before you can call it again.
$("#add").on('click', function (e) {
    e.preventDefault()
    $("#container").append(html);
    tinymce.remove()
    tinymce.init({
    selector:".yourSelectorName"
    });
  });


text:
Q: How to run nosetests without showing of my matplotlib's graph? I try to run my test without any messages displaying from my main program. I only want verbose messages from nosetests to display.
For example:

nosetests -v --nologcapture

All of my printout messages from my main program will be gone.
However, the graph that I call in my main program (plt.show() from matplotlib) still shows up.
How do I run the tests without matplotlib's graph showing up?

A: I assume that you're calling unittests on your code, so my recommendation would be for you to install the python Mock library. Any tests that will exercise the plt.show() function should mock it out to basically do nothing.
Here's an rough example of the idea inside your unittests:
from mock import patch

... unittest boiler plate stuff ...

@patch("matplotlib.pyplot.show")
def testMyCode(self, mock_show):
    mock_show.return_value = None  #probably not necessary here in your case
    ... rest of test code ...

The patch function will override the normal show function with this new mock_show which you could name to anything. This should basically make the show now do nothing in your tests and not have the graph show up.


text:
Q: How do you wrap the 'Convert' class into a Generic function Below is a simplified example of what I want to do. In the actual code I catch exceptions to do other things. But essentially I would like to wrap the 'Convert' class in a generic function, but alas this code generates an error saying that it cannot implicitly convert from type 'ushort' to 'T'.
Any ideas gratefully received. (It's my first question so go gentle with me!)
    private T ChangeValue<T>(T value, string x)
    {
        if (typeof(UInt16) == typeof(T))
        {
            value = Convert.ToUInt16(x);
        }
        return value;
    }

A: Are you looking for something like this?
private T ChangeType<T>(object value)
{
    return (T)Convert.ChangeType(value, typeof(T));
}

Usage:
double result = ChangeType<double>(true);


text:
Q: Distinct terms for a monolingual dictionary and a bilingual dictionary I am writing a text where I need to address two types of dictionaries distinctly;
The first type of dictionary presents words alongside one or more possible definitions, constrained to a single language. The second type is a bilingual/multilingual dictionary where words are presented with their translations.
I feel like monolingual does not automatically infer a dictionary of definitions. Also in general monolingual/bilingual/multilingual feels excessively technical and I'd resort to them if the distinction I'm trying to make cannot be conveyed by a simple term or phrase.
A quick Google search shows me https://www.merriam-webster.com/ is the first type of dictionary I'm trying to define while
https://www.collinsdictionary.com/dictionary/english-german is the second type.
I would like to know if distinct terms or phrases exist for these two dictionary types so I can clearly phrase which one I'm talking about during my writing.

A: On A Practical Guide to Lexicography (2003), edited by Piet van Sterkenburg, the first type of dictionary is referred as dictionary.

For us, looking for a definition of 'dictionary' is looking for a definition of the prototypical dictionary. The prototypical dictionary is the alphabetical monolingual general-purpose dictionary. Its characteristics are the use of one and the same language for both the object and the means of description, the supposed exhaustive nature of the list of described words and the more linguistic than encyclopaedic nature of the knowledge offered. The monolingual general-purpose dictionary . . .

contains primarily semasiological rather than onomasiological or non-semantic data, gives a description of a standard language rather than restricted or marked language varieties, and serves a pedagogical purpose rather than a critical or scholarly one.
    (Geeraerts 1989:293–294)

What makes the monolingual general-purpose dictionary so prototypical? I will continue here on the course set out by Béjoint (2000:40):

It is the one that every household has, that everyone thinks of first when the word dictionary is mentioned, it is the type that is most often bought, most often consulted, the one that plays the most important role in the society that produces it. (Page 3)

The second type of the dictionary is referred as multilingual or translation dictionary.

According to Zgusta (1971:294) the basic aim of multilingual or translation dictionaries is 'to co-ordinate with the lexical units of one language those units of another language which are equivalent in their lexical meaning'. On the microstructural level this function is realised by providing for a lemma in the source language one or more translation equivalents in the target language. (Page 67)

A: A monolingual dictionary is a dictionary with only one language in. A bilingual dictionary is one that has both the words in one language, and their divergent in another.


text:
Q: Medium Editor multi user with fake caret I'm trying to build a collaboration text editor using Medium Editor (https://github.com/yabwe/medium-editor).
What I'm trying to do is to implement this functionality into my editor:
https://github.com/convergencelabs/html-text-collab-ext
I'm not really an expert on Javascript and I'm facing some issues.
So far I created a Medium Editor extension that listen from the external users input, taking in input the caret position of the external changes (using the exportSelection() feature of the editor). What I'm trying to do now is to insert the fake caret (similar to the one seen on html-text-collab-ext) in the position where the changing was made, but of course without touching the real caret.
My Code:
    export const CollabAnchorPreview = MediumEditor.Extension.extend({
        name: 'collab-anchor-preview',

        init: function () {
            this.anchorPreview = this.createPreview();
            this.getEditorOption('elementsContainer').appendChild(this.anchorPreview);

            this.subscribe('externalWriting', this.showPreview.bind(this));
        },

        createPreview: function () {
            var el = this.document.createElement('div');

            el.id = 'medium-editor-anchor-preview-' + this.getEditorId();
            el.className = 'medium-editor-anchor-preview';
            el.innerHTML = this.getTemplate();

            return el;
        },

        getTemplate: function () {
            return '
' +
                '    ' +
                '
';
        },

        destroy: function () {
            if (this.anchorPreview) {
                if (this.anchorPreview.parentNode) {
                    this.anchorPreview.parentNode.removeChild(this.anchorPreview);
                }
                delete this.anchorPreview;
            }
        },

        hidePreview: function () {
            if (this.anchorPreview) {
                this.anchorPreview.classList.remove('medium-editor-anchor-preview-active');
            }
            this.activeAnchor = null;
        },

        showPreview: function(external_caret_position, editable) {
            console.log('Event');
            console.log(external_caret_position);

            // Here I don't know well how to go ahead.

Thank you very in advance.


text:
Q: How to find set difference of two files? I have two files A and B. I want to find all the lines in A that are not in B. What's the fastest way to do this in bash/using standard linux utilities? Here's what I tried so far:
for line in `cat file1`
 do
   if [ `grep -c "^$line$" file2` -eq 0]; then
   echo $line
   fi
 done

It works, but it's slow. Is there a faster way of doing this?

A: The BashFAQ describes doing exactly this with comm, which is the canonically correct method.
# Subtraction of file1 from file2
# (i.e., only the lines unique to file2)
comm -13 <(sort file1) <(sort file2)

diff is less appropriate for this task, as it tries to operate on blocks rather than individual lines; as such, the algorithms it has to use are more complex and less memory-efficient.
comm has been part of the Single Unix Specification since SUS2 (1997).

A: If you simply want lines that are in file A, but not in B, you can sort the files, and compare them with diff.
sort A > A.sorted
sort B > B.sorted
diff -u A.sorted B.sorted | grep '^-'

A: The 'diff' program is standard unix program that looks at differences between files.
% cat A
a
b
c
d
% cat B
a
b
e
% diff A B
3,4c3
< c
< d
---
> e

With a simple grep and cut one can select the lines in A, not in B.  Note that the cut is rather simplistic and spaces in the lines would throw it off... but the concept is there.
% diff A B | grep '^<' | cut -f2 -d" "
c
d


text:
Q: Choose best output neuron function for 2 class classification Which function is suitable for output neuron in 2 class classification problem with [0/1] output label ?
My answer was Hyperbolic Tangent Neuron - tanh(.)
But ans is not correct , it is logistics sigmoid neuron.
So why we can't use Hyperbolic Tangent Neuron?

A: It is perfectly possible to use a Hyperbolic Tangent function for a binary classification if you train one class with positive targets and another with negative. Recall the range of the Hyperbolic Tangent is (-1, 1).
However, it is far more common to use the Sigmoid activation function as it has a Probabilistic interpretation as it's range is (0, 1).
If P(class = 0) is given by the activation of a Sigmoid, then P(class = 1) = 1 - P(class = 0)
For multiclass classification, the Softmax function is commonly used for it's similar Probabilistic properties.


text:
Q: Problem while transferring data between POST request and GET in django I have a select tag, and what my logic is that after the user selects an option, we would send that response and search through the db to find similar records. The problem is how to access that data.
After the user has selected an option, I would take them to other page which is just a GET request page. So how to access the select tag data(which is a POST request data) on a GET request page.

A: You can send selected data to server with POST and save data in SESSION
and Redirected to Next Page


text:
Q: Adding a custom field on Joomla 2.5 contact form This maybe a question asked many times on Joomla forums, but after searching for some time, I did not find a good answer, instead of "its impossible" and "use a 3rd party form component".
I want to add another field (phone number) on the default Joomla 2.5 contact form, so the user can send that info, along with his message.
From what I've read, its said that is a Joomla limitation from his mail implementation, which can send only name, subject and message. I'm not a experienced Joomla developer, but from my limited knowledge, I belive this can be obtained in a simple way, just by adding fields in the template contact form and concatenate that fields with the message field (or at least that could solve my problem easily).
Like I said, I'm not a experienced developer, so I can't figure out exactly how to do it (and preferably not breaking Joomla installation by modifying too much the core files, if thats the case). Anyone can help? Or at least point me in the right direction?
Thanks.

A: You're right, most people people say "use a 3rd party extension". However there is a very good reason for this. When using Joomla, it's not recommended to edit core files. "Why" you might ask. Purely because of the following reasons:

*

*They may get overridden in Joomla updates

*Joomla's coding style is very different to what people are used to and therefore old coding standards, some of which are considered insecure now, might get used as a lot of people don't read the Joomla documentation. A prime example would be people asking why retrieving data from the database using their code isn't working and they ahev using mysql_connect rather than the Joomla database class.

*The final reason is that if you're a little unsure what you're doing, any code you add may cause problems and results in faulty functionality with existing features. You just never know.

So to answer you're question (even though you may not want to hear this), I'm going to say use a 3rd party extension from this category:
http://extensions.joomla.org/extensions/contacts-and-feedback/contact-forms
There are a very big variety so simply see which one suits your needs.
Hope this gave you a good insight of things.

A: You should never edit core files in Joomla, otherwise an update to those files could potentially bring your site down.  The following link will get you started creating a user plugin where you can add/remove all the fields you need.
http://docs.joomla.org/Creating_a_profile_plugin

A: Maybe a bit late and I hope you have solved your problem already.
But if not you can check out: Elin Warings tutorial for making a form plugin.
Or read about overrides for Joomla core functions:How to create a custom form field type.

A: You can make a plugin to add the field, it's not hard or you can use one of the many extensions available.

A: If you want to add fields to contact us default form.
You need to add fields in 4 files
1)  /components/com_contact/controllers/contact.php`
            $phone      = $data['contact_phone'];

2)  /components/com_contact/views/contact/tmpl/default_form.php

<?php echo $this->form->getLabel('contact_phone'); ?>

<?php echo $this->form->getInput('contact_phone'); ?>

3)  /components/com_contact/models/forms/contact.xml
<field name="contact_phone"
        type="phone"
        id="contact-phone"
        size="30"
        description="COM_CONTACT_PHONE_DESC"
        label="COM_CONTACT_PHONE_LABEL"
        filter="integer"
        required="false"
    />

4)  templates/your template/html/com_contact/contact/default_form.php

 <?php echo $this->form->getLabel('contact_phone'); ?>
 <?php echo $this->form->getInput('contact_phone'); ?>

Thanks & Regards,
Mithali


text:
Q: Command to find file names from grep of "string" inside files in Google cloud storage Buckets? I have many files in the GCS bucket and I would like to find the file name which contains my data (for ex: grep "APPLE"). Is there any way to find the file names based on the grep command?
The following command only results in the data with respective rows, but I want to find the file name in which the grep data resides
gsutil cat gs://my-bucket/part-2020-01-09** | grep 'APPLE'

Is there any way to find the respective file names?

A: You just have to use the -h command line option
gsutil cat -h gs://my-bucket/part-2020-01-09** | grep 'APPLE'

This would print a header with the object name before the contents of each text object that matched the wildcard.
https://cloud.google.com/storage/docs/gsutil/commands/cat

A: For doing this, I would write a script like this:
for i in $(gsutil ls gs://my-bucket/part-2020-01-09**)
do
    gsutil cat ${i} | grep 'APPLE' > /dev/null
    if [ "${?}" == "0" ]
    then
        echo ${i}
    fi
done

But it's not as efficient as a cat because it performs an API call for each file. I don't know the number of files that you have and if it's an acceptable solution.


text:
Q: How convert text from hex to string to utf8 I have set of content storing in database with hex encoded. Now I want to convert it back to readable message Following is my content
Hex code

0052004D0030002E003000300020804A592900204EE37801FF1A003100320033003400350036 30025C3D60C54EAB53D700200043006800690074006300680061007400205E26676576845FEB 4E505427FF01

After convert should be display like
example:

RM0.00 聊天 代码:123456。尽情享受 Chitchat 带来的快乐吧!

I'm trying to use query like below convert the hex back to utf8 string
SELECT CONVERT(UNHEX(content) USING UTF8) FROM mymsg

I also try to set connection to charset utf8, but it still not work for me.

A: I have used this function from http://www.mrleong.net/post/114389343529/unicode-hexadecimal-to-utf-8-string-conversion
and I have tried this also:
$data = '0052004D0030002E0030003000200053006E00610070006300680061007400204EE37801FF1A00360036003100330037003730025C3D60C54EAB53D700200053006E00610070006300680061007400205E26676576845FEB4E505427FF01';
echo iconv('UTF-16BE', 'UTF-8', hex2bin($data));

and used this
function hexToString($hex) {
return pack('H*', $hex);
}

echo mb_convert_encoding(hexToString($data), 'UTF-8', 'Unicode');

Their output is the same.
RM0.00 Snapchat 代码:661377。尽情享受 Snapchat 带来的快乐吧!

Read this article also FROM PHP the wright way :
http://www.phptherightway.com/#php_and_utf8
It explains how to use UTF-8 at the php, database and browser level.


text:
Q: per pixel image object detection in fabric js I have been trying to get the per pixel drag and drop feature working using images with fabric.js like in example on their website: http://fabricjs.com/per-pixel-drag-drop/. I would like the object to be detected when a non transparent part is moused over but if I set perpixeltargetfind to true nothing is detected. I have tried for a while now and even copying the example verbatim while using my own images has not worked. Would really appreciate some help figuring out what I am doing wrong if anyone has experience using this. Thanks.
Here is a link to a js fiddle I have been using: http://jsfiddle.net/ahalbleib/bdofdbqg/
and the code:
var canvas =this.__canvas = new fabric.Canvas('c1',{hoverCursor: 'pointer',
    selection: false});
var urls=['https://dl.dropboxusercontent.com/s/ix6mvv49wnx226a/Central-Richmon_clipped_rev_1.png?dl=0' ,
        'https://dl.dropboxusercontent.com/s/jjp2l0kgdw8iitb/Laurel-Heights.png?dl=0',
        'https://dl.dropboxusercontent.com/s/wdk02w40z1466g5/LoneMountain.png?dl=0',
        'https://dl.dropboxusercontent.com/s/t6tnptndu2k22xr/OuterRichmond.png?dl=0',
        'https://dl.dropboxusercontent.com/s/tv4rhwjc0nw35iz/Presidio-Heights.png?dl=0' ,
        'https://dl.dropboxusercontent.com/s/ttbf390w2vdx4id/Inner-richmond.png?dl=0'];
for (var i=0; i<urls.length; i++){
    fabric.Image.fromURL( urls[i], function(img){

        img.perPixelTargetFind = true;
         img.targetFindTolerance = 4;
          img.hasControls = img.hasBorders = false;
          canvas.add(img);

    });
}

canvas.findTarget = (function (originalFn) {
    return function () {
        var target = originalFn.apply(this, arguments);
        if (target) {
            if (this._hoveredTarget !== target) {
                canvas.fire('object:over', { target: target });
                if (this._hoveredTarget) {
                    canvas.fire('object:out', { target: this._hoveredTarget });
                }
                this._hoveredTarget = target;
            }
        }
        else if (this._hoveredTarget) {
            canvas.fire('object:out', { target: this._hoveredTarget });
            this._hoveredTarget = null;
        }
        return target;
    };
})(canvas.findTarget);

};
init();

A: That is because you don't take images from your own server and you'll get a Security error about tainted canvas. You need to set crossOrigin: 'Anonymous' to images. I made you a jsFiddle


text:
Q: Validate a form with using Jquery - Problems Sorry for my bad English.
Okay, let's go: when I try to validate my form using jQuery, it works just the else option.
I'm considering a spacing in between names, for identify the name input, for as fullname. But in doing so, nothing appears in my console.
Someone help me please.
$('form#form1').submit(function() {
    var fname = $('input[name=fullname]').val()
    var pho = $('input[name=phone]').val()
    var mai = $('input[name=email]').val()
    var amount = fname.split(' ').lenght
    var splitStr = fname.split(' ')

    if(amount >= 2) {
        console.log('It worked!')

        for(var i = 0; i < amount; i++ ) {
            console.log(splitStr[1])
        }
    } else {
        console.log("Wrong!")
        return false;
    }

    return  false;
}

A: It supposes to be fname.split(' ').length.
Writing fname.split(' ').lenght will result in amount == undefined and thus (undefined >= 2) will always be false.


text:
Q: Exception in thread "main" org.openqa.selenium.UnhandledAlertException: unexpected alert open SELENIUM and JAVA I am clicking on a popup to "accept it" and my Selenium automation is crashing at that point.
It is throwing this:
Exception in thread "main" org.openqa.selenium.UnhandledAlertException: unexpected alert open: {Alert text : Cannot perform that operation

These are my lines of code redarging to the action of "clicking the popup":
Thread.sleep(500);
((JavascriptExecutor) driver).executeScript("window.confirm = function(msg) { return true; }");
Thread.sleep(500);
driver.switchTo().alert().accept();

How should i make it work?


text:
Q: JS que bloquea abrir un enlace Me gustaría saber por qué se prioriza la ejecución de un js al clickar en un botón que a su vez tiene un enlace  definido.
Es decir, en el menú de navegación, cuando se clicka en un elemento, se despliega todas las opciones agrupadas en él (esta acción la ejecuta el js). Sin embargo, este mismo elemento también debería abrir una nueva ventana ya que tiene implementado un enlace  ¿Por qué ocurre esto y no se abre este enlace?
El ejemplo concreto es con el menú de navegación en versión mobile.
La página de categoría (imaginemos zapatos), al clickarse de despliegan todas las opciones (zapatos blancos y zapatos negros). Este elemento contiene un enlace  que debería abrirse cuando se clicka en el elemento, sin embargo, la unico que ocurre es que se despliegan todas las subcategorias.
Os dejo el código:

 Zapatos

Zapatos blancos

Zapatos negros

A: Para que vayas directo al link tienes que darle click en el span según estoy viendo, es decir, a la palabra concreta Zapatos blancos/negros.
Prueba a poner el a href al li completo, te fastidiará el CSS muy probablemente, pero así harás que el contenedor completo sea el link, que es lo usual.
A parte, como consejo, si vas a hacer eso, ya que es un problema de funcionalidad, le haría un hoover para que desplegase el contenido por CSS y no por click.


text:
Q: Allow chat rooms to define their own rules within limits Chat rooms can have very different policies and cultures, which leads to issues due to the global nature of the flagging system. One example that regularly causes confusion and drama is the question whether profanity is allowed in chat or not. Many chat rooms have a very informal atmosphere, and a bit of profanity (or even much more) doesn't tend to be a problem. But that isn't the case for all chat rooms.
Users that just entered a room or users that see a flag in a room they're not familiar with have no easy way to find the rules of a particular chat room. What I propose is a moderator-editable field for each chat that contains the rules the chat room community has agreed on. I'm thinking of a very short list, something like no more than 3-4 bullet points, not an epic essay. Just the most important stuff that isn't already in the SE code of conduct, e.g. "we curse like drunken sailors in here".
This short list of rules would be linked from the chat sidebar, so that new users could find it there. It would also be shown to flaggers along with the actual flag, so that they can quickly see the particular rules that apply in the room.
This is of course no license to do whatever you want in your chat room, the SE code of conduct and the terms of service still apply. So you can't make a room where insulting other users is acceptable, or a room for posting porn or something like that.


text:
Q: Display resolution and scaling I have a 27" monitor with 3840x2160 resolution.
I use 150 % scaling, does my monitor fit the same amount of information as a 2560x1440 monitor?
I consider getting ultrawide so I can keep two windows side-by-side with a decent width.
Either 34-35" 3440x1440 or 38" 3840x1600.

*

*Is it common to use 100 % scaling on those?

*Will they fit more information in width and height (or the same in height as 1440) than my current monitor?

A:
I use 150 % scaling, does my monitor show 2560x1440 pixels?

No, it still uses all 3840x2160 pixels, it can't divide pixels according to your settings. It just scales up everything.

Is it common to use 100 % scaling on those?

It's a very subjective question, depends on a lot of factor (content, watching distance...). The relative resolution (pixels per square inch / DPI) of your current monitor is much better compared to the new ones, it's likely you'll be able to notice that difference at whatever resolution you use.

Will they fit more in width and height (or the same in height for the 1440p) as my current monitor?

I'm afraid I don't understand your question here. Fit to what? 1440p vertically? If you choose a monitor with 1440 pixels vertically, that's exactly 1440p


text:
Q: Batch download PDF using Python I'm trying to use Python to batch download PDF's. The process of manually downloading the files are:

*

*Open https://www.ffiec.gov/nicpubweb/nicweb/HCSGreaterThan10B.aspx

*Click on any bank on the list. Let's say I pick the first one, JP Morgan.

*Click Create Report for the 4th report from the top (i.e.,
Banking Organization Systemic Risk Report (FR Y-15))

*Click Your request for a financial report is ready

*Download the PDF that opens up with the following url https://www.ffiec.gov/nicpubweb/NICDataCache/FRY15/FRY15_1039502_20160630.PDF

*Repeat this process for every bank on the list

To download the PDF for JP Morgan, my code is as follows
import urllib2

url = 'https://www.ffiec.gov/nicpubweb/NICDataCache/FRY15/FRY15_1039502_20160630.PDF'
res = urllib2.urlopen(url)
with open('jpm.pdf', 'wb') as handle:
    handle.write(res.read())

The code works on my machine but not on someone else's. I suspect this has to do with the NICDataCache part of the url. I've been to this url so the code knows where to grab the PDF; for someone who hasn't been to the site, if they punch in the above url, they get

The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

I can try to have Python simulate the button-clicking above and then download the PDF that opens up but was wondering if there's an easier way to do this -- a way that doesn't require me to visit every single url I want to download from. Thanks.

A: On the list of banks, notice the integer in parentheses.
Assumption: that integer uniquely identifies that bank.
This is the url that creates the cached resource for you to access:
https://www.ffiec.gov/nicpubweb/nicweb/FinancialReport.aspx?parID_RSSD={bank_id}&parDT=20160630&parRptType=FRY15
Notice the {bank_id} in the URL. I put that there. If you substitute any of the given integers wrapped in parens from the list of banks, it will generate the cached resource.
Then, if you visit this URL: https://www.ffiec.gov/nicpubweb/NICDataCache/FRY15/FRY15_{bank_id}_20160630.PDF
It will respond with the PDF for that bank.
Essentially, you need to go through the list of banks from the first page, generating the cached resource for each bank that you want (by using the first URL as a template, injecting the bank number), then you pull PDFs from the second URL template.


text:
Q: CSS Style Not Populating Correctly I have a flask app I'm building that I'm trying to make look better but the colors aren't populating as expected. Any idea why the colors don't come through correctly. (I've viewed it in IE and Chrome and it's the same).

The folder structure is (there are other HTML files, but they don't matter for recreating the issue):
main/site_tables.py
main/templates/view.html
main/static/style.css

The python code (site_tables.py) is:
#Import various necessary packages
from flask import render_template, Flask, request
import pandas
from pandas.tseries.holiday import USFederalHolidayCalendar
import datetime
import urllib2
import os.path

#Start App from Flask
app = Flask(__name__)

#Set IP Address and Port for outputting web address
out_IP_address = "0.0.0.0"
out_port = 5000

#Set location for original files being read in and edit file locations
#Kept seperate for audit reasons
origLoc = "C:/Orig"
editLoc = "C:/Edit"

#Set name of files prefix
fileName = "Rand_Calls"

#Define holidays for long period of time
cal = USFederalHolidayCalendar()
holidays = cal.holidays(start='2017-01-01', end='2030-12-31').to_pydatetime()

#Set first empty link - tables
@app.route("/tables/")
#Set dynamically populated links tables/date where date is formatted YYYYMMDD
@app.route("/tables/<date>",methods=['GET', 'POST'])
def j_show_html(date):
    #date provided by webaddress for example: date = "20170214"
    #Format date to datetime
    date2 = datetime.datetime.strptime(date,"%Y%m%d")
    if request.method == "GET":
        #If date hasn't occured; display why missing
        if date2 > datetime.datetime.today()  - datetime.timedelta(days=2):
            return render_template('future.html',
            labels = urllib2.unquote(date.encode('ascii','ignore')))
        #If date was a holiday; display why missing
        elif date2 in holidays:
            return render_template('holiday.html',
            labels = urllib2.unquote(date.encode('ascii','ignore')))
        #If date was a weekend; display why missing
        elif date2.weekday() in (5,6):
            return render_template('weekend.html',
            labels = urllib2.unquote(date.encode('ascii','ignore')))
        #Load report; if not edited before then from original location
        else:
            if os.path.isfile(editLoc+"/"+fileName+"_"+date+"_"+date+".xlsx"):
                report = pandas.read_excel(editLoc+"/"+fileName+"_"+date+"_"+date+".xlsx")
            else:
                report = pandas.read_excel(origLoc+"/"+fileName+"_"+date+"_"+date+".xlsx")
            return render_template('view.html',
            tables=[report.to_html(index=False)],
#            titles = ['na'],
            labels = urllib2.unquote(date.encode('ascii','ignore')))

#Call the app
if __name__ == "__main__":
    app.run(host=out_IP_address,port=out_port,debug=True)

The HTML file (view.html) is:

<!doctype html>
<title>{{labels}}</title>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">

QA_Report_{{labels}}

  {% for table in tables %}
    {{ table|safe }}
  {% endfor %}

The CSS file is (style.css) is:
body            { font-family: sans-serif;}
a, h1, h2       { color: #d03027; } /*Color = Specific Red */
h1, h2          { margin: 0; }
h1              { border-bottom: 2px solid #ceccd0; } /*Color - Light Grey*/
h2              { font-size: 1.2em; }

table.dataframe, .dataframe th, .dataframe td
{
  border: none;
  border-bottom: 1px solid #ceccd0; /*Color = Light Grey*/
  border-collapse: collapse;
  text-align:left;
  padding: 10px;
  margin-bottom: 40px;
  font-size: 0.9em;
}

tr:nth-child(odd)      { background-color:#ffffff; } /*Color = White            */
tr:nth-child(even)  { background-color:#004977; color:#ffffff; } /*Color = Specific Blue */
tr:hover            { background-color:#d03027; } /*Color = Specific Red  */

A: Figured out the issue.
The webpage was being cached. I cleared the browser history and the changes came through. (Reloading the page with Ctrl+Shift+R will allow new changes to come through as well).
Posting this as an answer in case it helps anyone running into the same issue.


text:
Q: JFreeChart is not visible in modal JDialog? I tried to display a JFreeChart inside a JDialog and it is displaying correctly but when i tried to display it in a modal JDialog it is not dispaying.Following program is not displaying JFreeChart graph until i comment line# 31. What is the reason?
import java.awt.BorderLayout;
import java.awt.Dialog;
import java.awt.Dimension;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GraphExample extends JDialog{
    private final JPanel contentPanel = new JPanel(new BorderLayout());
    /**
     * Launch the application.
     */
public static void main(String[] args) {
        try {
            GraphExample graph=new GraphExample(new JFrame(),"Testing");
            graph.createGraphPanel();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
public GraphExample(JFrame parent,String title) {
        super(parent,title);
        setPreferredSize(new Dimension(500, 500));
        this.setModal(true);
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(contentPanel, BorderLayout.CENTER);
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        pack();
        setVisible(true);
    }
public void createGraphPanel(){
        XYSeriesCollection dataset = new XYSeriesCollection();
        XYSeries series1= new XYSeries("First");
        series1.add(1.0, 1.0);
        series1.add(2.0, 4.0);
        series1.add(3.0, 3.0);
        series1.add(4.0, 5.0);
        series1.add(5.0, 5.0);
        series1.add(6.0, 7.0);
        series1.add(7.0, 7.0);
        series1.add(8.0, 8.0);
        dataset.addSeries(series1);
        final JFreeChart chart = createChart(dataset);//,xLabel,yLabel,title,seriesesVector,check);
        final ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new Dimension(400,400));//width height
        contentPanel.add(chartPanel,BorderLayout.CENTER);
        contentPanel.revalidate();
    }
 private JFreeChart createChart(final XYDataset dataset){//, String xLabel, String yLabel, String title,Vector seriesesVector,String check) {
     final JFreeChart result = ChartFactory.createXYLineChart(//createXYAreaChart(//also comment line#218 219 220 also uncomment line#250
             null,
             "X",
             "Y",
             dataset,
             PlotOrientation.VERTICAL,
             true,
             true,
             false
             );
     result.setTitle("Example");
     final XYPlot plot = result.getXYPlot();//domain is x and range is y
     plot.setDomainGridlinesVisible(false);
     plot.setRangeGridlinesVisible(false);
     return result;
 }
    }

How to show a JFreeChart in a Modal JDialog?

A: Don't call setVisible(true) on the JDialog until everything is set up. In fact, get it out of the constructor, and call it yourself in the code that declares and constructs the JDialog and only after all is done. Understand that code flow will be blocked when it is called, and so it must be called last.
So change this:
public GraphExample(JFrame parent,String title) {
    super(parent,title);
    setPreferredSize(new Dimension(500, 500));
    this.setModal(true);
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(contentPanel, BorderLayout.CENTER);
    setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    pack();
    setVisible(true);
}

to this:
public GraphExample(JFrame parent,String title) {
    super(parent,title);
    setPreferredSize(new Dimension(500, 500));
    this.setModal(true);
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(contentPanel, BorderLayout.CENTER);
    setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    pack();
    // setVisible(true); // **** **** **** ****
}

and this:
public static void main(String[] args) {
    try {
        GraphExample graph=new GraphExample(new JFrame(),"Testing");
        graph.createGraphPanel();
        graph.setVisible(true);  // ****** add *****
    } catch (Exception e) {
        e.printStackTrace();
    }
}


text:
Q: Add two selected value together, then display results JavaScript Been trying to get the values from ID tags totalDiv-totalDiv1 that each display the results from the selected values, then add them together to display the values combined in real time in ID tag totalall but I keep getting NaN.

£10 Each

<select name="iteam1" onChange="calc1()">
    <option value="10">1</option>
    <option value="20">2</option>
    <option value="30">3</option>
    <option value="40">4</option>
    <option value="50">5</option>
</select>

£10

£10 Each

<select name="iteam" onChange="calc()">
    <option value="10">1</option>
    <option value="20">2</option>
    <option value="30">3</option>
    <option value="40">4</option>
    <option value="50">5</option>
</select>

£10

Total

£0

A: Point to take care.
1. Don't mix value and symbol
2. You are adding symbol in Calc function in div and later tried to combine them both so it obiviously not a number;
http://jsfiddle.net/ga16gt74/

£10 Each

<select name="iteam1" onChange="calc1()">
    <option value="10">1</option>
    <option value="20">2</option>
    <option value="30">3</option>
    <option value="40">4</option>
    <option value="50">5</option>
</select>

£
  0

£10 Each

<select name="iteam" onChange="calc()">
    <option value="10">1</option>
    <option value="20">2</option>
    <option value="30">3</option>
    <option value="40">4</option>
    <option value="50">5</option>
</select>

£
  0

Total

£0

A: Do this:
var fruitOrEgg = parseInt(documentgetElementsByName("iteam")[0].value);

In your calculator function.


text:
Q: Editing a Post, 99% CPU? I have a blog with ~15k posts, and a DB size of 14.4M.
The website works blazingly fast from the front end, but post-edit and post-listing screens hang - either loading partially or not at all.
Even worse, the entire server gets bogged down after trying...
Examining the process manager showed that /public_html/wp-admin/edit.php or /public_html/wp-admin/post.php (post-listing and post-edit, respectively - yeah I know they seem backwards) was eating 99% CPU.
I experienced this problem on a 3rd tier Bluehost VPS, so I upgraded to a Heart Internet Hybrid 250 (12core, 28gb ram) to try and mitigate the problem - no dice :/
Any help getting this resolved is greatly appreciated - telling clients they have to edit pages through phpMyAdmin is not an option :)
Running MySQL processes:
Id      User    Host        db  Command     Time    State   Info

338     leech.. localhost   leech.. Sleep   1959            NULL
426     tmhp_.. localhost   tmhp_.. Sleep   581             NULL
433     root    localhost   NULL    Sleep   132             NULL
441     root    localhost   NULL    Query   0       NULL    SHOW PROCESSLIST

Process Example:
Pid     Owner   Priority    CPU %   Memory %    Command
29447   tmhp        0       99.8    0.6         /usr/bin/php /home/tmhp/public_html/wp-admin/edit.php

Edit: This might be pertinent:  When on the add-new or post-edit pages the title loads and is editable, but the content editor loads halfway, additionally, the text appears but is white and only visible when highlighted...
Also, using the 2012 theme with no plugins...
Edit2: Given enough time (~3-5 minutes), the post-edit page will load fully and the process will terminate.  This doesn't seem to happen with the post-listing page, however.
Additionally, I've narrowed down the problem on the post-edit page to the page-attributes meta-box.
As a short term remedy I've created a plugin which does the following:
//Remove some features of pages so editing is faster
if (is_admin()) :
function my_remove_meta_boxes() {
    remove_meta_box('pageparentdiv', 'page', 'side');
}
add_action( 'admin_menu', 'my_remove_meta_boxes' );
endif;

function remove_page_attribute_support() {
    remove_post_type_support('page','page-attributes');
}

add_action( 'init', 'remove_page_attribute_support' );

// Remove the Posts and Pages menus from the admin screen
function custom_admincss() {
   echo '<style type="text/css">
           #menu-pages{display:none !important}
           #menu-posts{display:none !important}
         </style>';
}

add_action('admin_head', 'custom_admincss');

A: You may be dealing with the dreaded mod_security when your posting or updating . see if it's enabled on the server first, if your using antimalware software it may be trying to scan on save . ok that's the easy try . the next is to turn off your plugins . wsiwig editors., seo plugins . caching plugins . they all can contribute to post updates becoming really slow.. this is a one-at-a-time kinda thing so it gets tedious.

A: I pinned it down to the hierarchy arg for the pages post-type:

hierarchical
(boolean) (optional) Whether the post type is hierarchical (e.g. page).
Allows Parent to be specified. The 'supports' parameter should contain 'page-attributes' to show the parent select box on the editor page.
Default: false
Note: this parameter was planned for Pages. Be careful, when choosing it for your custom post type - if you are planning to have many entries (say - over 100), you will run into memory issue. With this parameter set to true WordPress will fetch all entries of that particular post type, together with all meta data, on each administration page load for your post type.

Now, any idea how one can go about removing hierarchical support for pages w/o overwriting the core?


text:
Q: php gzfile not working This is working fine: readgzfile($filename);
This is not working: gzfile($filename);
gzfile function outputs this error:
Warning: gzfile(http://www.example.com/abc.xml.gz): failed to open stream: HTTP request failed! HTTP/1.1 503 Service Unavailable.

I checked my php.ini and phpinfo and found nothing is disabled!
I have verified with if (function_exists('gzfile')) to make sure it's available. 503 or any other error isn't taking place for readgzfile function!
This is a Windows 2008 server and PHP is 5.3.23.
Thanks for your kind help.


text:
Q: Icon not showing up in PopupMenuButton in Flutter I'm trying to create a PopupMenu in Flutter that comes down below the icon. However, the icon is not showing up. I am using the code suggested in this issue: Is it possible to use a DropDownButton within an IconButton in Flutter? but trying to adapt it to my widget tree.
I have attached a sample of the code I tried.
@override
  Widget build(BuildContext context) {
    return new Container(
      height: MediaQuery.of(context).size.height,
      child: SingleChildScrollView(
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            new Container(
              height: 220.0,
              width: MediaQuery.of(context).size.width,
              child: new GestureDetector(
                onTap: () {
                  FocusScope.of(context).requestFocus(new FocusNode());
                },
                child: Column(
                  children: <Widget>[
                    SizedBox(height: 40.0),
                    Row(
                      children: <Widget>[
                        Expanded(
                          child: Stack(
                            children: [
                              Center(
                                child: Text(
                                  'Profile',
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                    fontFamily: 'Lato',
                                    color: Colors.white,
                                    fontSize: 50.0,
                                    fontWeight: FontWeight.w700,
                                  ),
                                ),
                              ),
                              Positioned(
                                right: 8,
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    Padding(padding: EdgeInsets.only(top: 400)),
                                    PopupMenuButton<String>(
                                      icon: Icon(
                                        Icons.settings,
                                        color: Colors.white,
                                        size: 30.0,
                                      ),
                                      onSelected: choiceAction,
                                      itemBuilder: (BuildContext context) {
                                        return Constants.choices.map((String choice) {
                                          return PopupMenuItem<String>(
                                            value: choice,
                                            child: Text(choice),
                                          );
                                        }).toList();
                                      },
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),

A: I had a similar problem in Flutter: constructing a PopupMenuButton filled with PopupMenuItem that I intended to prepend with a basic Icon.
However, the icon was not displayed for some unknown reason. I solved that by using a ListTile builder, inspired by the source code of CheckedPopupMenuItem.
enum MyMenuEntries { previous, next }

class MyMenu extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return PopupMenuButton<MyMenuEntries>(
      onSelected: (MyMenuEntries entry) {},
      itemBuilder: (BuildContext context) => [
        PopupMenuItem<MyMenuEntries>(
          value: MyMenuEntries.previous,
          child: ListTile(leading: Icon(Icons.arrow_back), title: Text("Previous")),
        ),
        PopupMenuItem<MyMenuEntries>(
          value: MyMenuEntries.next,
          child: ListTile(leading: Icon(Icons.arrow_forward), title: Text("Next")),
        ),
      ],
    );
  }
}


text:
Q: Commit to Github from mongodb realm UI I have a mongodb realm app that is synced to a github repo, so when I push something to the github repo, it's automatically deployed to mongo. So far so good. However, if someone makes a change to the app directly in the mongodb UI, those changes will not end up in the github repo.
I want the sync to be in both directions, so if a change is made in the mongodb UI a new commit should be created in the github repo.
Is there any way to set this up? Thanks.

Edit: At this point, the mongodb team has added this feature themselves, so it should work out of the box.


text:
Q: How to use decider in Spring batch? I'm new to Spring batch. I've created a decider which returns a FlowExecutionStatus as "YES" / "NO". Based on the FlowExecutionStatus, I need to call step2() or step3().
In my below code, step2() is getting called before decider. How to modify the code so that decider will be called and based on the FlowExecutionStatus returned bu the decider, either step2() or step3() should be called. Please help.
@Autowired
private NumberDecider decider;

@Bean
public Job NumberLoaderJob() throws NumberFormatException, IOException {
    return jobBuilderFactory.get("numberLoaderJob").start(step1()).listener(new MyNumberJobListener())
            .next(decider).on("YES").to(step2())
            .from(decider).on("NO").to(step3()).end().build();
}

@Bean
public Step step1() {

    return stepBuilderFactory.get("step1").tasklet(new Tasklet() {

        @Override
        public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
            System.out.println("Exiting step1() execute()");
            return RepeatStatus.FINISHED;
        }
    }).build();
}

/**
 * Step 2
 *
 * @return
 * @throws NumberFormatException
 * @throws IOException
 */
@Bean
public Step step2() throws NumberFormatException, IOException {
    return stepBuilderFactory.get("step2").listener(new MyStepListener())
            .<OrderNumber, OrderNumber>chunk(Integer.valueOf(chunkSize)).faultTolerant()
            .listener(new MyChunkListener()).reader(new MyItemReader())
            .listener(new MyItemReaderListener()).writer(customItemWriter())
            .listener(new MyWriteListener()).build();
}

A: You would need to to set the exit status in step1 so that the decider picks it up and make the decision:
@Bean
public Step step1() {

   return stepBuilderFactory.get("step1").tasklet(new Tasklet() {

       @Override
       public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
          System.out.println("Exiting step1() execute()");
          chunkContext.getStepContext().getStepExecution().setExitStatus(new ExitStatus("YES")); // or NO
          return RepeatStatus.FINISHED;
       }

    }).build();
}

EDIT: I thought that the decider should make the decision based on the exit status of step1, hence the previous sample. So adding a sample to show how to use a decider (after clarification):
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.job.flow.FlowExecutionStatus;
import org.springframework.batch.core.job.flow.JobExecutionDecider;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableBatchProcessing
public class MyJob {

    @Autowired
    private JobBuilderFactory jobs;

    @Autowired
    private StepBuilderFactory steps;

    @Bean
    public Step step1() {
        return steps.get("step1")
                .tasklet((contribution, chunkContext) -> {
                    System.out.println("hello");
                    return RepeatStatus.FINISHED;
                })
                .build();
    }

    @Bean
    public JobExecutionDecider decider() {
        return (jobExecution, stepExecution) -> new FlowExecutionStatus("YES"); // or NO
    }

    @Bean
    public Step step2() {
        return steps.get("step2")
                .tasklet((contribution, chunkContext) -> {
                    System.out.println("world");
                    return RepeatStatus.FINISHED;
                })
                .build();
    }

    @Bean
    public Step step3() {
        return steps.get("step3")
                .tasklet((contribution, chunkContext) -> {
                    System.out.println("!!");
                    return RepeatStatus.FINISHED;
                })
                .build();
    }

    @Bean
    public Job job() {
        return jobs.get("job")
                .start(step1())
                .next(decider())
                    .on("YES").to(step2())
                    .from(decider()).on("NO").to(step3())
                    .end()
                .build();
    }

    public static void main(String[] args) throws Exception {
        ApplicationContext context = new AnnotationConfigApplicationContext(MyJob.class);
        JobLauncher jobLauncher = context.getBean(JobLauncher.class);
        Job job = context.getBean(Job.class);
        jobLauncher.run(job, new JobParameters());
    }

}

In this example, step1 is executed first, then the decider. If the decider returns YES, step2 is executed and if returns NO, step3 is executed.
Hope this helps.


text:
Q: Determine field type by it's name in Jackson I have an interface which takes events in it's API.
A base event looks like this:
class Event<T extends Details> {
    T details;
}

An example implementation looks like the following:
class UpdateEvent extends Event<UpdateDetails> {

    @JsonProperty("updateDetails")
    UpdateDetails details;

}

In the JSON, I would like to serialise/deserialise something like:
{
    "updateDetails": {...}
}

So, I would need to determine the type of the details field by it's name in Json, and instantiate the according child of the Event class when deserialising.
I have achieved so with creating a custom deserialiser, which checks for the exact name of the details object, but I don't like this solution (serialisation works out of the box because of the JsonProperty annotation). Does Jackson have a solution for this? I couldn't achieve it with the standard JsonTypeInfo annotations (it would always nest the details object one level lower in the JSON, or it would add a new attribute, which I unfortunately cannot do).


text:
Q: How to get song information from iTunes? I'm developing an app for Mac OS X to display lyric of the song iTunes is playing. I've done some searches and found only the way using AppleScript to realize it. Is there an API for Objective-C that I can use to fetch information about the song from iTunes? I want to know how Bowtie, CoverSutra and Last.fm did it.

A: In 10.9 you can use iTunes Library Framework (/Library/Frameworks/iTunesLibrary.framework) for iTunes  11.
#import <iTunesLibrary/ITLibrary.h>

NSError *error = nil;
ITLibrary *library = [ITLibrary libraryWithAPIVersion:@"1.0" error:&error];
if (library)
{
        NSArray *playlists = library.allPlaylists; //  <- NSArray of ITLibPlaylist
        NSArray *tracks = library.allMediaItems; //  <- NSArray of ITLibMediaItem
}

A: See the answer to my question:

Use the Scripting Bridge to ask iTunes. iTunes is even the example that the docs use.

It can be a bit tricky in the beginning, but as always with Cocoa: it's easy after you've done it once.

A: There's no Apple-supplied API that I know of, other than the AppleScript interface.
But it just so happens that iTunes posts distributed notifications whenever the track changes, so you can listen for those and get the currently playing song info that way.
See Objective-C Mac OS X Distributed notifications iTunes
I've never seen any official documentation of these notifications so I don't know if you can count on them working in the future, but they've worked for like the past decade.


text:
Q: c++ вычислить значение выражения Во входном потоке задано три вещественных числа a (a > 0), b (b < 0), x (-1 < x < 1). Значения исходных данных подобраны так, что выражение имеет смысл.
например, 2.4 -4.2 0.6
В выходной поток вывести единственное вещественное число с точностью три знака после запятой.
например, 2.425

Написал код, для значений из примера работает верно, но если x поменять на 0.5, то выводит ошибку (-nan).
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
  double a,b,x,p,sum=0;
  cin >> a >> b >> x;
  if ((1.2+8*x)<105)
  {
    for (double m=(8*x+1.2);m<=105.0;m++)
    {
      sum+=(pow((-1),m)*m+a)/(m*(m+1));
    }
  }
  p=(x-b)/(a+b);
  p=pow(p,3);
  p=sin(p)/cos(p);
  p=pow(p,3)*sum;
  p=p+(pow((x+pow(a,2)),1.0/2.0))/(x*pow((1-b),1.0/3.0));
  cout << fixed << setprecision(3) << p;
}

A: У вас получается возведение отрицательного числа в дробную степень
pow((-1),m)

при вашем значении x. У вас именно исходя из этого - наличия -1 в степени m эта переменная не может быть double, а вычисления должны проводиться при условии

Значения исходных данных подобраны так, что выражение имеет смысл

которое вы нарушили.
Впрочем, считать сумму таким образом - не то чтобы совсем некорректно... но ужасно некрасиво.
P.S. Для тангенса есть своя функция - tan().
P.P.S. Ваш ряд я бы считал иначе -


text:
Q: Grouping operators in Spotify advanced search I'm trying to use the Spotify web API to return multiple specific results in one response.
For example, maybe I want Spotify's detailed information for "Thriller", by Michael Jackson, and "Highway Star", by Deep Purple.
Since I don't already have the Spotify uris I need to use the Search method. And there's a page describing Spotify's advanced search syntax here. They support searching against specific fields, like track, artist, and album. They also support the basic boolean operators.
But there's nothing on that page (or anywhere else on the internet, as far as I can tell) describing how the boolean operator precedence works, or how you might go about grouping your search criteria.
I would need something effectively the same as (track:Thriller AND artist:"Michael Jackson") OR (track:"highway star" AND artist:"Deep Purple").
Using similar criteria to pull in just one track at a time works:
http://ws.spotify.com/search/1/track?q=track:"thriller"+AND+artist:"michael+jackson"
I tried to jump right in with the parentheses, even though they're not mentioned in the docs. No luck:
ws.spotify.com/search/1/track?q=(track:"thriller"+AND+artist:"michael+jackson")+OR+(track:"highway+star"+AND+artist:"deep+purple")
Then I thought I'd try playing with precedence. Maybe they don't just process left-to-right - maybe the ORs are all resolved, and then the ANDs:
ws.spotify.com/search/1/track?q=track:"thriller"+OR+track:"highway+star"+AND+artist:"michael+jackson"+OR+artist:"deep+purple"
That seemed promising, and returned 185 results, but it's not quite right. I'm seeing tracks named "Highway Star" from other bands. That seems to rule out "left-to-right", "OR-before-AND" AND "AND-before-OR". Which doesn't make any sense - what else is left?
Can anyone with more Spotify experience shed some light on how a query like this should work?

A: Unfortunately, there's not really much support for this in Spotify's Web API (I've tried myself, with the same outcome as you've had). And from the looks of it, the API's been worked on for a couple of years, so I wouldn't expect much to change.
However, I strongly recommend that you have a look at the Echo Nest API's instead; they support quite powerful queries and have a bunch of awesome stuff in their API.
Furthermore, they've also got support for getting Spotify URI:s for the search results (tracks, artists etc). This means that you could probably stick to the EN API altogether.
Also, The Echo Nest are continuously adding more features to their API, so it's really become the go-to API for music (outperforming Last.fm and similar by far).


text:
Q: Why does the value of a pointer change after passing it to a function that does not modify the pointer? The pointer in main(), ptrTop, is initialized to point to int topDeck = 1. Every time I run the program, the value of the (I think) dereferenced pointer changes to a different number. I believe that the problem lies in the deal() function. If I comment out the call to deal() in main(), the value of my pointer is not modified. I did not write any statements that change the value of the pointer. I wrote comments around the parts of the code that might be relevant to the question.
/*
 * This is a card dealing program.
 * the fucntion deal() keeps changing the value of
 * the int pointer ptrTop declared in main(). sometimes,
 * the value is what it is sopposed to be (1), but when i run
 * the program again, it is a different value. I used
 * gcc (GCC) 4.9.2 20150212 (Red Hat 4.9.2-6)
 */

int main(void) {

    int topDeck = 1;
    int *ptrTop = &topDeck;

    //this ptrTop is sopposed to keep track of the last
    //card dealt, but it randomly changes every time I run

    unsigned int handSuit[5] = {0};
    unsigned int handFace[5] = {0};

    unsigned int deck[SUITS][FACES] = {0};

    deal(deck, face, suit, ptrTop, handSuit, handFace);

    printf("%i\n", *ptrTop);
    // If print the value while I comment out the deal() in line 55,
    // the value of * ptrTop does not change.
    // this gives me reason to believe that deal() is causing the trouble.

}

void deal(unsigned int wDeck[][FACES], const char *wFace[], const char *wSuit[],
    int *ptrTop, unsigned int handSuit[], unsigned int handFace[])
{
    size_t card;
    size_t row;
    size_t column;
    int top = *ptrTop;
    // i have to use top because if i don't the dea() function will print
    // more than 5 cards (it is sopposed to print a 5 card hand.

    // these for loops loop through the double scripted array wDeck
    for (card = top; card <= top + 4; ++card) {

        for (row = 0; row < SUITS; ++row) {

            for(column = 0; column < FACES; ++column) {

                if(wDeck[row][column] == card) {
                    printf( "%s of %s \n", wFace[ column ], wSuit[ row ]);
                    handFace[card] = column;
                    handSuit[card] = row;
                }
            }
        }
    }
    // *ptrTop = card;
    // the value of *ptrTop consistently becomes six if line above is uncommented.
    // I would think that the value should still be 1
    // when the program is run in this state.
}

A: This obscure loop is the cause:
 for (card = top; card <= top + 4; ++card)

Card gets an index from 1 to 5, while you have variables
unsigned int handSuit[5] = {0};
unsigned int handFace[5] = {0};

That only supports index 0 to 4. You access these arrays out-of-bounds, and as a side effect of that undefined behavior, you overwrite other variables.

A: I'm not really sure what other value (than six) of *ptrTop you expect; let's take a look at deal:
for (card = top; card <= top + 4; ++card)
and remember, this is the value of top, as initialized in main:
int topDeck = 1;
int *ptrTop = &topDeck;

So, in deal, you loop five times, incrementing card, then in the last iteration the for loop will increment card for the fifth time, see that it is 6, and since 6 <= 5 is false, it will quit, then if you do *ptrTop = card;, *ptrTop is indeed consistently equal to six.


text:
Q: Reading nested configuration section element of same type from web.config file Ok this is a tricky one or I just don't know how to do it.
I have to problem creating and reading custom config sections like:

  <c/>
  <c/>

The issue I am having is reading the below configuration with ConfigurationManager.GetSection("a"):

  <c>
   <c/>
  <c>

Is there a way to get this working?
thank you.

A: My advice? Ditch configuration manager and load the config into an XDocument. Say you have a config file shown below:
<Settings>
    <ApplicationSettings>
        <AppSetting1 Value="Test1" />
        <AppSetting2 Value="Test2" />
    </ApplicationSettings>
    <DeviceSettings>
        <DeviceSetting1 Value="Test3" />
        <DeviceSetting2 Value="Test4" />
    </DeviceSettings>
</Settings>

To get a value from it you can load the config into an XDocument:
XDocument xdoc = XDocument.Load(@"Path\to\file.xml");

Then:
String test1 = xdoc.Element("Settings").Element("ApplicationSettings").Element("Appsetting1").Attribute("Name").Value;


text:
Q: why is TCP Connection state not changing from CLOSE_WAIT to CLOSED? I have a client server application running in:
Server: Windows server 2008 R2 [Standard]
Client: Windows XP SP3
Workflow:
Server listens for client connections at port YY.
Client connects to server at port YY.
Data gets transferred from Server to Client.
Server closes the socket ( with reuse option, TF_REUSE_SOCKET)
Client closes the socket.
Problem:
In normal scenarios when the data transfer is finished the server closes the socket and everything works fine.
But in scenarios when Client closes the socket first ( for cancelling the data transfer) then the socket state @ server changes to CLOSED_WAIT ( as server recieves FIN from client). At client side the socket state in FIN_WAIT_2.
This socket state remains forever. The sockets are not released at all.
The same application works fine if the server is also WindowsXP XP3.
IS there any settings in Windows2008 R2 which makes my application to not to release the socket ( or change the socket state from CLOSED_WAIT) ?
Note:
I configured [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Tcpip\Parameters]
TcpFinWait2Delay = 60
But of no use.

A: The client is not receiveing an ACK from the server for the FIN it sent to the server. I would recommend putting a packet capture on the client and the server to see what's happening.

A: The server code is broken. It is not calling CloseSocket (or the equivalent in the API you are using) and so its handle to the connection never closes.


text:
Q: How can I call a Web Service from Xamarin Studio? I have created a  web service which works fine and i have also added the webservice to my android app project in xamarin studio but i dont know how i can call my web service to work on my android app. I want to insert data into the remote database from my android app.
here is my webservice code
[WebMethod]
public string insertData(string title, string coment)
{
    string Message;

    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand("INSERT INTO Header (title, coment)
                    VALUES (@title, @coment)", con);

    cmd.Parameters.Add("@title", SqlDbType.NVarChar, 50).Value = title;
    cmd.Parameters.Add("@coment", SqlDbType.NVarChar, 50).Value = coment;

    con.Open();
    int result = cmd.ExecuteNonQuery();
    if (result == 1)
    {
        Message = " Details inserted successfully";
    }
    else
    {
        Message =" Details not inserted successfully";
    }
    con.Close();
    return Message;

}
also here is my android layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/backgd"
    android:minWidth="25px"
    android:minHeight="25px">
    <TextView
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView1" />
    <TextView
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView1" />
    <TextView
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView1" />
    <TextView
        android:text="Title"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView1" />
    <EditText
        android:inputType="textPersonName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText1"
        android:background="#ffffffff" />

    <TextView
        android:text="Comment"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView1" />
    <EditText
        android:inputType="textPersonName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText1"
        android:background="#ffffffff" />
    <Button
        android:text="Insert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button1" />
</LinearLayout>

I've added the webservice to my project which gives me a reference.cs code but i dont understand how to use it. can you help with how i can make the text filled data to be inserted into my remote database through my webservce. thanks


text:
Q: Pandas TypeError: unhashable type: 'list' when importing from csv I'm trying to clean some data from a csv file. Here's an example of the data I'm importing. What I'm trying to do is split the cell by the first comma. The data before the comma goes to one column, the data after goes to another.

I've set up a function to handle the data:
def soil_description(text_block):
    print(text_block, type(text_block))
    text_list = text_block.split(',')
    print(1)
    major = text_list[0]
    print(2)
    if len(major) == len(text_block):
        print(3)
        major = ''
        minor = text_block
    else:
        print(4)
        minor = text_block[(len(major)+2):]
    print(major, type(major))
    print(minor, type(minor))
    return major, minor

The csv file is loaded into a dataframe fgd_og_df and I'm trying to put it in two columns of the soil_gINT_df dataframe using the following:
soil_gINT_df[['USCS Major Constituent 1'],['Additional Description']] = fgd_og_df.apply(lambda row:pd.Series(soil_description(row['Description'])),axis=1)

This gives me the following error:
Traceback (most recent call last):
  File "C:/Users/main.py", line 128, in <module>
    soil_gINT_df[['USCS Major Constituent 1'],['Additional Description']] = fgd_og_df.apply(lambda row:pd.Series(soil_description(row['Description'])),axis=1)
  File "C:\Users\venv\lib\site-packages\pandas\core\frame.py", line 3645, in __setitem__
    self._set_item_frame_value(key, value)
  File "C:\Users\venv\lib\site-packages\pandas\core\frame.py", line 3770, in _set_item_frame_value
    if key in self.columns:
  File "C:\Users\venv\lib\site-packages\pandas\core\indexes\base.py", line 5008, in __contains__
    hash(key)
TypeError: unhashable type: 'list'

This is the output immediately before the error:
SHALE. <class 'str'>
1
2
3
<class 'str'>
SHALE. <class 'str'>
So it's getting through the function and giving an error when it tries to take the two strings back into the soil_gINT_df dataframe, but I'm not sure why. There are other text strings that are similar that work, so I'm at a bit of a loss.

A: The mistake was here, see chepner's comment pointing out that the first is a tuple of lists:
soil_gINT_df[['USCS Major Constituent 1'],['Additional Description']]

Should be:
soil_gINT_df[['USCS Major Constituent 1', 'Additional Description']]


text:
Q: JDialog isn't rendering content with no error package gui;

import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;

import listener.addHeaderListener;
import listener.removeHeaderListener;

public class headersGUI extends JDialog {
public JFrame GUI;
public JList headers;
public JTextField name;
public JTextField value;
public JButton addheader;
public JButton removeheader;
public headersGUI(JFrame initgui){
    super(GUI, "Headers");
    GUI=initgui;
    setup();
    layout();
    this.pack();
    this.setVisible(true);
}
public void setup(){
    headers=new JList(GUI.headervalues);
    headers.setLayoutOrientation(JList.VERTICAL);
    name=new JTextField(10);
    value=new JTextField(10);
    addheader=new JButton("Add");
    addheader.addActionListener(new addHeaderListener(this, GUI));
    removeheader=new JButton("Remove");
    removeheader.addActionListener(new removeHeaderListener(this, GUI));
}
public void layout(){
    JPanel bottompanel=new JPanel();
    this.getContentPane().add(headers, BorderLayout.CENTER);
    bottompanel.add(new JLabel("Name: "));
    bottompanel.add(name);
    bottompanel.add(new JLabel("Value: "));
    bottompanel.add(value);
    bottompanel.add(addheader);
    bottompanel.add(removeheader);
    this.getContentPane().add(bottompanel, BorderLayout.SOUTH);
}
}

that is the JDialog code, it just shows a blank JDialog i am using JDK 1.5 on mac OSX 10.5.8

A: The error isn't apparent in the code that you've posted, and this is why you are not getting answers. So now all we can do is guess, and my guess is that in all likelihood the data passed into the JDialog is deficient, possibly your passing in a different JFrame object from the one that is being displayed.  You should put debug statements into the code above and the code that uses the JDialog, such as:
public void setup(){
  headers=new JList(GUI.headervalues);
  system.out.println(/* display some property of the GUI here */ );

And you should create and post an sscce.
By the way, what are JFrame#headervalues? That's not part of the JFrame API.


text:
Q: Vertical centering in several columns in longtable I would like to change the vertical alignment of the second column in this table (the names of the hypotheses) to be centered, just as in the 1st column.
My mininal example:
\documentclass[a4paper,fontsize=12pt,a4paper,DIV=10,BCOR=10mm,twoside,titlepage=false,openany,pagesize]{scrbook}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{blindtext}
\setkomafont{disposition}{\normalfont\bfseries}
\usepackage{graphicx}
\usepackage[font=normalsize,labelfont=sc,singlelinecheck=false,justification=raggedright]{caption}
\usepackage[hyphens]{url}
\usepackage{setspace}
\usepackage{subfigure}
\usepackage{longtable}
\setlength\LTleft{0pt}
\setlength\LTright{0pt}
\usepackage{hyperref}
\hypersetup{
    colorlinks,
    citecolor=black,
    filecolor=black,
    linkcolor=black,
    urlcolor=black
}
\usepackage{array}
\usepackage{multirow}
\usepackage{tabulary}
\usepackage{booktabs}
\usepackage{feyn}
\usepackage[authoryear]{natbib}
\usepackage{chngcntr}
\usepackage{dcolumn}
\usepackage{amsmath}

\begin{document}

\fontsize{10pt}{11pt}\selectfont
\begin{longtable}[c]{l>{\centering\arraybackslash}p{0.2\textwidth}>{\centering\arraybackslash}p{0.4\textwidth}}
\captionsetup{justification=raggedright,width=.82\textwidth}
\caption{Hypotheses}
\label{tab:hypotheses}
\endfirsthead
\multicolumn{3}{c}{{\bfseries \tablename\ \thetable{} -- continued from previous page}}\\
\endhead
\midrule
\multirow{3}{*}{H1} & \textit{`lalalala' hypothesis} & Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. \\
\cmidrule(lr){2-2}\cmidrule(l){3-3}
\multirow{7}{*}{H2} & \textit{`lalalala' hypothesis} & Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec. \\
\cmidrule(lr){2-2}\cmidrule(l){3-3}
\multirow{6}{*}{H2a} & \textit{`lalalalalalalalala' hypothesis} & Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. \\
\cmidrule(lr){2-2}\cmidrule(l){3-3}
\multirow{6}{*}{H2b}& \textit{`lalalalalalalala' hypothesis} & Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. \\
\bottomrule
\multicolumn{3}{l}{\small{\emph{Source: Author's depiction}}}\\
\end{longtable}
\normalsize

\end{document}

A: You are abusing \multirow anyway, hence do it once more ;-).
\documentclass[a4paper,fontsize=12pt,a4paper,DIV=10,BCOR=10mm,twoside,titlepage=false,openany,pagesize]{scrbook}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{blindtext}
\setkomafont{disposition}{\normalfont\bfseries}
\usepackage{graphicx}
\usepackage[font=normalsize,labelfont=sc,singlelinecheck=false,justification=raggedright]{caption}
\usepackage[hyphens]{url}
\usepackage{setspace}
\usepackage{subfigure}
\usepackage{longtable}
\setlength\LTleft{0pt}
\setlength\LTright{0pt}
\usepackage{hyperref}
\hypersetup{
    colorlinks,
    citecolor=black,
    filecolor=black,
    linkcolor=black,
    urlcolor=black
}
\usepackage{array}
\usepackage{multirow}
\usepackage{tabulary}
\usepackage{booktabs}
\usepackage{feyn}
\usepackage[authoryear]{natbib}
\usepackage{chngcntr}
\usepackage{dcolumn}
\usepackage{amsmath}
\newcommand{\level}[1]{%
  \begin{tabular}{@{}>{\centering\arraybackslash}p{0.2\textwidth}@{}}
  \strut#1\strut
  \end{tabular}%
  }

\begin{document}

\fontsize{10pt}{11pt}\selectfont
\begin{longtable}[c]{l>{\centering\arraybackslash}p{0.2\textwidth}>{\centering\arraybackslash}p{0.4\textwidth}}
\captionsetup{justification=raggedright,width=.82\textwidth}
\caption{Hypotheses}
\label{tab:hypotheses}
\endfirsthead
\multicolumn{3}{c}{{\bfseries \tablename\ \thetable{} -- continued from previous page}}\\
\endhead
\midrule
\multirow{3}{*}{H1} & \multirow{3}{*}{\level{\textit{`lalalala' hypothesis}}} & Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. \\
\cmidrule(lr){2-2}\cmidrule(l){3-3}
\multirow{7}{*}{H2} & \multirow{7}{*}{\level{\textit{`lalalala' hypothesis}}} & Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec. \\
\cmidrule(lr){2-2}\cmidrule(l){3-3}
\multirow{6}{*}{H2a} & \multirow{6}{*}{\level{\textit{`lalalalalalalalala' hypothesis}}} & Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. \\
\cmidrule(lr){2-2}\cmidrule(l){3-3}
\multirow{6}{*}{H2b}& \multirow{6}{*}{\level{\textit{`lalalalalalalala' hypothesis}}} & Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. \\
\bottomrule
\multicolumn{3}{l}{\small{\emph{Source: Author's depiction}}}\\
\end{longtable}
\normalsize

\end{document}

The following does not abuse \multirow.
\documentclass[a4paper,fontsize=12pt,a4paper,DIV=10,BCOR=10mm,twoside,titlepage=false,openany,pagesize]{scrbook}

\usepackage[T1]{fontenc}
\setkomafont{disposition}{\normalfont\bfseries}
\usepackage[font=normalsize,labelfont=sc,singlelinecheck=false,justification=raggedright]{caption}
\usepackage{setspace}
\usepackage{longtable}
\setlength\LTleft{0pt}
\setlength\LTright{0pt}
\usepackage{array}
\usepackage{booktabs}
\newcommand{\level}[1]{%
  \begin{tabular}{@{}>{\centering\arraybackslash}p{0.4\textwidth}@{}}
  \strut#1\strut
  \end{tabular}%
  }
\newcommand{\levell}[1]{%
  \begin{tabular}{@{}>{\centering\arraybackslash}p{0.2\textwidth}@{}}
  \strut#1\strut
  \end{tabular}%
  }

\begin{document}

\fontsize{10pt}{11pt}\selectfont
\begin{longtable}[c]{l>{\centering\arraybackslash}p{0.2\textwidth}>{\centering\arraybackslash}p{0.4\textwidth}}
\captionsetup{justification=raggedright,width=.82\textwidth}
\caption{Hypotheses}
\label{tab:hypotheses}
\endfirsthead
\multicolumn{3}{c}{{\bfseries \tablename\ \thetable{} -- continued from previous page}}\\
\endhead
\midrule
H1 & \levell{\textit{`lalalala' hypothesis}} & \level{Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.} \\
\cmidrule(lr){2-2}\cmidrule(l){3-3}
H2 & \levell{\textit{`lalalala' hypothesis}} & \level{Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec.} \\
\cmidrule(lr){2-2}\cmidrule(l){3-3}
H2a & \levell{\textit{`lalalalalalalalala' hypothesis}} & \level{Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.} \\
\cmidrule(lr){2-2}\cmidrule(l){3-3}
H2b& \levell{\textit{`lalalalalalalala' hypothesis}} & \level{Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.} \\
\bottomrule
\multicolumn{3}{l}{\small{\emph{Source: Author's depiction}}}\\
\end{longtable}
\normalsize

\end{document}

Note that \level and \levell are different.

A: The m{} tabular alignment from the array package (which you already load) was made for this. Change your table spec to:
\begin{longtable}[c]{>{\centering\arraybackslash}m{0.1\textwidth}>{\centering\arraybackslash}m{0.2\textwidth}>{\centering\arraybackslash}m{0.4\textwidth}}

Then you can remove all of your \multirow kludges:
\documentclass[a4paper,fontsize=12pt,a4paper,DIV=10,BCOR=10mm,twoside,titlepage=false,openany,pagesize]{scrbook}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{blindtext}
\setkomafont{disposition}{\normalfont\bfseries}
\usepackage{graphicx}
\usepackage[font=normalsize,labelfont=sc,singlelinecheck=false,justification=raggedright]{caption}
\usepackage[hyphens]{url}
\usepackage{setspace}
\usepackage{subfigure}
\usepackage{longtable}
\setlength\LTleft{0pt}
\setlength\LTright{0pt}
\usepackage{hyperref}
\hypersetup{
    colorlinks,
    citecolor=black,
    filecolor=black,
    linkcolor=black,
    urlcolor=black
}
\usepackage{array}
\usepackage{multirow}
\usepackage{tabulary}
\usepackage{booktabs}
\usepackage{feyn}
\usepackage[authoryear]{natbib}
\usepackage{chngcntr}
\usepackage{dcolumn}
\usepackage{amsmath}

\begin{document}

\fontsize{10pt}{11pt}\selectfont
\begin{longtable}[c]{>{\centering\arraybackslash}m{0.1\textwidth}>{\centering\arraybackslash}m{0.2\textwidth}>{\centering\arraybackslash}m{0.4\textwidth}}
\captionsetup{justification=raggedright,width=.82\textwidth}
\caption{Hypotheses}
\label{tab:hypotheses}
\endfirsthead
\multicolumn{3}{c}{{\bfseries \tablename\ \thetable{} -- continued from previous page}}\\
\endhead
\midrule
H1  & \textit{`lalalala' hypothesis} & Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. \\
\cmidrule(lr){2-2}\cmidrule(l){3-3}
H2  & \textit{`lalalala' hypothesis} & Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec. \\
\cmidrule(lr){2-2}\cmidrule(l){3-3}
H2a & \textit{`lalalalalalalalala' hypothesis} & Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. \\
\cmidrule(lr){2-2}\cmidrule(l){3-3}
H2b & \textit{`lalalalalalalala' hypothesis} & Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. \\
\bottomrule
\multicolumn{3}{l}{\small{\emph{Source: Author's depiction}}}\\
\end{longtable}
\normalsize

\end{document}


text:
Q: Spring MVC4 + AngularJS - Resolve css/js and JSP I'm trying to integrate Spring MVC4 + Angular JS but i have some problems to load template from AngularJS side. On the net there are a lot of resources, but IMHO a bit confused.
Right now i've setup a simple controller that render a page under webapp/WEB-INF/jsp. This works fine but when in this page i try to load js (angular library) i got error (resource unavailable).
I've added this to my view.jsp and resource is not loaded:
<script src="resources/js/angular/angular.js"></script>

I'm my dispatcher-servlet.xml i have the follow configuration:
<mvc:annotation-driven />

<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
    </bean>

<mvc:resources mapping="/resources/**" location="/resources/" />

To load correctly my angular library, i have to use c tag library, why ?
<script src="<c:url value="/resources/js/angular/angular.js" />"></script>

Next on it, i have created a template under webapp/WEB-INF/jsp/templates/main.jsp and i'm trying to load it using $routeProvider (i've tried to load main.jsp too, but the error is the same - resource not found)
angular.module('MyApp', ['ngRoute'])
    .config(function($routeProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'templates/main'
            });
    });

My answer is:

*

*How i can load "library" without using c taglib ?

*What i have to add to my configuration to load templates from AngularJs ? (using templateUrl) ?

Thanks a lot!


text:
Q: Kids help family of aliens get to space I have been going crazy looking for it. I know a group of kids help a family of aliens hiding out on a windfarm to get home to outer space. I remember one of the aliens being pregnant. The aliens looked like larger E.T.s but I could not find a sequel. Help me if you know this movie!

A: Nothing says "E.T. ripoff" like Mac and Me

A Mysterious Alien Creature (MAC) trying to escape from NASA is
  befriended by a wheelchair-bound boy.