text:
Q: hide/show textarea via checkboxes with same classes for different sections Well, I have a form of interest and when I select an option from select list (e.g cars, motors) it gives me content relating to option.
Here is the test page -> Here
I also have created checkboxes for each section (from above instance) and I want when I check a specific checkbox (.other) to display a text box for details (.textbox) and when I uncheck it to get hidden by default. I gave to this specific checkbox and each textarea the same class for each section. For checkbox -> .other and for textarea -> .textbox
This is the code (of checkboxes) for each section:
Cars

<input type="checkbox" name="thrausi" id="thrausi">text

<input type="checkbox" name="odiki-car" id="odiki-car"text

<input type="checkbox" name="nomiki" id="nomiki">text

<input type="checkbox" class="other">**Other details**

<textarea class="textbox" name="other" style="display:none; width: 255px;" placeholder="text"></textarea>

Motors

<input type="checkbox" name="odiki-moto" id="odiki-moto">text

<input type="checkbox" class="other">**Other details**

<textarea class="textbox" name="other" style="display:none; width: 255px;" placeholder="text"></textarea>

And I tried this JS code:

But I do something wrong.
What do you suggest? Thanks in advance.

A: Use as

A: Check the DEMO [Click Here]
As on the selection of check box with class other you want to show the corresponding textarea
you can use the following code snippet for the resolution.
$(document).ready(function () {
        $(".other").change(function () {
            if ($(this).is(":checked"))
                $(this).parent().parent().parent().next(".textbox").show();
            else
                $(this).parent().parent().parent().next(".textbox").hide();
        });
    });

A: I have tuned your code a bit
jQuery Code:
  $('.other').removeAttr('checked');
  $('.other').on('click', function () {
    $(this).closest("div.par").find('.textbox').toggle();
  });

JSFIDDLE:
http://jsfiddle.net/dreamweiver/1y47bxfh/4/
Note: when your using jquery lib in your code, make sure you use it, dont use raw js code.as the tagline itself suggests write less do more.
Happy Coding :)


text:
Q: R: two data frame merge I want to merge two data frame, but there are some row names repeated.
If the numbers of row name in two data frame are different, I hope the it can show "NA" in the less one column.
My example:
test1 <- data.frame(name = c("A", "B", "C", "C", "C", "D"), n1 = c("15", "14", "13", "12", "11", "10"))
test2 <- data.frame(name = c("A", "B", "B", "C", "C", "D"), n1 = c("30", "31", "33", "39", "38", "40"))

Then I merge by name, I got

name n1.x n1.y
A   15   30
B   14   31
B   14   33
C   13   39
C   13   38
C   12   39
C   12   38
C   11   39
C   11   38
D   10   40

It will repeating
What I want to is

name n1.x n1.y
A   15   30
B   14   31
B   NA   33
C   13   39
C   12   38
C   11   NA
D   10   40

What Command should I use?
Thank you very much!

A: Try:
test1$indx <- with(test1, ave(1:nrow(test1), name, FUN=seq_along))
test2$indx <- with(test2, ave(1:nrow(test2), name, FUN=seq_along))
merge(test1, test2, by=c("name","indx"),all=T)[,-2]
 #   name n1.x n1.y
# 1    A   15   30
# 2    B   14   31
# 3    B <NA>   33
# 4    C   13   39
# 5    C   12   38
# 6    C   11 <NA>
# 7    D   10   40

A: I will post this before data.table.people come in with a slick, scalable and quicl solution.
Be warned, that this works for provided data set. You should examine the results of your production code carefully.
What the below code does is sticks together values for a common level. The rest is just bookkeeping.
ml <- vector("list", length(unique(test1$name)))
names(ml) <- unique(test1$name)

for (i in unique(test1$name)) {
  o1 <- test1[test1$name %in% i, , drop = FALSE]
  o2 <- test2[test2$name %in% i, , drop = FALSE]
  o.max <- max(c(nrow(o1), nrow(o2)))
  nc <- ifelse(o.max == 1, 2, o.max*2)
  out <- matrix(rep(NA, times = nc), nrow = nc/2)
  out[1:nrow(o1), 1] <- as.numeric(as.character(o1$n1))
  out[1:nrow(o2), 2] <- as.numeric(as.character(o2$n1))

  ml[[i]] <- out
}

count.each <- sapply(ml, nrow)
result <- do.call("rbind", ml)
colnames(result) <- c("n1.x", "n1.y")
data.frame(name = rep(names(ml), count.each), result)

  name n1.x n1.y
1    A   15   30
2    B   14   31
3    B   NA   33
4    C   13   39
5    C   12   38
6    C   11   NA
7    D   10   40

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the ideal way to set up multiple FTP enabled web accounts on Fedora? I'm setting up a test server for use as a web development platform, and I'd like to mimic as closely as I can a typical shared hosting setup. That is, I'd like my server to have multple user FTP accounts, each of which links to a directory containing the webroot of the site, and I'd like apache to be able to easily see and manupulate these files.
I'll admit: I'm not as familiar with Fedora as I'd like, I run Ubuntu on my home box and SElinux is giving me some grief. My initial plan was to have each user FTP into their home directory, and put the web directory there as well, but SElinux throws a hissy fit when apache tries to access anything outside of its web directory, so that plan was a no go.
Would it be wise to continue this route, and perhaps mount web directories in user home folders so that FTP could still be used to access them, even though apache saw them in var/www like it expects? Would it make more sense to set up custom FTP accounts and use a single FTP user on the server box? What's the general course of action on something like this? I'm using vsftpd right now to host web directories, which is why I'm liking the home directory approach (it's simple and secure) but of course there's bound to be a better way to go about it.
Thanks. (I'll leave other things, like restricted DB access and such, to another post. I'm interested right now with just getting FTP and apache to play nice in a multi-user environment.)
PS: For the record, an issue I ran into when doing all of this was that if apache isn't running as the same user as the FTP account is saving as, there are permissions errors when FTP creates files, requiring the remote user to chmod the files to fix it. A logical fix would be to run apache in a special group, put all web users in this group, and have FTP access default to giving this group read/write access to everything like apache would expect, but I never could figure out how to accomplish this. Bonus points and cake if you know a solution.

A: you can install one of those
as for the ps, here's my solution
1 - all files in the web root are owned by the user apache runs as (www, for example)
2 - the ftp daemon has the chroot option set on (ie nobody can get out of their home direectory) and the right umask for creating files
if you can name what ftp daemon you intend to use, I can be more specific

A: The first thing I'd suggest is installing Webmin. It will do exactly what you want, and many hosting providers use it too.

A: The ISPConfig control panel is fantastic and is very typical of shared hosting platforms I'd say.
Even if just administering one website I use it to alleviate lots of repetitive tasks.
It also has great setup HowTo's in the Documenttion section.


text:
Q: AngularJS injecting one module in another module and call function code taken from here http://plnkr.co/edit/jcOwg8HgBGPtod4yCR5j?p=info
i read the below code but still i have confusion that how notifytwo's instance is getting pass to factory notify ?
factory notify has function called sampleFun which call function sampleFunTwo of another factory called notifytwo but i have not found when and how notifytwo's instance is getting pass to factory notify ?
please help me to understand the code flow. thanks
var myModule= angular.module('MyServiceModuleOne', ['MyServiceModuleTwo']);
myModule.controller('TestController', ['$scope', 'notify', function($scope, notify){
        $scope.getFn = function() {
          notify.sampleFun();
        }
      }]);

    myModule.factory('notify',
        function(notifytwo) {
        return {

         sampleFun: function() {
                      notifytwo.sampleFunTwo();

                      },
              };
        }
    );

    var myModuleTwo= angular.module('MyServiceModuleTwo',[]);
    myModule.factory('notifytwo',
        function() {
        return {

         sampleFunTwo: function() {
                   alert('From notify two');
                  }
          };
        }
    );

A: The notify factory is able to call the factory notifyTwo because notifyTwo is being injected when creating the instance of notify:
myModule.factory('notify',
    function(notifytwo) //RIGHT HERE IS WHERE IT'S INJECTED


text:
Q: Using typealias in place of typedef defined in class in definition Why does this fail to compile?  I am trying to reduce the amount of repetition since in the real code the class name is huge and the type is actually a very long name
https://godbolt.org/z/8YarWs
#include <vector>

template<typename T>
struct S {
    using type = std::vector<T>;

    type f() const;
};

template<typename T>
using type_t = typename S<T>::type;

template <typename T>
type_t<T> S<T>::f() const { }

The code above fails as below
<source>:17:14: error: no declaration matches 'type_t<T> S<T>::f() const'
   17 | type_t < T > S < T >::f() const
      |              ^~~~~~~
<source>:8:10: note: candidate is: 'S<T>::type S<T>::f() const'
    8 |     type f() const
      |          ^
<source>:4:8: note: 'struct S<T>' defined here
    4 | struct S
      |        ^

A: This is a GCC bug; the closest(1) confirmed open bug report seems to be:

*

*Bug 69348: alias declarations can not be used inside qualifiers of declarators

which highlights that GCC rejects the following well-formed program:

template <class T>
struct X {
    int foo();
};

template <class T>
using foo2 = X<T>;

template <class T>
int foo2<T>::foo()
{
}

with the error message

error: invalid use of incomplete type 'struct X<T>'

(1) Scanning GCC:s bugzilla, there seems to be numerous "rejects valid" (open/unconfirmed) bug reports relating to alias templates, where in most reports clang is reported to accept the (arguably well-formed) example programs.

A: I don't remember the exact reason why, but I know it has something to do with the sequence in which the compiler resolves the type names and symbols...
You could get it to work by changing a bit the structure of the declaration.
Since I don't know how much of this is possible for you, I included some variants.
https://godbolt.org/z/bGPGhW
#include <vector>
#include <iostream>

template <typename T>
struct S
{
    using type = std::vector<T>;

    auto f() const -> decltype(type());
    auto g() const -> decltype(type());
    decltype(type()) h() const;
};

template <typename T>
using type_t = typename S<T>::type;

template <typename T>
auto S<T>::f() const -> decltype(type())
{
    std::cout << "foo" << std::endl;
    type_t<T> t;
    return t;
}

template <typename T>
using other_type_t = decltype(typename S<T>::type());

template <typename T>
auto S<T>::g() const -> other_type_t<T>
{
    std::cout << "bar" << std::endl;
    other_type_t<T> t;
    return t;
}

template <typename T>
using last_type_t = decltype(typename S<T>::type());

template <typename T>
last_type_t<T> S<T>::h() const
{
    std::cout << "foobar" << std::endl;
    last_type_t<T> t;
    return t;
}

int main(){
    S<int> s;
    auto t = s.f();
    auto r = s.g();
    auto l = s.h();
    return 0;
}

Output:
Program returned: 0
Program stdout

foo
bar
foobar


text:
Q: How to trigger a re-render in a component via useContext when said context is updated in another component I am attempting to update a table with with the response from an API.  The response comes to one component and the table lies in another.  I can see that I am successfully updating the context in the component but it doesn't seem to pass to the others.  I have tried updating context and then passing it via prop drilling but that didn't work either.  How do I get the component that contains the tables to listen to changes in the context?  The code for my components is below:
Component in which the context is updated:
import React, { useState, useContext } from 'react';
import { Card } from 'react-bootstrap';
import axios from 'axios';

import Cd from './types/Cd';
import Bond from './types/Bond';
import AssetContext from '../../context/AssetContext';

const fixedCard = (props) => {
const [fixed, setFixed] = useContext(AssetContext);
const [bond, setBond] = useState(false);

const assets = fixed;

const getResult = (event) => {
    const form = event.currentTarget;
    event.preventDefault();
    event.stopPropagation();

    let principle = form.principle.value;
    const iLength = form.investmentLength.value / 12;
    let compound = form.compound.value
    let rate = form.rate.value;
    let amount;

    if (form.amount) {
        amount = form.amount.value;
        principle = principle * amount;
    }

    if (isNaN(rate) || rate < 0) {
        alert("As much fun as it would be to calculate the result with \"" + rate + "\", it can't be done.  Please enter a valid number");
    } else {

        if (compound === "Monthly") {
            compound = 12;
        } else if (compound === "Annually") {
            compound = 1;
        } else if (compound === "Quarterly") {
            compound = 4;
        } else {
            compound = 365;
        }

        const headers = {
            'Content-type': 'application/json',
            'Access-Control-Allow-Origin': 'localhost:3000/',
            'Access-Control-Allow-Methods': 'POST',
        }

        const body = {
            principle: principle,
            interestRate: rate,
            length: iLength,
            compoundFrequency: compound
        }

        axios.post("http://localhost:8080/compound-calculator/savings", body, { headers })
            .then(res => {
                assets.push(res.data);
                setFixed(assets);
                fixed.map(asset => console.log(asset));
            });

    }
}

const linkCursor = { cursor: 'pointer' }

const toggleBond = () => {
    setBond(true);
}

const toggleCert = () => {
    setBond(false);
}

return (
    <Card body>
        <Card.Title>
            Compount interest calculator
        </Card.Title>
        <Card.Link onClick={() => toggleCert()} style={linkCursor}>Certificate</Card.Link>
        <Card.Link onClick={() => toggleBond()} style={linkCursor}>Bond</Card.Link>

        {!bond && <Cd getResult={getResult} />}
        {bond && <Bond getResult={getResult} />}

    </Card>
    );
}

export default React.memo(fixedCard);

Root component:
import React, { useState, useEffect } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import './GrowthCalculator.css';
import { Container, CardDeck } from 'react-bootstrap';

import FixedCard from '../components/fixedAssets/FixedCard';
import StockCard from '../components/StockCard';
import ResultCard from '../components/ResultCard';
import Navigation from '../components/Navigation';
import AssetContext from '../context/AssetContext.js';
import HowTo from '../components/HowTo';

const growthCalculator = (props) => {
    const [fixedState, setFixedState] = useState([]);
    const [stockState, setStockState] = useState([]);

    const assets = [fixedState, setFixedState, stockState, setStockState];

    return (

            <AssetContext.Provider value={[...assets]}>
                <Container>

                    <Navigation />
                </Container>

                <CardDeck>
                    <FixedCard /> //context updated here
                    <StockCard />
                    <ResultCard />  //trying to pass it here
                </CardDeck>

                <HowTo />
            </AssetContext.Provider>

    );
}

export default React.memo(growthCalculator);

Component I'm trying to pass it to (the layout here is still a work in progress):
import React, { useContext, useState } from 'react';
import { Card, Row, Col, Table } from 'react-bootstrap';

import AssetContext from '../context/AssetContext';

const resultCard = (props) => {
    // eslint-disable-next-line
    const [fixed, setFixed, stocks, setStocks] = useContext(AssetContext);

    return (
        <Card body>
            <Card.Title>
                Result card
            </Card.Title>

                <Row>
                    <Col>

                                        Compounding assets

                              //This doesn't render anything when fixed is updated in FixedCard.js
                                {fixed.map(asset => (

                                            ${asset.principle}

                                            total: ${asset.endValue}

))
                                }

                    </Col>
                    <Col>

                                        Stocks

                                        Ticker

                                        Fair price

                                        Discount price

                    </Col>
                </Row>

        </Card>
    );
}

export default resultCard;

To reiterate my question, How do I get resultCard to listen for changes in AssetContext?
Thanks

A: To listen to changes and then implementing a change, what i do is use useeffect where i have to listen to the change and make changes. For example you can pass the incoming response from the api as props to the component. In the child component you can use useEffect like this
  useEffect(() => {
       code here or change states, whichever you need to do
        })

    }, [props.responseIncomingFromParent])

Let me know if this works...

A: The answer given in another question was that I needed to spread the context variable into another constant and then use that one.
const fixedArr = [...fixed];

/* the code above*/

fixedArr.map(asset => {
    //the code you see above
    }
);


text:
Q: HttpClient SendAsync return unauthorized first request My login method logic is sending request to TokenController[AllowAnonymous] to get auth token then inject the auth token in to GetUser method by sending request to UserController[Authorized]. I tried the authorized endpoint on Postman, it works well. However, it always fails on the first request, I modified code just for testing that, if it return Unauthorized, resend the request, then it passes. I doubt that the first request httpClient.SendAsync loses the Authoriaztion headers. Anyone has suggestions?
public class LoginController : Controller
{
    private string GetToken(string username, string password)
    {
        using (var httpClient = new HttpClient())
        {
            var httpRequestMessage = new HttpRequestMessage
            {
                RequestUri = new Uri(_restServiceOptions.GetRestServiceUrl("/tokens")),
                Method = HttpMethod.Post
            };
            httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
            httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var tokenAuthentication = new DTO.TokenAuthentication
            {
                UsernameOrEmailAddress = username.Base64Encode(),
                Password = password.Base64Encode()
            };

            var deserializeObject = JsonConvert.SerializeObject(tokenAuthentication);

            httpRequestMessage.Content = new StringContent(deserializeObject, Encoding.UTF8, "application/json");

            using (var response = httpClient.SendAsync(httpRequestMessage).Result)
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var apiResponse = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                    var jwToken = apiResponse.GetValue("Data").ToObject<string>();
                    // Problem starts from here, look at the method GetAuthUser below
                    var user = RestHelper.GetAuthUser(RestServiceOptions restServiceOptions, string jsonWebToken);
                    if (user != null)
                    {
                        return user;
                    }
                    else
                    {
                        throw new Exception("User not found");
                    }
                }
            }
        }
    }
}

internal class RestHelper
{
    internal static DTO.User GetAuthUser(RestServiceOptions restServiceOptions, string jsonWebToken)
    {
    using (var httpClient = new HttpClient())
    {
        var httpRequestMessage = new HttpRequestMessage
        {
            RequestUri = new Uri(restServiceOptions.GetRestServiceUrl("/Users/GetJwtUser")),
            Method = HttpMethod.Get
        };
        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
        httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + jsonWebToken);
        // Always get unauthorized after the first time request sent by SendAsync
        using (HttpResponseMessage response = httpClient.SendAsync(httpRequestMessage).Result)
        {
            if (response.StatusCode == HttpStatusCode.OK)
            {
                var apiResponse = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                return apiResponse.GetValue("Data").ToObject<DTO.User>();
            }
            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                // Resend the request by GetAsync if unauthorized just for testing
                // This second time request sent, it passes
                var resendRes = httpClient.GetAsync(httpRequestMessage.RequestUri).Result;
                if (resendRes.IsSuccessStatusCode)
                {
                   var resendApiResponse = JObject.Parse(resendRes.Content.ReadAsStringAsync().Result);
                   var user = resendApiResponse.GetValue("Data").ToObject<DTO.User>();
                }

                throw new Exception("Unauthorized");
            }
            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                throw new Exception("NotFound");
            }
            if (response.StatusCode == HttpStatusCode.NotModified)
            {
                return null;
            }
        }
    }
    return null;
}


text:
Q: React Custom hooks - inheritance? I know that the whole point of react hooks are to get away from class based component and promote functional component.  However, is it possible to achieve inheritance in react hooks?
For example here, I create two hooks.
1. useEmailFormatValidator of which validates if input (onChange) is in valid Email format.
2. useEmailSignupValidator inherits useEmailFormatValidator but extends it's capability to verify user can use the username when (onBlur) event happens.
The whole point of these are useEmailFormatValidator can be used in log-in form where as useEmailSignupValidator can be used in sign-up form.
Below is my code
useEmailFormatValidator
import { useState } from 'react';

export const useEmailFormatValidator = () => {
  const [value, setValue] = useState('');
  const [validity, setValidity] = useState(false);

  const regex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

  const inputChangeHandler = event => {
    setValue(event.target.value.trim());
    if (regex.test(String(event.target.value.trim()).toLowerCase())) {
      setValidity(true);
    } else {
      setValidity(false);
    }
  };

  return { value: value, onChange: inputChangeHandler, validity };
};

useEmailSignupValidator
import { useState } from 'react';
import { useEmailFormatValidator } from "../auth";

export const useEmailSignupValidator = () => {
  const [value, setValue] = useState('');
  const [validity, setValidity] = useState(false);
  const emailFormatValidator = useEmailFormatValidator();

  const inputChangeHandler = event => {
    emailFormatValidator.onChange(event);
    setValue(emailFormatValidator.value);
    setValidity(emailFormatValidator.validity);
  };

  const verifyUserNameExists = event => {
    // Verify username is availble in back-end.
  };

  return { value: value, onChange: inputChangeHandler, onBlur: verifyUserNameExists, validity };
};

When I run a test, below does not work as expected and 'value' and 'validity' is undefined.
 const inputChangeHandler = event => {
    emailFormatValidator.onChange(event);
    setValue(emailFormatValidator.value);
    setValidity(emailFormatValidator.validity);
  };

Is there anyway to have inheritance in custom hooks?  Or how do you re-use code, of which is the purpose of react hooks?

A: This isn't really a custom hooks thing, imho. Why not do something like this?
const isValidEmail = email => {
    const regex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return regex.test(email);
};

const MyComponent = () => {
    const [inputVal, setInputVal] = useState('');

    return(
        <div>
            <input
                type='text'
                name='my-input'
                onChange={e => {
                    const email = e.target.value;
                    if(isValidEmail(email)){
                        setInputVal(email);
                    }else{
                        alert('invalid email')
                    }
                }}
            />
        </div>
    )
}


text:
Q: Index Json Document using Elasticsearch NEST C# I'm very new to Elasticsearch and Want to know How to create index and index following json document to Elasticsearch using NEST C#?
{
    "BookName": "Book1",
    "ISBN": "978-3-16-148410-0",
    "chapter" : [
        {
            "chapter_name": "Chapter1",
            "chapter_desc": "Before getting into computer programming, let us first understand computer programs and what they..."
        },
        {
            "chapter_name": "Chapter2",
            "chapter_desc": "Today computer programs are being used in almost every field, household, agriculture, medical, entertainment, defense.."
        },
        {
            "chapter_name": "Chapter3",
            "chapter_desc": "MS Word, MS Excel, Adobe Photoshop, Internet Explorer, Chrome, etc., are..."
        },
        {
            "chapter_name": "Chapter4",
            "chapter_desc": "Computer programs are being used to develop graphics and special effects in movie..."
        }
    ]
}

A: To create an index with NEST is as simple as
var client = new ElasticClient();
client.CreateIndex("index-name");

This will create an index with the default number of shards and replicas defined for the node.
To index a document represented as json into the index would be
var json = @"{
    ""BookName"": ""Book1"",
    ""ISBN"": ""978-3-16-148410-0"",
    ""chapter"" : [
        {
            ""chapter_name"": ""Chapter1"",
            ""chapter_desc"": ""Before getting into computer programming, let us first understand computer programs and what they...""
        },
        {
    ""chapter_name"": ""Chapter2"",
            ""chapter_desc"": ""Today computer programs are being used in almost every field, household, agriculture, medical, entertainment, defense..""
        },
        {
    ""chapter_name"": ""Chapter3"",
            ""chapter_desc"": ""MS Word, MS Excel, Adobe Photoshop, Internet Explorer, Chrome, etc., are...""
        },
        {
    ""chapter_name"": ""Chapter4"",
            ""chapter_desc"": ""Computer programs are being used to develop graphics and special effects in movie...""
        }
    ]
}";

var indexResponse = client.LowLevel.Index<string>("index-name", "type-name", json);

if (!indexResponse.Success)
    Console.WriteLine(indexResponse.DebugInformation);

Here we use the low level client to index json, available in NEST through the .LowLevel property on ElasticClient.
To search the indexed document would be
// refresh the index so that newly indexed documents are available
// for search without waiting for the refresh interval
client.Refresh("index-name");

var searchResponse = client.Search<dynamic>(s => s
    .Index("index-name")
    .Type("type-name")
    .Query(q => q
        .Match(m => m
            .Query("Photoshop")
            .Field("chapter.chapter_desc")
        )
    )
);

This returns the document indexed. The generic type parameter dynamic used in Search<T>() here means that the resulting documents will be deserialized to Json.Net JObject types.
When we created the index, we didn't specify a mapping for our type, type-name, so Elasticsearch inferred the mapping from the structure of the json document. This is dynamic mapping and can be useful for many situations however, if you know the structure of documents that you're going to be sending and it's not going to be destructively changed, then you specify a mapping for the type. The advantage of doing this in this particular example is that the chapter array will be inferred as an object type mapping, but if you wanted to search across both chapter name and chapter description of an individual chapter, then you probably want to map chapter as a nested type.


text:
Q: Exec run async function I know that I shouldn't use exec because it's insecure but the code it run comes from the same file and is a string. How can I use exec to run an async function? It always returns me SyntaxError: 'await' outside function if I try it.
Edit: This is the Code where I am using exec:
async def command_processor(guild):
    while True:
        commands = {"[1] - Bot Permissions abrufen" : "print_permissions(guild)",
                    "Derzeit nicht verwendbar - [2] - Invite zu Gilde erstellen (max Nutzungen pro Invite: 1)" : "await print_invite(guild)",
                    "[3] - Gebannte Benutzer auflisten (benötigt Berechtigung {Mitglieder bannen}" : "print_banned(guild)",
                    "[4] - Ausgewählten Server wechseln" : "change_guild()",
                    "[5] - Ausgewählten Bot wechseln" : "change_bot()",
                    "[6] - Beenden" : "sys.exit()"
            }
        print("\n\n--------------- Befehle ---------------\n")
        for i in range(len(commands.keys())):
            print(list(commands.keys())[i])
        sel = input()
        print()
        try:
            int(sel)
        except:
            print("Bitte hier nur die Zahl eingeben")
        if int(sel) in range(len(commands.keys())):
            exec(list(commands.values())[int(sel)-1])

A: You could do this, I think. The problem with exec is that it doesn't return anything, so you would need to use eval instead. I think this could work:
async def command_processor(guild):
    while True:
        commands = {"[1] - Bot Permissions abrufen" : "print_permissions(guild)",
                    "Derzeit nicht verwendbar - [2] - Invite zu Gilde erstellen (max Nutzungen pro Invite: 1)" : "await print_invite(guild)",
                    "[3] - Gebannte Benutzer auflisten (benötigt Berechtigung {Mitglieder bannen}" : "print_banned(guild)",
                    "[4] - Ausgewählten Server wechseln" : "change_guild()",
                    "[5] - Ausgewählten Bot wechseln" : "change_bot()",
                    "[6] - Beenden" : "sys.exit()"
            }

# ...

        if int(sel) in range(len(commands.keys())):
            await eval(list(commands.values())[int(sel)-1])

But there's no need to use eval here, and you have a lot to lose. A simple way could be to use a dict, something along the lines:
commands = {1: {"description": "[1] - Bot Permission abrufen", "command" : print_permissions, "args": [guild]},
# ...
}

for cmd in commands:
    print(cmd['description'])

# ...
selected_command = commands[sel]
await selected_command['command'](*selected_command['args'])

But it gets tricky, since sometimes you have a coroutine and sometimes a regular method. To get around that, I guess you could do this:
commands = {
    1: {"description": "[1] - Bot Permission abrufen", "exec" : print_permissions, "args": [guild]},
    2: {"description": "Derzeit nicht verwendbar - [2] - Invite zu Gilde erstellen (max Nutzungen pro Invite: 1)", "exec": print_invite, "args": [guild]},
# ...
}

for cmd in commands:
    print(cmd['description'])

# ...
selected_command = commands[sel]
if asyncio.iscoroutinefunction(selected_command['exec']):
    await selected_command['exec'](*selected_command['args'])
else:
    selected_command['exec'](*selected_command['args'])

On a final note: It make's me nervous that we now have the key that needs to pressed in two different places. This will lead to tears in the end, mark my words. I would do something like this:
commands = [
    {
        "description": "[{keynum}] - Bot Permission abrufen",
        "exec" : print_permissions, "args": [guild]
    },
    {
        "description": "Derzeit nicht verwendbar - [{keynum}] - Invite zu Gilde erstellen (max Nutzungen pro Invite: 1)",
        "exec": print_invite, "args": [guild]
    },
]

for keynum, command in enumerate(commands):
    print(command['description'].format(keynum=keynum))

I haven't tested that code, so there's probably a bug, but you get the idea.


text:
Q: Socket versus URL website access I have a Java application which opens an existing company's website using the Socket class:
Socket sockSite;
InputStream inFile = null;
BufferedWriter out = null;

try
{
    sockSite = new Socket( presetSite, 80 );
    inFile = sockSite.getInputStream();
    out = new BufferedWriter( new OutputStreamWriter(sockSite.getOutputStream()) );
}
catch ( IOException e )
{
    ...
}

out.write( "GET " + presetPath + " HTTP/1.1\r\n\r\n" );
out.flush();

I would read the website with the stream inFile and life is good.
Recently this started to fail. I was getting an HTTP 301 "site has moved" error but no moved-to link. The site still exists and responds using the same original HTTP reference and any web browser. But the above code comes back with the HTTP 301.
I changed the code to this:
URL url;
InputStream inFile = null;

try
{
    url = new URL( presetSite + presetPath );
    inFile = url.openStream();
}
catch ( IOException e )
{
    ...
}

And read the site with the original code from inFile stream and it now works again.
This difference doesn't just occur in Java but it also occurs if I use Perl (using IO::Socket::INET approach opening the website port 80, then issuing a GET fails, but using LWP::Simple method get just works). In other words, I get a failure if I open the web page first with port 80, then do a GET, but it works fine if I use a class which does it "all at once" (that just says, "get me web page with such-and-such an HTTP address").
I thought I'd try the different approaches on http://www.microsoft.com and got an interesting result. In the case of opening port 80, followed by issuing the GET /..., I received an HTTP 200 response with a page that said, "Your current user agent
In one case, I tried the "port 80" open followed by GET / on www.microsoft.com and I received an HTTP 200 response page that said, "Your current user agent appears to be from an automated process...". But if I use the second method (URL class in Java, or LWP in Perl) I simply get their web page.
So my question is: how does the URL class (in Java) or the LWP module (in Perl) do its thing under the hood that makes it different from opening the website on port 80 and issuing a GET?

A: If you use a packet capturing software to see what's being sent when URL is used, you'll realize that there's a lot more than just "GET /" being sent. All sorts of additional header information are included. If a server gets just a simple "GET /", it's easy to deduct that it can't be a very sophisticated client on the other end.
Also, HTTP 1.0 is "outdated", the current version is 1.1.

A: Java URL implementation delegates to HttpURLConnection if it starts with "http:"

A: Most servers require the Host: header, to allow virtual hosting (multiple domains on one IP)


text:
Q: conditional on last item in array using handlebars.js template I am leveraging handlebars.js for my templating engine and am looking to make a conditional segment display only if it is the last item in array contained in the templates configuration object.
{
  columns: [{<obj>},{<obj>},{<obj>},{<obj>},{<obj>}]
}

I've already pulled in a helper to do some equality/greater/less-than comparisons and have had success identifying the initial item this way but have had no luck accessing my target array's length.
Handlebars.registerHelper('compare', function(lvalue, rvalue, options) {...})

"{{#each_with_index columns}}"+
"
"+
"
"+
"{{/each_with_index}}"

Does anyone know a shortcut, different approach, and some handlebars goodness that will keep me from having to tear into the handlebars.js engine to determine best course?

A: If you just try to handle the first item of the array, this may help
{{#each data-source}}{{#if @index}},{{/if}}"{{this}}"{{/each}}
@index is provided by the each helper and for the first item, it would be equal to zero and thus can be handled by the if helper.

A: Since Handlebars 1.1.0, first and last has become native to the each helper. See ticket #483.
The usage is like Eberanov's helper class:
{{#each foo}}

{{@key}} - {{@index}}

{{/each}}

A:
As of Handlebars v1.1.0, you can now use the @first and @last booleans in the each helper for this problem:

{{#each foo}}

      {{@key}} - {{@index}}

{{/each}}

A quick helper I wrote to do the trick is:
Handlebars.registerHelper("foreach",function(arr,options) {
    if(options.inverse && !arr.length)
        return options.inverse(this);

    return arr.map(function(item,index) {
        item.$index = index;
        item.$first = index === 0;
        item.$last  = index === arr.length-1;
        return options.fn(item);
    }).join('');
});

Then you can write:
{{#foreach foo}}

{{/foreach}}

A: Solution:

Leveraging helpers from the following blog and gist...
https://gist.github.com/2889952
http://doginthehat.com.au/2012/02/comparison-block-helper-for-handlebars-templates/
// {{#each_with_index records}}
//
{{Name}}

// {{/each_with_index}}

Handlebars.registerHelper("each_with_index", function(array, fn) {
  var total = array.length;
  var buffer = "";

  //Better performance: http://jsperf.com/for-vs-foreach/2
  for (var i = 0, j = total; i < j; i++) {
    var item = array[i];

    // stick an index property onto the item, starting with 1, may make configurable later
    item.index = i+1;
    item.total = total;
    // show the inside of the block
    buffer += fn(item);
  }

  // return the finished buffer
  return buffer;

});

Handlebars.registerHelper('compare', function(lvalue, rvalue, options) {

    if (arguments.length < 3)
        throw new Error("Handlerbars Helper 'compare' needs 2 parameters");

    operator = options.hash.operator || "==";

    var operators = {
        '==':       function(l,r) { return l == r; },
        '===':      function(l,r) { return l === r; },
        '!=':       function(l,r) { return l != r; },
        '<':        function(l,r) { return l < r; },
        '>':        function(l,r) { return l > r; },
        '<=':       function(l,r) { return l <= r; },
        '>=':       function(l,r) { return l >= r; },
        'typeof':   function(l,r) { return typeof l == r; }
    }

    if (!operators[operator])
        throw new Error("Handlerbars Helper 'compare' doesn't know the operator "+operator);

    var result = operators[operator](lvalue,rvalue);

    if( result ) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }

});

Notice the starting index is correctly 1.

A: I made a little improvements in helper from Matt Brennan, you can use this helper with Objects or Arrays, this solution required Underscore library:
Handlebars.registerHelper("foreach", function(context, options) {
  options = _.clone(options);
  options.data = _.extend({}, options.hash, options.data);

  if (options.inverse && !_.size(context)) {
    return options.inverse(this);
  }

  return _.map(context, function(item, index, list) {
    var intIndex = _.indexOf(_.values(list), item);

    options.data.key = index;
    options.data.index = intIndex;
    options.data.isFirst = intIndex === 0;
    options.data.isLast = intIndex === _.size(list) - 1;

    return options.fn(item, options);
  }).join('');
});

Usage:
{{#foreach foo}}

{{@key}} - {{@index}}

{{/foreach}}

A: Just FYI: If you are stuck with Handlebars < 1.1.0 (like me) you might wann try this workaround:
Define a property like isLast on the objects you are iterating and use it like
{{#each objectsInList}}"{{property}}": "{{value}}"{{#unless isLast}},{{/unless}}{{/each}}
to build a JSON object.


text:
Q: Exibir imagem dentro da div Tenho uma div uma imagem.
Seria necessário exibir parte da imagem (centralizada, por exemplo) e diminuir o tamanho da div.
Se eu der um overflow hidden com width de 50% em alguma div acima da imagem, funciona, mas fica um buraco que não alinha o outro lado.
Seria possível diminuir a div sem diminuir a imagem?
Essa é a ideia original:

E isso o que perguntei:

.news-section .slide-item.right-margin {
  margin-right: 13px;
}

.news-section .slide-item.column-margin {
  padding-top: 10px;
  padding-bottom: 40px;
}

.news-section .slide-item .image-box {
  position: relative;
  display: table-cell;
}

figure {
  margin: 0;
}

a {
  text-decoration: none;
  cursor: pointer;
  color: #2681c3;
}

.news-section .slide-item .image-box img {
  border-radius: 5px;
}

.news-section .slide-item .image-box:after {
  position: absolute;
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
  content: '';
  border-radius: 5px;
  /* background: rgba(0, 0, 0, 0.3); */
}

.news-section .slide-item .date-box {
  position: absolute;
  width: 60px;
  height: 60px;
  right: 30px;
  top: 40px;
  background: #2681c3;
  z-index: 9;
  border-radius: 5px;
}

.news-section .slide-item .date-box h5 {
  font-size: 27px;
  font-family: 'Larsseit-Bold';
  line-height: 20px;
  color: #ffffff;
  margin-top: 10px;
  text-transform: uppercase;
}

.news-section .slide-item .date-box h5:before {
  color: #2681c3;
  content: "\f0da";
  font-family: FontAwesome;
  position: absolute;
  right: -8px;
  top: 10px;
  transition: all 500ms ease;
  -moz-transition: all 500ms ease;
  -webkit-transition: all 500ms ease;
  -ms-transition: all 500ms ease;
  -o-transition: all 500ms ease;
}

.news-section .slide-item .date-box h5 span {
  font-size: 15px;
  font-family: 'Larsseit-Thin';
  color: #ffffff;
}

.news-section .slide-item .inner-box {
  position: relative;
  display: table-cell;
  left: -20px;
  vertical-align: top;
  padding-top: 24px;
}

.news-section .slide-item .inner-box .info-outer {
  position: relative;
  /* padding: 30px 16px; */
  margin-right: -20px;
}

.corpo_blog {
  padding: 16px 16px 30px 16px;
  background: #ffffff;
  border-radius: 5px;
  border: 1px solid #e5e5e5;
}

.news-section .slide-item .inner-box .info-outer h5 {
  font-size: 20px;
  /* color: #2e2e2e; */
  letter-spacing: .5px;
  text-transform: uppercase;
  font-family: 'Larsseit-Bold';
  text-align: initial;
  display: -webkit-box;
  height: 44px;
  line-height: 22px;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.cor_titulos {
  color: #2e2e2e;
}

.news-section .inner-box .info-outer .link-btn {
  margin-top: 48px;
  text-align: right;
}

.news-section .inner-box .info-outer .link-btn a {
  line-height: 24px;
  text-transform: capitalize;
  transition: all 500ms ease;
  letter-spacing: .5px;
  font-family: 'Larsseit-Bold';
  font-size: 15px;
  text-align: right;
  color: #2681c3;
  text-transform: uppercase;
}

.news-section .inner-box .info-outer h6 {
  font-size: 17px;
  /* color: #2e2e2e; */
  margin-top: 10px;
  font-family: 'Larsseit-Light';
  text-align: initial;
  display: -webkit-box;
  height: 88px;
  line-height: 22px;
  -webkit-line-clamp: 4;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">

03
Jul

Carga de pneus avaliada em cerca de R$ 500 mil é recuperada pela PRF/AL

Um caminhão com carga avaliada em aproximadamente R$ 500 mil foi recuperado pela Polícia Rodoviária Federal (PRF/AL) na madrugada desta sexta-feira (29), nas proximidades do km 84 da BR-101, entrada da Empresa Britex Minerações, no município
                  de Rio Largo/AL. Segundo a PRF, houve intensa troca de tiros com os suspeitos que estavam com a carga, mas ninguém ficou ferido.Ainda de acordo com a polícia, a denúncia chegou através da Central de Informações, que recebeu uma ligação
                  da Empresa de Rastreamento informando que havia perdido o sinal de rastreamento de um dos seus veículos. Ao receberem a informação, as equipes se deslocaram para averiguação.Ao chegarem ao local, o caminhão estava com as portas abertas,
                  o motorista sendo mantido refém por um indivíduo armado e outros retirando a carga do veículo. Quando perceberem a chegada das viaturas, os assaltantes começaram a efetuar disparos de arma de fogo em direção aos policiais, que revidaram
                  a agressão. Após a troca de tiros, os assaltantes fugiram em direção a um matagal.O motorista do caminhão informou à polícia que foi rendido por três homens armados em um posto de combustível localizado às margens da BR-101, no município
                  de Messias/AL. Ele informou ainda que, na ocasião, havia outro veículo dando cobertura.A mercadoria que estava sendo transportada - cerca de 550 pneus - foi recuperada intacta. Além disso, um aparelho utilizado pelos assaltantes para
                  bloquear o sinal de rastreamento do veículo foi apreendido pelos policiais. O veículo recuperado e o aparelho apreendido, bem como a vítima, um senhor de 56 anos, foram encaminhados à Delegacia de Roubos e Furtos de veículos em Maceió.

              saiba mais

A: Rogério pelo que entendi é que quando vc coloca a imagem menor fica um espaço em brando entre a imagem e o box com a informação correto? Se for isso acho que esse css abaixo pode te ajudar.
Mas independente disso vc vai ter que pensar bem nessa estrutura para ela funcionar de forma responsiva direito. Vc poderia ter usado display:flex em vez de colocar display:table-cell que acredito estar dificultando as coisas...
O modelo que fiz foi tipo pegando a tag
 e colocando nela uma largura em PX (só consegui fazer funcionar assim para mexer o mínimo possível no seu css) com o Overflow:hidden. Também coloquei um transform:translateX(-25%) pra vc controlar qual parte da imagem vai querer mostrar.

     .news-section .slide-item.right-margin {
      margin-right: 13px;
    }

    .news-section .slide-item.column-margin {
      padding-top: 10px;
      padding-bottom: 40px;
    }

    .news-section .slide-item .image-box {
      position: relative;
      display: table-cell;
    }

    figure {
      margin: 0;
    }

    a {
      text-decoration: none;
      cursor: pointer;
      color: #2681c3;
    }

    .news-section .slide-item .image-box img {
      border-radius: 5px;
    }

    .news-section .slide-item .image-box:after {
      position: absolute;
      top: 0px;
      left: 0px;
      right: 0px;
      bottom: 0px;
      content: '';
      border-radius: 5px;
      /* background: rgba(0, 0, 0, 0.3); */
    }

    .news-section .slide-item .date-box {
      position: absolute;
      width: 60px;
      height: 60px;
      right: 30px;
      top: 40px;
      background: #2681c3;
      z-index: 9;
      border-radius: 5px;
    }

    .news-section .slide-item .date-box h5 {
      font-size: 27px;
      font-family: 'Larsseit-Bold';
      line-height: 20px;
      color: #ffffff;
      margin-top: 10px;
      text-transform: uppercase;
    }

    .news-section .slide-item .date-box h5:before {
      color: #2681c3;
      content: "\f0da";
      font-family: FontAwesome;
      position: absolute;
      right: -8px;
      top: 10px;
      transition: all 500ms ease;
      -moz-transition: all 500ms ease;
      -webkit-transition: all 500ms ease;
      -ms-transition: all 500ms ease;
      -o-transition: all 500ms ease;
    }

    .news-section .slide-item .date-box h5 span {
      font-size: 15px;
      font-family: 'Larsseit-Thin';
      color: #ffffff;
    }

    .news-section .slide-item .inner-box {
      position: relative;
      display: table-cell;
      left: -20px;
      vertical-align: top;
      padding-top: 24px;
    }

    .news-section .slide-item .inner-box .info-outer {
      position: relative;
      /* padding: 30px 16px; */
      margin-right: -20px;
    }

    .corpo_blog {
      padding: 16px 16px 30px 16px;
      background: #ffffff;
      border-radius: 5px;
      border: 1px solid #e5e5e5;
    }

    .news-section .slide-item .inner-box .info-outer h5 {
      font-size: 20px;
      /* color: #2e2e2e; */
      letter-spacing: .5px;
      text-transform: uppercase;
      font-family: 'Larsseit-Bold';
      text-align: initial;
      display: -webkit-box;
      height: 44px;
      line-height: 22px;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .cor_titulos {
      color: #2e2e2e;
    }

    .news-section .inner-box .info-outer .link-btn {
      margin-top: 48px;
      text-align: right;
    }

    .news-section .inner-box .info-outer .link-btn a {
      line-height: 24px;
      text-transform: capitalize;
      transition: all 500ms ease;
      letter-spacing: .5px;
      font-family: 'Larsseit-Bold';
      font-size: 15px;
      text-align: right;
      color: #2681c3;
      text-transform: uppercase;
    }

    .news-section .inner-box .info-outer h6 {
      font-size: 17px;
      /* color: #2e2e2e; */
      margin-top: 10px;
      font-family: 'Larsseit-Light';
      text-align: initial;
      display: -webkit-box;
      height: 88px;
      line-height: 22px;
      -webkit-line-clamp: 4;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    figure {
      max-width: 325px;
      overflow: hidden;
    }
    figure a img {
      transform: translateX(-25%);
    }
  <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />

03
Jul

Carga de pneus avaliada em cerca de R$ 500 mil é recuperada pela PRF/AL

Um caminhão com carga avaliada em aproximadamente R$ 500 mil foi recuperado pela Polícia Rodoviária Federal (PRF/AL) na madrugada desta sexta-feira (29), nas proximidades do km 84 da BR-101, entrada da Empresa Britex Minerações, no município
                      de Rio Largo/AL. Segundo a PRF, houve intensa troca de tiros com os suspeitos que estavam com a carga, mas ninguém ficou ferido.Ainda de acordo com a polícia, a denúncia chegou através da Central de Informações, que recebeu uma ligação
                      da Empresa de Rastreamento informando que havia perdido o sinal de rastreamento de um dos seus veículos. Ao receberem a informação, as equipes se deslocaram para averiguação.Ao chegarem ao local, o caminhão estava com as portas abertas,
                      o motorista sendo mantido refém por um indivíduo armado e outros retirando a carga do veículo. Quando perceberem a chegada das viaturas, os assaltantes começaram a efetuar disparos de arma de fogo em direção aos policiais, que revidaram
                      a agressão. Após a troca de tiros, os assaltantes fugiram em direção a um matagal.O motorista do caminhão informou à polícia que foi rendido por três homens armados em um posto de combustível localizado às margens da BR-101, no município
                      de Messias/AL. Ele informou ainda que, na ocasião, havia outro veículo dando cobertura.A mercadoria que estava sendo transportada - cerca de 550 pneus - foi recuperada intacta. Além disso, um aparelho utilizado pelos assaltantes para
                      bloquear o sinal de rastreamento do veículo foi apreendido pelos policiais. O veículo recuperado e o aparelho apreendido, bem como a vítima, um senhor de 56 anos, foram encaminhados à Delegacia de Roubos e Furtos de veículos em Maceió.

                  saiba mais


text:
Q: Power series solutions
Construct two linearly independent, power series solutions to the ODE
  $$u''+zu'+u=0.$$
  Hence find the solution which satisfies $u(0)=1$ and $u'(0)=1.$

I have come up with the solution for the coeffecient, however I am not sure why we multiply them with $z^2$ instead of $z.$

A: Let us consider your differential equation:
$$\frac{d^2u(z)}{dz^2}+z\cdot\frac{du(z)}{dz}+u(z)=0$$
Apply the reverse product rule:
$$\frac{d}{dz}\frac{du(z)}{dz}+\frac{d}{dz}(z\cdot u(z))=0$$
Integrate with respect to $z$:
$$\int\frac{d}{dz}\left(\frac{du(z)}{dz}+z\cdot u(z)\right) dz=0$$
$$\frac{du(z)}{dz}+z\cdot u(z)=C_1$$
Multiply on both sides by $e^{\frac{z^2}{2}}$:
$$e^{\frac{z^2}{2}}\cdot\frac{du(z)}{dz}+z\cdot e^{\frac{z^2}{2}}\cdot u(z)=C_1\cdot e^{\frac{z^2}{2}}$$
Recognize that $z\cdot e^{\frac{z^2}{2}}=\frac{d}{dz}\left(e^{\frac{z^2}{2}}\right)$ and apply the reverse product rule:
$$\frac{d}{dz}\left(e^{\frac{z^2}{2}}\cdot u(z)\right)=C_1\cdot e^{\frac{z^2}{2}}$$
Integrate with respect to $z$:
$$\int\frac{d}{dz}\left(e^{\frac{z^2}{2}}\cdot u(z)\right) dz=\int C_1\cdot e^{\frac{z^2}{2}} dz$$
$$e^{\frac{z^2}{2}}\cdot u(z)=C_1\cdot\sqrt{\frac{\pi}
{2}}\cdot \text{erfi}\left(\frac{z}{\sqrt{2}}\right)+C_2$$
Multiply on both sides by $e^{-\frac{z^2}{2}}$:
$$u(z)=C_1\cdot\sqrt{\frac{\pi}{2}}\cdot \text{erfi}\left(\frac{z}{\sqrt{2}}\right)\cdot e^{-\frac{z^2}{2}}+C_2\cdot e^{-\frac{z^2}{2}}$$
The first derivative is given by
$$\frac{du(z)}{dz}=C_1-C_1\cdot \sqrt{\frac{\pi}{2}}\cdot \text{erfi}\left(\frac{z}{\sqrt{2}}\right)\cdot z \cdot e^{-\frac{z^2}{2}}-C_2\cdot z \cdot e^{-\frac{z^2}{2}} $$
Apply conditions:
$$u(0)=1\rightarrow u(0)=C_2\rightarrow C_2 =1$$
$$u'(0)=1\rightarrow u'(0)=C_1\rightarrow C_1=1$$
Thus, a solution is given by
$$u(z)=\sqrt{\frac{\pi}{2}}\cdot \text{erfi}\left(\frac{z}{\sqrt{2}}\right)\cdot e^{-\frac{z^2}{2}}+e^{-\frac{z^2}{2}}$$


text:
Q: Changing PHP version wamp I've been asked to change my PHP environement locally for a project so that go from PHP 5.6 to PHP 7 (or higher).
So I've changed the PHP version of my wamp but it doesn't show any error it just says :

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

I'd like to know how can I display errors so that I can start to change stuff in the code.
Configuration of php.ini :
error_reporting = E_ALL

Thanks a lot


text:
Q: How to retrieve model ID when creating new? Using Backbone.JS, I am able to successfully create new models and save them to the server.  They successfully make an ajax call and the subscribed UI elements update appropriately.  The problem I then run into is that I don't know the ID of the newly created object.
I can see in the response headers for my create calls, that the sever is returning a location header like:  Location   https://localhost/rest/beta/mobile/footer/OTo3Njow with the last parameter being the newly created ID.
How can I get this ID without overriding backbone.sync?  If I have to override backbone.sync, what is the cleanest method?
UPDATE
It looks like my organization is using an older Backbone.js in which the parse method of models does not provide a reference to the XHR object, otherwise I could catch the ID and do the assigning there.

A: The server should send back a JSON object containing the id of the model, plus any other attributes that it wants to update. If it does, Backbone will automatically grab the id.
If that's not an option, you should override Backbone.sync, because then your API (which communicates the new id in the location header instead of the response body) doesn't conform to what Backbone supports out of the box.

If the server already does this, and you just want to get at the id, it depends on who needs to know. If it's the code calling model.save(), then it can pass in a success callback:
model.save({}, {
    success: function(){
        // do something with model.id
    }
});

If the model itself needs to be notified when it gets an id, you can use an initializer:
var MyModel = Backbone.Model.extend({
    initialize: function(){
        this.bind("change:id", function(){
            // …
        });
    }
});

A: I solved this by overloading the success param in backbone.sync
// Return XHR on success
params.success = function(response, text, XHR) {
  if(_.isFunction(model.xhrParse)) { model.xhrParse.call(model, response, XHR); }
  success.call(model, response);
}

and by adding a new method to my base model "xhrParse":
xhrParse: function(resp, XHR) {
   var locationHeader = XHR.getResponseHeader('Location');
   if(locationHeader && !this.id) {
     var xplode = locationHeader.split("/");
     this.id = xplode[xplode.length - 1];
   }
   return resp;
 }

A: http://documentcloud.github.com/backbone/#Model-id
The model.id property?


text:
Q: How to implement logout with custom authentication routes in ServiceStack Simple question, I've got the code below to specify the routes for my user authentication using a custom CredentialsAuthProvider (put together using what I found in the documentation)
// inside 'Configure()'....
Dictionary<Type, string[]> serviceRoutes = new Dictionary<Type, string[]>();
serviceRoutes.Add(typeof(AuthService), new[] { "/user/auth" });
AuthFeature authFeature = new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
    new myCompany.web.JSONService.myCompanyCredentialsAuthProvider()
});
authFeature.IncludeAssignRoleServices = false;
authFeature.ServiceRoutes = serviceRoutes; //specify manual auth routes
Plugins.Add(authFeature);

which creates a route of /user/auth, what I'd also like is a route like this :
/user/logout

but there is very little in the documentation about logout functionality. Is this a custom route I have to build into my service like all my other API calls, or is there a configuration option I can use?
Also, i'm currently using the swagger plugin to document and test my service, but it shows me the /user/auth route as 'get' enabled, I'd like to restrict it to 'post' verb only, if that's possible? Secondary question, mostly want to know correct way to implement logout

A: The AuthFeature creates a route at /auth/logout and you can hit it with a GET or POST to log out


text:
Q: Android calendar view date color I have a list of dates that I want to color in red on calendarview .
how can I do ?
my activity..
public class Calendario extends Activity {

    RelativeLayout rl;
    final Calendar calendar = Calendar.getInstance();
    CalendarView cal;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.calendar);

        rl = (RelativeLayout) findViewById(R.id.rl);
        cal = new CalendarView(Calendario.this);

        rl.addView(cal);
        cal.setOnDateChangeListener(new OnDateChangeListener() {

        @Override
        public void onSelectedDayChange(CalendarView view, int year, int month,
                int dayOfMonth) {
            // TODO Auto-generated method stub

        }
    });
    }

}

What code i've to add in order to color a date ?

A: Your best bet might be to create your own CalendarView class i.e. CalendarViewCustom based on the source code found here.
You could then add an extra method to the LegacyCalendarViewDelegate class similar to the setFocusedMonthDateColor() method to iterate through the weeks and set a date and colour in the WeekView class (might be worth storing these key/value date/colours as an Map collection instance variable in the WeekView class). e.g.
public void setMonthDateColor(Date date, int color) {
    final int childCount = mListView.getChildCount();
    for (int i = 0; i < childCount; i++) {
        WeekView weekView = (WeekView) mListView.getChildAt(i);
        if (weekView.isDateInWeek(date)) {
            //this method adds the date and colour to a
            //Map collection in weekView Object
            weekView.setDateColour(date, color);
        }
    }
}

The above method then needs to be exposed by adding another method to the parent class CalendarViewCustom (similar to its existing methods) which can then be called on an instance of the class i.e.
public int setMonthDateColor(Date date, int color) {
    return mDelegate.getMonthDateColor(date, color);
}

All you need to do then is draw the listed colours on the canvas in the WeekView class method called drawWeekNumbersAndDates() for the specified dates using the existing for loop ( for (; i < nDays; i++) ) and iterate over the Map and change the paint colour for the date text i.e. mMonthNumDrawPaint.setColor().
Hope this points you in the right direction.

A: Try this. Hope this helps
android:weekDayTextAppearance="@style/CalendarWeekDateText"

<style name="CalendarWeekDatText" parent="TextAppearance.AppCompat.Button">
    <item name="android:textColor">#000000</item>
</style>

A: android:theme="@style/testTheme"

Use this theme or a custom theme which has parent as this theme.
To make it white
To Choose other than white change the color use the following
android:textColorPrimary="@color/yourColor"

for other text colors use the following
android:weekDayTextAppearance="@style/weekDayTextAppearance"
    android:dateTextAppearance="@style/appTextAppearance"
    android:unfocusedMonthDateColor="@color/colorLoginBtn"
    android:selectedWeekBackgroundColor="@color/colorLoginBtn"
    android:weekSeparatorLineColor="@color/colorLoginBtn"
    android:focusedMonthDateColor="@color/colorLoginBtn"
    android:weekNumberColor="@color/colorLoginBtn"


text:
Q: Java equals and hashCode methods - technical constraints I've got question about java's equals(Object o) and hashCode() methods. What are the technical constraints of implementation this both methods? Is there something that I can't do during implement this methods?

A: None. It's just two methods in Object class. You could even change an object's state within this methods and this will freak out every developer and system but it's still valid from technical point of view.

A: You can technically anything inside them you can do in any other methods.
Instead what you concern yourself with are the practical and contractual obligations of the methods.
Good rules of thumb:

*

*If you override one, override the other.

*Variables used in one should be used in the other.

A: a given object must consistently report the same hash value
two objects which equals() says are equal must report the same hash value - so no timestamps in the hashcode :).
Two unequal objects can also have the same hashcode, though it is better to make the hashcode difficult to repoduce.

A: All you need to remember, is:

*

*those constrains are very important

*all are very well documented in javadoc for Object.hashCode() and Object.equals()
Make sure you understand it every time you override any of those methods.

A:
Is there something that I can't do during implement this methods?

Well, as a rule of thumb (and as already @RHT mentioned above and @Antti Sykäri explains here) do your future self a favor and always use EqualsBuilder and HashCodeBuilder from the Apache Commons Lang library. Because, quite frankly, at least in my case I never get to remember all the nitty-gritty details that a correct implementation would require. ;-)


text:
Q: Prove: If tournament $T$ is transitive, then every two vertices of $T$ have distinct outdegrees. Here is a proof of the above statement that I would like to verify. I would like to know any possible errors or improvements possible.
Proof: Suppose tournament $T$ is transitive. Let $x$ and $y$ be any two vertices of $T$ and assume, without loss of generality, $(x,y)$ is an arc in $T$. Now let $U$ be the set of all vertices in $T$ that are adjacent from vertex $y$. Then it follows that $U$={$u \in V(T)$ | $(y,u)$ is an arc in $T$}, and the $outdegree (y) = |U|$. For each $u \in U$, the tansitivity in T implies that $(x,u)$ is an are in $T$. Thus the $outdegree(x) \ge |U|+1 \gt outdegree(y)$ and it is clear then that every two veritces of $T$ have distinct outdegrees.


text:
Q: Android number input with plus and minus sign I am developing in Android and I would like an input field for numbers, where the user can select the correct number using the plus sign at the top and the minus sign at the bottom of the input field. I know this works for DatePicker. Is there some property or something similar to make this available for any integer number input field?
Thanks

A: NumberPicker is now available in Android SDK. (Added in API level 11)
http://developer.android.com/reference/android/widget/NumberPicker.html

A: I've just released some code that does just what you want. Check out my custom control, NumberPicker, which can be seen here:
http://www.technologichron.net/?p=42

A: As far as I know, there's no built-in widget for doing this.  You'd have to write your own.  Here's the source for DatePicker - you can use it for inspiration.

A: The open source number picker project found here:
https://github.com/mrn/numberpicker
does precisely what is requested

A: Maybe useful:
http://groups.google.com/group/android-developers/browse_thread/thread/65da9820998fddc9


text:
Q: Simulating multiple regression data with fixed R2: How to incorporate correlated variables? I'd like to simulate data for a multiple linear regression with four predictors where I am free to specify

*

*the overall explained variance of the model

*the magnitude of all standardized regression coefficients

*the degree to which the predictor variables are correlated with each other

I arrived at a solution that fulfills the first two points but is based on the assumption that all independent variables are not related to each other (see code below). In order to get standardized regression coefficients, I sample from population variables with mean=0 and variance=1.
# Specify population variance/covariance of four predictor variables that is sampled from
sigma.1 <- matrix(c(1,0,0,0,
                    0,1,0,0,
                    0,0,1,0,
                    0,0,0,1),nrow=4,ncol=4)
# Specify population means of four predictor varialbes that is sampled from
mu.1 <- rep(0,4)

# Specify sample size, true regression coefficients, and explained variance
n.obs <- 50000 # to avoid sampling error problems
intercept <- 0.5
beta <- c(0.4, 0.3, 0.25, 0.25)
r2 <- 0.30

# Create sample with four predictor variables
library(MASS)
sample1 <- as.data.frame(mvrnorm(n = n.obs, mu.1, sigma.1, empirical=FALSE))

# Add error variable based on desired r2
var.epsilon <- (beta[1]^2+beta[2]^2+beta[3]^2+beta[4]^2)*((1 - r2)/r2)
sample1$epsilon <- rnorm(n.obs, sd=sqrt(var.epsilon))

# Add y variable based on true coefficients and desired r2
sample1$y <- intercept + beta[1]*sample1$V1 + beta[2]*sample1$V2 +
beta[3]*sample1$V3 + beta[4]*sample1$V4 + sample1$epsilon

# Inspect model
summary(lm(y~V1+V2+V3+V4, data=sample1))

Call:
lm(formula = y ~ V1 + V2 + V3 + V4, data = sample1)

Residuals:
    Min      1Q  Median      3Q     Max
-4.0564 -0.6310 -0.0048  0.6339  3.7119

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.496063   0.004175  118.82   <2e-16 ***
V1          0.402588   0.004189   96.11   <2e-16 ***
V2          0.291636   0.004178   69.81   <2e-16 ***
V3          0.247347   0.004171   59.30   <2e-16 ***
V4          0.253810   0.004175   60.79   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.9335 on 49995 degrees of freedom
Multiple R-squared:  0.299, Adjusted R-squared:  0.299
F-statistic:  5332 on 4 and 49995 DF,  p-value: < 2.2e-16

Problem: If my predictor variables are correlated, so if their variance/covariance matrix is specified without the off-diagonal elements being 0, the r2 and regression coefficients differ largely from how I want them to be, e.g. by using
sigma.1 <- matrix(c(1,0.25,0.25,0.25,
                    0.25,1,0.25,0.25,
                    0.25,0.25,1,0.25,
                    0.25,0.25,0.25,1),nrow=4,ncol=4)

Any suggestions?
Thanks!

A: After thinking about my problem a bit more,  I found an answer.
The code above first samples the predictor variables with a given degree of correlation among each other. Then a column for the error is added based on the desired value of r2. Then with all of that together a column for y is added.
So far, the line that creates the error is just
var.epsilon <- (beta[1]^2+beta[2]^2+beta[3]^2+beta[4]^2)*((1 - r2)/r2)
sample1$epsilon <- rnorm(n.obs, sd=sqrt(var.epsilon))

So it assumes that every beta coefficient contributes 100% to the explanation of y (=no interrelation of independent variables). But if x-variables are related, every beta is not(!) contributing 100%. That means the variance of the error has to be bigger, because the variables take some variability from each other.
How much bigger? Just adapt the creation of the error term like follows:
var.epsilon <- (beta[1]^2+beta[2]^2+beta[3]^2+beta[4]^2+cor(sample1$V1, sample1$V2))*((1 - r2)/r2)

So the degree to which the independent variables are correlated is just added to the error variance by adding cor(sample1$V1, sample1$V2). In the case of the interrelation being 0.25, e.g. by using
sigma.1 <- matrix(c(1,0.25,0.25,0.25,
                0.25,1,0.25,0.25,
                0.25,0.25,1,0.25,
                0.25,0.25,0.25,1),nrow=4,ncol=4)

cor(sample1$V1, sample1$V2) resembles 0.25 and this value is added to the variance of the error term.
Assuming that all interrelations are equal, like this, any degree of interrelation among the independent variables can be specified, together with the true standardized regression coefficients and an desired R2.
Proof:
sigma.1 <- matrix(c(1,0.35,0.35,0.35,
                    0.35,1,0.35,0.35,
                    0.35,0.35,1,0.35,
                    0.35,0.35,0.35,1),nrow=4,ncol=4)
# Specify population means of four predictor varialbes that is sampled from
mu.1 <- rep(0,4)

# Specify sample size, true regression coefficients, and explained variance
n.obs <- 500000 # to avoid sampling error problems
intercept <- 0.5
beta <- c(0.4, 0.3, 0.25, 0.25)
r2 <- 0.15

# Create sample with four predictor variables
library(MASS)
sample1 <- as.data.frame(mvrnorm(n = n.obs, mu.1, sigma.1, empirical=FALSE))

# Add error variable based on desired r2
var.epsilon <- (beta[1]^2+beta[2]^2+beta[3]^2+beta[4]^2+cor(sample1$V1, sample1$V2))*((1 - r2)/r2)
sample1$epsilon <- rnorm(n.obs, sd=sqrt(var.epsilon))

# Add y variable based on true coefficients and desired r2
sample1$y <- intercept + beta[1]*sample1$V1 + beta[2]*sample1$V2 +
  beta[3]*sample1$V3 + beta[4]*sample1$V4 + sample1$epsilon

# Inspect model
summary(lm(y~V1+V2+V3+V4, data=sample1))

> summary(lm(y~V1+V2+V3+V4, data=sample1))

Call:
lm(formula = y ~ V1 + V2 + V3 + V4, data = sample1)

Residuals:
     Min       1Q   Median       3Q      Max
-10.7250  -1.3696   0.0017   1.3650   9.0460

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.499554   0.002869  174.14   <2e-16 ***
V1          0.406360   0.003236  125.56   <2e-16 ***
V2          0.298892   0.003233   92.45   <2e-16 ***
V3          0.247581   0.003240   76.42   <2e-16 ***
V4          0.253510   0.003241   78.23   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.028 on 499995 degrees of freedom
Multiple R-squared:  0.1558,    Adjusted R-squared:  0.1557
F-statistic: 2.306e+04 on 4 and 499995 DF,  p-value: < 2.2e-16

A: Here is my solution. It is more general than the previous:
M <- t(as.matrix(beta)) * sample1[1:length(beta)]
var.epsilon <- sum(cov(M))*(1 - r2)/r2

sample1$epsilon <- rnorm(n.obs, sd=sqrt(var.epsilon))

# Add y variable based on true coefficients and desired r2
sample1$y <- intercept + M + sample1$epsilon

# Inspect model
summary(lm(y~V1+V2+V3+V4, data=sample1))

Lion Beherns's answer starts in the right direction but it is mathematically wrong, and it is also less general than it could be.
var.epsilon, the variance of the error term equals the sum of the variances and covariances of the predictor variables times their coefficients.  None of the existing answers get this right. Instead, they assume the variances of the predictors equals 1 and sum their squares and then add the correlations (not the covariance).
To help understand how my solution relates to the previous. I'll share a more verbose implementation:
# this matrix has to be positive definite, but doesn't have to have constant off the diagonal and doesn't have to have 1s on the diagonal.
sigma.1 <- matrix(c(1,0.12,0.23,0.7,
                    0.35,1,0.02,0.15,
                    0.35,0.35,1,0.3,
                    0.5,0.35,0.35,1),nrow=4,ncol=4)
# Specify population means of four predictor variables that is sampled from
mu.1 <- rep(0,4)

# Specify sample size, true regression coefficients, and explained variance
n.obs <- 500000 # to avoid sampling error problems
intercept <- 0.5
beta <- c(0.4, 0.3, 0.25, 0.25)
r2 <- 0.15

# Create sample with four predictor variables
library(MASS)
sample1 <- as.data.frame(mvrnorm(n = n.obs, mu.1, sigma.1, empirical=FALSE))

# Add error variable based on desired r2
var.epsilon <- (var(beta[1]*sample1$V1) +
var(beta[2]*sample1$V2)+var(beta[3]*sample1$V3)+var(beta[4]*sample1$V4)+
2*cov(beta[1]*sample1$V1, beta[2]*sample1$V2) +
2*cov(beta[1]*sample1$V1, beta[3]*sample1$V3) +
2*cov(beta[1]*sample1$V1,beta[4]*sample1$V4) +
2*cov(beta[2]*sample1$V2,beta[3]*sample1$V3) +
2*cov(beta[2]*sample1$V2, beta[4]*sample1$V4) +
2*cov(beta[3]*sample1$V3,beta[4]*sample1$V4))*((1 - r2)/r2)

sample1$epsilon <- rnorm(n.obs, sd=sqrt(var.epsilon))

# Add y variable based on true coefficients and desired r2
sample1$y <- intercept + beta[1]*sample1$V1 + beta[2]*sample1$V2 +
  beta[3]*sample1$V3 + beta[4]*sample1$V4 + sample1$epsilon

# Inspect model
summary(lm(y~V1+V2+V3+V4, data=sample1))

This way of calculating var.epsilon is super verbose and inefficient. We can improve that with some linear algebra.


text:
Q: Pros and Cons of Various Function Scopes/Event Binds in JavaScript/jQuery What are the pros and cons of the following function scopes:
Global Function/Inline JS

<script>
    function funcA() {
        //do something
    }
</script>
<button id="buttA" onclick="funcA();">Click Me</button>

Global Function/Non-inline JS

<script>
    function funcA() {
        //do something
    }
    $(function() {
        $('#buttA').on('click', funcA);
    });
</script>
<button id="buttA">Click Me</button>

Non-global Function/Non-inline JS

<script>
    $(function() {
        $('#buttA').on('click', funcA);
        function funcA() {
            //do something
        }
    });
</script>
<button id="buttA">Click Me</button>

Which combination is better and why?

A: I think the big argument to not use global variables comes with the nature of web collaboration. If you're build a site-wide script, and you have a team of lets say two others working on plugins, you don't want your variables to be overwritten or invoked by your collaborators. Additionally, having people consistently asking you to provide them with a list of your program variables and functions is going to slow everything down.
/* Private namespace */
(function () {

   var sum_1 = 10;
   var sum_2 = 20;

   var myFunction = function (x, y) {
      return x * y;
   };

   myFunction(sum_1, sum_2);

})();


text:
Q: How to replace first n occurrences of a character for each line? Suppose, I have
type,type,type,type,description,description,description.
type,type,type,type,description,description.

I want to -
type|type|type|type|description,description,description.
type|type|type|type|description,description.

Where I have no I idea about the content of the file. Just I know that I have to substitute first n occurrence of , with | for each line.

A: Nothing sofisticated but it get's the job done
:%norm f,r|;.;.;.

breakdown
:%norm       start a normal command on all lines
f,r|        f(ind) a ',' and r(eplace) with '|'
;.;.;.      ';' jumps to next match and '.' repeats the change

A: I guess it could solve your problem
:%s/\v(type)./\1|/g

\v ......... very magic to avoid "\"
(type) ..... group 1
.   ........ any char (in our case ,)
\1 ......... back reference to group 1
| .......... literal |

A: Use a macro.
Create a macro. Repeat it on all lines. Done.


text:
Q: R: shinyMobile - f7DatePicker not Working on iPad Apologies if I am missing any basic information. But, I am using shinyMobile to develop a mobile data collection interface on an iPad. I am experiencing that f7DatePicker is not responding on the iPad. I checked the same code on an iPhone8 with 13.3.1 (software version) and it is working. However, f7Stepper and f7checkBox widgets are working on the iPad. The specifications on the iPad are referred to below,
Device: iPad-Pro(12.9)
Model: ML0N2B/A
Software Version: iPadOS 13.5
Is this an expected issue? Hoping for any feedback to resolve issue.
Thanks


text:
Q: passing 'const this argument discards qualifiers [-fpermissive] I have a class Cache which has a function write specified as
bool write(const MemoryAccess &memory_access, CacheLine &cl);

I am calling this function like this.
const Cache *this_cache;
c = (a==b)?my_cache:not_cache;
c->write(memory_access,cl);

The above line is giving me following error

"passing 'const Cache' as 'this' argument of 'bool Cache::write(const
  MemoryAccess&, CacheLine&)' discards qualifiers [-fpermissive]."

the this argument is compiler specific which helps in code-mangling and breaking local namespace variable priority. But such a variable is not being passed here.

A: Since c is of type const Cache *, you can only call const member functions on it.
You have two options:
(1) remove const from the declaration of c;
(2) change Cache::write() like so:
 bool write(const MemoryAccess &memory_access, CacheLine &cl) const;

(Note the added const at the end.)

A: When you call a method via a pointer to an object, this object is implicitly passed to the method as this pointer. c probably has type const Cache*. Since method write is not declared as const, it has non-const this pointer accessible from its body requiring const qualifier of c to be discarded.

A: Also if your class's method returns pointer on any member you shouldn't forget write const before returning type example:

const float * getPosition() const{...}


text:
Q: How to render a part of QGraphicsScene and save It as image file PyQt5 Suppose I have QGraphicsPixmapItem from loaded image which is added to QGraphicsScene. And suppose I'll add several QGraphicsPolygonItem's on scene. How I can render a part of the scene as full-size image both with polygons that are not in blank area and save this area as image file.
class ImageView(QtWidgets.QGraphicsView):

    def __init__(self, parent):
        super(ImageView, self).__init__(parent)
        self.setFocus()
        self._zoom = 0
        self._empty = True
        self.scene = QtWidgets.QGraphicsScene(self)
        self._image = QGraphicsPixmapItem()
        self.scene.addItem(self._image)
        self.setScene(self.scene)

        # some other actions
        foo()

    def fitInView(self):
        # custom fit in view and scaling
        bar()

    # some other methods

class MainWindow(QtWidgets.QWidget):
    def __init__(self):
        self.viewer = ImageView(self)
        foo()

    def _save_image(self):
        # method that I need to implement
        pass

A: Untested, but using QGraphicsScene::render you should be able to do something like...
def _save_image(self):

    # Get region of scene to capture from somewhere.
    area = get_QRect_to_capture_from_somewhere()

    # Create a QImage to render to and fix up a QPainter for it.
    image = QImage(area.size(), QImage.Format_ARGB32_Premultiplied)
    painter = QPainter(image)

    # Render the region of interest to the QImage.
    self.scene.render(painter, image.rect(), area)
    painter.end()

    # Save the image to a file.
    image.save("capture.png")

A: I wanted to add that render requires the QRectF object for the image.area() and area parameters, otherwise it throws a TypeError.
I did:
QtCore.QRectF(image.rect())

and created a QRectF object for the area parameter.


text:
Q: SQL - OleDbCommand not changing Sql Parameter Below is the code for my Select * Function - It WORKS well and does everything great until i change the SQL string from Select * From Company to
        query = "Select * From @1";

and then do the following
        query = "Select * From @1";
        OleDbCommand Command = new OleDbCommand(query, sqlConnStr);

        DataTable Table = new DataTable();
        DataSet dataSet = new DataSet();
        Table = null;

        //Add Parameters
        Command.Parameters.AddWithValue("@1", SQLTables.Company);

        try
        {
            Command.ExecuteNonQuery();
            adapter.SelectCommand = Command;
            adapter.Fill(dataSet);
            Table = dataSet.Tables[0];
        }
        catch (Exception e)
        {
            MessageBox.Show("A Error occured whilst trying to execute the command.\n" + e.Message);
        }

        return Table;

The DBMS keeps sending back "Query incomplete" - I assume The Command variable is sending the string query through without changing the Parameter from @1 to Company

Here is a piece of code (mine) where this does work. This is an insert statement rather that a select - Correct me if i am wrong but should it not also work with the SELECT aswell
private void MainActionsInsert(string Action, bool Checked)
{
    OleDbCommand Command = new OleDbCommand("INSERT INTO MainActions Values (ID, Action, BoolValue)", DataBaseConnection);
    //Add Parameters
    Command.Parameters.AddWithValue("ID", GenerateID());
    Command.Parameters.AddWithValue("Action", Action);
    Command.Parameters.AddWithValue("BoolValue",Checked);
    //Add Command
    MainActionsAdapter.InsertCommand = Command;
    //Execute Agains DataBase
    Command.ExecuteNonQuery();
    //Accept Changes
}

`

A: OLEdb doesn't recognize named parameters. You must use ? in the query text.
However, you also can't use dynamic table names with parameterized queries, so even using a ? will not help.
You need to use full dynamic SQL, though that can open you up to SQL Injection. Make sure you read the full article I linked.

A: OleDbCommand Does accept Parameterized SQL just not in the From Clause - It Has to be either in a WHERE clause or something like that. Like you said it Worked with the insert function because it expects "parameters" there. For example this will work
    query = "Select * From Company Where @param = 1";
    OleDbCommand Command = new OleDbCommand(query, sqlConnStr);

    DataTable Table = new DataTable();
    DataSet dataSet = new DataSet();
    Table = null;

    //Add Parameters
    Command.Parameters.AddWithValue("param", "ID");

    try
    {
        Command.ExecuteNonQuery();
        adapter.SelectCommand = Command;
        adapter.Fill(dataSet);
        Table = dataSet.Tables[0];
    }
    catch (Exception e)
    {
        MessageBox.Show("A Error occured whilst trying to execute the command.\n" + e.Message);
    }

    return Table;

Funny though that it doesn't work for the Select part though


text:
Q: How can I redirect based on a selection of a DropDownList I have a TextBox1 and a Search button in my application with this following code:
protected void Button1_Click(object sender, EventArgs e)
{
    Response.Redirect("~\\searchpage.aspx?PatientNRIC=" + TextBox1.Text);
}

Which means, if the user type ONLY IC NO:S1234567D, then when click it will show the patient detailview.
So I now I'm doing almost the same thing but now I have a TextBox2 and a DropDownList1. Inside DropDownList1, I have "Name", "IC No", "Test_Date".
So for an example, I type "S1234567D" in the textbox1, and I choose "IC No" in DropDownList1 it should redirect me to a page of the S1234567D's patient detailview.
How could I do my code? Thanks!

A: Something like the following might work for you:
protected void Button1_Click(object sender, EventArgs e)
{
    if(dropdownlist1.SelectedValue == "IC No")
    {
        // assuming this is the redirect to your patients details view
        // but you MUST use only forward slashes to make it work (!)
        Response.Redirect("~/searchpage.aspx?PatientNRIC=" + TextBox1.Text);
    }
}

A:     name.Text = ddl1.DataTextField;
    ICNo.Text = ddl1.DataValueField;
    textBox1.Text = name.text+ICno.Text;

protected void Button1_Click(object sender, EventArgs e)
{
if(textbox1 != null)
      {
          Response.Redirect("~/searchpage.aspx?PatientNRIC=" + TextBox1.Text);
      }
    }
}


text:
Q: How do I serialize dependencies in JSchema with newtonsoft With Newtonsoft.Json.Schema I am trying to add dependencies and serialize to a json-schema (.json file).
var schema = new JSchema()
{
    Type = JSchemaType.Object,
    SchemaVersion = new Uri("http://json-schema.org/draft-07/schema#")
};

schema.Properties.Add("ShowField", new JSchema() { Type = JSchemaType.Boolean });

var oneOf1 = new JSchema();
oneOf1.Properties.Add("ShowField", new JSchema() {Enum = { false }});

var oneOf2 = new JSchema();
oneOf2.Properties.Add("ShowField", new JSchema() { Enum = { true } });
oneOf2.Properties.Add("ExtraField", new JSchema() { Type = JSchemaType.String });

var oneOf = new JSchema();
oneOf.OneOf.Add(oneOf1);
oneOf.OneOf.Add(oneOf2);

schema.Dependencies.Add("ShowField", oneOf);

Console.WriteLine(schema.ToString());

My expected and desiered reult is this:
{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {
        "ShowField": {
            "type": "boolean"
        }
    },
    "dependencies": {
        "ShowField": {
            "oneOf": [
                {
                    "properties": {
                        "ShowField": {
                            "enum": [false]
                        }
                    }
                },
                {
                    "properties": {
                        "ShowField": {
                            "enum": [true]
                        },
                        "ExtraField": {
                            "type": "string"
                        }
                    }
                }
            ]
        }
    }
}

But when I run the code the result is this:
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "ShowField": {
      "type": "boolean"
    }
  }
}

I have checked the JSchema object, and verified that the dependency is added to the object, but there are still noe serialization of the dependencies.
Any tips? Any errors in the code?

A: This was an issue with Newtonsof.Json.Schema. It has now been fixed:
https://github.com/JamesNK/Newtonsoft.Json.Schema/issues/187


text:
Q: Windows Update Error Code 80072EFE I have installed Windows Server 2012 R2 RTM. Now, in order to install SharePoint, seems like I will have to update the server upto April 2014 update. But no matter, whatever I do, I see the following error:

Anyone who can help me on this? Need an urgent fix.

A: This is most likely due to time skew on the server, or possibly Windows Firewall getting in the way.
First, I would double check the server has the correct Time Zone, Date, and Time. (If you have trouble setting the time, and the server is a virtual machine, on the hypervisor side, disable clock syncing of the VM to the host hardware)
After rebooting the server, and it holds the correct date/time, then try the update again. If still no luck, you can easily disable the windows firewall with the below command in an administrator command prompt:
NetSh Advfirewall set allprofiles state off

If needed, you can reenable the firewall with this similar command:
NetSh Advfirewall set allprofiles state on

Try the update again once you've disabled the Windows firewall
Bonus fun command to show the current status of the Windows firewall:
Netsh Advfirewall show allprofiles

A: That error code indicates the network connection was "terminated".

0x80072EFE ERROR_INTERNET_CONNECTION_ABORTED   The connection with the server has been terminated.

Doesn't sound like an actual network issue, so I would advise trying to download and install the update manually from the Microsoft Update Catalog site.  It might work, or you might get a more useful error message about why the update can't be installed.
I've seen similar issues when a prerequisite update has been expired or superseded, or when the Windows Update client is out of date, so you might need to install other updates first.  It might also turn out that the specific update you're trying to install is itself superseded or expired, and you need a more recent patch instead of the one you're trying to install.  Either way, you should know more after you try manually installing the update in question.

A: For this error on Windows 7 and Windows 2008 R2, this is the fix.  That is, install KB3138612.


text:
Q: Modernizr media query triggering inconsistently I'm trying to have my script trigger only when the screen size is above a specific size (800px), not just on load, but on screen resize.
I've put it inside a Modernizr mq script, but it's triggering inconsistently. Sometimes it will trigger my script at a small screen size.. sometimes at large.. sometimes not at all. Which leads me to believe that I've completely screwed it up!
Can anyone point me in the right direction?
$(function() {
  $(window).resize(function(){
    if (Modernizr.mq('(min-width: 800px)')) {

      // script to trigger
      $('.dropdown').on('mouseenter mouseleave click tap', function() {
        $(this).toggleClass("open");
      });

    }
  }).resize();
});

A: Could be because you are triggering the resize event from the resize event, which causes an infinite looping of event triggering.
Also, why not just test the screen size directly?
$(function() {
  $(window).resize(function(){

    // Use this for browser width: if(window.innerWidth >= 800)
    if (screen.width >= 800) {

      // script to trigger
      $('.dropdown').on('mouseenter mouseleave click tap', function() {
        $(this).toggleClass("open");
      });

    }
  });
});


text:
Q: JQuery Retrive data-attribute from on click function I have a div structure like this:

JOIN ME

PLAY ME

GO TO LIST

GO TO TOP 10

How can I refer to their data attribute by onClick function?
I tried with
$(".bar .element").on('click', ()=> {
    alert($(this).data('big'));
});

But it always alert "undefined".
EDIT:
My assertion was bad from the beginning, I was using a lambda (or arrow) expression from the Typescript language. That makes the different meaning of the keyword "this".
the snippet:
$(".bar .element").on('click', function(){
    alert($(this).data('big'));
});

works as espected.

A: You do not have a .barra (as you had in your original JS -- $(".barra .element")) element in your HTML and you've not written the callback properly:
$(".bar .element").on('click', function() {
    alert($(this).data('big'));
});

    $(".bar .element").on('click', function() {
        alert($(this).data('big'));
    });

JOIN ME

PLAY ME

GO TO LIST

GO TO TOP 10

A: you should change your function like below
$(".bar .element").on('click', function() {
    alert($(this).attr('data-big'));
});

A: In TypeScript, the arrow function expression (() =>) is used to preserve the lexical scope. This means that when you use this inside of an arrow function, it will refer to the same scope as using this outside of the function.
In your case, you want the function to run with the scope of the onclick event, not the lexical scope, so you should avoid using the arrow function and instead use function ().

A: Here is the working solution:
jQuery:
$(".bar .element").on('click', function() {
    alert($(this).attr('data-big'));
});

DEMO

A: you can use "id" to do it:

JOIN ME

$("#div1").on('click', ()=> {
    alert($(this).data('big'));
});


text:
Q: How to prove something on limit points... $X = \mathbb R^n$. How to prove that the interior point of a subset of $X$ is also limit point?
Don't know where to start... by definition, an interior point is such if it exists an e-neighborhood such that it is included in the set.
Limit points in the other hand are such that every neighborhood will contain a point of the set.
What's so special about $\mathbb R^n$...

A: Let $a$ be an interior point of $X$. Since $a$ is an interior point of $X$ there is a neighborhood $A$ of $a$ such that $a \in A \subset X$. This shows that $a \in X$. Now let $B$ be any neighborhood of $a$. Then $a \in B \cap X$ and since $a \in X$ any neighborhood of $a$ contains a point in $X$. Thus $a$ is a limit point of $X$.

A: As $\mathbb{R}^{n}$ is a first countable topological space, you can reason on sequences; let $x \in Y \subset X$, by definition of interior point you get the existence of an $ \epsilon >0$ such that $ \mathcal{B}_{\epsilon}(x) \subset Y$ (Y is the subset of which x is an interior point). It's clear that each ball with same center and smaller radius is included in Y, thus you easily get a sequence that converges to x by picking an element in $ \mathcal{B}_{\frac{\epsilon}{n}}(x) \subset Y$. By definition of the metric topology, each neighborhood of x has to contain one of that ball and so one of that points, of course each of which is different from x.


text:
Q: Mysql search string in all fields slowness after version upgraded to 5.6 Current mysql version is 5.5. I upgraded a copy to version to 5.6.
Below query get 15secs to execute from 5.5.
But the version 5.6 took 750+s to run same query.
Query :
SELECT  SQL_NO_CACHE *
    FROM  RECORDS
    LEFT OUTER JOIN  AUTH  ON RECORDS.`id` = AUTH.`id`
    LEFT OUTER JOIN  STAFFCOMMENTS  ON RECORDS.`id` = STAFFCOMMENTS.`id`
    WHERE  (ODATE LIKE '%Jan%')
      AND  (ODATE LIKE '%2021%')
      AND  RECORDS.NAME <> 'CUSTOMER'
      AND  (RECORDS.NAME <> 'COURIER-ORDER')
  order BY RECORDS.ID DESC
    LIMIT  35000

A: Assuming ODATE is of datatype DATE or DATETIME (which it should be!), change
       (ODATE LIKE '%Jan%')
  AND  (ODATE LIKE '%2021%')

to
       ODATE >= '2021-01-01'
  AND  ODATE  < '2021-01-01' + INTERVAL 1 MONTH

Then show us the indexes so we can judge whether they can be improved.


text:
Q: Web Scraping Image URL for a series of events in ESPN Play-By-Play I am trying to use web scraping to generate a play by play dataset from ESPN. I have figured out most of it, but have been unable to tell which team the event is for, as this is only encoded on ESPN in the form of an image. The best way I have come up with to solve this problem is to get the URL of the logo for each entry and compare it to the URL of the logo for each team at the top of the page. However, I have been unable to figure out how to get an attribute such as the url from the image.
I am running this on R and am using the rvest package. The url I am scraping is https://www.espn.com/mens-college-basketball/playbyplay?gameId=400587906 and I am scraping using the SelectorGadget Chrome extension. I have also tried comparing the name of the player to the boxscore, which has all of the players listed, but each team has a player with the last name of Jones, so I would prefer to be able to get the team by looking at the image, as this will always be right.
library(rvest)
url <- "https://www.espn.com/mens-college-basketball/playbyplay?gameId=400587906"
webpage <- read_html(url)

# have been able to successfully scrape game_details and score
game_details_html <- html_nodes(webpage,'.game-details')
game_details <- html_text(game_details_html) %>% as.character()

score_html <- html_nodes(webpage,'.combined-score')
score <- html_text(score_html)

# have not been able to scrape image
ImgNode <- html_nodes(webpage, css = "#gp-quarter-1 .team-logo")
link <- html_attr(ImgNode, "src")

For each event, I want it to be labeled "Duke" or "Wake Forest".
Is there a way to generate the URL for each image? Any help would be greatly appreciated.

A: "https://a.espncdn.com/combiner/i?img=/i/teamlogos/ncaa/500/150.png&h=100&w=100"
"https://a.espncdn.com/combiner/i?img=/i/teamlogos/ncaa/500/154.png&h=100&w=100"
Your code returns these.
500/150 is Duke and 500/154 is Wake Forest. You can create a simple dataframe with these and then join the tables.
link_df <- as.data.frame(link)

link_ref_df <- data.frame(link = c("https://a.espncdn.com/combiner/i?img=/i/teamlogos/ncaa/500/150.png&h=100&w=100", "https://a.espncdn.com/combiner/i?img=/i/teamlogos/ncaa/500/154.png&h=100&w=100"),
                             team_name = c("Duke", "Wake Forest"))

link_merged <- merge(link_df,
                    link_ref_df,
                    by = 'link',
                    all.x = T)

This is not scalable if you're doing hundreds of these with other teams, but works for this specific option.