Google Maps heatmap returning 404 on tiles when coordinates in array are the same

Question: I'm experiencing a weird error when using the Google Maps JS API 3.
I'm generating a heatmap based on an array of coordinates. At times and when filtering the results of the array, the resulting list consists of the same coordinate repeated several times in the array (X cases occurring in the same coordinates).
When this happens, the map will not render correctly and I'll get an array of 404 errors for the corresponding tiles, as shown below:

If then I touch the map zoom either up or down, it will render correctly.
This only happens if the coordinates are the same, if there's 2 different locations in the array, it will be rendered correctly.
Here's the code that renders my map:
$scope.renderHeatMap = function() {
  $timeout( function(){
    $scope.outbreakfin = [];
      for (var i in $scope.resultsheat) {
        $scope.outbreakfin.push(new google.maps.LatLng($scope.resultsheat[i][0], $scope.resultsheat[i][1]));
    };
    console.log($scope.outbreakfin);

    var map, heatmap;

    map = new google.maps.Map(document.getElementById('heatmap'), {
      mapTypeId: 'satellite'
    });

    var bounds = new google.maps.LatLngBounds();
    for (var i = 0; i < $scope.outbreakfin.length; i++) {
      bounds.extend($scope.outbreakfin[i]);
    }
    map.fitBounds(bounds);

    var center = map.getCenter();
    google.maps.event.trigger(map, 'resize');

    var options = {
      imagePath: 'images/m',
      gridSize:5
    };

    map.setCenter(center);

    heatmap = new google.maps.visualization.HeatmapLayer({
      data: $scope.outbreakfin,
      map: map
    });

    heatmap.set('radius', heatmap.get('radius') ? null : 15);
    heatmap.set('opacity', heatmap.get('opacity') ? null : 0.7);
    heatmap.set('dissipating', heatmap.get('dissipating') ? null : true);
    heatmap.set('maxIntensity', heatmap.get('maxIntensity') ? null : 15);

  }, 0 );
};

Anyone has any idea about what I could try?
Answer: So, for any future wanderers around this issue, I've figured it out.
The problem is around the map.fitBounds(bounds); call.
If all the coordinates are the same, the fitBounds will most likely try to display set a very high zoom level, which triggers the 404 errors.
To fix the issue, I've found a way to reset the zoom level after the fitBounds is set.
It looks like this:
var bounds = new google.maps.LatLngBounds();

for (var i = 0; i < $scope.outbreakfin.length; i++) {
      bounds.extend($scope.outbreakfin[i]);
}
map.fitBounds(bounds);

var listener = google.maps.event.addListener(map, "idle", function() {
  if (map.getZoom() > 18) map.setZoom(18);
  google.maps.event.removeListener(listener);
});


MS Access open error message

Question: When I tried to open MS Access from the command line I got the following error message:

The command line you used to start Microsoft Office Access contains an option that micosoft Access doesn't recognize.

My command is very simple:
"C:\Program Files (x86)\Microsoft Office\Office14\MSACCESS.EXE" E:\MonthlyCompAudit\"Audit - Test - Copy.accdb"

If I just run
"C:\Program Files (x86)\Microsoft Office\Office14\MSACCESS.EXE"

it works.
After I included the database name, it does not work. The Access file path/name is current, because I verified with dir command.
Answer: Your quotation marks are around only the file name, not the entire path. Try:
"C:\Program Files (x86)\Microsoft Office\Office14\MSACCESS.EXE" "E:\MonthlyCompAudit\Audit - Test - Copy.accdb"

Source: https://support.office.com/en-us/article/Command-line-switches-for-Microsoft-Office-products-079164cd-4ef5-4178-b235-441737deb3a6

You can include a path, if necessary. If the path contains spaces, enclose it in quotation marks.
Comment: @PaulZ Those questions are probably better answered by raising two new questions.
Comment: Good call - I moved the quote position and it works. I do have a few extra questions: (1) Is there a way this batch runs on 'silence' mode that does not disturb other users? (2) In my command line, I plan to call a Macro with -x option. The Macro is a function that pop up a message box and asked for 'Yes' or 'No'  - how can I let the batch know that a defaut 'Yes' is always selected?
Comment: @PaulZ If the link I provided does not answer your additional questions regarding further switches, please raise new questions.

MS Access open error message


easy inequality to prove

Question: Prove that $\log_2(x)+\frac{1-x}{x} > 0$
I think the answer is easy but I've no clue how to go about it.
Answer: Take the exponents of both sides, it is equivalent to showing $xe^{\frac{1}{x}-1} > 1$. But $e^x = 1+x+\cdots > 1+x$ whenever $x$ is positive, and thus $xe^{\frac{1}{x}-1} > x(1+\frac{1}{x}-1) = 1$.
Answer: $$\log x+\frac{1-x}{x} > 0
\iff \log x+\frac{1}{x} - 1> 0
\iff \frac{1}{x} -1 >  \log \frac 1x
$$
follows from
$$
\frac 1{1+t}< 1\implies \log(1+u) = \int_0^u \frac{dt}{1+t} < u
$$when $u>0.$
Answer: Let $f(x) = x\ln x + 1 - x$, then $f'(x) = \ln x + 1 - 1 = \ln x < 0$ since $x < 1$. So $f$ decreases, and $f(x) > f(1) = 0$, so $$x\ln x + 1 - x > 0\implies \ln x + \frac{1 - x}x > 0.$$
Comment: your method works the most simply but thanks very much everyone for answering

easy inequality to prove


Issue Converting Between Watts and ft*lbf/s

Question: I am solving a mechanical engineering fluids problem and I've run into a weird unit conversion issue:
The density of water is $1000\ \mathrm{kg}/\mathrm{m}^3$. This is $62.43\ \mathrm{lb}/\mathrm{ft}^3$ calculation on wolframalpha
The flow rate is $1.5\ \mathrm{ft}^3/\mathrm{s}$ which is $0.0425\ \mathrm{m}^3/\mathrm{s}$ calculation on wolframalpha
The diameter of the nozzle is 4 inches which is $\pi\cdot (4/2)^2 = 12.6\ \mathrm{in}^2$ which is $0.008107\ \mathrm{m}^2$ or $0.08727\ \mathrm{ft}^2$.
When I take all of the quantities in meters, kg, and seconds, I get 0.7832 horsepower calculation on wolframalpha
When I take all of the quantities in feet, pounds, and seconds, I get 25.15 horsepower calculation on wolframalpha.
This makes no sense to me... Please help
Answer: I figured it out! The issue is that foot pounds of force aren't the same as lb*ft^2/s^3 https://en.wikipedia.org/wiki/Pound_(force)


Number of Non-Isomorphic linear orders on $\kappa$ elements

Question: After having proven that there is no $\kappa$-categorical axiomatizations of strict linear order for any infinite cardinality $\kappa$, a professor of mine mentioned in passing that it was actually the case that there are in fact $2^{\kappa}$ non-isomorphic SLOs on any infinite $\kappa$, in contrast to $\kappa +$ wellorders. He also mentioned that the assertion that number of wellorders is equal to the number of strict linear orders is equivalent to the continuum hypothesis. Sadly, class ended and I was unable to get clarification (and now am too interested to wait for the next office hours).
I am confused on a few points:
1) why are there $2^\kappa$ such non-isomorphic orders?
Any texts/reading that could be suggested to address any of these questions, or any explanation thereon, would be much appreciated. Thanks!
Update: 2, 3 should've been obvious. They're below in case anyone ever asks the same question. Still interested in 1.
2) what does $\kappa +$ mean?
3) how is the assertion that $2^\kappa = \kappa +$ equivalent to the continuum hypothesis?
Comment: If $\kappa$ is a cardinal, then $\kappa^+$ is the next cardinal. The generalized continuum hypothesis is literally the statement that for every cardinal, $2^\kappa=\kappa^+$.
Comment: Welp, that should've been obvious. That covers 2 and 3, thanks!
Answer: Here's my shot at answering (1).
There cannot be more than $2^\kappa$ linear orders on a set of cardinality $\kappa$, since the number of binary relations on $\kappa$ is $2^{\kappa^2}$ and since $\kappa$ is infinite, $\kappa^2 = \kappa$ so there are a total of $2^\kappa$ binary relations on $\kappa$.
Since $\kappa$ is infinite, $\kappa = \kappa \times \aleph_0$, so if $S$ is of size $\kappa$, then the number of non-isomorphic linear orders on $S$ is the same as that on $S \times \mathbb{N}$. Now, for every map $f : S \to \{0, 1\} $, consider the order on $S \times \mathbb{N}$, where $\preceq$ is a fixed well ordering on $S$.
$(s_0, n_0) < (s_1, n_1)$ if $s_0 \prec s_1$
$(s, n_0) < (s, n_1)$ if $f(s) = 0$ and $n_0 < n_1$ or if $f(s) = 1$ and $n_0 > n_1$
This scheme should produce non isomorphic linear orders for any distinct $f_1, f_2$, since if $s$ is the least element under $\preceq$ of $S$ such that $f_1(s) \neq f_2(s)$, then any order isomorphism must map $\{s'\} \times \mathbb{N}$ to itself for each $s' \preceq s$, but this is impossible for $s$.
Thus, there is a distinct order for each function from $S$ to $\{0,1\}$, of which there are $2^\kappa$. This means that there are at least $2^\kappa$ orderings, and since there are no more than $2^\kappa$, this is the exact cardinality.
Answer: Given $X\subseteq \kappa$, let $slo(X)$ be the simple linear order that results from replacing every $\alpha \in X$ with a copy of $\omega^* + \omega$ (the order type of $\Bbb Z$). This is actually the ordered sum along $\kappa$ of linear orderings $R_{\alpha}$, where $R_{\alpha}$ is equal to $\omega^* + \omega$ for $\alpha \in X$, and equal to $1$ otherwise.
This order has $\kappa$-many elements, and we can ensure in a canonical way that all of its elements are members of $\kappa$. Clearly (yes?), $X\mapsto slo(X)$ is an injection on $\mathcal{P}(\kappa)$, and furthermore, if $X,Y\subseteq \kappa$ and $X\neq Y$ then $slo(X)$ is not isomorphic to $slo(Y)$.
Comment: Makes sense, thanks!
Comment: You're welcome!


Copiar valor de um input para outro

Question: Estou precisando que quando eu coloque qualquer valor dentro do input1, esse valor apareça já no input2. Sendo que os dois estão na mesma página, tem como fazer isso?
Answer: Pode fazer com jQuery capturando o evento keyup.
Execute o código abaixo e veja abaixo um exemplo funcionando:

// JavaScript (usando jQuery).

$('#input1').keyup(function(){
    $('#input2').val($(this).val());
});

<input id="input1"/>
<input id="input2"/>
Comment: Muito obrigado, era exatamente isto que eu precisava.
Comment: Suponhamos q o campo ja tenho um valor quando abrirmos a página, tem como copiar o código no momento em q se abre a página?

Copiar valor de um input para outro


htaccess folder to subdomain rewrite

Question: How can example.com/blog seamlessly show the content of blog.example.com without a redirect?
Not this:
RewriteRule ^/blog http://blog.example.com [R=301,L]

Thanks.
Answer: In order for this to occur, both the domain and subdomain would have to be running from the same directory of files. Then you could just rewrite the /blog path to the same file that the subdomain is using to run. Depending on your permissions, it could be possible to specify a ../ path to the file that it's using if you get the directories right.
However, anytime you specify a full domain path in a rewrite rule, Apache will always redirect the request. You can't get around that.
Answer: if example.com/blog and blog.example.com(subdomain) both points to same directory(blog). Then you can directly access the specified path without any redirection.

htaccess folder to subdomain rewrite


Start /WAIT RDP FIle in Windows 8

Question: I am not sure if I should post this one here or  in StackOverflow.
I want a BAT that opens a RDP connection file and then, when the connection is closed, logoff the machine.
start /WAIT "ConnectionFile.rdp"
logoff

But the logoff happens instantaly, it doesnt wait for exit.
I also try this using C# and Process.WaitforExit().
What should you do? I think is a issue with mstsc.exe when the parameter is a RDP file.
Update: I was testing and this works well in Windows 7, but in Windows 8 and in Windows 7 Thin PC it doesnt work.
Update Using powershell I advance a little.
I my bat looks like this, launchin the process in Powershell it works.
powershell -version 2.0 -Sta -ExecutionPolicy UnRestricted Start-Process -Wait -FilePath mstsc -ArgumentList ConnectionFile.rdp; logoff

But if the RDP is a valid file when windows asks the credentials it fails and continue with next process. For demo purposes I changed the logoff for a calc.
Comment: Very odd.. Removing my incorrect answer... Could you test with PowerShell on Windows 8?  `Start-Process -Wait -FilePath mstsc -ArgumentList ConnectionFile.rdp`
Comment: With Powershell works. I am creating a bat that launches Powershell. I'll comment soon.
Comment: With powershell works but not well when windows asks for credentials
Answer: Try this:
START /WAIT !_MSTSC! !_FILE! !_CONSOLE!
where

!_MSTSC! is the path to MSTSC.EXE
!_FILE! is a path to a saved RDP file, containing hostname, login and pwd, perhaps the name of a file to execute on connection, blah blah blah
!_CONSOLE! is set to either "" (null) or "/ADMIN" as needed

This hinges WAIT on MSTSC explicitly, not just the "successful open" of your RDP file.  As such, it should (!) work a little better.
And... here's an interesting caveat from the START helptext:
    If Command Extensions are enabled, external command invocation
    through the command line or the START command changes as follows:

    When executing an application that is a 32-bit GUI application, CMD.EXE
does not wait for the application to terminate before returning to
the command prompt.  This new behavior does NOT occur if executing
within a command script.

So... what may be needed here is to wrap the MSTSC command and parameters into a CONNECT-REMOTE.CMD file, and wait for THAT to terminate.
Comment: Thanks @George but It does not work. Look at this image with the result of testing it https://dl.dropbox.com/u/300838/error2.png
Comment: Interesting.  The "verify the cert is OK" prompt is interrupting MSTSC, obviously, but didn't think that'd cause WAIT to trigger... do you get the same results if you check the checkbox "Don't Ask me again" and then retry?

The only other way I can think of is to kludge a "flag" variable/file that would get set before running MSTSC, and then deleted by the remote session using \\tsclient\ ... and a test loop that would trigger your next step in your batch when the flag file no longer existed.
Answer: For anyone finding this article and fighting with this issue, insert the following rule between the mstsc.exe command and the logoff:
powershell wait-process -name mstsc

When combining with this article: https://www.experts-exchange.com/articles/10032/MSTSC-as-a-Shell.html the mstsc.cmd contains:
C:\Windows\System32\mstsc.exe RDPLocation
powershell wait-process -name mstsc
logoff

Start /WAIT RDP FIle in Windows 8


Is it possible to retrieve the name of a file from redirection?

Question: I am doing some basic file manipulations, and would like to store the name the file passed to an executable C program and create a new file that has an extension tacked on the original filename. For example, if this were what I typed on the command line:
a.out < some_file.txt

Where a.out is an executable, is there a way to get the string some_file.txt, so I could open up a new file and call it some_file.text.mod or something else?
argv[0] gets you a.out, and  in scripting you could use $1 to access arguments (but not the filenames used in redirection), but neither of those is much use here.
Any ideas?
Comment: A shell script called with input redirected to a file and no other parameter will give you nothing in `$1`.
Answer: It's possible on some platforms, using platform specific constructs.
e.g. on linux you can call readlink() on /proc/self/fd/0
Other forms of redirection will not provide access to the file name, there might not be a file - the data might be supplied through a pipe.
For your case, you're likely better off letting the user decide the output filename in the cases the input is redirected through stdin
Comment: Thanks for the quick reply. I hadn't thought about other situations where it might not be a file, that makes sense though now that it wouldn't be easily possible.
Answer: Sometime (and almost always in practice) /proc/self/fd/0 could be a symbolic link to the file. (But the symlink could be crappy, e.g. for a pipe, and this is Linux specific).
So from inside your a.out you could call the readlink(2) system call on /proc/self/fd/0
But doing that is a bit disgusting. However it works:
% ls -l /proc/self/fd/0 < ~/.zshrc
lr-x------ 1 basile basile 64 Nov  6 19:22 /proc/self/fd/0 -> /home/basile/.zshrc

% date | ls -l /proc/self/fd/0
lr-x------ 1 basile basile 64 Nov  6 19:23 /proc/self/fd/0 -> pipe:[599869]

Again, it is highly Linux specific and not portable to other Posix systems.
Comment: Oj! That is messy, I think I shall figure out another way to name this file. Thanks for such a detailed response!


Combining Absolute and Relative Error

Question: When using a machine-learning model to predict a quantity for different sub-populations of different sizes, I'd like to compare the error between sub-populations (e.g. future population per country over a group of countries).
I want to quantify the fit of the model. When looking at prediction errors, the absolute error is higher for larger countries so this is not a good way to evaluate model fit across countries. A natural step would be to look at the % error. However, this results in larger errors for smaller countries because the sample size is lower and the variance is higher.
Is there a good measure of error which independant of both scale and sample size?
Comment: "However, this results in larger errors for smaller countries because the sample size is lower and the variance is higher." This does not make sense to me. Could you please elaborate? Shouldn't it be the case that, if the sample size for such a country is low, then you lack precision in your estimates? Sure, it would be nice to tighten-up your estimates (it would be nice to get every prediction perfect every time), but your result seems to reflect the reality of your predictions.
Comment: @Dave you're probably right for this example. My actual situation is loads of fertilizer. It's not just a sampling problem - there are fewer loads for smaller companies. So a smaller change in loads from year to year has a larger outcome on the percentage change.
Comment: It still seems like this is just the reality of your problem. If you miss by one load of fertilizer for a company that usually gets two, your miss really is a huge deal. If you miss by one load of fertilizer for a company that usually gets thousands, they might not notice.
Answer: You can scale error measures. Two ways are common:

Scaling by the actual level of the time series. You can, e.g., scale each absolute error by dividing it by the corresponding actual, then average - this is the Mean Absolute Percentage Error (MAPE). Alternatively, people will also scale the sum of the absolute errors by the sum of the actuals, which can be interpreted as a weighted MAPE. The question here is whether to use historical sums (or means, which make more sense if your time series have different lengths).

Scaling by a benchmark error. For instance, you could scale each series' Mean Absolute Error (MAE) by the MAE achieved on this series by a random walk forecast, or by the historical average. The effect is to quantify how much your focal forecasting method improves over the benchmark. A variant is the Mean Absolute Scaled Error (MASE), which scales the MAE by the MAE achieved by the one-step-ahead naive forecast in-sample.

You can also scale other error measures, like the Root Mean Squared Error, in either one of these two ways. What is important in any case:

Be transparent and precise about what you are doing, e.g., when you take sums or means (before or after dividing), especially if you have to communicate your errors, or if other people also calculate errors.
Note that series on smaller scales are often harder to forecast, simply because they have more relative noise.
Note that minimizing the MAPE will induce a bias. Similar effects occur if you minimize the MAE or a scaled variant thereof, but the effect is likely small if you are forecasting demographics, which presumably have nice symmetric conditional distributions.

To be honest, I don't think there is a single "good" error measure. All have hidden pitfalls and drawbacks. It's important to understand what prediction your error measure rewards. See here.

Combining Absolute and Relative Error


Convert image to individual cell value to sort in excel

Question: This issue is related to Microsoft Excel 2016.
I have an excel file where the column cell values are filled with images, and the Filter is not applying on the images. Is there any other way where we can either convert the image to cell value by converting the Image with Number or color to make it easy for filter?
Want to filter the column Shapes with :) so that the final result after filter should show me Sr.No 2,3,5,7

Filter option will list me Blanks only
Answer: You can use the following code to place the name of each picture in the cell the picture is located in
<code>Sub setPicNames()
    Dim ws As Worksheet
    Dim curPic As Shape

    Set ws = ActiveSheet
    For Each curPic In ws.Shapes
        curPic.TopLeftCell.Value = curPic.Name 'Or use curPic.BottomRightCell, or combine the two to get TopRight or BottomLeft
    Next curPic
End Sub
</code>


What does "Purple label" mean when people are describing a Yamaha YSS-62 soprano sax?

Question: My title pretty much says it all. I recently purchased a Yamaha YSS-62, and I am in heaven. It sounds great and plays easily (I now have a full rack!). But when I do research on the model I repeatedly see references to purple label. Now, this horn does have a label that includes the Yamaha logo and then the word "YAMAHA" on the first line, and then the word "JAPAN" on the second line. The color of this label is what I would describe as dark red. Is this a purple label horn, and how is it different from other YSS-62 soprano saxes?
-------------------- Edit ------------------
When I viewed the label in bright light, it certainly appeared to be purple.
Also, nuggethead suggested that I post a picture of the label, which I am doing now. Unfortunately, the picture is not of great quality, but I took many shots and this was the best one.
-------------------- Edit ------------------
Given the following picture, and the logo and text are definitely purple when viewed in bright light, this must be a YSS-62 Purple label. If someone out there has seen one, and can confirm that Purple label refers to this logo, the word YAMAHA, and the word JAPAN, in purple, I would appreciate the confirmation.
And @Aaron, if you change your comment to an answer, I'll mark it as correct.
Comment: Like @Aaron said, it seems to be a period distinction. A search of "purple logo" gets lots of results including forums and items for sale.
Comment: So, similar slang to the well-known  Conn "naked lady" which refers to a few model types also easily identifed by serial number series.
Answer: I can't say definitively, but some Google searching suggests that the purple label was used during the earliest period of the 62's construction. It either appears deep red to some people or was changed to a deep red at some point. The purple label period seems to be the one most sought after, and it appears to be what you have.


VOLTTRON Csv Driver Agent scheduled task

Question: Is there a way I could call an agent to start a certain time every day?
For example I would like to create an agent that creates an API call at 4AM everyday (to openweathermap) to check the hourly forecast for the day. Basically if the hourly forecast yield's ideal conditions the agent could do building pre-cooling... Else if the hourly weather conditions starting at 4AM through the afternoon hours are not ideal the agent would not do anything (pass). Hopefully that makes sense! just one API call at 4AM to make some decisions, else pass.
Also having some extra logic if current time equals a winter month to pass as well. datetime.datetime.now().month?
#@Core.receiver("onstart")
def onstart(self, sender, **kwargs):
    """
    This is method is called once the Agent has successfully connected to the platform.
    This is a good place to setup subscriptions if they are not dynamic or
    do any other startup activities that require a connection to the message bus.
    Called after any configurations methods that are called at startup.

Usually not needed if using the configuration store.
"""
# Every 120 seconds, ask the core agent loop to run the actuate point method with no parameters
self.core.periodic(600, self.actuate_point)

def actuate_point(self):
"""
Request that the Actuator set a point on the CSV device
"""
Answer: You could use the built in cron scheduler (https://volttron.readthedocs.io/en/main/developing-volttron/developing-agents/agent-development.html?highlight=cron#periodics-and-scheduling).  This uses the same style of cron that your linux system uses.  Put the following decorator on your function and the specified cron will just work.
from volttron.platform.scheduling import cron

@Core.schedule(cron('0 1 * * *'))
def cron_function(self):
   print("this is a cron-scheduled function")

Some useful crons are located https://crontab.guru/examples.html


How can I provide a defaulted parameter without repeating preceding ones?

Question: I've searched many resources and in the examples that they provide, it looks like this:
void bar(int a = 4, char b = 'A')
{
}

According to this resource  it can be called like:

bar(b : 'Z');

but it gives me an error identifier "b" is undefined.
I am using Visual Studio 2015 Update 3 Enterprise.
Any suggestions how to specify only the second parameter?
Comment: By the way, this proposal probably will never be implemented (as far as I can tell), because it clashes with the technicalities of how C++ functions are called, and makes offering linkable libraries incompatible to anything that's out there.
Comment: Ok, will be closed
Comment: @MarcusMüller Tbh I don't quite see how that makes the question off-topic.
Comment: @BaummitAugen well, we close questions as off-topic that just exist because the author had a typo in their code. Misunderstanding the role of something that is a proposal is pretty much the same; it can be fixed by pointing the author to the mistake, which is of a low-level "lexing" nature, and doesn't hold future value for other visitors (unless the misunderstanding/typo is likely to happen to someone else).
Comment: FWIW, the best I've seen right now that actually works uses `bar("b"_arg = 'Z')` syntax, but I believe it uses a non-standard language feature that GCC and Clang support.
Comment: @MarcusMüller I don't agree with that. Not knowing what a C++ standards proposal paper is feels like a legitimate mistake to make and, unlike a typo mistake, can neither be solved by the author staring at the code nor reiterated in infinitely many near-equivalent variants. So even if that was the core of the question, it may be a dupe / downvotable for lack of research effort, but off-topic by analogy to typo seems like a stretch.
Comment: Hm, I can see that point; I'll retract my close vote.
Answer: The paper you link is just a proposal¹. The mechanism you try to use is (currently) not a part of C++ as defined in the standards. You can thus not expect compilers to implement it.
There are currently no other standard workarounds. If you want to set some parameter, you also need to provide all parameters that precede it in the function declaration.
You can use something like Boost Parameter or implement something similar yourself to emulate the feature with user code. Whether or not that is a good idea is up to debate, it is not all too common and may thus be confusing for other programmers.

¹This might be a language problem: A "proposal" is something that someone says would be good, not the state things are.
Answer: One possible solution might be to use std::bind with the placeholders defined in that namespace. For example:
void bar(int a = 4, char b = 'A') {
}

using namespace std::placeholders;
auto f = std::bind(bar, 2, _2);
f('Z'); // equivalent to bar(2, 'Z');

As suggested in the other answer, there's no way to have the std::bind expression use the default argument from the function declaration, but it at least allows you specify only one of the arguments to it.


PlayerPrefs Unity3D

Question: Estou desenvolvendo um jogo para android mas estou com uma dificuldade na hora de salvar o tipo de input. Por exemplo nesse jogo o usuário pode escolher se quer jogar no touch ou acelerômetro, na unity + remote funciona bem essa troca mas quando eu compilo e instalo o apk no celular não funciona. Alguém pode me ajudar?
<code>    void Start()
    {

        if (PlayerPrefs.HasKey("playerChoice"))
        {

            if (value == 1)
            {
                inputAC.SetActive(true);
                inputTC.SetActive(false);
            }

            if (value == 0)
            {
                inputAC.SetActive(false);
                inputTC.SetActive(true);
            }
        }
    }

    void Update()
    {
        if (gameRunning)
            uiManagerScript.ShowScoreText(playerScript.score);

    }

    public void GameOver(int score)
    {
        scoreManger.AddScore(score);
        gameRunning = false;
        playerScript.gameObject.SetActive(false);
        uiManagerScript.GameEnd();
        plataformSpawnerScript.enabled = false;
        playerScript.isDead = true;
        plataform.gameObject.SetActive(false);
    }

    public void StartGame()
    {

        plataformSpawnerScript.enabled = true;
        cameraScript.ResetCam();
        uiManagerScript.GameStart();
        playerScript.score = 0;
        playerScript.isDead = false;
        gameRunning = true;
        plataform.gameObject.SetActive(true);

    }

    public void InputChoiceFalse()
    {
        if (PlayerPrefs.HasKey("playerChoice"))
        {

            PlayerPrefs.SetInt("playerChoice", playerChoice ? 0:1);

            value = 1;
            PlayerPrefs.Save();
        }

    }

    public void InputChoiceTrue()
    {
        if (PlayerPrefs.HasKey("playerChoice"))
        {

            PlayerPrefs.SetInt("playerChoice", playerChoice ? 0 : 1);

            value = 0;
            PlayerPrefs.Save();
        }

    }

    public void QuitGame()
    {
        Application.Quit();
    }

}
</code>
Answer: Olá,
Parece que a variável value não está com o valor do PlayerPrefs quando você faz a condição no Start().
Você verifica se existe playerChoice no arquivo salvo(PlayerPrefs), mas não carrega para o value. Acho que é o que falta no seu código. Porque o Start() é executado no frame em que o script é habilitado, o valor de value então, seria o valor previamente estabelecido, possivelmente no Inspector.
EDIT:
Eu faria assim:
<code>...
if (PlayerPrefs.HasKey("playerChoice"))
   {
   value = PlayerPrefs.GetInt("playerChoice");

       if (value == 1)
       {
...
</code>
Espero ter ajudado.

PlayerPrefs Unity3D


Modal popup on dropdown list selection

Question: Is it possible to popup a modal(AJAX) on drop downlist selection.
I have a user control which has  a ddl and another usercontrol which has that modal popup.On selection of specific item i need to popup modal.
Modal popup is in another usercontrol.
Answer: I did an example of how to do it entirely client side using a ClientEventPool - http://www.aaron-powell.com/blog/january-2009/fun-with-a-client-event-pool-and-modal-popups.aspx
For AJAX work avoid postbacks at all costs!
Comment: This is what I was referring to, this is a better example.
Answer: If I am reading you correctly, you will need to use either chained events or event bubbling to force the drop down selection to fire an event.  Then your second user control must listen for that event, and fire the event that "shows" the modal popup.
Without testing code, your structure on the primary control might look like this:
public delegate void DDLHandler(int selectedValue);

public event DDLHandler DDLChanged;

public void DDLChanged(int selection)
{
    if (DDLChanged != null)
    {
        DDLChanged(selection);
    }
}

Then you drop down control has it's event wired to call the handler
protected void ddlOne_SelectedIndexChanged(object sender, EventArgs e)
{

    //fire event handler for fetching value for this selection
    DDLChanged(Int32.Parse(ddlMeasurementOptions.SelectedValue));
}

Modal popup on dropdown list selection


To find match between two strings based on word sequence in R Language

Question: Please guide me if any functions in R Language available to match two words in sequence to another string (instead of matching single word to single word).
Answer: I'm not sure what you want as a result but using lubridate::intersect and splitsplit may helps,
df <- data.frame(
  string1 = c("Raj ate food", "Raj is working", "Raj ate food"),
  string2 = c("Raj ate nice food", "Car is driven by Raj", "Raj us not having food")
)

for (i in 1:dim(df)[1]){
  print(lubridate::intersect(strsplit(df$string1, " ")[[i]] , strsplit(df$string2, " ")[[i]]))
}

[1] "Raj"  "ate"  "food"
[1] "Raj" "is"
[1] "Raj"  "food"

Comment: Thanks, I need matching score between two strings and it should provide more score if two consecutive words are matching.
Comment: @SivaMani Then you may start with the code above. It will give common words row-wise.


Back transforming log data

Question: I have a dataset with biomass, dbh, height, wood density, site, and species. As data were not normally distributed, I converted biomass, dbh and wd using the log() function. Then I developed a linear mixed model using the lmer() function in R Studio. I kept biomass as the response variable and the remaining other parameters as the fixed and random effects as shown below:
lmer(B~D + H + WD +(1|species) + (1|site)

Now, the problem I am facing is how to back-transform the model in order to calculate the bias and correction factor. In linear regression, we can back-transform by using exp(), but in my case, I don't have any idea.  I went into lots of tutorials but these tutorials cannot solve my problem. Additionally, how do I perform train/test splits and cross-validation on my lmer model using caret()?
This is the first time I am developing a model and I am not from a statistics background. Can anyone please help me out?
Comment: As an extension of linear regression, linear mixed models only integrate additional random effects in the variance component estimation. If your question is to back transform fixed effects you can do that as you did in linear regression. However, it is worth noting that in practice, we are not very interested in the distribution of the outcome but more the residuals (and the random effects here). So probably a log transform is not necessary. Check your assumptions. I would surely provide a comprehensive answer if needed.
Comment: Instead of transforming the inputs to the model, try using the log link function when running the model.
Answer: Welcome to the site.
First, linear models don't require that the data be normally distributed. Some models make assumptions about the error and, since we can't know the error, we look at the residuals.
Second, even if the residuals aren't normally distributed, these days, there are models that make fewer assumptions. Some of these are old, but computer intensive and didn't become practical until there were fast computers.
So, don't transform the data unless you have a substantive reason for doing so. That is, do it when you want to look at variables multiplicatively rather than additively (this often happens with variables related to money).
There are a bunch of nonlinear mixed models. Without knowing more about your goals, I'm not sure which is best, but one possibility is a quantile model, which is available in R with the lqmm package.
Comment: So that means that I can continue further without back-transforming the outcome. And will you please help me out with the model validation part?  @Mangnier Loïc
Comment: Thank you for your suggestion. I will try to do it in that manner also @ Mike Hunter
Comment: The main objective of my work is to develop an allometric model for a particular forest. @Peter Flom

Back transforming log data


Passar valor de um select por javascript

Question: Boa tarde, sou novo no desenvolvimento e estou tentando criar um formulário que colete determinadas informações e gere um arquivo .xls. para evitar erros do preenchimento inseri select com todas as opções possíveis porem precisava otimizar a busca e pesquisando vi a possibilidade de usar jquerry que permitiam digitar e facilitar a busca porem ao usar o script meu form não retorna o valor selecionado na select.
exeplo do html - esta no meu index.html:
<select id="fornecedor" class="form-control" placeholder="Selecione o fornecedor"></select>

Script que utilizo para permitir pesquisar valores dentro da select

exemplo de como estou preenchendo o select - combo.js:
var comboForn = document.getElementById("fornecedor");
var opt0fn  = document.createElement("option"); opt0fn.value = "0"; opt0fn.text = "Selecione o fornecedor",comboForn.add(opt0fn, comboForn.options[0]);
var opt1fn = document.createElement("option");opt1fn.value = "0";opt1fn.text = "0 - INDEFINIDO",comboForn.add(opt1fn, comboForn.options[1]);
var opt2fn = document.createElement("option");opt2fn.value = "100034";opt2fn.text = "100034 - LOJAS AMERICANAS S.A.",comboForn.add(opt2fn, comboForn.options[2]);

form - book-form.js onde monto meu arquivo para gerar posteriormente o .xls
const bookForm = (function($){
    var BOOK_SOLIC = $('#solicitante');
    var BOOK_FIL = $('#filial');
    var BOOK_TIP = $("#tipo");
    var BOOK_PLANO = $("#plano");
    var BOOK_CENT = $("#centro");
    var BOOK_FOR = $("#fornecedor");
    var BOOK_VLRT = $("#valor_total");
    var BOOK_VLRP = $("#valor_parcela");
    var BOOK_QT = $("#quantidade")
    var BOOK_DESC = $("#descricao");
    var BOOK_APR = $("#aprovacao");

    const BOOK_UPDATE_BUTTON = $("#updateButton");

    function clear() {
        setData();
        BOOK_SOLIC.focus();
    }

    function hasErrors() {
        return BOOK_SOLIC.val() === null || BOOK_SOLIC.val() === '';
    }

    function getData() {
        return {
            solicitante: BOOK_SOLIC.val(),
            filial: BOOK_FIL.val(),
            tipo: BOOK_TIP.val(),
            plano: BOOK_PLANO.val(),
            centro: BOOK_CENT.val(),
            fornecedor: BOOK_FOR.val(),
            valor_total: BOOK_VLRT.val(),
            valor_parcela: BOOK_VLRP.val(),
            quantidade: BOOK_QT.val(),
            descricao: BOOK_DESC.val(),
            aprovacao: BOOK_APR.val(),
        };
    }

    function setData(solicitante='', option='', tipo='', plano='', centro='', fornecedor='', valor_total='',  valor_parcela='', quantidade='', descricao='', aprovacao='') {
        BOOK_SOLIC.val(solicitante);
        BOOK_FIL.val(filial);
        BOOK_TIP.val(tipo);
        BOOK_PLANO.val(plano);
        BOOK_CENT.val(centro);
        BOOK_FOR.val(fornecedor);
        BOOK_VLRT.val(valor_total);
        BOOK_VLRP.val(valor_parcela);
        BOOK_QT.val(quantidade);
        BOOK_DESC.val(descricao);
        BOOK_APR.val(aprovacao);
    }

    function setSubmitButtonText(str) {
        BOOK_UPDATE_BUTTON.text(str);
    }

    function getSubmitButtonText() {
        return BOOK_UPDATE_BUTTON.text();
    }

    return {
        clear: clear,
        hasErrors: hasErrors,
        getData: getData,
        setData: setData,
        setSubmitButtonText: setSubmitButtonText,
        getSubmitButtonText: getSubmitButtonText,
    };
})(jQuery);

desculpem se não tiver no padrão de perguntas e desde já agradeço pela ajuda. abs.
Answer: como é um select experimenta esse modelo aqui:
var se_pais = $("#comboboxpais option:selected").val();

Comment: Ao tentar este método não trouxe o valor selecionado para a tabela, mais não deu erro quando tento inserir o valor como nos outros que tentei, creio que falte apenas uma pequena coisa no código que ainda não consegui identificar
Comment: Melhora sua pergunta. Dá uma olhada como fazer isso. https://pt.stackoverflow.com/conduct


How do you test a null that a single regression line adequately describes the data?

Question: I was wondering how you would test the null that a single regression line adequate describes the data, i.e.
$H_A: $ two parallel lines needed (additional indicator variable here)
Comparing summary outputs from both I can see that with two lines, you get a higher F-stat, lower respective p-value, and higher Adjusted-$
R^2$, but I'm not sure what to test for in this case.
All help appreciated, thanks!
Comment: how would you interpret the predicted results of two parallel regression lines?
Comment: @TilefishPoele I assume he means a linear regression model with one continuous covariate and one categorical covariate with 2 levels.
Comment: @AndyKreek yes that's what I mean and I found the solution! It involves calculating (SS of the full model, subtracting it SS of the reduced model / predictors tested) / (SSE full / n-k-1)
Answer: In a linear regression setting, "two parallel lines" is equivalent to $E(y) = \beta_0 + \beta_c c + \beta_x x$ where $x$ is a continuous covariate (hence the line) and $c$ is a binary indicator (hence 2 parallel lines with intercepts depending on whether $c=1$ or $c=0$).
So, your test is equivalent to the test $H_0:$ $\beta_c= 0$ vs. $H_A:$ $\beta_c \neq 0$.
In fact, the $p$-value in standard regression output for the coefficient $\beta_c$ is exactly the $p$-value for this test.
So if the $p$-value for $\beta_c$ is smaller some threshold, typically 0.05, then you can conclude that there is strong evidence in your data to reject $H_0$. In this case, "2 parallel lines" would describe your data better than one.
(Note, simply having a smaller $p$-value for your $F$ test doesn't indicate that the coefficient $\beta_c \neq 0$. The $p$-value for the overall $F$ test indicates the degree to which there is evidence in your data that any $\beta$ in the model is non-zero. You can, however, compare $F$ statistics for 2 nested models, e.g. models with and without the variable $c$. In this case, that would be  equivalent to above test.)
Answer: Found the answer my prof. was looking for in the textbook:


Como manipular objetos em uma Thread?

Question: Tenho o seguinte código:
MinhaClasse[] obj = new MinhaClasse[QtdUsuario];
Thread th;

For(int i = 0; i < QtdUsuario; i++)
{
    obj[i] = new MinhaClasse();

    th = new Thread(new ParameterizedThreadStart(Metodo));
    th.SetApartmentState(ApartmentState.STA);
    th.IsBackground = true;
    th.Start(obj[i]);
}

Cada objeto mostra uma imagem na tela, e essas imagens ficam se movimentando na tela.
Ex: se o usuário definir a variavel QtdUsuario para 5 eu terei 5 objetos e cada objeto em uma thread. Então na tela eu terei 5 imagens se movimentando aleatoriamente.
Meu objetivo é:
Como posso identificar possíveis colisões entre esses objetos(imagens) ?
E como posso definir valores individuais para cada objeto ?
Ex: o usuário dirá que a imagem 1 terá idade = 5, e decrementa e ou incrementa
essa idade ?
Answer: Neste momento as suas threads nao tem informacao suficiente.
Isto porque as threads necessitam de saber o estado dos objetos nas threads restantes (ou sejam elas necessitam de partilhar estado).
Pode nao ser óbvio, mas o estado que voce tem que partilhar é o array e ele nao precisa de ser sincronizado.
Já o acesso a cada elemento do array precisa, no momento em que consulta os objetos das outras threads.
Vou dar um exemplo, mas sem quaisquer garantias que pode ser útil no seu cenário:
public class Imagem{
    public Point Posicao{get; set;}

    public int Idade{get; set;}
}

public class Estado{
    public Imagem[] Imagens{get; set;}

    public Imagem MinhaImagem{get; set;}
}

var imagens = new Imagem[QtdUsuario];
//vamos assegurar que o array é inicializado antes de o passar como estado as threads
for(var i = 0; i < QtdUsuario; ++i){
    imagens[i] = new Imagem();
}

for(var i = 0; i < QtdUsuario; ++i){
    var thread = new Thread(new ParameterizedThreadStart(Metodo));
    thread.SetApartmentState(ApartmentState.STA);
    thread.IsBackground = true;
    thread.Start(new Estado(){Imagens = imagens, MinhaImagem = imagens[i]});
}

private void Metodo(object parametro)
{
    Estado estado = parametro as Estado;

    //o lock está a ser feito perante o array
    //porque é necessário fazer lock por um objeto comum
    lock(estado.Imagens){
        //Verifica qual o estado das restantes imagens
        var algumaImagemNaPosicao = estado.Imagens
           .Any(img => img != estado.MinhaImagem &&
                img.Posicao.X == 10 && img.Posicao.Y == 2);

        if(!algumaImagemNaPosicao){
            //faz coisas com a imagem
            estado.MinhaImagem.Posicao.X = 10;
            estado.MinhaImagem.Posicao.y = 2;
        }
    }
}

Comment: Se calhar era melhor ter apenas uma thread. Como pode ver a maior parte do código tem sincronizacao e por isso nao terá proveito do paralelismo
Answer: O delegate ParameterizedThreadStart possui a seguinte assinatura:
public delegate void ParameterizedThreadStart(object obj);

Isso indica que o seu método Metodo deverá segui-la, recebendo o estado como um object.
private void Metodo(object parametro)
{
   // Neste ponto já estamos em outra thread
   var paramMinhaClasse = (MinhaClasse) parametro;
}

Uma outra maneira de fazer seria passar diretamente um lambda como argumento na criação da Thread:
th = new Thread(() => Metodo(obj));

Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/49278/discussion-between-bruno-costa-and-meuchapeu).

Como manipular objetos em uma Thread?


Start and stop animation with CABasicAnimation iphone

Question: I want to use animation for image, start on button clicked and stop after 5 seconds.I use this code.
-(IBAction) btnClicked
{
    CABasicAnimation *fullRotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    fullRotation.fromValue = [NSNumber numberWithFloat:0];
    fullRotation.toValue = [NSNumber numberWithFloat:((360*M_PI)/180)];
    fullRotation.duration = 6;
    fullRotation.repeatCount = 1e100f;
    fullRotation.delegate = self;
    [imgView.layer addAnimation:fullRotation forKey:@"360"];
    [imgView.layer setSpeed:3.0];
}

with this code animation is started but i don't know how to stop this animation after 5 seconds.
Comment: Goto This Link It's Have Your Perfect Solution.
[enter link description here](http://stackoverflow.com/questions/2306870/is-there-a-way-to-pause-a-cabasicanimation)
Answer: Don't even deal with CoreAnimation. I think this can be do this with UIView animations, which are easier to program. Look at UIView documentation and try the block animations (assuming iOS 4.0. if not, use older style).
Look here for the docs on UIView animations.  Set the transform property to do the rotation using CGAffineTransformMakeRotation.
Here is a UIView based animated rotation:
- (void)viewDidLoad
{
    [super viewDidLoad];
    UIView *viewToAnimate = [[[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)] autorelease];
    viewToAnimate.backgroundColor = [UIColor blueColor];
    [self.view addSubview:viewToAnimate];
    [UIView animateWithDuration:5 animations:^{
        viewToAnimate.transform=CGAffineTransformMakeRotation(M_PI);
    }];
}

Comment: Thanks Davidneiss.But I want this animation with clockwise and anti-clockwise will it be possible with UIView animation ?


adonis vs. adonis2

Question: I am trying to conduct permanova tests on a dataset. There are multiple options for doing this in R and I am not sure how to decide what to use.
What is the difference between adonis() and adonis2() in the R vegan package? Also, what are the "by" and "strata" arguments for? It seems to me like these are the most important differences between adonis and adonis2.
Answer: So both adonis and adonis2 essentially get at the same goal. They are an implementation of a non-parametric permutation based MANOVA (often called PERMANOVA). The goal of this test is to tell you if there are significant differences in your response variables among your groupings. In adonis terms are tested sequentially and this is the only option. This means that the order you enter your variables is important (if design is unbalanced). For example using the dune and dune.env data sets in vegan, adonis(dune~Management+Use, data=dune.env) will give a different result than adonis(dune~Use+Management, data=dune.env). This is because the first explanatory variable is added to the model. Then the next one is added to see if it explains significantly more variation not explained by the previous variables. This is equivalent to using by="terms" in adonis2. If you don't want the order to matter you can use adonis2 with by="margin", or if you want to check if the model as a whole is significant you can use by=NULL. Order does not matter when by="margin" because the significance is tested against a model that includes all other variables not just the ones preceding it in the formula. It seems that strata is now deprecated in favor of defining blocks in the permutations argument now (see adonis help). Anyway, these arguments allow you to specify how to restrict which rows can be exchanged during the permutation procedure used to calculate p values.
It's also worth noting that adonis and adonis2 also use different code to do similar things. According to the help page, adonis "is directly based on the algorithm of Anderson (2001)" which was about a permutational manova, while adonis2 is "based on the principles of McArdle & Anderson (2001)." That paper is actually about distance-based redundancy analysis (multivariate multiple regression) which can be used as a MANOVA by transforming categorical variables into dummy variables of 1's and 0's. This is likely why adonis2 has some additional flexibility compared to adonis.
Answer: Assuming that you have a disease and two confounding factors sex and age. So I would built the following model -distance_matrix~ disease + sex + age.
If you wish to take into account confounding factors while executing PERMANOVA would you use "margin" or NULL?
It seems that "terms" test sequentially, so the model won't really incorporate the confounders.

adonis vs. adonis2


Advice on using Organic Groups for course management in an academic context

Question: I am thinking about using Organic Groups for course management in an academic context.
Initially I was going to create an OG group per course e.g. Physics 101.
However if the users change per semester this could become tricky to manage...
There are 2 options I can think of:

Create a new group each semester e.g "Physics 101 – Semester 1, 2013"

But would soon end up with 1000's of groups.

Somehow archive the data, clear down the group and re-enrol the next class each semester

I'm unsure how we could effectively do the archival while keeping the data available, and it seems like it would become a convoluted process

I would love to know how other users of OG handle this type of problem?
Is there any online material that would help me learn how to use OG in this way?
Thanks for your help in advance!
Joe
Answer: I currently run a site where every 6-12 months users Groups (OG) will change. To help me, I use the Profile2 module, it makes dynamically changing user info such as OG memberships simple. If you're not already using it, have a read of the handbook.
The way I have solved the issue you have addressed is to have a spreadsheet of all the users who have changed groups, run a simple code on my spreadsheet to edit the "groups" column of the users to what they will now be, (you can simply cross reference another sheet, say the enrollment sheet for that class, and if the username or student ID appears there, put that class ID into the group column in the sheet), and when the spreadsheet is complete, simply export as a csv and then run an import through the Feeds module. This gives you the option to update the existing user information, and you have all of the old spreadsheets as an "archive". Alternatively, you could take a snapshot of the tables database, keep this in an archive, and run simple SQL Queries to update the groups of a user.
Let me know if you need more information, if you choose to approach it this way!


Meu Node.JS continua executando na versão antiga

Question: Olá, estou fazendo notificações com cloud functions e node.js, a minha versão do Node.Js é a 12 mas o deploy está sendo na 8, alguém pode me ajudar ? PS: O Google vai deixar de aceitar a versão 8.
Answer: Segundo a documentação, basta adicionar a linha:
"engines": {"node": "10"}

No seu package.json
Comment: Muito obrigado pela ajuda, deu certo, valeu \0/


Open and closed balls in $C[a,b]$

Question: Let $X$ be a non empty set and let $C[a,b]$ denote the set of all real or complex valued continuous functions on $X$ with a metric induced by the supremum norm.
How to find open and closed balls in $C[a,b]$? Can we see them geometrically? For example what is an open ball $B(x_0;1)$ i.e. ball centered at $x_0$ with radius $1$ in $C[a,b]$. I can visualize them in $\mathbb R^n$ but when it comes to functional spaces I have no clue how to identify them?
Thanks for helping me.
Comment: I assume $X$ is the interval $[a,b]$? Given a continuous function $f:[a,b]\to\Bbb R$ I would visualize the open ball of radius one around $f$ to be the set of all functions whose graphs exist in the strip between the graphs of $y=f(x)+1$ and $y=f(x)-1$.
Answer: Yes, you should think of it just like you think of any other metric space. Every norm $\|\cdot\|$ induces a metric $d(x,y) := \|x-y\|$.
In your example,
$$ B(x_0, 1) = \{ f: X \to \mathbb R \Big \vert \|f - x_0\|_\infty < 1 \}$$
In the $\sup$-norm, these $f$ are all functions that are never further away from $x_0$ at any given $x$ in $\mathbb R$. This is what it looks like:
Comment: @srijan Does the picture help?
Comment: Note also: the graphs of the functions inside the open/closed ball can intersect the black curve, and the boundary of the closed ball (the sphere) are those functions inside whose graphs *touch* (at least once) one of the two red curves that bound the strip.
Comment: @srijan Glad I could help : )
Comment: Thanks for answering but still i am not able to see it geometrically.
Comment: N  I am very much thankful to you. Now things are transparent.
Comment: @anon Thanks for pointing that out!
Answer: So I'm new here and sorry if I have this wrong, but apparently I'm not meant to respond to other answers; yet I also need 50 reputation to add a comment, so I can't do that? Anyway, I believe the above answers are incorrect. Just take the center of an open ball to be the zero function (radius 1) and $f$ to be $2/\pi \arctan(x)$. Then $f(x)$ is always within a distance of 1 from the center (strictly) in R, but $f$ is a distance of 1 from the zero function (exactually 1, so not in the open ball) in the function space, because the supremum of $\{f(x)-0 | x \in R\}$ is indeed 1. In fact f is on the boundry in the function space despite its values never touching 1 or -1 in R.
Comment: OP's question was specifically about $C[a,b]$ not $C(\mathbb R)$ which indeed behaves a bit differently.
Comment: $\mathbb{R}$ behaves differently because it isn't bounded; hence it isn't compact.  Since $[a,b]$ is compact, any function attains its supremum value somewhere on the interval, thus we won't run into this problem.
Comment: I agree with the comments give above.

Open and closed balls in $C[a,b]$


Migrated to new server, DNS setup >48 hrs, some MySQL inserts from domain still show up on old server

Question: Title says it all - I've migrated to a new dedicated server at a different IP..  It's been more than 48 hours since DNS was setup. Some MySQL inserts (standard php variables invoke mysql) from at least one domain this server hosts still show up on the old server, rather than the new. What's happening?
Here's one domain to check - http://inacentaur.com
Answer: While most DNS servers observe cache settings, some providers set a minimum TTL to cut down on the load of having to verify domain names.  At one point, AOL.com used to set a minimum TTL of 7 days.
After 48 hours, depending on the TTL you set on your domain (or your host set), you should see about 95% of your traffic moved over.
If possible, allow remote mysql connections and have your old server connect via TCP to your new server to get any transaction.  The latency shouldn't be too bad and since it is only the stragglers, you shouldn't see too much effect, and won't lose any data.
Comment: Big prob is that the old server (from a different provider) has its term ending tonight, so will be taken off anytime now..
Comment: With the economy the way it is, it is difficult to say whether a hosting company will take a server offline the instant it is available.  Many will leave it running until they get to it or need to allocate it to another client.  However, in that situation, there really isn't much else you can do other than hope.
Comment: Unfortunately, one of the big reasons why I had to move was because my old provider was getting too promiscuous in hunting down new customers, such that they started to totally ignore their old customers (folks who had been with them for ten years) in hopes of impressing new customers. In any case, it looks like they took down my old server on the hour.
Answer: A couple of days before migraitsey needed to reduce the TTL to 15 days.
Before the migration, make proxy requests to the old server to new server. And then edit the DNS.


I need to get the post id for the first post of the current user in wordpress

Question: I have this so far
get_currentuserinfo(); $the_post = get_posts("author=" . $current_user->ID . "&posts_per_page=1"); $the_post = $the_post[0];
but I'm not sure how to get just the ID out of the array
Answer: get_posts() will return an array of posts ordered by the date of publication, in descending order. So, with the code you posted, the first post in the array ([0]) will be the last post published by the author. If you really want the first post of the user, you can just add the order argument to the call (&order=ASC) to override the default.
I think the key for the ID is just "ID", so you can retrieve it with $the_post = $post[0]['ID']. But I have to admit I can't remember for sure and the documentation does not detail that, it could also be "post_id". You can do a: print_r($the_post) to check the keys of the returned array.
Comment: @Cadoc: My mistake, you're right, it returns an array of post objects, so the ID would be retrieved with $the_post[0]->ID.
Comment: Wordpress Dokumenation @ http://codex.wordpress.org/Function_Reference/get_posts states: To access a post's ID or content without calling setup_postdata(), or in fact any post-specific data (data retained in the posts table), you can use $post->COLUMN, where COLUMN is the table column name for the data. So $post->ID holds the ID, $post->post_content the content, and so on. To display or print this data on your page use the PHP echo command, like so:

ID; ?>
Answer: You can write query like this way-
 $oldest_post_query = get_posts("post_type=post&numberposts=1&order=ASC");
 $oldest_post_id = $oldest_post_query[0]->ID;

 //print the post title

'.get_the_title( $oldest_post_id ).'
';


netcat not found in Amazon AMI (Centos)

Question: I followed this guide to migrate my amazon image from one zone to another. Everything goes fine, but when i run this command:
netcat -p 9999 -l >/dev/sdf

It shows that the command is not found. Then i tried to use nc instead:
nc -p 9999 -l >/dev/sdf

It seems that nc cannot be run with the combination of -p and -l option. What is the exactly same command i should run on my system in equivalent to "netcat -p 9999 -l >/dev/sdf" ?
i am using "Basic 32-bit Amazon Linux AMI 2011.02.1 Beta" as my primary image. It seems that it's centos based. Any help would be much appreciated.
Comment: Archive of the linked post found here: https://web.archive.org/web/20130410051019/http://blog.taggesell.de/index.php?/archives/85-Amazon-EC2-How-to-migrate-an-EBS-backed-image-from-US-to-EU-or-wherever.html
Answer: Some nc versions has -p option with different meaning:
-p source_port
             Specifies the source port nc should use, subject to privilege restrictions and availability.  It is
             an error to use this option in conjunction with the -l option.

while another:
-p port      local port number (port numbers can be individual or ranges: lo-hi [inclusive])

In your case, just use nc -l 9999 > /dev/sdf is enough.

netcat not found in Amazon AMI (Centos)


How do I limit API requests in my app Angular 9

Question: This is my first time trying to do that, if someone can guide that would be very helpful. What I need or I'm trying is to wait every HTTP answer when you do a request to the API until you don't get the answer you cant click in a button again, but really don't know how to start
This is the code where I call to the function that does the POST method to the API
constructor(
    private _builder:FormBuilder, private usersService: UsersService,private router: Router,
    public _snackBar: MatSnackBar
    ) {}

  sendUser(){
    this.bSignIn = true;
    let formData = new FormData();
    formData.append('Identifier', this.loginForm.get('Identifier').value);
    formData.append('Password', this.loginForm.get('Password').value);
    setTimeout(() => {
    this.usersService.validateUserCredentials(formData)
    .subscribe(
      res => {
        this.bSignIn = false;
        let auxRes: any = res;
        if(auxRes.type == 'success'){
          let auxUser = {
            userId: auxRes.id,
            personId: auxRes.person_id,
            clientId: auxRes.client_id,
            projectId: auxRes.project_id
          }
          this.isSigned = true;
          //this.usersService.validateSigned(auxRes);
          localStorage.setItem('leadLogged', JSON.stringify(auxUser));
          this.goToUsersDashboard(auxRes.id);
        }
        else{
          this.openSnackBar(this.snackMessage);
          this.loginForm.reset();
        }
      },
      err => {
        console.log("else");
        window.alert('Introduce valid data');
        }
    )}, 4000);

  }

ValidateUserCridentials is the function that does the POST method
ValidateUsersCridentials function
validateUserCredentials(user: any){
    return this.http.post(this.API_URL+'NONE-NONE-2/'+ENDPOINT_NAME+'/login/', user, this.httpOptions);
  }

This is my button
<button mat-raised-button [class.black]="!loginForm.invalid" [disabled]="loginForm.invalid" type="submit">Sign in</button>

Comment: So you want to disable the button until the request finishes?
Comment: Yes I want that @mwilson
Answer: Its easy, just use some variable blockButton=false - and when user click on button then inside click event handler, at the beginning use
if(this.blockButton) return;
this.blockButton=true;

so in this way you "block" click handler (at "first click") to execute main code as long as blockButton is true. Then in your .subscribe section (which is executed when your API return response) write
this.blockButton=false

This will unblock your button (only when you get response from serwer)
Comment: The problem i had with this is when someone click my submit button they can click it very fast and do many API requests i want it to be like you click one time wait the response and then click again, maybe your solution could work but how i tried with your example dont
Comment: @Rinzler21  when you use above solution - when someone click, and send request then when he click again (before response came) he will not send new request (because blockButton=true). This is how it works, but may be I don't understand your problem
Comment: Can you put an example?
Answer: When you click on logIn button, disable it in typescript code and then call the api.
Once you get the result, enable it again.
Do something like...
<button [disabled]="disabled" (click)="send()">Login</button>

Code behind:
async send(){
    // disable the login button
    this.disabled = true;

    // using delay for http response
    await this.delay(3000);

    this.disabled = false;

  }

  private delay(ms: number){
  return new Promise(resolve => setTimeout(resolve, ms));
  }

disable is property in your component and set it to true once you click on it and then make API request.
Quick demo --> https://stackblitz.com/edit/angular-qe11v1
Comment: Ready men i put this because of the properties of my button [disabled]="loginForm.invalid || disabled"
Comment: You need to be more specific about the answer i understand your idea but really don't understand how to implemented
Comment: @Rinzler21 edited my answer with an angular playground link for understanding.
Comment: Yes this is pretty much what I'm looking for
Comment: did you bind the button disabled property to the typescript property in html?
Answer: You will want to create a variable to track the disabled state, then apply the state to true when they click and return it to false when your subscription completes. The following example is created from the Angular example docs:
Relevant code:
component.ts
  disableConfig = false;

  showConfig() {
    this.configService.getConfig()
      .subscribe(
        (data: Config) => this.config = { ...data }, // success path
        error => this.error = error, // error path
        _ => this.disableConfig = false // on complete
      );
  }

component.html
  <button [disabled]="disableConfig" (click)="clear(); disableConfig = true; showConfig()">get</button>

Test on the following stackblitz by clicking the get button to see how it disables on click and re-enabled when a response is returned (or error). The code is contained within the config folder.
https://stackblitz.com/edit/angular-ycvjsz
Comment: This looks very good for me, let me see how can i implement something like this in my code


How to get all the same field matching nested object on JSON

Question: Below is my JSON Object. In that i need to filter only leaf as true field. [
   {
      "id":1,
      "title":"ASD Headquarters",
      "items":[
         {
            "id":11,
            "title":"San Jose",
            "items":[
               {
                  "id":13,
                  "title":"Jensen Chapman's Team",
                  "items":[
                     {
                        "id":14,
                        "title":"Jimmy John",
                        "leaf":"true"
                     },
                     {
                        "id":15,
                        "title":"Daniel Mills",
                        "leaf":"true"
                     },
                     {
                        "id":16,
                        "title":"Chris Boden"
                     }
                  ]
               }
            ]
         },
         {
            "id":12,
            "title":"Irvine",
            "items":[
               {
                  "id":24,
                  "title":"San Jesus"
               },
               {
                  "id":25,
                  "title":"Fat Albert"
               },
               {
                  "id":26,
                  "title":"Connor McDavid",
                  "leaf":"true"
               }
            ]
         },
         {
            "id":30,
            "title":"San Diego",
            "items":[
               {
                  "id":31,
                  "title":"Duran Duran's Team",
                  "items":[
                     {
                        "id":32,
                        "title":"Amberlynn Pinkerton"
                     },
                     {
                        "id":33,
                        "title":"Tony Mejia"
                     },
                     {
                        "id":34,
                        "title":"Richard Partridge",
                        "leaf":"true"
                     },
                     {
                        "id":35,
                        "title":"Elliot Stabler"
                     }
                  ]
               },
               {
                  "id":40,
                  "title":"Steely Dan's Team",
                  "items":[
                     {
                        "id":36,
                        "title":"Tony Stark"
                     },
                     {
                        "id":37,
                        "title":"Totally Rad"
                     },
                     {
                        "id":38,
                        "title":"Matt Murdock"
                     },
                     {
                        "id":39,
                        "title":"Stan Lee"
                     }
                  ]
               }
            ]
         },
         {
            "id":64,
            "title":"Richard Partridge Stark",
            "leaf":"true"
         }
      ]
   }
]
Output that required is: [
   {
      "id":14,
      "title":"Jimmy John",
      "leaf":"true"
   },
   {
      "id":15,
      "title":"Daniel Mills",
      "leaf":"true"
   },
   {
      "id":26,
      "title":"Connor McDavid",
      "leaf":"true"
   },
   {
      "id":34,
      "title":"Richard Partridge",
      "leaf":"true"
   },
   {
      "id":64,
      "title":"Richard Partridge Stark",
      "leaf":"true"
   }
]
Comment: Just create a recursive function, if it is not a `leaf` then pass the `items` attribute to the function.
Comment: What did you try?
Answer: Below function i used to get the respective data.

angular.module('demoApp', [])

.controller('MainCtrl', function($scope) {
    $scope.json = [{
      "id":1,
      "title":"ASD Headquarters",
      "items":[
         {
            "id":11,
            "title":"San Jose",
            "items":[
               {
                  "id":13,
                  "title":"Jensen Chapman's Team",
                  "items":[
                     {
                        "id":14,
                        "title":"Jimmy John",
                        "leaf":"true"
                     },
                     {
                        "id":15,
                        "title":"Daniel Mills",
                        "leaf":"true"
                     },
                     {
                        "id":16,
                        "title":"Chris Boden"
                     }
                  ]
               }
            ]
         },
         {
            "id":12,
            "title":"Irvine",
            "items":[
               {
                  "id":24,
                  "title":"San Jesus"
               },
               {
                  "id":25,
                  "title":"Fat Albert"
               },
               {
                  "id":26,
                  "title":"Connor McDavid",
                  "leaf":"true"
               }
            ]
         },
         {
            "id":30,
            "title":"San Diego",
            "items":[
               {
                  "id":31,
                  "title":"Duran Duran's Team",
                  "items":[
                     {
                        "id":32,
                        "title":"Amberlynn Pinkerton"
                     },
                     {
                        "id":33,
                        "title":"Tony Mejia"
                     },
                     {
                        "id":34,
                        "title":"Richard Partridge",
                        "leaf":"true"
                     },
                     {
                        "id":35,
                        "title":"Elliot Stabler"
                     }
                  ]
               },
               {
                  "id":40,
                  "title":"Steely Dan's Team",
                  "items":[
                     {
                        "id":36,
                        "title":"Tony Stark"
                     },
                     {
                        "id":37,
                        "title":"Totally Rad"
                     },
                     {
                        "id":38,
                        "title":"Matt Murdock"
                     },
                     {
                        "id":39,
                        "title":"Stan Lee"
                     }
                  ]
               }
            ]
         },
         {
            "id":64,
            "title":"Richard Partridge Stark",
            "leaf":"true"
         }
      ]
   }
];
    $scope.obj = [];
    finddata($scope.json, 'leaf', 'true')
    function finddata(list, key, val) {
        if(!list)
            return;
        list.forEach(item => {
            if(!item)
                return;
            if(item[key] === val){
                $scope.obj.push(item)
                return;
            }else
            finddata(item.items, key, val)
            return;
        })
    }

})

{{obj | json}}


Expected number of request at a given time, knowing requests per minute and average request processing length

Question: Imagine a server that takes requests from clients and returns a response to them. We model it by assuming a certain average number of requests received per minute (let's say 100), and also by assuming an average time it takes to process a request (let's say 0.1 seconds). For simplicity, we assume that the server can take and process an arbitrary number of requests in parallel.
I would like to calculate the expected number of requests that are being processed at any given moment.
What kind of approach should I take? What other assumptions I will also need to make the calculation possible?
Comment: @lulu If you receive on average $100$ requests a minute, and process each in an average of $\frac1{600}$ of a minute, then a natural guess for the expected number of requests that are being processed at any given moment is $\frac16$.  Can you find a case where that does not apply?  Your clustering would lead to more being processed in parallel (pushing up the expectation) but also more time when none are being processed (pushing down the expectation)
Comment: You'll need a model for the request process.  Standard would be a Poisson distribution (implementing the assumption that a request is equally likely to come in at any time).  That distribution has the problem that it scales.  That is to say, the distribution of requests in a specified $.1$ second window is again Poisson with the appropriately scaled parameter.
Comment: @Henry  Ah, you are right. If we have $N$ requests, they consume $N\times .1$ seconds of processing time, and that's all you need to know.  Thanks.  I'll delete that comment.
Comment: @Henry that argument sounds reasonable, can you please write it up as an answer?
Answer: Requested from comments:
If you receive on average $100$ requests a minute, and process each in an average of $\frac1{600}$ of a minute, then a natural guess for the expected number of requests that are being processed at any given moment is $\frac16$.


Tomcat 7 symbolic link to war file

Question: I would like to have a symbolic link in tomcat's webapps directory that points to a war file at another place in my file system, and I would like that war file to be served as the default webapp. I have pieced together the following solution, but the app is not accessible from the browser.
I have a folder in my home directory ~/tomcat/webapps. The owner is tomcat7. In this folder, I have my war file, myapp-1.0.war.
In my /var/lib/tomcat7/webapps directory, I have a symbolic link:
myapp -> /home/[me]/tomcat/webapps/myapp-1.0.war.

In my /etc/tomcat7/server.xml, I have:
<Context docBase="/var/lib/tomcat7/webapps/myapp" path="" reloadable="true" allowLinking="true"/>

Tomcat starts with no complaints in the logs, but my app is not accessible.
[host]:8080/rest/ returns 404, where it would normally take me to the home page.
I partially want to do this to abstract out the version number from my war file. Any ideas why this is not working, or what I'm doing wrong?
Thanks.
Comment: Fixed it. I must have stared at it too long. Basically, the symlink needs to have a .war extension.
Comment: these are both in the ```/webapps``` directory?
Comment: I don't fully understand your question. I have a symlink in the tomcat7/webapps directory. The actual war being linked to is in an external directory of my creation that happens to be named tomcat/webapps.
Answer: I found the problem. The symlink in the webapps directory needs to have a .war extension. So, instead of:
myapp -> /home/[me]/tomcat/webapps/myapp-1.0.war

It should be:
myapp.war -> /home/[me]/tomcat/webapps/myapp-1.0.war

I was also able to shorten the value of the docBase attribute as below:
<Context docBase="myapp" path="" reloadable="true" allowLinking="true"/>

Tomcat 7 symbolic link to war file


*Updated* Problem showing General Distributive Law In Suppes Axiomatic Set Theory

Question: In Suppes's Axiomatic Set Theory, we are asked to prove the following:
Theorem 84 $A \cap \bigcup B = \bigcup_{C \in B} (A \cap C)$
Definition Schema:
$\bigcup_{x \in A} t(x) = \bigcup \{y : \exists x(y = t(x)\,\&\,x \in A\}$
where $t(x)$ denotes a term schema.
I'm stuck on the part showing that $A\cap \bigcup B \subset \bigcup_{C \in B} (A \cap B)$ where I am at so far:
Let $x \in A \cap \bigcup B$. Then $x\in A$ & $x\in D$ & $D\in B$. So, $(x\in A \cap D)\& (D \in B)$. To show that $x\in \bigcup_{C \in B} (A \cap C)$ we need to show that $\exists D'(x \in D' \space \land$ $D' \in\{y : \exists C(y = A \cap C \space \& \space C \in B) \}$.
The issue and problem I am running into is showing $D'\in\{y:\exists C(y = A \cap C \space \& \space C \in B)\}$.
The appropriate $D'$ seems to be $A \cap D$, since $A\cap D = A\cap D\;\&\; D\in B$ is true, i.e., $\varphi(A \cap D)$ is true. But this doesn't allow us to infer  $A \cap D \in \{y : \exists C(y = A \cap C \space \& \space C \in B) \}$, since it's not true that $\varphi(A \cap D) \implies A \cap D \in \{y : \exists C(y = A \cap C \space \& \space C \in B) \}$. We can only make that inference if we have either $\{y : \exists C(y = A \cap C \space \& \space C \in B) \}$ is not empty or $\exists Z \forall x(x \in Z \iff \exists C(x= A \cap C \space \& \space C \in B)$ as per the definition by abstraction.
Suppes Definition for abstraction notation $\{ x\mid \varphi(x) \}$ is given here: Definition by Abstraction in Axiomatic Set Theory by Suppes.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/141031/discussion-on-question-by-jcal-updated-problem-showing-general-distributive-la).
Answer: I have now figured this out, We need the power set axiom introduced in the next section as indicated by the Hint in the Dover edition (which I am not using) this hint is not in the original edition.
From this we can deduce. $\exists Z \forall x(x \in Z \iff \exists C(x= A \cap C \space \& \space C \in B)$ as per the definition by abstraction, and Whence the desired inference. I knew something wrong was going on here in the edition I have.
Answer: For every $p$ we have
$p\in A\cap (\bigcup B) \iff$
$(p\in A)\land (p\in\bigcup B)\iff$
$(p\in A)\land (\exists C\in B\,(p\in C)) \iff$
$\exists C\in B\,(p\in A\land p\in C) \iff$
$\exists C\in B\,(p\in A\cap C)\iff$
$p\in\bigcup_{C\in B} \,(A\cap C).$
Comment: The last equivalence is incorrect '$\implies$' For this present theory. see updated question
Comment: The proof does not explain the problem that I am stuck on, which is the basis of my question. See updated post.
Comment: From: Let $x \in A \cap \bigcup B$ we need to show that $x\in \bigcup_{C \in B} (A \cap C)$ to do this we need to show that $\exists D'(x \in D' \space \land$ $D' \in\{y : \exists C(y = A \cap C \space \& \space C \in B) \}$.

How?
Comment: I am correct for this theory that last equivalence is incorrect.


What are the named ports for iptables?

Question: When setting up iptables you can name the port ssh which will use port 22. Is there a list of all the named ports? Specifically I need ssh, http, https and mysql.
Answer: On your installation, the list will be based on the file /etc/services
Comment: Thanks this definately makes iptables more readable to other admins.
Answer: The list of "Well-Known Ports" is maintained by the Internet Assigned Numbers Authority (IANA).  The latest version can be found at http://www.iana.org/assignments/port-numbers.
Note that most Linux distributions include a subset of the list in /etc/services for use in referring to them symbolically.  Windows has it in %windir%\system32\drivers\etc\services.
Comment: Keep in mind that this is not governed, though, and it's not an exhaustive list of what you might find. A developer can pick whatever port they want for the app to talk on. Doesn't mean it's smart, but they can do it...
Answer: ssh tcp/22
http tcp/80
https tcp/443
mysql clustering tcp/1186 and udp/1186
mysql tcp/3306

What are the named ports for iptables?


Dealing with large arrays in PHP

Question: Okay a couple of simple questions.
First, am I correct to assume that doing this is a bad idea because the array gets recreated each time the function is called?
function foo(){
    $arr = {"REALLY_BIG_ARRAY":"HAS LIKE 1000 ELEMENTS"};
}

Now to deal with this I came up with the idea of doing this:
class example {
    public static $property =  {"REALLY_BIG_ARRAY":"HAS LIKE 1000 ELEMENTS"};
}

function foo(){
    //to use the array I do
    foo::$property["some_element"]; //Do something with this
}

I am using this in a small web app I am currently building. Are there any good ways of dealing with big data arrays in PHP. This function gets called a lot so thats why putting the array in DV seemed like a bad idea.
Comment: Are you going to need all 1000 every time you load ... is there a way to lazy load only the values that you need? What do you have to do to get at the 1000 elements... maybe some kind of cache could be utilized.
Comment: You don't need to hardcode your data in PHP. Just use data store like Memcache or Redis.
Answer: You can use a static variable:
function foo(){
    static $arr = {"REALLY_BIG_ARRAY":"HAS LIKE 1000 ELEMENTS"};
}

It will only be created the first time you call the function, future calls will reuse the value.

Dealing with large arrays in PHP


Shell script for loop is behaving unexpected

Question: Shell script for loop is behaving unexpected ! The requirement is need to iterate the loop line by line of the property file.  Its mandatory to use the  for loop.
hostnamefl=/tmp/propperty.txt

for property  in $(cat $hostnamefl)
do
hostname=`echo $property | awk '{print $1}'`
echo $hostname
user=`echo $property | awk '{print $2}'`
echo $user
pas=`echo $property | awk '{print $3}'`
echo $pas
echo "---------------------------------------------------------------------------------"
done

propperty.txt
host1 host1user host1pas
host2 host2user host2pas
host3 host3user host3pas

I am getting the result as given below :
host1
---------------------------------------------------------------------------------
host1user
---------------------------------------------------------------------------------
host1pas
---------------------------------------------------------------------------------
host2
---------------------------------------------------------------------------------
host2user
---------------------------------------------------------------------------------
host2pas
---------------------------------------------------------------------------------
host3
---------------------------------------------------------------------------------
host3user
---------------------------------------------------------------------------------
host3pas
---------------------------------------------------------------------------------

Expected result:
host1
host1user
host1pas
---------------------------------------------------------------------------------
host2
host2user
host2pas
---------------------------------------------------------------------------------
host3
host3user
host3pas
---------------------------------------------------------------------------------

For loop is iterating word by word rather than line by line, how should I resolve it ?
Comment: This question would be best addressed on the UNIX SE and certainly this is not a place to handle homework problems.
Answer: That's how for loops work — they treat all input as whitespace-delimited words.  What you want is the read builtin command, which reads a line at a time.
while read line ; do
    for word in $line; do
        echo $word
    done
    echo ---------------------------------------------------------------------------------
done < /tmp/propperty.txt

Answer: If cat /tmp/propperty.txt does output setting the IFS variable might help
host1 host1user host1pas
host2 host2user host2pas
host3 host3user host3pas

See Sepcial Paramenters in bash man page
IFS=:
hostnamefl=/tmp/propperty.txt

for property  in $(cat $hostnamefl)
do
hostname=`echo $property | awk '{print $1}'`
echo $hostname
user=`echo $property | awk '{print $2}'`
echo $user
pas=`echo $property | awk '{print $3}'`
echo $pas
echo "---------------------------------------------------------------------------------"
done

Comment: It is not working, I need to itrate the loop row base of property.txt...
Answer: If rhasti's answer doesn't work for you. You can do this
while read property
do
    hostname=`echo $property | awk '{print $1}'`
    echo $hostname
    user=`echo $property | awk '{print $2}'`
    echo $user
    pas=`echo $property | awk '{print $3}'`
    echo $pas
    echo "---------------------------------------------------------------------------------"

done < /tmp/propperty.txt

Comment: Sorry Mike I couldint use the while loop, its mandatory to use the  for loop.
Comment: ohh so it's a homework assignment then
Comment: Thanks Mike, Do to some application behavior we are in need of only to user the "for loop", so Its mandatory to use the for loop. The requirement is,  need to iterate the loop line by line of the property file. I dont know why the for loop is behavior is like this, I think it is taking column ...
Answer: read can parse the line for you: there is no need for awk
while read hostname user pas
do
   echo $hostname
   echo $user
   echo $pas
   echo -------------
done < /tmp/property.txt


Can i compare two array using computed property in Vue js?

Question: I am so sorry if I didn't explain this clearly. I want to create an edit amenity like Airbnb.
I have the "Amenity" array with id, name. Then I loaded all the amenities for house_id = 2 to an array called "house_amenities".
What I want is when a record in house_amenities with amenites_id match with id from "Amenities" a checkbox will be ticked.
What i want to achieved: [1]:https://postimg.cc/bGhvGGSP
I tried using the computed property but haven't had any luck yet. It always returned "[Vue warn]: Error in render: "TypeError: Cannot read property 'length' of undefined"

        ID
        Amenities

            <input class="selectable-item" type="checkbox">

            {{index+1}}
            {{amenity.name}}

                <input class="selectable-item" type="checkbox" value="check[index]"  >

And here is vue code:
computed: {
    checked: function(){
        this.amenitiesLst.map(function(item){
            for(var i = 0; i < this.houseAmenitiesLst.length; i++)
            {
                if(item.id == this.houseAmenitiesLst[i].amenities_id)
                    return true;
                else
                    return false;
            }
        })
    }
},

Comment: `return` in for means it gets only first time executed.
Comment: Can you tell me more about this? It's mean only the first record in this.houseAmenitiesLst got compared? I get the error "[Vue warn]: Error in render: "TypeError: Cannot read property 'length' of undefined"
Comment: yes, only the first one. Becaue if it's either true or false, it ends cycle.
Answer: I think the problem is with the context, this inside the map function doesn't refer to the Vue instance so houseAmenitiesLst is not defined
Try with:
computed: {
    checked: function(){
        this.amenitiesLst.map((item) => {
            for(var i = 0; i < this.houseAmenitiesLst.length; i++)
            {
                if(item.id == this.houseAmenitiesLst[i].amenities_id)
                    return true;
                else
                    return false;
            }
        })
    }
},

Comment: thanks for your suggestion I tried but it's still throwing this error "[Vue warn]: Error in render: "TypeError: Cannot read property '0' of undefined". I think this checked[index] is the one causing this. Still trying to understand why :(
Comment: Yeah i tried it too on the jsfiddle. My question is: why do you have a v-for on the tbody? I probably didn't understand what you want to achieve. Do you just need a list with all amenities and check the ones who are mapped into houseAmenities?
Comment: i want to achieve something like Airbnb did on their edit page. They have all amenities shown then checked the one that house already have and unchecked if it doesn't. Like this picture: https://postimg.cc/bGhvGGSP
Comment: http://jsfiddle.net/msr0wL7v/1/ i tweaked a bit your jsfiddle, is that what you want?
Comment: oh my, it is. Thank you so much.
Answer: Your issue is that the computed property is executed before you have any values in your amenitiesList in your function just add a check to only execute when is initiated like this:
checked: function(){
if(this.amenitiesLst){
        this.amenitiesLst.map(function(item){
            for(var i = 0; i < this.houseAmenitiesLst.length; i++)
            {
                if(item.id == this.houseAmenitiesLst[i].amenities_id)
                    return true;
                else
                    return false;
            }
        })
    }
return
    }

The computed property is executed each time a dependency changes therefore as soon as amentiesList is initialized it will return your value. You may also need to put a v-if on your template to make sure you don't have a render error.
Comment: i tried your suggestion but it still return the same error :(
Comment: try `if(!!this.amentiesList)` also try: `if(this.amenitiesList && this.amentiesList.length > 0`
Comment: now it throw this error: "[Vue warn]: Error in render: "TypeError: Cannot read property '0' of undefined". I checked and it seems that this "checked[index]" is causing the error. I've made a jsfiddle. Can you take a look for me? http://jsfiddle.net/alexvu2412/5dg64vcj/9/


Created custom entity with Entity Construction Kit but cannot filter in Views by taxonomy

Question: I'm new to D7 but have extensive experience as a site builder in D6.
I created a custom entity type using the Entity Construction Kit(ECK) and then added a bundle with a term reference field using a hierarchical taxonomy and the Simple Hierarchical Select widget.  Everything works fine except when I try to build a view to display the fields and filter by the taxonomy terms selected using the SHS widget.
When you start building the view the preselector screen asks what to show; content, users, my custom entity/bundle, etc.  If I select my custom entity bundle, taxonomy terms don't show up as available for filtering.  If I select content, then my custom entity is not available presumably because content means nodes.
How do I build a view that displays fields from my custom entity and can be filtered using taxonomy?  If I create a custom content type instead of an entity, there's no problem filtering by terms, as expected.  What am I missing?
Tnx,
Jeff
Answer: SHS doesn't work with entities, only nodes.  The Hierarchical Select module doesn't support Views exposed filters yet either.
The taxonomy terms didn't show up as filters because I hadn't selected the bundle in the Views preselector screen.  I was trying to generalize the view to filter at any level with SHS but no workee.
This forces me to use nodes where entities are more appropriate, or try some other taxonomy scheme to get some useable exposed filter UI, using entities.
Ugh.


JSON file not all caught in a Jquery ajax request

Question: I have a problem sending my JSON file parameters through HTTP POST method.
The file is properly generated but only part of it is sent.
       $("#catalogOfService").jqGrid('navGrid',"#catalogOfService_pager").jqGrid('navButtonAdd', '#catalogOfService_pager', {
        caption: "Export to Excel",
        onClickButton: function () {
            var json = $("#catalogOfService").getRowData();
            var name = "report_catalogue";
            console.log(json);

            $.ajax({
                type: "POST",
                async: false,
                url: "ExportCatalogueExcell.php",
                data: {
                          name: name,
                          data: json,
                },

                success: function(result)
                {
                },
                success: function(e){
                    setTimeout(function() {
                        console.log(yeah);
                        window.open("../tmp/" + name + '.csv');
                    }, 1000);
                }
            });
        }
    });

Comment: You need to provide more details about the specific problem you are having
Comment: two `success` callbacks....?
Comment: what is in`ExportCatalogueExcell.php`?
Comment: I'm using jquery to send a JSON file in order to generate a CSV file. I get the JSON from a jqgrid data that contains more than 230 lines .The problem that only 82 line of the table are sent in the HTTP POST method
Comment: Have you watched the request / response in the browser's console?
Comment: Yes , the console.log(json) shows all my data(233 lines)  and  in the  POST HTTP  there is only 82.
Comment: Given the organization of your code I would imagine that it throws errors.
Answer: You may need to update this part:
data: JSON.stringify(json)

JSON.stringify() converts a JavaScript value to a JSON string, in other words, it converts a JavaScript object to JSON text and stores that JSON text in a string. And, this JSON text is what you need as the data in your POST request.
Comment: I think there are a lot more problems than this with the OP's code.
Comment: It would also be good to explain why this line needs to be updated.


How can I limit an entity reference selection to a specific field value on the reference

Question: I have a content type Research which has a an entity reference type of People.
The problem is that I don't want to show ALL people but only people which have a certain value under their field named type.
I was trying to find it here:

Anyone an idea how to only show a content-type for a certain field value of that content type
Answer: You can create an Entity Reference display in a view and use that to generate the available options.

In your view of choice, create a new display of type Entity Reference and configure it so that it only shows the content you want.
Navigate back to your field configuration screen (the one in your screenshot) and change Reference Method from "Default" to "Views: Filter by an entity reference view" and choose the display you created in step 1.