text:
Q: CrawlSpider Rule not working for a link that actually exists in target site I'm stuck trying to find a way to make my spider work. This is the scenario: I'm trying to find all the URLs of a specific domain that are contained in a particular target website. For this, I've defined a couple of rules so I can crawl the site and find out the links of my interest.
The thing is that it doesn't seem to work, even when I know that there are links with the proper format inside the website.
This is my spider:
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

class sp(CrawlSpider):
     name = 'sp'

     start_urls = ['https://nationalpavementexpo.com/show/floor-plan-exhibitor-list/']

     custom_settings = {
        'LOG_LEVEL': 'INFO',
        'DEPTH_LIMIT': 4
     }

    rules = (
        Rule(LinkExtractor(unique=True, allow_domains='a2zinc.net'), callback='parse_item'),
        Rule(LinkExtractor(unique=True, canonicalize=True, allow_domains = 'nationalpavementexpo.com'))
    )

    def parse_item(self, response):
        print(response.request.url)
        yield {'link':response.request.url}

So, in summary, I'm trying to find all the links from 'a2zinc.net' contained inside https://nationalpavementexpo.com/show/floor-plan-exhibitor-list/ and its subsections.
As you guys can see, there are at least 3 occurrences of the desired links inside the target website.
The funny thing is that when I test the spider using another target site (like this one) that also contains links of interest, it works as expected and I can't really see the difference.
Also, if I define a Link Extractor instance (as in the snippet below) inside a parsing method, it is also capable of finding the desired links, but I think this won't be the best way of using CrawlSpider + Rules.
def parse_item(self, response):
    le = LinkExtractor(allow_domains='a2zinc.net')
    links = le.extract_links(response)

    for link in links:
        yield {'link': link.url}

any idea what the cause of the problem could be?
Thanks a lot.

A: Your code works. The only issue is that you have set the logging level to INFO while the links that are being extracted are returning status code 403 which is only visible at the DEBUG level. Comment out your custom settings and you will see that the links are being extracted.
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

class sp(CrawlSpider):
    name = 'sp'

    start_urls = ['https://nationalpavementexpo.com/show/floor-plan-exhibitor-list/']

    custom_settings = {
    # 'LOG_LEVEL': 'INFO',
    # 'DEPTH_LIMIT': 4
    }

    rules = (
        Rule(LinkExtractor(allow_domains='a2zinc.net'), callback='parse_item'),
        Rule(LinkExtractor(unique=True, canonicalize=True, allow_domains = 'nationalpavementexpo.com'))
    )

    def parse_item(self, response):
        print(response.request.url)
        yield {'link':response.request.url}

OUTPUT:


text:
Q: Laplace using $t$-shift Hello I'm doing a exercise that says to use the $t$-shift to find inverse laplace of
$$
F(s) = \frac{5s+4}{s^2} \cdot e^{-2s}.
$$
I'm not sure how to rewrite it so they have the same shift term on top and bottom

A: $$F(s)=\frac{5}{s}e^{-2s}+\frac{4}{s^2}e^{-2s}.$$
Now, if we apply the shift theorem we end up with
$$f(t)=5\,\mathcal U(t-2)+\dots.$$
You can do the other one, where $\mathcal U(\cdot)$ is the Heaviside step function:
$$\mathcal U(t-a)=\cases{1 & if $t\ge a$\\0 & if $t<a$}$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't display custom field from Wordpress REST API custom endpoint I'm using the Wordpress Rest API to import content from a Wordpress website into a PHP application.
It's nothing complex, just a main page with the list of posts and the pages for individual posts.
I added some fields to the API response, in particular one to get the url of the first image inserted in the post.
This is the code for this part:
add_action('rest_api_init', function () {
    register_rest_field('post', 'post_images', array(
        'get_callback'    => 'get_first_image',
        'update_callback' => null,
        'schema'          => null
    ));
});

function get_first_image($obj, $name, $request)
{
    $images = get_attached_media('image', $obj['id']);
    $imagesArray = (array) $images;
    reset($imagesArray);
    $firstImageId = current($imagesArray)->ID;
    $imageSrc = wp_get_attachment_image_url($firstImageId);
    return $imageSrc;
}

It works fine when I'm listing posts in the main page, but from the individual post page the field is empty. The only explanation I can come up with for this is that I have this custom endpoint for the single posts:
function post_by_slug(WP_REST_Request $request)
{
    $postSlug = $request->get_param('post_slug');
    $lang     = $request->get_param('my_lang');
    $myPost   = get_page_by_path($postSlug, OBJECT, 'post');
    $targetPostId   = apply_filters('wpml_object_id', $myPost->ID, 'post',
        false, $lang);
    $targetPost     = get_post($targetPostId);
    $postController = new \WP_REST_Posts_Controller($targetPost->post_type);
    $response       = $postController->prepare_item_for_response($targetPost,
        $request);

    return rest_ensure_response($response);
}

add_action('rest_api_init', function () {
    register_rest_route('pc/v1',
        "/post-slug/(?P<post_slug>\S+)/(?P<my_lang>\w+)", [
            'methods'  => 'GET',
            'callback' => 'post_by_slug',
            'args'     => [
                'post_slug' => 'required',
                'my_lang'   => 'required'
            ]
        ]);
});

From my app, I call it this way:
$client = new Client([
    'base_uri' => 'http://example.com/wp-json/pc/v1/',
    'headers' => [
        'Content-Type' => 'application/json',
        "Accept" => "application/json",
    ],
    'verify' => false,
]);

var_dump(json_decode($client->get("post-slug/$slug/$lang")
                             ->getBody()->getContents()));

What's strange is that accessing the same endpoint directly from the browser I can see all the fields correctly. Am I missing something ovious?

A: Just answering my own question because I've found what was causing the endpoint to work correctly from my browser but not when accessed through Guzzle.
The problem was that I was logged in as an admin, so the WPML plugin that I'm using to manage multiple languages on the website was setting this cookie:
wp-wpml_current_admin_language_d41d8cd98f00b204e9800998ecf8427e:"de"

So the problem was related to this plugin, which I'm actually using in the post_by_slug function.
Somehow, specifying the language as I do here is not enough, or just serves a different purpose, not sure:
$targetPostId   = apply_filters('wpml_object_id', $myPost->ID, 'post', false, $lang);

There are two solutions I could find:
1) explicitly setting the languge using the plugin switch_lang() method:
function post_by_slug(WP_REST_Request $request) {
  global $sitepress;
  $postSlug = $request->get_param('post_slug');
  $lang = $request->get_param('my_lang');
  $sitepress->switch_lang($lang);

2) change the guzzle GET request to pass the language as a query parameter, which seems to automatically work with the plugin:
$response = $client->get("post-slug/$slug", ['query' => ['lang' => $lang]])->getBody()->getContents();

I realize that this is a very specific problem, but maybe it will be of help to someone else.


text:
Q: Using Dojo Uploader with AJAX on select I want to create a Dojo Uploader button.
When the user finishes selecting a file, I want to upload the file to the server immediately (don't wait for a submit click).
Here's my code:

In the body of the HTML doc:
<input name="restoreFile" multiple="false" type="file" id="restoreBtn"
       data-dojo-type="dojox/form/Uploader"
       data-dojo-props='label: "Upload",
                        url: "<s:url action="restore-backup" />",
                        uploadOnSelect: "true"' />

I tried putting both of these tags into a form tag, but there was no change in behavior.
When I click on the uploader, I see the file picker.
When I select the file and click "Open," the FileList shows the selected file, but nothing is sent to the server.
I tried requiring all three of the uploader plugins, HTML5 (isn't supported in IE, but doesn't work as desired in Chrome either), IFrame, and Flash.
An I misunderstanding how uploadOnSelect is supposed to work? Why is the uploader not uploading the file after it is selected?

A: Simply info; as I'm Not sure if this applies to your issue - but the uploader works best if used with the legacy loader (synchronious XHR pre 1.7 loader). This is due to the way the author has chosen the architecture for the plugins (flash / iframe / html5). However, it should not mess with the event handling

*

*I'm thinking, try set it up as a programattic component - after dojo.ready and dojo.parser has both completed their tasks..

Alternatively, test if a version 1.6 would work - or if setting dojo.config.async = false helps you.

A: You can use dojox.form.Uploader along with dojox.form.uploader.FileList. Just declare these 2 as follows.
up = new dojox.form.Uploader({
            label: 'Select files',
            multiple: true,
            class:"browseButton",
            url: "UploadFile.php"
        }).placeAt(form);

        list = new dojox.form.uploader.FileList({
            uploader: up
        }).placeAt(form);

        btn = new Button({
            label: 'upload',
            onClick: function() {
                up.upload();
            }
        }).placeAt(form);

        btn.startup();
        up.startup();
        list.startup();

A: I did try the same thing and it worked after removing the quotes
(using Dojo 1.10)
data-dojo-props="uploadOnSelect: true" instead of data-dojo-props='uploadOnSelect: "true"'


text:
Q: Using asynchronous boost asio code for synchronous operation I have a server and a client code written in boost ASIO and it works pretty fine.
Since synchronous and asynchornous boost asio API's are different, is it possible in any way that the code I have written for asynchronous communication behaves and works in a synchronous fashion instead of asynchronous. ?

A: You can run any asynchronous code on a dedicated io_service, and simply run the service blocking:
Live On Coliru
#include <boost/asio.hpp>
#include <boost/asio/high_resolution_timer.hpp>
#include <iostream>

using namespace std::chrono_literals;
using namespace boost::asio;
using boost::system::system_error;

io_service svc;
high_resolution_timer deadline(svc, 3s);

void task_foo() {
    deadline.async_wait([](system_error) { std::cout << "task done\n"; });
}

int main() {
    task_foo();

    std::cout << "Before doing work\n";

    svc.run(); // blocks!

    std::cout << "After doing work\n";
}

Prints
Before doing work
task done
After doing work

Alternatively:
You can always use futures that you can then await blocking:
Live On Coliru
#include <boost/asio.hpp>
#include <boost/asio/high_resolution_timer.hpp>
#include <boost/make_shared.hpp>
#include <future>
#include <iostream>
#include <thread>

using namespace std::chrono_literals;
using namespace boost::asio;
using boost::system::system_error;

io_service svc;
high_resolution_timer deadline(svc, 3s);

std::future<int> task_foo() {
    auto p   = boost::make_shared<std::promise<int> >();
    auto fut = p->get_future();

    deadline.async_wait([p](system_error) {
        std::cout << "task done\n";
        p->set_value(42);
    });

    return fut;
}

int main() {

    auto foo = task_foo();

    std::cout << "Before doing work\n";

    std::thread([] { svc.run(); }).detach(); // doesn't block!

    std::cout << "After starting work\n"; // happens before task completion

    auto result = foo.get(); // blocks again!

    std::cout << "Task result: " << result << "\n";
}

Prints
Before doing work
After starting work
task done
Task result: 42

This way you can still have the io_service running concurrently and don't require it to complete even though a particular task completes synchronously (foo.get())


text:
Q: Mandatory not working If both blank it works but one of these filled then not work and only one value inserted in DB const handleChange = (e) => {
        console.log("handleChange")
        setSuccessMessage("")
        setErrorMessage("")
        setMandatory(false)

        let { name, value } = e.target

        validator(name, value);
    }

const handleSubmit = (e) => {
        e.preventDefault();
        setSuccessMessage("")
        setErrorMessage("")
        if (formValue.userName === "" || formValue.passWord === "") {
            console.log("Mandatory")
            setMandatory(true)
        }
        else {
            axios.post(url, formValue)
                .then(response => {
                    console.log(response);
                    let newMsg = "Loged in successfully for ID: " + response.data.id
                    setSuccessMessage(newMsg)
                })
                .catch(error => {
                    console.log(error);
                    setErrorMessage(message.ERROR)
                })
        }

 const validator = (name, value) => {
        console.log("validator")
        switch (name) {

            case "userName":
                console.log("switchName")
                // let regex=/^[A-Za-z]+([\s][A-Za-z]+)*$/;
                setformValue({
                    "userName": value
                })
                if (!(value.match(/^[A-Za-z]+([\s][A-Za-z]+)*$/))) {
                    setformErrors({
                        "username": "Enter letters only"
                    })
                }
                else {
                    setformErrors({
                        "username": ""
                    })
                }
                break;

            case "passWord":

                setformValue({
                    "passWord": value
                })
                if (!value.match(/^.*[A-Z].*$/)) {
                    setformErrors({
                        "password": "Password should contain at least one capital letter"
                    })
                }
                else if (!value.match(/^.*[a-z].*$/)) {
                    setformErrors({
                        "password": "Password should contain at least one small letter"
                    })
                } else if (!value.match(/^.*[!@#$%^&*].*$/)) {
                    setformErrors({
                        "password": "Password should contain at least one symbol"
                    })
                }
                else if (!value.match(/^.*[0-9].*$/)) {
                    setformErrors({
                        "password": "Password should contain at least one number"
                    })
                }

                else {
                    setformErrors({
                        "password": ""
                    })
                }
                if (value.length < 7) {
                    setformErrors({
                        "password": "Password length should at least 8 "
                    })
                }
                break;
            default:
        }
        if (Object.values(formErrors).every((value) => value === "")) {
            console.log("Valid true")
            setValid(true)
        }
        else {
            setValid(false)
        }
    }

//Input
<form className='form' onSubmit={handleSubmit}>

                        <input type="text" className='form-control ' name="userName" placeholder='Enter Username'
                            value={formValue.userName} onChange={handleChange} />
                        User Name
                        {formErrors.username}

                        <input type="password" className='form-control' name="passWord" placeholder='Enter Password'
                            value={formValue.passWord} onChange={handleChange} />
                        Password
                        {formErrors.password}

                    <button type='submit' className='badge p-2 m-2 btn-success fw-bold'
                        disabled={!valid}>Login</button>

{
                        mandatory ? message.MANDATORY : null
                    }

{successMessage}

            </form>

If both the fields are blank, then it shows the error message but one of these filled then it is showing success message. If second value is entered, then it will clear the first value and also only one field is added in DB. What is wrong with code? ............................................................................................................................................

A: in these if if the first value is true then its going to execute ,it wont see the second value, so try to change the condition .write if else if like it may work


text:
Q: Replacing a term in a sequent by a variable I'm going through 'Proof Theory' by Gaisi Takeuti (second edition 1987). Theorem 6.9 on page 34 talks about when one can replace all occurrences of a term $t$ in a provable sequent $S$ by a free variable to get another provable sequent $S'$. The sufficient condition stated in the theorem is that there's no sub-semi-term of $t$ is $S$.
My question is: what examples exist where the existence of a sub-semi-term of $t$ in $S$ prevents a proof of $S'$? As far as I can tell, one can still construct a proof $P'$ of $S'$ from the original proof $P$, albeit with possibly partial replacement of $t$ in sequents other than the lowest one.


text:
Q: The space of $L^2$ integrable holomorphic functions on the unit disk I am to show that the space of $L^2$-integrable, holomorphic functions on the unit disk is a Hilbert space.
I am very unfamiliar with this material, so please forgive any confusion coming through in my following "explanation".
I have finally understood the proof that $L^2$ is complete, and given the inner product, $\langle f|g \rangle= \int_{-\infty}^{\infty}\bar{f}(z)g(z)dz$, this makes it a Hilbert space.
My confusion is how to adapt this to specifically the holomorphic functions on the unit disk. Does it change the terms of integration? What other changes do I need to make? Any extra explanation would be of great help. TIA.

A: Let's call this space $L^2_h := \big\{ f : \mathbb D \to \mathbb C : f \text{ is holomorphic and } f \in L^2 (\mathbb D ) \big\}$. For $a \in \mathbb D$ you can show $\vert f(a) \vert \leq C \cdot \Vert f \Vert_{L^2}$ for some constant $C>0$ which is locally independent of $a$.For this calculation see this script, prop. 5.6.1. It is in German but you'll just have to see the calculation.Therefore, if you have a Cauchy-sequence $(f_n)_n$ in $L^2_h$, it follows that this sequence converges locally uniformly to some function $f \colon \mathbb D \to \mathbb C$. This implies, that $f$ is holomorphic.


text:
Q: Package todo - cut off at page end I am using the todonotes package. However, when the \todos get too long  the text goes over the page and cannot be seen. Here is an example of what I tried:
\documentclass{article}

\usepackage{todonotes}

\usepackage{lipsum} %for dummy text

\begin{document}

\todo[inline,caption={}]{
Some notes:
\begin{itemize}
\item \lipsum[1]
\item \lipsum[2]
\item \lipsum[1]
\item \lipsum[2]
\item \lipsum[1]
\item \lipsum[2]
\item \lipsum[1]
\item \lipsum[2]
\end{itemize}
}
\end{document}

Therefore, how can you do a page break in the todonotes package, so that the notes go on on the next page?
I appreciate your answers!

A: todonotes uses tikz nodes for its contents, and node contents can not be broken across pages.
Hence to put large amount of text with a frame and coloured background, todonotes is not a good choice. Better use tcolorbox. Here is an example as requested.
\documentclass{article}

\usepackage[most]{tcolorbox}

\usepackage{lipsum} %for dummy text

\begin{document}

\begin{tcolorbox}[colback=orange,colframe=black,enhanced jigsaw,
                   arc=3mm,boxsep=4pt,boxrule=0.5pt,breakable]
Some notes:
\begin{itemize}
\item \lipsum[1]
\item \lipsum[2]
\item \lipsum[1]
\item \lipsum[2]
\item \lipsum[1]
\item \lipsum[2]
\item \lipsum[1]
\item \lipsum[2]
\end{itemize}
\end{tcolorbox}
\end{document}


text:
Q: Access - Link to Outlook Contacts in Access I had a linked table sourcing from Outlook contacts, which I then used for further data elaboration.
Since some weeks I get "unable to find field" error.
I then tried to:

*

*create a new linked table from scratch but I get error An error occurred trying to link to file 'Contacts'. The link was not created

*create a new imported (not linked) table but I get error The Microsoft Access database engine could not find the Object ". Make sure the Object exists and that you spell its name and the path name correctly. If " is not a local Object check your network connection or contact the server administrator.
Has something been changed from Outlook side?
What could be the reason for these errors?

A: From the perspective of Outlook client, if you are using Exchange account,it is suggested to turn off your cache mode and see if the issue has any difference. Besides, I also found some other information related to Import or link to contacts from an Outlook address book, please check https://support.microsoft.com/en-us/office/import-or-link-to-contacts-from-an-outlook-address-book-e2ff9669-5b95-483e-be8d-83590c2085a3


text:
Q: How to conditionally pass values to django's queryset.values I have a HTML form that is being submitted to a django view via get method. The goal is to print a list of users from the users table but only print the fields that have been selected in the form i.e. the user will select the columns that they want to print.
In my View, I check to see if a given column is selected then append it to a list. I then pass this list to django's queryset.values() method. However, it does not accept a list object as an argument.
class PrintUsers(TemplateView):
    template_name = 'users/print-users.html'

    def get(self, request, *args, **kwargs):

        context = super(PrintUsers, self).get_context_data(**kwargs)

        users_list = Member.objects.all()

        values_list = []

        if self.request.GET.get('category') == 'on':
            values_list.append("category")

        if self.request.GET.get('email') == 'on':
            values_list.append("email")

        users_list.values(values_list) # this does not work

        context['users_list'] = users_list

        return render(request, self.template_name, context=context)

How can I conditionally build the *fields values as the documentation does not explain this here https://docs.djangoproject.com/en/2.1/ref/models/querysets/#values ??


text:
Q: Select element in document using JQuery How can I write this?
$('document #filters input')

I've tried:
$(document).$('#filters input')

A: If you need document, it should be:
$(document).find("#filters input");

or the equivalent:
$("#filters input", document);

document is a variable. Unprefixed names in a selector are tag names, not expanded as variables, so your selector was looking for a <document> tag somewhere.

A: Just use $("#filters input"). In your first example you are treating "document" as an element and in your second example, the code is incorrect. Look up jQuery's .find method for more help with the latter.

A: What you are looking for is called .filter() and it is used like so:
$(document).filter('#filters input');


text:
Q: select particular input field name of particular form i have some html code like this
<form name="first"><input name="firstText" type="text" value="General" />
<input name="secondText" type="text" value="General" />
<input name="ThirdText" type="text" value="General" />
<input name="FourthText" type="text" value="General" />
<input name="FifthText" type="text" value="General" />
</form>

<form name="second"><input name="firstText" type="text" value="General" />
<input name="secondText" type="text" value="General" />
<input name="ThirdText" type="text" value="General" />
<input name="FourthText" type="text" value="General" />
<input name="FifthText" type="text" value="General" />
</form>

i want to select "secondText" of form "second" using jquery or javascript and i want to change value of it using jquery.

A: To the point with pure JS:
document.querySelector('form[name=particular-form] input[name=particular-input]')

Update:
This selector will return the input named "particular-input" inside form named "particular-form" if exists, otherwise returns null.
The selector filter "form[name=particular-form]" will look for all forms with name equals "particular-form":
<form name="particular-form">
The selector filter "input[name=particular-input]" will look for all input elements with name equals "particular-input":
<input name="particular-input">
Combining both filters with a white space, I mean:
"form[name=particular-name] input[name=particular-input]"
We are asking for querySelector(): Hey, find all inputs with name equals "particular-input" nested in all forms with name equals "particular-form".
Consider:
<form name="particular-form">
  <input name="generic-input">
  <input name="particular-input">
</form>
<form name="another-form">
  <input name="particular-input">
</form>
<script>
  document.querySelector('form[name=particular-form] input[name=particular-input]').style.background = "#f00"
</script>

This code will change the background color only of the second input, no matter the third input have same name. It is because we are selecting only inputs named "particular-input" nested in form named "particular form"
I hope it's more clear now.
;)
By the way, unfortunately I didn't found good/simple documentation about querySelector filters, if you know any reference, please post here.

A: // Define the target element
elem = jQuery( 'form[name="second"] input[name="secondText"]' );

// Set the new value
elem.val( 'test' );

A: Using jQuery:
var element = $("form[name='second'] input[name='secondText']");

Using vanilla JS:
var element = document.querySelector("form[name='second'] input[name='secondText']");

Changing the value: element.val(value) or element.value = value, depending of what you are using.

A: You can do it like this:
jQuery
$("form[name='second'] input[name='secondText']").val("yourNewValue");

Demo: http://jsfiddle.net/YLgcC/
Or:
Native Javascript
Old browsers:
var myInput = [];
myInput = document.getElementsByTagName("input");

for (var i = 0; i < myInput.length; i++) {
    if (myInput[i].parentNode.name === "second" &&
       myInput[i].name === "secondText") {
        myInput[i].value = "yourNewValue";
    }
}

Demo: http://jsfiddle.net/YLgcC/1/
New browsers:
document.querySelector("form[name='second'] input[name='secondText']").value = "yourNewValue";

Demo: http://jsfiddle.net/YLgcC/2/

A: Try
$("form[name='second'] input[name='secondText']").val("ENTER-YOUR-VALUE");

A: You can try this line too:
$('input[name="elements[174ec04d-a9e1-406a-8b17-36fadf79afdf][0][value]"').mask("999.999.999-99",{placeholder:" "});

A: Add button in both forms. On Button click find nearest form using closest() function of jquery. then using find()(jquery function) get all input values. closest() goes in upward direction in dom tree for search and find() goes in downward direction in dom tree for search. Read here
Another way is to use sibling() (jquery function). On button click get sibling input field values.


text:
Q: When and why we use list view instead of scrollview in Android? I understand we always use listview to display list of items instead of Scrollview. But I know we can do it with scrollview also. I understand that performance of list view is better than ScrollView when you want to display list of items. My question is there are any reason for that also? And why nobody use scrollview to display list of items? Please give me your opinion. Thank you.

A: I often use Scrollview for displaying a limit of items, this number rarely be changed on runtime, such as in a configuration page. Otherwise, ListView is for display a lot of items. Those items may be the same type such as a list of Students, Messages, etc.

A: ListView uses a concept of dequeueing that is removing view from the view hierarchy when they are not visible. For example if you have 20 items and only 10 are visible at a time.

The listview will remove the top 1st element when 11th element comes
  into view using scrolling. This reduces memory load and gives smoother
  performance. Battery consumption is major factor of phone these days
  and no one wants a app that consumes all the phone battery.

Scrollview on the other hand keeps all the view added in it in the view heirarchy all the time therefore increased memory usage and performance issues when the number of views added are huge.

A: ScrollView is used to put different or same child views or layouts and the all can be scrolled.
ListView is used to put same child view or layout as multiple items. All these items are also scrollable.
A scrollview on the other hand is quite different. You add other views to a scrollview which allows you to have more elements than what would fit on screen. Say, for example, you wanted to have 50 buttons or a large chunk of text. By using a listview you have a container that is the size of the screen but allows the user to scroll up and down to see the other views.


text:
Q: Mysql query to get data by latest date and time I have a table which contains two columns names Date and Time.Date column has dataype of DATETIME and time has varchar.Now as per my requirement i have to get the data by latest Date and latest time .For Example
2014-09-12  10:00
2014-09-12  12:00
2014-09-12  16:00
2014-09-19  10:00
2014-09-19  12:00
2014-09-19  16:00

I want data to be fetched like ..
2014-09-19  16:00
2014-09-19  12:00
2014-09-19  10:00
2014-09-12  16:00
2014-09-12  12:00
2014-09-12  10:00

Here is the query that i am using but data regarding time order is not maintained.
select date as Date,time as Time from table ORDER BY date DESC;

Please help me with this..
Thanks  in advance..

A: if date and time are two different columns then try this query
select date as Date,time as Time from table ORDER BY date DESC, time DESC;

A: Concat both fields and make order bid concatenated field, see below
select date as Date,time as Time from table
ORDER BY DATE_FORMAT(CONCAT_WS(' ', `date`, `time`), "%Y-%m%d %H:%i:%s") DESC

A: select date as Date,time as Time from table ORDER BY Date DESC, Time DESC;
If you want to sort by two columns, use two columns


text:
Q: isql не могу подключиться к oracle Добрый день. не могу подключиться к oracle через isql.
[08004][unixODBC][Oracle][ODBC][Ora]ORA-12154: TNS:could not resolve the connect identifier specified

[ISQL]ERROR: Could not SQLConnect

/etc/odbc.ini
   [mthbz]
Driver= ORACLE
DSN= mthbz
ServerName= mth
UserID= dan
Password= dan

/etc/odbcinst.ini
[ORACLE]
Description = Oracle ODBC Connection
Driver = /usr/lib/oracle/12.2/client64/lib/libsqora.so.12.1
Setup =
FileUsage =

/usr/lib/oracle/12.2/client64/network/admin/tnsnames.ora
MTHBZ =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 10.98.10.20)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = mth)
    )
  )

env
ORACLE_HOME=/usr/lib/oracle/12.2/client64
ODBCINI=/etc/odbc.ini
LD_LIBRARY_PATH=/usr/lib/oracle/12.2/client64/lib:/usr/lib64:/usr/lib:/usr/lib/oracle/12.2/client64/bin
ODBCSYSINI=/etc
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/lib/oracle/12.2/client64/bin:/usr/lib/oracle/12.2/client64/bin

A: Ответ на основе комментариев
Необходимо исправить ODBC:
   [mthbz]
Driver= ORACLE
DSN= mthbz
ServerName= MTHBZ
UserID= user
Password= pass

В ServerName указывается алиас из TNS, а был указан SERVICE_NAME


text:
Q: C - Memory size pointer of char I am trying to write a function to assign text input to a char**. Where each word is stored in a char*. When I was doing this I was getting errors that I think indicated that I didn't allocate enough memory so I wrote a little test program.
#include <stdio.h>
#include <stdlib.h>

int main(){
    char **input=NULL;
    char **help=NULL;
    for(int i=1;i<300;i++){
        help=realloc(input,i*(sizeof(char*)));
        if (!help)
            return 0;
        input=help;
        input[i]="test";
    }
    return 1;
}

Now this works just fine, but when I assign per character as follows.
#include <stdio.h>
#include <stdlib.h>

int main(){
    char **input=NULL;
    char **help=NULL;
    char *help2=NULL;
    for(int i=1;i<300;i++){
        help=realloc(input,i*(sizeof(char*)));
        if (!help)
            return 0;
        input=help;
        for (int j=1;j<5;j++){
            help2=realloc(input[i-1],j);
            if (!help2)
                return 0;
            input[i-1]=help2;
            input[i-1][j-1]='t';
        }
    }
    return 1;
}

I get a segmentation fault on line 14. I think this is because the input does not have enough space. But since the size of a character is one and I used sizeof(char*) I don't see how it is not enough. How much memory would I need to allocate and why did it work in my first example? Thanks!

A: clang finds the problem right away.
test(72707,0x7fffe32443c0) malloc: *** error for object 0x7fffe0051090: pointer being realloc'd was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6

The problem is here.
help2=realloc(input[i-1],j);

While input has been allocated, none of its elements have been initialized. realloc will act like malloc if the pointer is null, but if its asked to reallocate the uninitialized garbage pointer in input[i-1] it will freak.
Instead you must properly initialize input before trying to realloc its elements.
A memory checking tool such as Valgrind will help find these sorts of mistakes.


text:
Q: Blinking cursor visible on texts after voiceover off on safari I am using safari on Mac. Cursor and focus on field looks fine. But when I starts voiceover and after terminating it, the blinking cursor starts appearing on all texts like they are input fields.
To replicate this, use any html page, start voiceover on it and then close voiceover. You will be seeing blinking cursor on all texts.
Is there any way to fix this?


text:
Q: Excel VBA: Getting subfolders' names as array of strings My VBA program code access files inside each subfolder. So I am storing those subfolders' names in an array and using for loop to access. I want to make my program more general. How can we get subfolders' names as an array of strings to a variable? If you know any function, please help me. Thanks in advance.
My code
Sub CSVtoXLSX_Click()
 Dim CSVfolder As String, XlsFolder As String, fname As String
 Dim wBook As Workbook
 Dim vArr, vFile
 vArr = Array("subfolder1", "subfolder2", "subfolder3", "subfolder4", "subfolder5")
 CSVfolder = "C:\Work\"
 XlsFolder = "C:\Work\"
 For Each vFile In vArr
 fname = Dir(CSVfolder & vFile & "\" & "*.csv")
 Do While fname <> ""
    Application.ScreenUpdating = False
    Set wBook = Workbooks.Open(CSVfolder & vFile & "\" & fname, Format:=6, Delimiter:=",")
    wBook.SaveAs XlsFolder & vFile & "\" & Replace(fname, ".csv", ""), xlOpenXMLWorkbook
    Application.CutCopyMode = False
    wBook.Close False
 fname = Dir()
 Loop
 Kill CSVfolder & vFile & "\" & "*.csv"
 Next
End Sub

A: Try this:
Sub CSVtoXLSX_Click()
 Dim CSVfolder As String, XlsFolder As String, fname As String
 Dim wBook As Workbook
 Dim colSF As Collection, vFile
 Dim bHadFiles As Boolean

 CSVfolder = "C:\Work\"
 XlsFolder = "C:\Work\"

 Set colSF = GetSubFolders(CSVfolder)
 For Each vFile In colSF
    fname = Dir(CSVfolder & vFile & "\" & "*.csv")
    bHadFiles = False
    Do While fname <> ""
        bHadFiles = True '<< at least one file to delete using Kill...
        Application.ScreenUpdating = False
        Set wBook = Workbooks.Open(CSVfolder & vFile & "\" & fname, _
                                   Format:=6, Delimiter:=",")

        wBook.SaveAs XlsFolder & vFile & "\" & Replace(fname, ".csv", ""), _
                      xlOpenXMLWorkbook

        Application.CutCopyMode = False
        wBook.Close False
        fname = Dir()
    Loop
    If bHadFiles Then Kill CSVfolder & vFile & "\" & "*.csv" '<< will error if nothing to delete
 Next
End Sub

'get all subfolders under the provided path
'  return as a Collection
Function GetSubFolders(sPath As String) As Collection

    Dim col As New Collection, f

    f = Dir(sPath, vbDirectory + vbNormal)
    Do While f <> ""
        If GetAttr(sPath & f) And vbDirectory Then
            If f <> "." And f <> ".." Then col.Add f
        End If
        f = Dir()
    Loop
    Set GetSubFolders = col

End Function


text:
Q: How to Cast geometry to Geography in SQL script in MS SQL Server? I have a Table with some spatial Data in MS SQL Server. The datatype of the spatial column is geometry.
I'm trying to get the closest data from an input file using the following query:
DECLARE @g geometry;
SET @g= geometry::STGeomFromText('POINT(-74.19432 43.745)', 4326);

SELECT TOP(1) Shape,  Shape.ToString(), UID, Colour, Shape.STDistance(@g) FROM dbo.roads
WHERE Shape.STDistance(@g) IS NOT NULL
ORDER BY Shape.STDistance(@g);

This query runs successfully, but I want the distance between my input point and the Shape in meters; Right now the value is in Decimal Degrees, since my data is WGS84-lat-long.
To get Distance in Meters, I need to convert the geometry on the fly to Geography
I can't find the syntax to do this Casting in the Select Clause of the Query.
(All the examples That I find, do the casting outside the Actual Select statement. )
How do I temporarily cast the geometry to geography on the fly?

A: I'm not sure this is the most efficient way of doing it, but it certainly works:
SELECT geography::STGeomFromText([geom].STAsText(),4326)

where 4326 is the spatial reference ID (SRID)


text:
Q: How to remove an item from cart using magento api in android? I am using "shoppingCartProductRemove" api to remove an item from cart in magento. For that i am using the following code:
SoapObject item = new SoapObject(NAMESPACE,"shoppingCartProductEntity");
                PropertyInfo pinfo = new PropertyInfo();
                String productid = productId.get(deleteProductPosition);
                pinfo.setName("product_id");
                pinfo.setValue(productid);
                pinfo.setType(String.class);
                item.addProperty(pinfo);

                pinfo = new PropertyInfo();
                String productsku = productSku.get(deleteProductPosition);
                pinfo.setName("sku");
                pinfo.setValue(productsku);
                pinfo.setType(String.class);
                item.addProperty(pinfo);

                pinfo = new PropertyInfo();
                int productQty = Qty.get(deleteProductPosition);
                pinfo.setName("qty");
                pinfo.setValue(productQty);
                pinfo.setType(Double.class);
                item.addProperty(pinfo);

SoapObject EntityArray = new SoapObject(NAMESPACE,"shoppingCartProductEntity");
                EntityArray.addProperty("productsData", item);

            SoapObject request = new SoapObject(NAMESPACE, "shoppingCartProductRemove");
                request.addProperty("sessionId", sessionId);
                request.addProperty("quoteId", 118);
                request.addProperty("productsData", item);

                env.setOutputSoapObject(request);
                androidHttpTransport = new HttpTransportSE(URL);
                androidHttpTransport.call("", env);
                Object catrInfoObjs = env.getResponse();

but i am getting the xml pullparser exception. Is there any reference to remove an item from cart. Need help here!!

A: I got it using the following code:
SoapObject item = new SoapObject(NAMESPACE, "shoppingCartProductEntity");
                PropertyInfo pinfo = new PropertyInfo();

                pinfo.setName("product_id");
                pinfo.setValue(productId.get(deleteProductPosition));
                pinfo.setType(String.class);
                item.addProperty(pinfo);

                pinfo = new PropertyInfo();
                pinfo.setName("sku");
                pinfo.setValue(productSku.get(deleteProductPosition));
                pinfo.setType(String.class);
                item.addProperty(pinfo);
                int productQty = Qty.get(deleteProductPosition);
                pinfo = new PropertyInfo();
                pinfo.setName("qty");
                pinfo.setValue(productQty);
                pinfo.setType(Double.class);
                item.addProperty(pinfo);

                pinfo = new PropertyInfo();
                pinfo.setName("options");
                pinfo.setValue(" ");
                pinfo.setType(String[].class);
                item.addProperty(pinfo);

                SoapObject EntityArray = new SoapObject(NAMESPACE, "shoppingCartProductEntityArray");
                EntityArray.addProperty("products",item);

                SoapObject request = new SoapObject(NAMESPACE, "shoppingCartProductRemove");
                request.addProperty("sessionId", sessionId);
                request.addProperty("quoteId", 74);
                request.addProperty("products",EntityArray);

                env.setOutputSoapObject(request);
                androidHttpTransport = new HttpTransportSE(URL);
                androidHttpTransport.call("", env);

                Object result = (Boolean) env.getResponse();


text:
Q: How to find the limit $\lim_{n \to \infty} \int_0^1\frac{x^ne^x}{1 +e^x}dx$ Find the limit
$$
\lim_{n \to \infty} \int_0^1\frac{x^ne^x}{1 +e^x}dx
$$
By intuition, I can guess the answer is $0$, but I have no idea how to start to prove it.
What I have tried is using the mean value theorem. There exists $c \in (0, 1)$:
$$
\lim_{n \to \infty} \int_0^1\frac{x^ne^x}{1 +e^x}dx = \lim_{n \to \infty}\frac{c^ne^c}{1 +e^c}
$$
and I don't see how I should continue from here.

A: From
$$
0\le \int_0^1{\frac{x^ne^x}{1+e^x}}dx=\int_0^1{\frac{x^n}{1+e^{-x}}}dx\le \int_0^1{\frac{x^n}{1}}dx=\int_0^1{x^n}dx
$$
From the squeeze theorem, take limits on both sides and we get
$$
0\le \lim_{n\rightarrow \infty} \int_0^1{\frac{x^ne^x}{1+e^x}}dx=\lim_{n\rightarrow \infty} \int_0^1{\frac{x^n}{1+e^{-x}}}dx\le \lim_{n\rightarrow \infty} \int_0^1{x^n}dx=0
$$
and thus
$$
\lim_{n \to \infty} \int_0^1\frac{x^ne^x}{1 +e^x}dx=0
$$

A: We have
$$
0 < \frac{{e^x }}{{1 + e^x }} < 1
$$
for $0<x<1$, thus
$$
0 < \int_0^1 {\frac{{x^n e^x }}{{1 + e^x }}dx}  < \int_0^1 {x^n dx}  = \frac{1}{{n + 1}}.
$$
Consequently, by the squeeze theorem,
$$
\mathop {\lim }\limits_{n \to  + \infty } \int_0^1 {\frac{{x^n e^x }}{{1 + e^x }}dx}  = 0.
$$

A: Since the integrand is a continuous function, the mean value theorem for integrals tells us that there exists $\;0<c<1\;$ s.t.
$$\int_0^1x^n\frac{e^x}{1+e^x}\,dx=c^n\frac{e^c}{1+e^c}\xrightarrow[n\to\infty]{}0$$
since $\;c^n\to 0\;$ and $\;0\le \cfrac{e^x}{1+e^x}\le 1\;$ is bounded.


text:
Q: To retrieve access token I have created a MVC application to escalate work to other person inside my organization. I have added all the members in my organization to AAD,
and registered an application there, created app service and linked that app service to registered app with SSO enabled.
Now every time someone visits the app, they can login successfully using their respective credential.
What I want to do know is to retrieve all the members in my AAD and display them inside dropdown list so that anyone can escalate to others by just looking in the dropdown list.
I have tried with sample graph SDK to get the name of users in my organization
with this code
    private string redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];
    private string appId = ConfigurationManager.AppSettings["ida:AppId"];
    private string appSecret = ConfigurationManager.AppSettings["ida:AppSecret"];
    private string scopes = ConfigurationManager.AppSettings["ida:GraphScopes"];

public async Task<string> GetUserAccessTokenAsync()
    {
        string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
        HttpContextWrapper httpContext = new HttpContextWrapper(HttpContext.Current);
        TokenCache userTokenCache = new SessionTokenCache(signedInUserID, httpContext).GetMsalCacheInstance();
        //var cachedItems = tokenCache.ReadItems(appId); // see what's in the cache

        ConfidentialClientApplication cca = new ConfidentialClientApplication(
            appId,
            redirectUri,
            new ClientCredential(appSecret),
            userTokenCache,
            null);

        try
        {
            AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes.Split(new char[] { ' ' }), cca.Users.First());
            return result.AccessToken;
        }

        // Unable to retrieve the access token silently.
        catch (Exception)
        {
            HttpContext.Current.Request.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties() { RedirectUri = "/" },
                OpenIdConnectAuthenticationDefaults.AuthenticationType);

            throw new ServiceException(
                new Error
                {
                    Code = GraphErrorCode.AuthenticationFailure.ToString(),
                    Message = Resource.Error_AuthChallengeNeeded,
                });
        }
    }

with some change in scope.
<add key="ida:AppId" value="xxxxx-xxxxxxx-xxxxxx-xxxxxxx"/>
<add key="ida:AppSecret" value="xxxxxxxxxxx"/>
<add key="ida:RedirectUri" value="http://localhost:55065/"/>
<add key="ida:GraphScopes" value="User.ReadBasic.All User.Read Mail.Send Files.ReadWrite"/>

This enables me to get basic details of all user in my organization.
But how I can achieve this in my app where authentication related stuffs are done in azure only, and there is no code for authentication and authorization in entire solution.
Thanks
Subham, NATHCORP, INDIA

A:
But how I can achieve this in my app where authentication related stuffs are done in azure only, and there is no code for authentication and authorization in entire solution.

Based on my understanding, you are using the build-in feature App Service Authentication / Authorization. You could follow here to configure your web app to use AAD login. And you need to configure the required permissions for your AD app as follows:

Note: For Azure AD graph, you need to set the relevant permissions for the Windows Azure Active Directory API. For Microsoft Graph, you need to configure the Microsoft Graph API.
Then, you need to configure additional settings for your web app. You could access https://resources.azure.com/, choose your web app and update App Service Auth Configuration as follows:

Note: For using Microsoft Graph API, you need to set the resource to https://graph.microsoft.com. Details, you could follow here.
For retrieving the access token in your application, you could get it from the request header X-MS-TOKEN-AAD-ACCESS-TOKEN. Details, you could follow Working with user identities in your application.
Moreover, you could use Microsoft.Azure.ActiveDirectory.GraphClient package for Microsoft Azure Active Directory Graph API, Microsoft.Graph package for Microsoft Graph API using the related access token.


text:
Q: How to Show Revolution Slider on Category Page in Magento? I want to show revolution slider on category page using by "nwdthemes revolution slider".
I am doing this:
1) created a category "Men"

2) created a revolutions slider with alias "category_men" and short-code {{revslider alias="category_women"}} using by "nwdthemes revolution slider"

3) In category Custom Design tab, put below code into Custom Layout Update field

<reference name="top.container">
    <block type="nwdrevslider/revslider" name="revslider">
        <action method="setAlias"><alias>category_men</alias></action>
    </block>
</reference>

But revolution slider is not showing on category page front-end. Any help would be appreciated.

A: You probably need to go into the Revslider global settings and set it to load scripts globally for it work on category pages.

A: The code you post looks correct. Try to clear cache in System > Cache management. If you are using any 3rd-party cache extensions - clear their cache too.
You can also insert slider instead of category image

*

*Check if category has image. If yes - remove it

*Open "Display Settings" tab and set "Display Mode" to Products Only

*Update xml code to
<reference name="content">
    <block type="nwdrevslider/revslider" name="revslider" before="-">
        <action method="setAlias"><alias>ecorecycle</alias></action>
    </block>
</reference>
Full article can be found here - https://nwdthemes.com/2015/04/29/slideshow-for-category-page-with-slider-revolution-magento-extension/

A: please try with below code snippet :
   <referenceContainer name="page.top">
      <block class="Nwdthemes\Revslider\Block\Revslider">
          <arguments>
               <argument name="alias" xsi:type="string">category_men</argument>
          </arguments>
      </block>
   </referenceContainer>

and don't forget to clear the cache


text:
Q: Angular : How to get constant values in the component after setting them? I've a constant array of orders like this in constants.ts file
       export const ORDERS = [
           {
            'id': 'PROCESSING',
            'displayName': null
           },
           {
            'id': 'SHIPPED',
            'displayName': null
           }
        ];

Here in my component I'm setting the value of 'displayName'
import { ORDERS } from './constants';
-----------------
--------------
setOrders() {
        ORDERS.forEach((order: any) => {

        if(order.id === 'PROCESSING') {
           order.displayName = 'Processing';
        }

        if(order.id === 'SHIPPED') {
           order.displayName = 'Shipped';
        }

     });
    }

But here when I try to get values of 'displayName' in another funtion it return null, but in the object order I can see the value of 'displayName'
getOrders() {
        ORDERS.forEach((order: any) => {
                console.log(order); // displayName exists in the object
                console.log(order.displayName); // But here null
        });
    }

Both functions are in a same component. Please help me how to resolve this thanks.
Update : Full implementation
getTimePeriod() {
        return Promise.resolve((() => {

            this.orderService.getTimePeriod()
                .subscribe(
                    (data) => {
                        this.orderStatusList = data.configParameters;
                        this.orderStatusList.forEach(
                            (s: any) => {
                                if (s.status === 'PROCESSING') { this.setOrders(s.status, s.name); }

                                if (s.status === 'SHIPPED') { this.setOrders((s.status, s.name); }
                            }
                        );
                    },
                    error => {
                        this.errorMessage = this.orderService.handleError(error);
                    }
                );
                })());
    }

    setOrders(status, name) {
        ORDERS.forEach((order: any) => {
            if (order.id === status) {
                order.displayName = name;
            }
        });
    }

     getOrders() {
        return Promise.resolve((() => {

        ORDERS.forEach((order: any) => {
            const { displayName } = order;

            console.log(order); // displayName exists in order
            console.log(displayName); // Null

            this.orderService.getOrdersByDisplayName(buildQuery(null, displayName, null, null))
                .subscribe(
                    (data) => {
                        this.ordersWidgetInfo.push({

                            ...order,
                            ...data,
                            number: data.orders && data.orders.length,
                        });
                    },
                    error => {
                        console.log(`error for ${orderType} : ${error}`);
                    }
                );
        }
        );
        })());
    }

A: The only way a bug like this would occur (other than the code being wrong) is with an invalid order of execution.
However, after trying your code, it seems to works just fine. See example on JSFiddle.
This leads me to conclude that your problem is most likely that getOrders is being invoked before setOrders, thus the null values. To fix this, make sure you are calling setOrders before you call getOrders.


text:
Q: How can I access the request object in an aspectj class in web application I'm working on a Liferay 7.0 plugin project (traditional WAR packaging). I'm using AOP in it and have made my required AspectJ classes. I want to get the request object in the aspect class and get some attributes from it.
For this task, I implemented a ServletRequestListener that set the request object in a ThreadLocal variable; but because of the setter thread may be different from the getter thread, the ThreadLocal variable's value may be null sometimes, when I get it in the aspect class.
What solution do you suggest to solve this problem?


text:
Q: How to close a hanged (dos not respond) android App by another App programmatically With this code I can close App (B) by another App (A):
App (A) code:
var
  LService: JObject;
begin
      LService := TAndroidHelper.Context.getSystemService(TJContext.JavaClass.ACTIVITY_SERVICE);
       if LService <> nil then
       TJActivityManager.Wrap(JObjectToID(LService)).killBackgroundProcesses(StringToJString('App B Name'));

end;

But when App  (B) hanged (dos not respond) this code not effect.
How can close it.(Delphi Code needed)


text:
Q: Can't enable File Sharing under OSX Lion So I've upgraded to Lion, but now I can't enable File Sharing, when I press the checkbox, it simple shows the "correct" symbol and in less than half of a second it removes it again.
This happens the same for the 2 checkboxes under the Options... as well.
What can I do to enable File Sharing again?

A: It turns out it's not only me, but following this amazing tutorial everything whent smooth and worked out nicely...


text:
Q: .Where in LinQ not working correctly I have Documents table and Signs table. Document record can be related with many records in Signs table.
Now, I want to get all records of Documents table when document ID appears in Signs table.
Here I get all documents:
var documents = (from c in context.documents select c);

Here I get all my signs and save into List:
var myDocuments = (from s in context.signs where s.UserId== id select s.ID).ToList();

This list contains collection on document ID.
And here, I'm trying to get all documents that exists in myDocuments list:
documents.Where(item => myDocuments.Contains(item.ID));

But, when I do .ToList() allways return all records (in database only exists one compatible record)
What is wrong in LinQ statement?

A: The problem is that this statement doesn't modify the contents of documents, it merely returns the results (which you're not doing anything with):
documents.Where(item => myDocuments.Contains(item.ID));

documents is still the full list.
Change this line to something like:
var matchingIDDocs = documents.Where(item => myDocuments.Contains(item.ID));

And then use matchingIDDocs in place of "documents" later in your code.


text:
Q: Search Box Customization in MOSS 2007 How to customize Search Box webpart so that to have a dropdown with items taken from a SharePoint list. User can search only from these dropdowns.
I know about configuiring scope. But this is little more.. I am looking for dropdown in 2nd box( Query box).
For ex: I have a list in my sharePoint site as Keywords. Now I want to add a Search Box in my home page where user can search which list they want to choose( can be done by search scope) and then input words in second search box. These words should come in a dropdown form with all contents from KeyWords library.
Hope I am clear with my explaination.

A: you can add drop-down control on page after the free textbox using jquery. And while adding the drop-downto page also populate it with the data from the litusing jquery / list service. I have done similar thing in sharepoint 2010 .

A: you could develop a custom delegate control.
In this post you can understand how: http://salvatoredifaziosharepoint.blogspot.co.uk/2012/02/delegate-controls-small-search-input.html


text:
Q: MBSA offline scanning problem with new version of wsusscn2 I have problem with MBSA offline scanning for MS security updates. Problem has started with new version of "wsusscn2.cab" file.
Up until now, everything working fine, with older version of "wsusscn2.cab".
When I started scanning this month I recived an error: "An error occurred while scanning for security updates. (0x80070057)".
When I was scanning with older version of "wsusscn2.cab" everything passed OK.

A: I've seen this twice in the five years I've been using MBSA offline scanning. In both instances, Microsoft messed up the wsusscn2.cab file. My machines run in a very secure environment, so I just waited until the following month, and ran it with the new wsusscn2.cab file.
I only use MBSA offline scanning right before creating an updated disk image. Our next image update doesn't occur until August, so I haven't used the most current wsusscn2.cab file.

A: Problem is Windows Update Agent (wuauclt.exe). Update file to the latest version 7.2
Download of new version on http://support.microsoft.com/kb/949104


text:
Q: Determinant of an anti-diagonal block matrix Is it true in general that if $A$ and $B$ are two $n \times n$ matrices, then the determinant of the anti-diagonal block matrix
$$
J = \left[\begin{array}{cc} 0 & A  \\ B& 0  \end{array}\right]
$$
is $\det(J)=\det(B)\det(A)$?
It is simple to prove this if $n=2$, but I have no idea on how to generalize it.

A: One has: $$J:=\begin{pmatrix}0 & A\\B & 0\end{pmatrix}=\begin{pmatrix}A& 0\\0 & B\end{pmatrix}\times\begin{pmatrix}0 & I_n\\I_n & 0\end{pmatrix}.$$
You only have to compute: $$\varepsilon:=\det\left(\begin{pmatrix}0 & I_n\\I_n & 0\end{pmatrix}\right).$$
Indeed, using the first equality, one has: $$\det(J)=\varepsilon\det(A)\det(B).$$
If $n$ is odd, the result appears to be false, you will get: $$\det(J)=-\det(A)\det(B).$$

A: The definition of determinant through permutation will give the answer.
For a matrix $C=(c_{i,j})_{m \times m}$
$$\mathrm{det}(C)=\sum \limits_{\sigma \in S_{m}} \mathrm{sgn}~\sigma\cdot c_{1,\sigma(1)}c_{2,\sigma(2)} \cdots c_{m,\sigma(m)}$$
If we write, $J=(x_{i,j})_{2n \times 2n}$ then,
$$\mathrm{det}(J)=\sum \limits_{\sigma \in S_{2n}} \mathrm{sgn}~\sigma\cdot x_{1,\sigma(1)}x_{2,\sigma(2)} \cdots x_{n,\sigma(n)}x_{n+1,\sigma(n+1)} \cdots x_{2n,\sigma(2n)}$$
For $\sigma \in S_{2n}$ with $\sigma(i) \in \{1,2, \cdots,n\}~ \mathrm{for~some~} i \in \{1,2, \cdots,n\}$ or, $\sigma(i) \in \{n+1,n+2, \cdots,2n\}~ \mathrm{for~some~} i \in \{n+1,n+2, \cdots,2n\}$, the term $x_{1,\sigma(1)}x_{2,\sigma(2)} \cdots x_{n,\sigma(n)}x_{n+1,\sigma(n+1)} \cdots x_{2n,\sigma(2n)} = 0$
Let, $H=\{\sigma \in S_{2n}~|~ \sigma(i) \in \{n+1,n+2, \cdots,2n\}~ \forall i \in \{1,2, \cdots,n\} ~\mathrm{and}~\sigma(i) \in \{1,2, \cdots,n\}~ ~ \forall i \in \{n+1,n+2, \cdots,2n\} \}$
So, $$\mathrm{det}(J)=\sum \limits_{\sigma \in H} \mathrm{sgn}~\sigma\cdot x_{1,\sigma(1)}x_{2,\sigma(2)} \cdots x_{n,\sigma(n)}x_{n+1,\sigma(n+1)} \cdots x_{2n,\sigma(2n)}$$
For, $(\sigma_1,\sigma_2) \in S_n \times S_n$, define $\sigma(i)=\sigma_1(i)+n~ \forall i \in \{1,2, \cdots,n\}$ and $\sigma(i)=\sigma_2(i-n)~ \forall i \in \{n+1,n+2, \cdots,2n\}$.
Then, $\sigma \in H$ and $$S_n \times S_n \rightarrow H$$ $$(\sigma_1,\sigma_2) \mapsto \sigma$$
is a bijection and $\mathrm{sgn}~\sigma= (-1)^n \cdot \mathrm{sgn}~\sigma_1\cdot \mathrm{sgn}~\sigma_2$ (verify).
So,
\begin{eqnarray*}
\mathrm{det}(J) &=& (-1)^n \cdot\sum \limits_{(\sigma_1,\sigma_2) \in S_n \times S_n} \mathrm{sgn}~\sigma_1\cdot \mathrm{sgn}~\sigma_2 \cdot x_{1,\sigma_1(1)+n}x_{2,\sigma_1(2)+n} \cdots x_{n,\sigma_1(n)+n}x_{n+1,\sigma_2(1)} \cdots x_{2n,\sigma_2(n)}\\
&=& (-1)^n \cdot\sum \limits_{\sigma_1 \in S_n} \sum \limits_{\sigma_2 \in S_n} \mathrm{sgn}~\sigma_1\cdot \mathrm{sgn}~\sigma_2 \cdot x_{1,\sigma_1(1)+n}x_{2,\sigma_1(2)+n} \cdots x_{n,\sigma_1(n)+n}x_{n+1,\sigma_2(1)} \cdots x_{2n,\sigma_2(n)}\\
&=& (-1)^n \cdot\sum \limits_{\sigma_1 \in S_n} \left(\mathrm{sgn}~\sigma_1\cdot x_{1,\sigma_1(1)+n}x_{2,\sigma_1(2)+n} \cdots x_{n,\sigma_1(n)+n} \times \sum \limits_{\sigma_2 \in S_n} \mathrm{sgn}~\sigma_2\cdot x_{n+1,\sigma_2(1)} \cdots x_{2n,\sigma_2(n)} \right)\\
&=& (-1)^n \cdot\sum \limits_{\sigma_1 \in S_n} \left(\mathrm{sgn}~\sigma_1\cdot x_{1,\sigma_1(1)+n}x_{2,\sigma_1(2)+n} \cdots x_{n,\sigma_1(n)+n} \times \mathrm{det}(B) \right)\\
&=& (-1)^n \cdot\mathrm{det}(B)\times \left(\sum \limits_{\sigma_1 \in S_n} \mathrm{sgn}~\sigma_1\cdot x_{1,\sigma_1(1)+n}x_{2,\sigma_1(2)+n} \cdots x_{n,\sigma_1(n)+n}\right)\\
&=& (-1)^n \cdot\mathrm{det}(B)\mathrm{det}(A)
\end{eqnarray*}

A: There are block matrix determinant identities that will give you this, but if you want to solve using basic determinant formulas consider the full expansion formula for the determinant using permutations, giving a sum of $n!$ terms for an $n \times n$ matrix, where each term is either $1$ or $-1$ multiplied by $n$ entries in the matrix. If a term includes an entry in either of the zero blocks, then the term is $0$. So every non-zero term is a product of entries selected from $A$ and entries selected from $B$. If you consider all terms you can get by selecting entries just from $A$ and $B$, and group them together according to entries selected in $A$, you will see that for each choice of entries in $A$, when you consider the sum of terms, you can factor out $\det B$ from the sum and get just the product of terms selected in $A$. So then when you add those up (after factoring out $\det B$) you get $\det A$. There is a small detail in handling the signs of the permutations, but this is pretty straightforward.


text:
Q: Have two different homepages based on customer logged in or not I have set login page as home page using cms page but I want to display login page as home page before login but after login my category page should display as home page how to do this

A: I would hook into the event controller_action_predispatch_customer_customer_login, check wether the user is logged in, if it is the case, throw an exception of the form
$e = new Mage_Core_Controller_Varien_Exception();
$e->prepareForward('catalog','category','view', array('id' => $categoryId));
throw $e;

If the user is not logged in, the default behaviour is used, which is the login form.
How to do it?
Implement your own module
As @MagikTejas explains in another answer, you need to implement your own Module, by creating a YourCompany_YourModule.xml in app/etc/modules, but instead of implementing your own route, you implement an observer as described here: https://stackoverflow.com/a/11197771/1480397
Observer are implement inside of the config.xml in app/code/<local|community>/YourCompany/YourModule/etc/. The question wether you use community or local depends on whether you want to publish your module (aka use it in more than one installation)
Your config.xml should contain this part:
<frontend>
    <events>
        <controller_action_predispatch_customer_customer_login>
            <observers>
                <yourmodule_save_order_observer>
                    <class>YourCompany_YourModule_Model_Observer</class>
                    <method>controllerActionPredispatchCustomerCustomerLogin</method>
                </yourmodule_save_order_observer>
            </observers>
        </controller_action_predispatch_customer_customer_login>
    </events>
</frontend>

Now you implement your observer, the observer lives in app/code/<local|community>/YourCompany/YourModule/Model/Observer.php
The name of the observer is YourCompany_YourModule_Model_Observer and it contains the method controllerActionPredispatchCustomerCustomerLogin
public function controllerActionPredispatchCustomerCustomerLogin() {
    //check wether customer is logged in, if yes, redirect him
    if(Mage::getSingleton('customer/session')->isLoggedIn()) {
        // you need to get the $categoryId, but this is your part. You could hardcode it (which is a bad idea) or add a configuration setting (just google, how to do it) or something else, this is up to you.
        $e = new Mage_Core_Controller_Varien_Exception();
        $e->prepareForward('catalog','category','view', array('id' => $categoryId));
        throw $e;
    }
}

A: You can do this by creating a custom module as follows:
Create following directories for the module -
/app/code/local/Mycompany/Mymodule
/app/code/local/Mycompany/Mymodule/controllers
/app/code/local/Mycompany/Mymodule/etc

To set up a module that will let you redirect an incoming root website link to
wherever you want, first set up a module xml file under /app/etc/modules/Mycompany_Mymodule.xml containing this
<?xml version="1.0"?>
<config>
    <modules>
        <Mycompany_Mymodule>
            <active>true</active>
            <codePool>local</codePool>
        </Mycompany_Mymodule>
    </modules>
</config>

Create your config file in /app/code/local/Mycompany/Mymodule/etc/config.xml:
<?xml version="1.0"?>
<config>
    <modules>
        <Mycompany_Mymodule>
            <version>0.1.0</version>
        </Mycompany_Mymodule>
    </modules>
    <frontend>
        <routers>
            <mycompany>
                <use>standard</use>
                <args>
                    <module>Mycompany_Mymodule</module>
                    <frontName>mycompany</frontName>
                </args>
            </mycompany>
        </routers>
    </frontend>
</config>

Now, create the controller file in /app/code/local/Mycompany/Mymodule/controllers/PageController.php
<?php
class Mycompany_Mymodule_PageController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
          if(Mage::getSingleton('customer/session')->isLoggedIn())
          {
         $this->getResponse()->setRedirect('catalog/category/view/id/10'); //10 is the category id which you want to display as home page
          }
          else
          {
          $this->_redirect('contacts'); //contacts - is the URL identifier of cms page add you login page identifier here.
          }
    }
}

Now the most important thing to make this work as expected go to "System > Configuration > Web > Default Pages" and enter the following for the "Default web url" option:
mycompany/page/
mycompany/page/ - this will call index action of our custom module.
Hope this will help you.

A: To change homepage layout with login layout you can able to do using event controller_action_layout_load_before
You can follow below working code:
create one module, add below code in MyCompany/MyModulename/etc/config.xml
<events>
        <controller_action_layout_load_before>
            <observers>
                <mymodulename>
                    <class>MyCompany_MyModulename_Model_Observer</class>
                    <method>changeHomepageContent</method>
                </mymodulename>
            </observers>
        </controller_action_layout_load_before>
    </events>

Create observer file in MyCompany/MyModulename/Model/Observer.php
class MyCompany_MyModulename_Model_Observer
{
    /**
     * change homepage content
     * @param Varien_Event_Observer $observer
     */
    public function changeHomepageContent(Varien_Event_Observer $observer) {
       $fullActionName = $observer->getEvent()->getAction()->getFullActionName();
       if($fullActionName == 'cms_index_index') {
             if (!Mage::getSingleton('customer/session')->isLoggedIn()) { // check if customer is not logged in
                   $layout = $observer->getEvent()->getLayout();
                   $layout->getUpdate()->removeHandle('cms_page');// this will remove existing cms page content.
                   $layout->getUpdate()->addHandle('customer_account_login'); //this code will add login page content to homepage.
            }
        }

    }
}

I hope above code will help you :)


text:
Q: Grab columns from multiple .csv files as sample for ANOVA in R? I have a few .CSV files and want to perform an ANOVA test in R using the last column from each .CSV file as samples for the ANOVA.
To make an example, here's the first file:
E, Run1, Run2, ..., Runn, Mean
0, 1.48, 1.22, ..., 1.01, 1.24
1, 1.42, 1.12, ..., 1.00, 1.18
2, 1.11, 1.11, ..., 0.98, 1.07
3, 1.00, 0.98, ..., 0.90, 0.96
..., ..., ..., ..., ..., ...

And the second:
E, Run1, Run2, ..., Runn, Mean
0, 2.11, 2.00, ..., 1.98, 2.03
1, 2.00, 1.99, ..., 1.64, 1.88
2, 1.98, 1.90, ..., 1.60, 1.83
3, 1.90, 1.85, ..., 1.22, 1.66
..., ..., ..., ..., ..., ...

Declaratively, I want the final column of each file, and ignore the first row. So I might have sample1 = [1.24, 1.18, 1.07, 0.96, ...], and sample2 = [2.03, 1.88, 1.83, 1.66, ...]. Then I can do an ANOVA using the two samples.
My example uses two files but if there's an approach that can do an arbitrary number of .CSV files and performs the ANOVA, that's preferable.
I'm not terribly familiar with R so any help is appreciated. I've tagged as bash and awk because I don't mind using those.

A: This would be one way, with the data at hand:
library(purrr)

data1 <- read.table(text=
"Epoch, Run 1, Run 2, Run 3, Mean
0, 1.48, 1.22, 1.01, 1.24
1, 1.42, 1.12, 1.00, 1.18
2, 1.11, 1.11, 0.98, 1.07
3, 1.00, 0.98, 0.90, 0.96
",header=TRUE, sep=",")

data2 <- read.table(text=
"Epoch, Run 1, Run 2, Run 3, Mean
0, 2.11, 2.00, 1.98, 2.03
1, 2.00, 1.99, 1.64, 1.88
2, 1.98, 1.90, 1.60, 1.83
3, 1.90, 1.85, 1.22, 1.66
",header=TRUE, sep=",")

list(data1, data2) %>%
    imap_dfr( ~ data.frame( sample=paste0("sample",.y), value=.x[,ncol(.x)] ) )  %>%
    lm( data=., value~sample ) %>% anova

Output:
> anova(lm(value~sample, data=d))
Analysis of Variance Table

Response: value
          Df  Sum Sq Mean Sq F value    Pr(>F)
sample     1 1.08781 1.08781  56.424 0.0002881 ***
Residuals  6 0.11567 0.01928
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

To generalize across multiple files:
library(purrr)
dir( "some/where/", pattern="\\.csv$", full.names=TRUE ) %>%
    map_df( ~ read.csv( .x ) %>% select(last_col()), .id="filename" ) %>%
    setnames( c("filenumber", "value" ) ) %>%
    lm( data=., value~. ) %>% anova


text:
Q: Assigning value type vs reference type I am calling this method that returns type map[int64]Block and I am a bit confused how to properly do this in Go. In Java higher abstract types are pass by reference and can be reassigned. Here I am getting an error when I try to assign variable to a structure type.
storageNodes[id].blocks = initBlock()
..
func initBlock() map[int64]Block {
    block := make(map[int64]Block)
    block[0] = generateBlockOfRandomFiles()
    return block
}
..
type StorageNode struct {
    *Node
    blocks map[int64]Block
}

Here it's stopping me from initializing blocks value -  Cannot assign to storageNodes[id].blocks. Why is that?
EDIT---
The ... just means that there's code in between. StorageNode is in a different file.
EDIT2---
This is what I have now:
        storageNodes[id].blocks = initBlock()
...
func initBlock() map[int64]*Block {
    block := make(map[int64]*Block)
    block[0] = generateBlockOfRandomFiles()
    return block
}

I am still getting an error when I try assign storageNodes to a point that is passed back from the function.

A: StorageNode and initBlock should be before storageNodes[id].blocks = initBlock()
So you can try something like this:
...
type StorageNode struct {
    *Node
    blocks map[int64]Block
}
...
func initBlock() map[int64]Block {
    block := make(map[int64]Block)
    block[0] = generateBlockOfRandomFiles()
    return block
}
...
storageNodes[id].blocks = initBlock()

A: Assuming that storageNodes is of type StoregeNode:
You cannot assign the struct members of that map, because they are not addressable.
The definition map[int64]Block stores copies of Block structs. The expression storageNodes[id] returns a copy of the Block instance at that index. Since this is only a copy, assignments to it will be lost.
There are two ways you can solve this:

*

*Declare the map as map[int64]*Block. This way, map indexing will return a pointer to the stored object, and you can set the values in it

*Work on the copy, and set it back:

tmp:=storageNodes[id]
tmp.id=initBlock()
storageNodes[id]=tmp

See the definition of Addressable in the language spec:
https://golang.org/ref/spec#Address_operators
It also helps to remember that, unlike Java, everything is passed by value in Go. That's why you have to explicitly pass pointers, or return pointers. The slice, map, and channel types are references to complex data types, so passing them by value passes the reference to these underlying structs.
EDIT ----
//another file
type StorageNode struct {
*Node
blocks map[int64]Block
}
modified code:
            storageNodes := make(map[int64]StorageNode)
            //some code b/t
            tempBlocks := make(map[int64]Block)
            tempBlocks[0] = GenerateBlockOfRandomFiles()
            storageNodes[int64(id)].blocks = tempBlocks //error Cannot assign to storageNodes[int64(id)].blocks


text:
Q: ASP.NET Core Incorrect Route for LoginPath I have two controllers in the Controllers folder: HomeController and LoginController.
I am using cookie authentication and set the LoginPath to /Login, expecting it to route to the LoginController.
However, when I click on the login link, the app routes to Home/Login instead of /Login. How can it get it to route to /Login correctly?
Routes
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.MapControllerRoute(
    name: "login",
    pattern: "{controller=Login}/{action=Login}");

LoginPath:
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
    options.LoginPath = "/Login";
    options.AccessDeniedPath = "/Home/Denied";
});

Folders:

A: Firstly, the codes options.LoginPath = "/Login"; would redirect you to https://localhost:xxxx/Login when you visit the endpoint has Authrize attribute on it if you're not authenticated;If the Login Action is in Login Controller,For your requirement,it should be "/Login/Login"
Secondly,

However, when I click on the login link, the app routes to Home/Login

it depends on how you configured the link,but you haven't show it.
you need a link like:<a asp-controller="Login" asp-action="Login"> Login </a>
And the second route parttern  you configured is not necessary
You could check this document for more details


text:
Q: Thread is denied access to file (Update Impersonation) In an MVC .NET application I have an action on a controller that takes some documents and does some processing.  The processing can take a long time to finish so I decided to start a thread to do the work while the users can go off and do more work.  However, when I start a new thread through
Thread thread = new Thread(finishedDocument.SplitAndIndex);
thread.Start();

the thread gets an UnauthorizedAccessException.  The method is accessing some files on a server but if I do just finishedDocument.SplitAndIndex
(so not inside a thread) it runs just fine.  I've ensured that all resources are released but even to test if that was the case I put a file out there called test.txt and the only part of my application that touches it is in that method, and still I get the error.
I thought that threads were supposed to have the same permissions/privileges as the process/thread that created it.  Is that not the case?  Is there something I should be doing?  I'm really at a loss here and any help would be great.
Update
I know it has to do with impersonation, I just can't seem to get a thread safe way to do impersonation now.


text:
Q: What is the best way to store a large amount of photos in an app? I'm talking 7,500+ images. The user needs to be able to access about 150 at a time, almost instantly.
I currently have them all saved as PFFiles on Parse.com, but retrieving them is VERY slow and buggy.
My thought is to store all of them locally on the device, but that would cause my app to be about 1GB in size. It may be something I'm willing to do, considering the nature of the app, but does anybody know of anything better?
My code for populating UICollectionViewCells with PFFiles is here:
var images = [PFFile]()

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return images.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell: CardsCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CardsCollectionViewCell
    images[indexPath.row].getDataInBackgroundWithBlock{
        (imageData: NSData?, error: NSError?) -> Void in
        if error == nil {
            let image = UIImage(data: imageData!)
            cell.cardsImg.image = image
        }
    }
    return cell
}

A: As @rghome says, thumbnails could be an interesting way of doing for the size of the app.
If you really want to have them in the app and retrieve them quickly, I would use Realm (realm.io) because they have a database which is easy to use and that retrieves data really fast.
If you want to keep your high-res images in the cloud for the size of the app, reducing the size of them in the app (thumbnails) can be a good way but I'm not a fan of his way.


text:
Q: Correlation of model and experimental results I am trying to find a scientifically accepted method to compare my model predictions with experimental values. Here, my model predicts the concentration of DNA as a function of time. DNA concentration is also measured at several points in time in vivo in an experimental setting.
Is it valid to compare the model predictions to observed values with a Pearson Correlation Coefficient? Would a considerably big coefficient be taken as an accepted 'method' to prove that model predictions are close to experimental and, thus, that the model is valid?

A: In medical sciences, calibration can refer to the precision of assays. The goal of your comparison is a calibration study to determine if your model is valid for predicting DNA concentration as a function of time.
The basic concept of a Pearson correlation coefficient is sufficient to identify discrimination: that is that comparing any two observations, better discrimination means that the one with higher predicted values is likely to have higher observed values. This is a result of the fact a correlation coefficient is a weighted average of the pairwise slopes between all observed values.
A negative consequence of the Pearson correlation coefficient is that it is invariant to scale/shift. That means that with an observed sequence [0,1,2,3,4] and predicted sequence [500,505,510,515,520] your agreement is 100% but the predictions are orders of magnitude off.
If you want a measure of predictive accuracy that ranges from -1 to 1 and achieves a value of 1 if and only if the predictions are identical to observed values, fit the following linear model:
$$ E[\text{Observed}_i|\text{Predicted}_i] = 0 + 1 \text{Predicted}_i$$
This can be done with regression through the origin and fitting the predicted value as an offset term. Then, using model statistics, calculate the square root of the $R^2$ coefficient from that. The sign of direction must be found post-hoc, but let us assume it's not an issue unless the model in question is terrible.
This model has a correspondence with the concordance calibration coefficient of Lin 1989. There are analogues for mixed/repeated measures designs.
An example of performing such a design is shown here. I am using data from Margaret Pepe's study on inspecting a biomarker's relation to development of AKI (Acute Kidney Injury) following cardiac surgery. The biomarker is longitudinal, but I am using just the first observed value for each patient.
aki <- read.csv('http://research.fhcrc.org/content/dam/stripe/diagnostic-biomarkers-statistical-center/files/aki_sim.csv')
aki <- aki[!duplicated(aki$id),]
set.seed(123)
itrain <- sample(1:nrow(aki), nrow(aki)/2)
aki.train <- aki[itrain, ]
aki.test <- aki[-itrain, ]
pred.model <- lm( statusall ~ y, data=aki.train)
pred <- predict(pred.model, newdata=aki.test)

plot(pred, aki.test$statusall, xlab='Predicted status',
  ylab='Observed status \n(0: no AKI, 1: mild AKI, 2: severe AKI, 9: death)')
abline(0,1)
calib.model <- lm(statusall ~ 0 + offset(pred), data=aki.test)

Gives:

summary(calib.model)

Call:
lm(formula = statusall ~ 0 + offset(pred), data = aki.test)

Residuals:
    Min      1Q  Median      3Q     Max
-0.6599 -0.4257 -0.3525 -0.2539  8.7043

No Coefficients

Residual standard error: 0.9518 on 900 degrees of freedom

So $\sqrt{1-0.9518}$ gives a calibration coefficient of 0.22 which is very poor. This is likely a result of the ordinal encoding of AKI severity which includes 9 as death from AKI. Obviously, biological measurements like creatinine clearance would be preferable.
Excluding "9"s as deaths: the R^2 is much better:
> calib.model <- lm(statusall ~ 0 + offset(pred), data=aki.test, subset=statusall != 9)
> summary(calib.model)

Call:
lm(formula = statusall ~ 0 + offset(pred), data = aki.test, subset = statusall !=
    9)

Residuals:
    Min      1Q  Median      3Q     Max
-0.6599 -0.4269 -0.3528 -0.2570  1.8659

No Coefficients

Residual standard error: 0.6419 on 894 degrees of freedom

Gives a calibration coefficient of sqrt(1-0.6419) = 0.60 which is still low.
A last issue to consider is: what is the appropriate scale on which to calibrate the expected and observed values? The raw scale is nice because it is interpretable, but DNA concentrations are often measured on a log scale or a complementary log-log scale. Consider these changes of variable based on your knowledge of the problem.


text:
Q: How to return value from "eventCallBack" from JS method How to return value from "eventCallBack" from JS method
see JS function definition:
window.plugins.GCM.register("428641231987", "GCM_Event", this.GCM_Success, this.GCM_Fail);

Here
@param senderId - GCM service identifier

@param eventCallback - {String} - Name of global window function that will handle incoming events from GCM
@param successCallback - {Function} - called on success on registering device

@param failureCallback - {Function} - called on failure on registering device

Now I want to return value generated in "GCM_Event"
var requiredValue = window.plugins.GCM.register("428641231987", "GCM_Event", this.GCM_Success, this.GCM_Fail);

I want value in requiredValue


text:
Q: Performance concerns about wrapping every method with "try catch" in JavaScript I want to know your opinions on a function I made, that wraps every method of an object, adding "try catch" handlers to log JavaScript errors on server side.
I don't want to use window.onerror, because of this security restriction, and my scripts are going to be hosted on a different domain on a CDN.
/*
 * object: Object to be wrapped
 * errorHandler: Instance of ErrorHandler Object
 */
function addLog(object, errorHandler) {
    var name, method;

    for (name in object) {
        method = object[name];
        if (typeof method === "function") {
            object[name] = function(method, name) {
                return function() {
                    try {
                        return method.apply(this, arguments);
                    } catch (ex) {
                        ex.message += "; method: '" + name + "'";
                        errorHandler.addToStack(ex.message);
                        throw ex;
                    }
                };
            }(method, name);
        }
    }
    return object;
}

errorHandler.addToStack is a method on a custom object that asynchronously sends error reports to a server using Ajax messages.
I want to wrap every object instantiated on my application with this function, but I'm not sure if:

*

*Is this a bad practice?

*Does it has performance issues?

*Are there's a better ways for doing this?

Thanks in advance!

A: Unlike stricter codes like Java, Javascript doesn't require try/catch for most objects instanciated. It tends to simply just not work if something goes wrong, and doesn't explode or end on you.
Some parts do however end the function, so a better method would be to surround the code as a whole with a try/catch, so that it fails silently, and use the catch to recall the original code while sending off an error report.

A: I think that the best way is to avoid try catch statements by preventing errors to occur adding validations and checks, but if you really need to do it this way, I don't think it will have a great performance issue.
Here I made a jspref test to measure it, and the difference shows only in IE, but it's not very significant.
I don't know if the errorHandler method has performance problems or slows down your code, but if it is async, I guess it won't be a problem.

A: you can still send log to server using a global try/catch because exception objects contains the information.
however error object is not standard among browsers, i think


text:
Q: How do I create table using row & col index in jQuery? My JSON looks like this:-
{
"tblDetails": [{
    "id": 1,
    "rowIndex": 1,
    "colIndex": 1
},
{
    "id": 2,
    "rowIndex": 1,
    "colIndex": 2
},
{
    "id": 3,
    "rowIndex": 1,
    "colIndex": 4
},
{
    "id": 4,
    "rowIndex": 1,
    "colIndex": 6
}
]}

And HTML Structure as below:-

I am using jQuery ajax to fetch JSON data.
 $.ajax(
 {
   url : "/hello/data.json",
   type: "GET",
   success: function(data)
   {
       var tbl  = data.tblDetails;
       tbl.forEach(item)
       {
       var html = item.id;
       $('#tblLayout> tbody > tr:eq('+(item.rowIndex)+') td:eq('+(item.colIndex)+')').append(html);
       }

   },
   error:function(e)
   {

   }
 })

Now how do I append the html at the specified row-col in the table tblLayout.

A: I am not sure if this is the exact solution but this is what I did for the required layout.
I replaced table with ul as:-

jQuery ajax
$.ajax(
{
url : "/hello/data.json",
type: "GET",
success: function(data)
{
   var tbl  = data.tblDetails;
   tbl.forEach(item)
   {
   var html ="
" + item.id+ "
";

   $('#tblLayout>).append(html);

   }
   },
  error:function(e)
  {

  }
  })

A: You get data from "data.json" in JSON format. Try this:
  $.ajax({
url: "data.json",
type: "GET",
success: function (data) {
  var tbl = JSON.parse(data).tblDetails;
  $.each(tbl, function (k, v) {
    var html = v.id;
    $('#tblLayout> tbody > tr:eq(' + (v.rowIndex) + ') td:eq(' + (v.colIndex) + ')').append(html);
  });

},
error: function (e) {

}

});


text:
Q: Java Optimization with Threads I'm using a custom class Foo in Java as the key type in a HashMap. All the fields of Foo instances are immutable (they are declared final and private and are assigned values only in the constructor). Thus, the hashCode() of a given Foo object is also fixed, and for optimization purposes, I am calculating it in the constructor and simply returning that value in the hashCode() method.
Instances of Foo also have a value() method which returns a similar fixed value once the object has been instantiated. Currently I am also calculating it in the constructor and returning it in the method, but there is a difference between hashCode() and value(): hashCode() is called for the first time almost instantly after the object is created, but value() is called much later. I understand that having a separate Thread to calculate the hash-code would simply increase the run-time because of synchronization issues, but:

*

*is this a good way to calculate value()? Would it improve run-time at all?

*are simple Threads enough, or do I need to use pools etc.?

Note: this may seem like I'm optimizing the wrong parts of my program, but I've already worked on the 'correct' parts and brought the average run-time down from ~17 seconds to ~2 seconds. Edit: there will be upwards of 5000 Foo objects, and that's a conservative estimate.

A: It definitely sounds like deferred calculation is a good approach here - and yes, if you create a lot of these objects, a thread pool is the way to go.
As for value()'s return value until it's ready, I would stay away from returning invalid values, and instead either make it blocking (and add some isValueReady() helper) or make it instantly return a "future" - some object that offers those same isReady and a blocking get methods.
Also, never rely on "much later" - always make sure the value there is ready before using it.

A: I recommend creating a Future for value - create a static fixedTheadPool and submit the value calculations on it.  This way there's no risk that value will be accessed before it's available - the worst case is that whatever is accessing value will block on a Future.get call (or use the version with a timeout if e.g. deadlock is a concern)
Because Future.get throws checked exceptions which can be a nuisance, you can wrap the get call in your class's getter method and wrap the checked exceptions in a RuntimeException
class MyClass {
    private static final ExecutorService executor = Executors.newFixedThreadPool(/* some value that makes sense */);

    private final Future<Value> future;

    public MyClass() {
        future = executor.submit(/* Callable */);
    }

    public boolean isValueDone() {
        return future.isDone();
    }

    public Value value() {
        try {
            return future.get();
        } catch(InterruptedException|ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}


text:
Q: java protected why is this working through non-inheritance? I'm obviously missing the obvious in this but given:
package a;
public class Class1 {
    protected int a=1;
}

package b;
import a.*;

public class Class2 extends Class1 {
    Class2() {
        Class1 c1=new Class1();
        Class2 c2=new Class2();
        System.out.println(a);     //1
        System.out.println(c1.a);  //2
        System.out.println(c2.a);  //3
    }
}

I know //1 is fine due to being used through inheritance and //2 fails because it's not being access through inheritance, but why is //3 ok too? I thought variable a was being accessed through a new object and a resides in Class1?
Thanks.

A: Since any object of Class2 is-a Class1, it can access all of Class 1's member variables with scopes default, protected and public.
Besides, trying to understand scope and inheritance rules through working with objects that are of the class you are using to play with scopes/inhertiance is not a good idea, since it works in a different way than through a third-party (which is the most common use.)
For instance, this is allowed:
public class Something {
   private int something;

   public int stealSomething(final Something otherthing) {
       return otherthing.something;
   }
}

Try making a third class, that is not in the hierarchy of the classes you are using to test.

A: When you are manipulating an object inside its class, you have full access to all his attributes, including the private ones. As c2 is a instance of Class2 and you are manipulating it inside the Class2 code, you can see the protected attribute.

A:
why is //3 ok too?

And why shouldn't it be ok? Given that Class2 is the subclass of Class1, so a protected fields of Class1 are accessible through the instance of Class2. And that is what you are doing here. c2 is an instance of Class2, and a field is visible for it.
NOTE: A protected member is accessible to any direct subclass, whether in same package or in different package.

I thought variable a was being accessed through a new object

Yeah, that's true.

and a resides in Class1?

That really doesn't matter here. As far as a is accessible to Class2 instance, it is valid.
And just FYI, your code will die of StackOverflowError. You need to take care of it.

A: I don't understand the problem.
Class1 has a variable named 'a'.  Since it is 'protected', that variable is visible within any object of Class1 and any object of a class extending Class1.
If 'a' were private, then it would not be visible this way in objects of classes extending Class1.


text:
Q: How do I order by and group by in a Linq to objects query? How do I order by and group by in a Linq query?
I tried..
Dim iPerson = From lqPersons In objPersons Where Len(lqPersons.Person) > 0 Group lqPersons By key = lqPersons.Name Into Group Order By Group descending Select Group, key

    For Each i In iPerson
        tmp = tmp & vbNewLine & i.key & ", " & i.Group.Count
    Next

The above works if I remove the Order By Group Descending claus, but with it, I get an error on the Next statement..

At least one object must implement IComparable.

My query is to obtain a list of the people in my class/object with how many times their name is used as an item of the class/object.
I.e.
Joe, 4 |
James, 5 |
Mike, 4
Does anyone have any ideas what I'm doing wrong?

A: Your query is fine (there's no problem with using Group in VB.NET as a name BTW ... actually you MUST use Group, so don't worry about that), except you should have Order By key.
p.s.  Tested.
EDIT:  For completeness, you can rename your Group like so:
Dim iPerson = From lqPersons In objPersons
              Where Len(lqPersons.Person) > 0
              Group lqPersons By key = lqPersons.Name Into g = Group
              Order By key Descending
              Select g, key

However that has nothing to do with your problem ... just clarifying that point.

A: Excuse my C#, but couldn't you do something like...
objPersons.Where(p=> p.Person > 0).GroupBy(p => p.Name).Select(p => new { Name= p.Key, Number = p.Count()}).OrderByDescending(p=> p.Number);

Main Idea:

*

*GroupBy as you did

*Select into a new object using your Key (Name) and counting how many in that group

*Order by descending

A: You get the error on the next statement because the query is executed when the For Each loop is executes (it's called defferd execution).
The error actually says that you can't do Ordey By Group because IGrouping doesn't implement IComparable, so the result of your Group By-statement can't be ordered by the IGrouping itself.
You have to order by the number of elements of the IGrouping objects.

Try this (note that I don't know how your classes look like...):
Dim objPersons = New YourClass() {New YourClass("Joe"), _
                                  New YourClass("Joe"), _
                                  New YourClass("Joe"), _
                                  New YourClass("James"), _
                                  New YourClass("James"), _
                                  New YourClass("James"), _
                                  New YourClass("James"), _
                                  New YourClass("Mike"), _
                                  New YourClass("Mike")}

Dim query = objPersons.Where(function(p) p.Person > 0) _
                      .GroupBy(Function(p) p.Name) _
                      .OrderByDescending(Function(g) g.Count) _
                      .Select(function(g) g.Key & ", " & g.Count())

For Each s In query
    Console.WriteLine(s)
Next

Output:
James, 4
Joe, 3
Mike, 2

A: is lqPersons.Name a string, or a struct or class containing first, last, middle, etc names? If it's the former, you should be good with this as strings are IComparable. If Name is an object of some user-defined class, you will either need to implement IComparable on that class (providing a CompareTo() method used by sorting algorithms), or Order By a "primitive" sub-property of Name, like LastName.
EDIT: Just saw something else. When you use Group By, the object that results is a Lookup; basically a KeyValuePair with a collection of Values instead of just one. Lookups are not IComparable. So instead of ordering by the Group, try ordering by the key identifier for that Group (lqPersons.Name).

A: I've done something similar in VB. I have it on my blog as well. But basically here is the SQL I started with.
SELECT orgno, psno, sche, projid, RecType,
SUM(OBBudExpAmt) AS OBBudExpAmt,
SUM(ABBudEncAmt) AS ABBudEncAmt
FROM tbl908_BudSPDGrps
WHERE orgno = '210'
GROUP BY orgno, psno,  sche, projid, RecType

And here is the corresponding LINQ.
Dim projids = From p In db.tbl908_BudSPDGrps _
Where p.orgno = options.GroupFilter  _
Group p By p.orgno, p.psno, p.sche, p.projid, p.RecType _
Into g = Sum(p.OBBudExpAmt), h = Sum(p.ABBudEncAmt) _
Order By orgno, psno, sche, projid, RecType _
Select sche, RecType, g, h

Pretty self-explanitory. Hope it helps you.


text:
Q: Register ngRx effect on a "success" action? Or should this be decoupled with a service? Currently I subscribe a ngRx effect on a "success" action (assuming my action is loadDataSuccess)?
createEffect(() => {
    return this.actions$.pipe(
        ofType(loadDataSuccess), ...

It somehow stings in my head, that this is bad practice. Is it better if I'd subscribe in a service on the selector for data (which will fire after the loadDataSuccess action) and then dispatch a new action loadAdditionalStuffAfterLoadingData ?
store.select(data).subscribe(
    data => store.dispatch(loadAdditionalStuffAfterLoadingData(data)));

A: Both are valid, and serve their purposes.
Personally, I would use the Success action to load the additional information in your case. Because that makes the intention more clear. It's also more dangerous to listen to the state to dispatch an action, because that action could potentially update the same slice of the state, resulting in an infinite loop.
I would like to also mention, that if you're listening to the selector to fetch data, that that could also be an effect, https://timdeschryver.dev/blog/start-using-ngrx-effects-for-this/#using-rxjs-observables.
changed$ = createEffect(() => {
  return store.select(data).pipe(
    map(() => loadAdditionalStuffAfterLoadingData(data))
})