Dynamically Add Variable Name Value Pairs to JSON Object

Question: I have a json object full of ips like
var ips = {}

I then add ip objects to this object like so
ips[ipID] = {}

I then need to add dynamic/variable name value pairs to each ip so I am using code like this
var name; var value; var temp = {};
tmp[name] = value

My question is, how can I add these name value pairs/ tmp to my ipID objects so that my outcome turns out like
ipID = { name : value, anotherName : anotherValue }

Comment: Do you also need code to produce the final JSON?
Comment: possible duplicate of [Using a variable for a Javascript object key](http://stackoverflow.com/questions/2274242/using-a-variable-for-a-javascript-object-key)
Answer: That's not JSON. It's just Javascript objects, and has nothing at all to do with JSON.
You can use brackets to set the properties dynamically. Example:
var obj = {};
obj['name'] = value;
obj['anotherName'] = anotherValue;

This gives exactly the same as creating the object with an object literal like this:
var obj = { name : value, anotherName : anotherValue };

If you have already added the object to the ips collection, you use one pair of brackets to access the object in the collection, and another pair to access the propery in the object:
ips[ipId] = {};
ips[ipId]['name'] = value;
ips[ipId]['anotherName'] = anotherValue;

Notice similarity with the code above, but that you are just using ips[ipId] instead of obj.
You can also get a reference to the object back from the collection, and use that to access the object while it remains in the collection:
ips[ipId] = {};
var obj = ips[ipId];
obj['name'] = value;
obj['anotherName'] = anotherValue;

You can use string variables to specify the names of the properties:
var name = 'name';
obj[name] = value;
name = 'anotherName';
obj[name] = anotherValue;

It's value of the variable (the string) that identifies the property, so while you use obj[name] for both properties in the code above, it's the string in the variable at the moment that you access it that determines what property will be accessed.
Comment: This would work fine but my names are also variables. So when the name changes it overwrites the previous name value pair.
Comment: @Mike: You can use a variable to specify the name of the property. It's the value of the variable at the moment of accessing the object that decides what property is accessed, so changing the variable to a different string between accesses is not a problem. See my addition above.
Comment: Well, I am using a .change function to generate this and for some reason it keeps overwriting my name. Is there anyway to temporarily deference the variable?
Comment: Post code for the .change function and we can better help you.
Comment: http://pastie.org/1264618 as I mentioned, it only allows for one name value pair...
Comment: Setting one property doesn't overwrite another property. The likely reason is that you are creating a new object each time which replaces the previous, so that it only has the latest property in it.
Comment: yes, that is precisely what is happening. See my pastie. Do you see anyway around that?
Comment: @Mike: You can check if the object already exist, so that you only create one the first time: http://pastie.org/1264654
Answer: With ECMAScript 6 there is a better way.
You can use computed property names in object property definitions, for example:
var name1 = 'John';
var value1 = '42';
var name2 = 'Sarah';
var value2 = '35';

var ipID = {
             [name1] : value1,
             [name2] : value2
           }

This is equivalent to the following, where you have variables for the property names.
var ipID = {
             John: '42',
             Sarah: '35'
           }

Comment: Nice Solution and working.

let dataToUpdate = {
    [field]: body[field],
  };

To update specific field and its value
Answer: when using javascript objects, you can also just use "dot notation" to add an item, (which JSLint prefers)
var myArray = { name : "john" };
//will initiate a key-value array with one item "name" and the value "john"
myArray.lastName = "smith";
//will add a key named lastName with the value "smith"
//Object {name: "john", lastName: "smith"}

Here is a screenshot from testing in the Chrome console
Comment: Is `myArray` really an array?  It appears to be an `Object` or hash.
Comment: yep, myObject would have been a better name choice
Answer: I'm assuming each entry in "ips" can have multiple name value pairs - so it's nested. You can achieve this data structure as such:
var ips = {}

function addIpId(ipID, name, value) {
    if (!ips[ipID]) ip[ipID] = {};
    var entries = ip[ipID];
    // you could add a check to ensure the name-value par's not already defined here
    var entries[name] = value;
}

Answer: in Javascript.
    var myObject = { "name" : "john" };
    // { "name" : "john" };
    myObject.gender = "male";
    // { "name" : "john", "gender":"male"};

Comment: I get an error "myObject.push is not a function" when I try that.
Answer: if my understanding of your initial JSON is correct, either of these solutions might help you loop through all ip ids & assign each one, a new object.
// initial JSON
var ips = {ipId1: {}, ipId2: {}};

// Solution1
Object.keys(ips).forEach(function(key) {
  ips[key] = {name: 'value', anotherName: 'another value'};
});

// Solution 2
Object.keys(ips).forEach(function(key) {
  Object.assign(ips[key],{name: 'value', anotherName: 'another value'});
});

To confirm:
console.log(JSON.stringify(ips, null, 2));

The above statement spits:
{
  "ipId1": {
    "name":"value",
    "anotherName":"another value"
  },
  "ipId2": {
    "name":"value",
    "anotherName":"another value"
  }
}

Answer: From what the other answers have proposed, I believe this might help:
var object = ips[ipId];
var name = "Joe";
var anothername = "Fred";
var value = "Thingy";
var anothervalue = "Fingy";
object[name] = value;
object[anothername] = anothervalue;

However, this is not tested, just an assumption based on the constant repetition of:
object["string"] = value;
//object = {string: value}

Answer: You can achieve this using Lodash _.assign function.

var ipID = {};
_.assign(ipID, {'name': "value"}, {'anotherName': "anotherValue"});
console.log(ipID);


How to test if a sample proportion matches a population proportion, should I use the z-test or the t-test?

Question:
For (a), $H_0 = 0.75$ and $H_a \ne 0.75$.
For (b), how can I get an answer with a $z$-value? Why can't I use a $t$-value to answer this question? Is the idea: $p \pm Z (p(1-p)/N)^{0.5}$?
Comment: How would you calculate the sample standard deviation for a t-statistic (and while that's possible, if non-obvious -- why would the result have a t-distribution)? Note that "infected" and "not-infected" are two states, so the sample observations are not drawn from a normal distribution. Please show your actual reasoning or an actual attempt at the question. Why do you think it's a Z -- are you working from some answers? (If so I suggest you put the answers away, and try to solve these without ever looking at the answers, by using the information you have been supplied in the subject)
Answer: T-values are used for inference with means because the sample standard deviation has to be used as an estimate for a population standard deviation, rather than using the population standard deviation directly (this is generally unknown).
Proportions are a little different in that the standard deviation of the hypothetical curve with mean $ p $ can be calculated by $ \sqrt{\frac{p(1-p)}{n}} $. (This has to do with the Central Limit Theorem.) The z-score of your hypothesis test is calculated by $ \frac{\hat p - p}{\sqrt{\frac{p(1-p)}{n}}} = z$. You can use the $ z $ value you calculate to find a P-value and reject or fail to reject $ H_0 $
Comment: Remember, $ p $ is the population parameter (the thing you're hypothesizing; 0.75.) $ \hat p $ is the sample you took of your population (0.716)
Comment: If you're talking about a confidence interval (a range for $ p $), that is different than a hypothesis test. The OP asked if there is evidence, so all you need to do is a hypothesis test.
Comment: n/m. I see what you mean now.
Comment: I calculated based on the equation that you gave to me. It was 1.686 while the answer is 1.756. I think it is not simply calculation mistake. Is there another equation for getting z value? anway, thank you for answering.
Comment: @sss please show your working. I get $z=-1.756$ using Zach's formula. My guess is you used the sample proportion in the denominator; in Zach's formula $\hat{p}$ is the sample proportion and $p$ is the hypothesized proportion. Note there are no $\hat{\ }$'s over the $p$'s in the denominator
Comment: Please show any working in your question. Note the rest of my comment above (I was editing it as you replied, sorry). My guess was correct. The approach you took would also converge to a standard normal distribution as $n\to\infty$, but relies on an additional theorem over the CLT and would have a flipped sign compared to the direction of the difference you'd want to look at, which may be confusing to beginners. The usual version of the proportions test -- and the one you've apparently been taught -- uses the null hypothesis values for the standard error of the proportion.
Comment: I did like 0.75-0.716 / (0.716*0.284/500)^0.5
Comment: oh then I should put 0.716 for ^p!
Comment: Oh, now I got -1.756. Then, according to p with ^ +- 1.756*(0.75*0.25/500)^0.5, 0.682 < p < 0.75, 75% is out of range that H0 can be rejected?
Comment: I am confused that how to calculate range of P from Zach's formula. Do I need to find the range of P from the table?


Reporting data from view in rails after_filter

Question: I want to log the number of cache misses for certain blocks in my views.  I do the log storing in an after_filter in my controller.
It doesn't seem possible to manipulate instance variables inside of views. What's the best way to store information during view rendering that is then made available to a controller's after_filter?
Comment: I've had threading problems storing controller data in models before, solved using the `Thread.current[]` construct.
Comment: I hope finally cache misses would get recorded somewhere through model, why not let a model handle this, let a model be a middle person, holding data in between, which both controller and view can access any time.
Comment: Is it easy to hold this data in a model in a thread-safe way? The cache-miss statistics seem like they should be removed from model logic as they're only related to the view rendering itself (this is cached HTML).
Comment: Do you already smelling any threading issue? As in all of your comments you seem to have concerns about thread-safe.
Comment: (which I should point out is generally a bad thing to do, but sometimes your problem just doesn't fit the MVC separation and it's not worth forcing that model)
Answer: I would consider moving the logic into a dedicated model  object.
class MyController > ApplicationController
  around_filter :record_cache_misses

  def record_cache_misses
    @cache_miss_logger = CacheMissLogger.new
    yield
    @cache_miss_logger.persist_count
  end
end

And in the view it would be a normal method call.
<% @cache_miss_logger.increment_count %>

Comment: It seems overkill to create a separate class just to hold the value. Why do this instead of the instance-variable idea of @kelvin ?
Comment: Hi Spike.  The other answer would work fine, too.  It's a matter of preference.  I think I'm still highly influenced by Avdi Grimm's Objects on Rails books with its emphasis on small, single responsibility classes.
Comment: Depending on what `persist_count` does, there could be a race condition. Just writing to a log shouldn't be a problem though.
Answer: Not sure if this is the best solution, but it works in a test rails app:
Add a method to your controller. It must be public, unless you're ok using send to call it.
def increment_miss
  @miss_count ||= 0
  @miss_count += 1
end

Then an after_filter (I've restricted mine to :index):
after_filter :only => :index do
  Rails.logger.info("miss_count: #{@miss_count.to_i}")
end

Then call the method in your view as many times as you need to:
<% controller.increment_miss %>

You may want to modify the method to take an optional increment_by param if you want to be able to increment by more than 1 per call.
Comment: do you know how this interacts with threading? Will `@miss_count` be shared across all threads running on that instance of the app, or is it local to the request?
Comment: `@miss_count` is local to the thread serving the current request, just like any other controller instance variable (e.g. those used to store objects to be passed to the view). Rails creates a new controller instance for every request.
Comment: that makes sense to me. I'll come back and accept this after I get a chance to implement it in the next couple of days. Thanks for the help.
Comment: views manipulations stays in views only, sorry Kelvin, this does not work.
Comment: @AmolPujari That is only true for certain changes the views make, such as setting an instance variable. But if the view calls a method that mutates the controller's state, that change persists and is available to the `after_filter`. Have you actually tried the code?
Comment: yes, I tried out with rails 3.2.3, it wasn't that way as you saying.
Comment: This solution is working for me.  I did use `helper_method :increment_miss` instead of making it a public method.
Comment: @spike yes, helper method is a bit cleaner if you don't want to explicitly reference the controller in the view code.
Answer: I found one more way out, I hope/guess it would be thread-safe, would be great if anybody confirms
# in controller
before_filter :foo
after_filter :bar

def foo
  class << @cache_miss
    attr_accessor :count
  end

  @cache_miss.count = 1
  puts "----------#{@cache_miss.count}" # => 1
end

def bar
  puts "----------#{@cache_miss.count}" # => 2
end

#in views
<% @cache_miss.count = 2 %>

Comment: Where are you assigning `@cache_miss`? If you don't assign it, you'll be adding the singleton accessor to the global `nil` object. Also, it will only be thread safe if you set it to an object that isn't shared. You could use an `OpenStruct`.
Answer: I suggest,

There is no straight forward way to achieve this as its not per rails MVC rule, and in any way it is not doable(unless you change rails)
You deal with data that has scope starting from and ending with views, so why to go reverse and make controller responsible for logging/utilizing it, let view/helper method log it
So you may initiate it in controller, you may have referred to cache in controller, take it forward, let view manipulate it, and in views/helpers you can log it, keep a separate log storing module/file take care of this concern, let helper include it, call it from views.
Comment: Sure, you could make it a helper method, but then you'd have to make sure to call it in the view *after* you've finished counting *all* the cache misses. This makes it very fragile because you have to remember to move the method call further down every time you add new code to that view file that needs to increment the counter. It gets even more confusing with partials.
Comment: you should have a space after footer in the layouts


Como somar valores de JSpinners?

Question: Quero fazer um simples programa onde o usuário põe um numero num JSpinner e, ao clicar num botão, aparecerá em outro JSpinner, o valor do primeiro somado por 2.
Porém, não consigo fazer a soma entre o valor indicado no JSpinner e 2, pois o valor do JSpinner não é considerado int. Como faço?
Aqui está uma amostra do codigo:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

    Object w = jSpinner2.getValue();
    jSpinner1.setValue(w+2); //Aqui acontece o erro

    //JSpinner1 é o valor final.
    //JSpi nner2 é o valor indicado pelo usuario.
}

Comment: Já tentou fazer um parse para int?
Comment: Desculpe sou novo em java, poderia-me explicar o que é um parse int?
Answer: Tente fazer o cast para Integer antes de somar o valor no novo Spinner:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

    int w = (Integer)jSpinner2.getValue();//cast de object para int
    jSpinner1.setValue(w+2);

}

Comment: Muito obrigado! Já funcionou

Como somar valores de JSpinners?


How can I Make my Custom Directive work inside the ng-repeat

Question: I have this directive for my ld Client. I tried to use it inside an ng-repeat but it wont work. What is the problem with this one? how can i make it work?
Tried to add the directive outside of ng-repeat and its working.
ldClient is a api variable in other module which returns true or false base on the flag variation.
Actually It doesnt even evaluate the directive like it not even calling it when its inside the ng-repeat

app.directive('flag', function (utilService) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
          ldclient.on('ready', function() {
            var flag = false;
            console.log(element);
            flag= ldclient.variation(attrs.flag, false);
            if(flag == false){
              element.remove();
            }
          });
        }
   }
});
Comment: what is ldclient ? Can u please add ng-repeat html?
Comment: @RIYAJKHAN ldclient is a flagging client module. my ng-repeat html is kinda long thats ehy i havent included it. I tried to use the directive outside of a ng-repeat and its working. but if its inside an ng-repeat its a different story
Answer: If ldclient is on the scope that ng-repeat is under, then you can add scope: true and use scope.ldclient.on('ready') etc.
Try this:
app.directive('flag', function (utilService) {
    return {
        restrict: 'A',
        scope: true,
        link: function (scope, element, attrs) {
          scope.ldclient.on('ready', function() {
            var flag = false;
            console.log(element);
            flag= scope.ldclient.variation(attrs.flag, false);
            if(flag == false){
              element.remove();
            }
          });
        }
   }
});

This ensures that your directive will share a scope within the DOM that it is placed.
Comment: How about if the ldclient is not on scope? its been declared in a javascript variable that are not part of a scope
Comment: try using console.log(attrs.flag) and see if your value there is being set correctly. Otherwise I don't see why ldclient, if it is present on the window, wouldn't be available within this block.
Comment: i logged the attrs.flag and it show the flag that i want.. Its on the ldclient.on event it didnt get.. seems like it can access the ready event that the ldclient emited when he finished its initialization
Comment: could you post a change to your code to reflect where things are working and where they are going wrong?


Azure AD error : The specified page token value has expired and can no longer be included in your request

Question: Getting below error while reading users from Azure Active Directory group
<code>Exception: System.AggregateException: One or more errors occurred. ---> System.AggregateException: One or more errors occurred. ---> Microsoft.Data.OData.ODataErrorException: The specified page token value has expired and can no longer be included in your request. ---> System.Data.Services.Client.DataServiceQueryException: An error occurred while processing this request. ---> System.Data.Services.Client.DataServiceClientException: {"odata.error":{"code":"Directory_ExpiredPageToken","message":{"lang":"en","value":"The specified page token value has expired and can no longer be included in your request."}}}
   at System.Data.Services.Client.BaseAsyncResult.EndExecute[T](Object source, String method, IAsyncResult asyncResult)
   at System.Data.Services.Client.QueryResult.EndExecuteQuery[TElement](Object source, String method, IAsyncResult asyncResult)
   --- End of inner exception stack trace ---
   at System.Data.Services.Client.QueryResult.EndExecuteQuery[TElement](Object source, String method, IAsyncResult asyncResult)
   at System.Data.Services.Client.DataServiceRequest.EndExecute[TElement](Object source, DataServiceContext context, String method, IAsyncResult asyncResult)
   at System.Data.Services.Client.DataServiceContext.EndExecute[TElement](IAsyncResult asyncResult)
   at Microsoft.Azure.ActiveDirectory.GraphClient.Extensions.DataServiceContextWrapper.<ExecuteAsync>b__6b[TSource,TInterface](IAsyncResult i)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Azure.ActiveDirectory.GraphClient.Extensions.DataServiceContextWrapper.<ExecuteAsync>d__70`2.MoveNext()
   --- End of inner exception stack trace ---
   at Microsoft.Azure.ActiveDirectory.GraphClient.Extensions.DataServiceContextWrapper.<ExecuteAsync>d__70`2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Azure.ActiveDirectory.GraphClient.Extensions.PagedCollection`2.<GetNextPageAsync>d__0.MoveNext()
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at Microsoft.Azure.ActiveDirectory.GraphClient.Extensions.TranslatingPagedCollection`2.<GetNextPageAsync>b__0()
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
</code>
using package id="Microsoft.Azure.ActiveDirectory.GraphClient" version="2.1.0" targetFramework="net452"
Thanks for your help.
Sanjay A.
Comment: Is it possible that another user/system is updating the group members at the same time? https://stackoverflow.com/questions/42650625/unable-to-get-user-groups-from-azure-active-directory
Comment: I don't think so, but I will check on that item.
Answer: Do you still see the issue?
Can you please share the timestamp and correlation id of the error which will help us to find out the root cause.
Workaround: Starting enumerating the members of the group again.
Comment: I am not seeing this issue anymore.


Prove that $\gcd(n!+1,(n+1)!+1)=1$

Question: I'd like to solve this one similarly to my previous question: Is this a Valid proof for $(2n+1,3n+1)=1$?
I did find a somewhat related post that uses a different method: How to show that $\gcd(n! + 1, (n + 1)! + 1) \mid n$?
So how would I go about this? I can write the above like:
$\exists \ d \ \in \mathbb{Z}$

$n!+1 \equiv 0$ (mod $d$)
$(n+1)!+1 \equiv 0$ (mod $d$)

Not sure what to do next. Any hints?
Thanks!
Answer: By the Euclidean Algorithm  $$\left(n!+1,\ (n+1)!+1\right)=\left(n!+1,\ (n+1)!+1-(n!+1)\right)$$  $$=\left(n!+1,n\cdot n!\right).$$  It is clear the last two must be relatively prime, since if $p|\ (n!\cdot n)$ then $p| n!$ (and there is an extra +1 hanging around).
Answer: Here's a purely equational proof. Simply put $\rm\ k = (n-1)!\ $ in
Theorem $\rm\ \ ((n+1)\, n\, k+1,\ n\, k+1)\ =\ 1$
Proof $\ \ $ Working modulo the gcd $\rm\: := d\:$ we have
$(1)\rm\quad\quad (n+1)\, \color{#c00}{n\, k}\ \equiv\: -1\quad\quad$ by $\rm\ d\ |\ (n+1)\, n\, k+1$
$(2)\rm\quad\quad\phantom{(n+1)\, } \color{#c00}{n\, k}\ \equiv\: -1\quad\quad$ by $\rm\ d\ |\ n\, k+1$
$(3)\rm\quad\quad\phantom{(n+1)\ n\ } n\ \equiv\,\ \ \ 0\quad\quad $ by substituting $\:\color{#c00}{(2)}\:$ in $\:(1)\:$
$(4)\rm\quad\quad\phantom{(n+1)\ n\ } 0\ \equiv\: -1\quad\quad$ by substituting $\:(3)\:$ in $(2)$
Thus we conclude $\rm\: 0\ \equiv\ 1,\, $ i.e. $\rm\ d\ |\ 1\quad$ QED
Unwinding the linear relations used in the above proof (or, equivalently, using the extended Euclidean algorithm) yields the Bezout relation that I gave in the question that you linked to, viz.
$$ \rm 1\ =\ (n-1)!\ ((n+1)!+1)\ +\ (1-(n+1)!/n)\ (n!+1)$$
Notice how what seems like magic viewed in terms of divisibility relations is reduced to a purely mechanical elimination process in equational form. In higher number theory you'll learn more precisely how linear algebra methods such as Gaussian elimination extend from fields to certain rings, e.g. google Hermite and Smith normal forms.
Comment: Hm, I don't see how n! is also congruent to -1. Could you expand on that? Thanks for the encouragement! I am just an engineer, so this one class will probably all the number theory I will learn, unless I end up inventing error correcting codes at my job. I am enjoying it though!
Comment: Ah wait. $n! + 1 \equiv 0$ means $n! \equiv -1$? I can just do that, just as if the $\equiv$ were an =? That n! is congruent to both 0 and -1 makes no sense in my head though....
Comment: @Chris: Yes, you can add and multiply congruence just like integer equations. For an introduction see the Wikipedia article on [modular arithmetic.](http://en.wikipedia.org/wiki/Modular_arithmetic)
Answer: Suppose $m$ is a positive integer dividing both $n! + 1$ and $(n+1)! + 1$. The goal is to show that $m = 1$. Note that $m$ also divides $(n+1)*(n! + 1) - ((n+1)! + 1)$, which is equal to $(n+1)! + (n+1) - (n+1)! - 1 = n$. Since $m$ divides $n$, it also divides $n!$. Since it divides $n! + 1$ as well, it divides $n! + 1 - n!$ or just $1$. Hence $m = 1$ as needed.
Comment: if $m$ divides $a$ and $b$ then $m$ divides $ka + lb$ for any integers $k$ and $l$. So here $a = n! + 1$ and $b = (n+1)! + 1$, while $k = (n+1)$ and $l = -1$.
Comment: Could you explain how you know that m divides (n+1)∗(n!+1)−(n+1)!+1?
Comment: You can also argue that two consecutive integers are coprime, so it suffices to prove m divides $n!$ for the prove to be done (since gdc is unique)
Answer: This is a direct application to the division algorithm which says:

for any two integers a,b, a>b the following holds: $$a = qb + r$$

If we show that $0<r<b$, we are done.
Replace $a$ by $(n+1)!+1$, $q$ by $n$, $b$ by $(n!+1)$ and $r$ by $n!-n+1$ which is greater than $0$ and less than $b$, as required.
More Clarificatoin:
The left hand side is:$$(n+1)!+1$$ while the right hand side is:
$$n(n!+1)+(n!-n+1) \Longrightarrow nn!+n+(n!-n+1) \Longrightarrow n!(n+1)+1 \Longrightarrow (n+1)!+1$$
Answer: This is just an alternative to the approach in Eric Naslund's answer.
From the rule $(a,b)=(a,b-ka)$ for any $k$ along with $(a,b)=(b,a)$ and $(a,b)=(|a|,|b|)$, we have
$$\begin{align}
(n!+1,(n+1)!+1)
&=(n!+1,(n+1)!+1-(n+1)(n!+1))\\
&=(n!+1,-n)\\
&=(n,n!+1)\\
&=(n,n!+1-(n-1)!n)\\
&=(n,1)\\
&=1
\end{align}$$

Prove that $\gcd(n!+1,(n+1)!+1)=1$


How to set Vertical alignment to text in textbox control in Winforms?

Question: I'm trying to align the text in the middle to my textbox control in winforms.I also increased the height of the textbox by setting the  multiline property to true. But when editing the text, the text goes to the top-left position. I want it to be in the same position,even on edit mode and normal mode.
I want to achieve it like
Excel-Normal mode and Excel-EditMode.Is this possible? Thanks in advance.
Answer: What you're thinking of is a RichTextBox.
I forget if it supports vertical alignment, though I'm sure there is a work around.


Showing $\frac{r}{2(n+r)}\binom{2n}{n}\binom{2r}{r}\in \Bbb N^{+}$

Question: For any integers $n\ge 0,$ and $r\ge 1$,show that
$$f(n,r)=\dfrac{r}{2(n+r)}\binom{2n}{n}\binom{2r}{r}\in \Bbb N^{+}$$
I know that $f(0,r)=\binom{2r-1}{r}$ are integers and that $f(n,1)=\dfrac{1}{n+1}\binom{2n}{n}$  are Catalan numbers.
Comment: Just playing around, inspired by the catalan recursion, I noticed that $f(n+r,r)=\sum_{i=0}^n f(i,r)f(n-i,r)$.
Comment: @soktinpk: neat way to express the convolution identity which follows from my approach through (bivariate) generating functions, indeed.
Comment: That convolution strongly suggests that there's a nice combinatorial interpretation for these, too; I'd love to know what they count.
Answer: We may consider
$$ \sum_{r\geq 1}\sum_{n\geq 0}\frac{r}{2}\binom{2r}{r}\binom{2n}{n}x^r y^n z^{n+r-1} = \frac{x}{(1-4xz)^{3/2}(1-4yz)^{1/2}}\tag{1}$$
which by applying $\int_{0}^{1}(\ldots)\,dz$ to both sides leads to
$$ \sum_{r\geq 1}\sum_{n\geq 0}\frac{r}{2(n+r)}\binom{2r}{r}\binom{2n}{n}x^r y^n = \frac{2x}{\sqrt{1-4x}(\sqrt{1-4x}+\sqrt{1-4y})}.\tag{2}$$
It is enough to show that all the coefficients of the (bivariate) Maclaurin series of the RHS are integers.
This clearly happens for $\frac{1}{\sqrt{1-4x}}=\sum_{m\geq 0}\binom{2m}{m}x^m$, and the RHS of $(2)$ can be written as
$$ \frac{2x}{\sqrt{1-4x}}\cdot\frac{\sqrt{1-4x}-\sqrt{1-4y}}{4(y-x)} \tag{3}$$
where $\sqrt{1-4x}=\sum_{m\geq 0}\binom{2m}{m}\frac{x^m}{1-2m}$ also has integer coefficients. The claim easily follows.
Comment: @Batominovski: by just multiplying the known series $\sum_{m\geq 0}\binom{2m}{m}a^m$ and $\sum_{m\geq 0}\binom{2m}{m}m b^m$, after a suitable change of variables.
Comment: How did you get Equation (1), though?


Does anyone know of a program like Winplot?

Question: Someone could tell me if there is any other program that shows graphs of functions online? is because I'm using a computer where I can not do downloads, and needed an online version.
Very Thanks!
Answer: Not sure how Winplot works but have you tried Wolframalpha?
Also there is:

Fooplot
Rechneronline
Plotgraphs.com
Comment: Any example of function you want to get plotted @user73276 ?


How can I delete taxonomy terms for a specific node type?

Question: I had a taxonomy vocabulary (Tags) shared across all of my content types including those like forum and blog that could be user created. I'd like to remove the terms / Tags from all node types except story. Story can only be created by site authors. Is there an acceptable way to do this?
I tried deleting the tag field from the content type. However, it does just that.  The field isn't part of the type, but the terms remain assigned to the existing nodes.
If I were going to do this programmatically with a MySQL script, are there tables other than taxonomy_index, field_data_taxonomy_vocabulary_, and field_revision_taxonomy_vocabulary_ that I'd need to delete rows from? It seems like I could generate a list of nids I want to remove terms from, and then delete the corresponding rows from those 3 tables.
Thanks in advance for any help. I'd be happy to provide additional information.
Answer:
The field isn't part of the type, but the terms remain assigned to the existing nodes.

That doesn't sound right; to the best of my knowledge removing the field from a content type will (normally) remove all data attached to nodes of that type. They get moved to a field_deleted_* table and then purged on a cron job.
It might indicate there's a problem somewhere in your installation, or it might just be 'one of those things'.
The 3 tables you mentioned are the only places you'll need to delete data from, but you'll also need to flush the caches after the purge (or at least truncate cache_field)
Comment: I appreciate your help.

I ran cron and cleared my cache. There's no sign of a field_deleted_* table in my database. Odd. Is it possible things are a bit off because these terms were originally present in my D6 install, which was then upgraded to D7?

When I go to /category/tags/TERM (my path to a term) the nodes still show up.
Answer: Deleting the taxonomy field from the content type didn't remove the taxonomy terms from the nodes. Therefore, I wrote a PHP script to generate MySQL code to programmatically delete the terms after removing the taxonomy field from the nodes via the admin menu.
<?php

// put your database name here
$database = '';

// put your vocabulary table suffix here
// will be appeneded to table names like `field_data_taxonomy_` and `field_revision_taxonomy_`
$vocabulary = 'vocabulary_2';

$connection = mysql_connect(HOST, USER, PASS);
$nids = array();
$fp = fopen('taxonomy_clean.sql', 'w');

if (!$connection)
{
    echo 'Unable to connect to database: ' . mysql_error();
    exit;
}

if (!mysql_select_db($database))
{
    echo 'Unable to select ' . $database . ': ' . mysql_error();
    exit;
}

// get nid from all nodes except story type
$result = mysql_query('select * from ' . $database . '.node where type != \'story\' order by nid asc;');

while ($row = mysql_fetch_assoc($result))
{
    $nid = $row['nid'];
    $nids[] = $nid;
}

echo PHP_EOL, count($nids), ' nids', PHP_EOL;

// remove the taxonomy terms from the nodes
$taxonomy_index = 'DELETE FROM ' . $database . '.taxonomy_index WHERE nid IN (' . implode(',', $nids) . ');';

$field_data_taxonomy_vocabulary = 'DELETE FROM ' . $database . '.field_data_taxonomy_' . $vocabulary . ' WHERE entity_id IN (' . implode(',', $nids) . ');';

$field_revision_taxonomy_vocabulary = 'DELETE FROM ' . $database . '.field_revision_taxonomy_' . $vocabulary . ' WHERE entity_id IN (' . implode(',', $nids) . ');';

// write the MySQL script to disk
fwrite($fp, $taxonomy_index . PHP_EOL . PHP_EOL);
fwrite($fp, $field_data_taxonomy_vocabulary . PHP_EOL . PHP_EOL);
fwrite($fp, $field_revision_taxonomy_vocabulary . PHP_EOL . PHP_EOL);

fclose($fp);

?>

The script worked fine with PHP 5.4, and will generate taxonomy_clean.sql. I used mysql via the command line to run taxonomy_clean.sql. I cleared the cache after and everything worked fine.
Answer: You can do it using Drush field-delete,
Delete a field and its instances.
Examples:
 field-delete city                         Delete the city field and any instances it might have.
 field-delete city --bundle=article        Delete the city instance on the article bundle

Arguments:
 field_name                                Name of field to delete.

Options:
 --bundle                                  Only delete the instance attached to this bundle. If omitted, admin can choose to delete one instance or whole
                                           field.
 --entity_type                             Disambiguate a particular bundle from identically named bundles. Usually not needed.

Original Source


How can I query a database created using the previous core version from the new core version?

Question: I want to query users, nodes etc in my D7 database that I am currently migrating to D8 to compare with the migrated content.
I want to use custom Drush commands to run some checks.
Is this possible?
Comment: No, not really. You can query data from as secondary database, Drupal or otherwise, but you won't be able to load D8 objects from a D7 database - the underlying architecture is incompatible.
Comment: Ah ok I thought that might be the case. Thanks. Great talk @DrupalSouth too btw ;)
Comment: Thanks!  (post must be 15 characters)
Answer: You can add external databases in your settings.php file:
<code>$databases['external']['default']= array(
  'database'=>'',
  'username'=>'',
  'password'=>'',
  'prefix'=>'',
  'host'=>'',
  'port'=>'3306',
  'namespace'=>'Drupal\\Core\\Database\\Driver\\mysql',
  'driver'=>'mysql',
);
</code>
Then, in a custom module you can query for nodes, terms etc.
<code>// Switch to external database
\Drupal\Core\Database\Database::setActiveConnection('external');

// Get a connection going
$db = \Drupal\Core\Database\Database::getConnection();

$vid = 5; // The vocabulary I want to query
$query = $db->select('taxonomy_term_data', 't');
$query
  ->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
$query
  ->addTag('translatable')
  ->addTag('taxonomy_term_access')
  ->fields('t')
  ->fields('h', array(
    'parent',
  ))
  ->condition('t.vid', $vid)
  ->orderBy('t.weight')
  ->orderBy('t.name');
$results = $query->execute()->fetchAll();
</code>
Switch back to your current db
<code>\Drupal\Core\Database\Database::setActiveConnection();
</code>
Save the results to a d8 vocabulary
<code>foreach($results as $result) {
  Term::create([
    'tid' => $result->tid,
    'name' => $result->name,
    'vid' => 'my_d8_vocabulary_name'
   ])->enforceIsNew()->save();
}
</code>


On construction of double cover of $\mathbb{R}P^{m}$

Question: Consider the map $f : S^{m} \rightarrow Sym(\Bbb R^{m+1})$ from the unit sphere into the space of symmetric matrices that takes a point to the reflection about the corresponding line. It is claimed that we can "identify" the real projective space $\mathbb{R}P^{m}$ with the image $f(S^{m}$).
What does "identify" mean in this context? $\mathbb{R}P^{m}$ is the space of equivalence classes of lines in $\mathbb{R^{m+1}}$  and $f(S^{m})$ is a subset of matrices. The only thing they have incommon is that two points are sent to one in the same fashion, is that all there is to it?
Answer: There are two possible viewpoints for the real projective space of dimension $m$. You can see it as the quotient space obtained from $\Bbb R^{m+1}-0$ by identifying collinear points (i.e it's the space of lines in $\Bbb R^{m+1}$). You can see it at the quotient obtained from the $m$-sphere $S^m$ by identifying antipodal points. See here.
If $x,y\in S^m$ then you can check that $f(x)=f(y)$ if and only if $x=y$ or $x=-y$. Take the viewpoint of the real projective space as a quotient of the $m$-sphere. The continuous map $f$ factors to a continous bijection $$ \widetilde{f}:\Bbb RP^m\longrightarrow f(S^m).$$ Because
the projective space is compact
and $f(S^m$) is Hausdorff, $\widetilde{f}$ is a homeomorphism. This is how you can identify the projective space and $f(S^m)$.


Android: OnTouchListener.OnTouch not called in multiTouch

Question: I implemented multitouching buttons in my app, by definyng and attaching my version of OnTouchListener (and onTouch method) to all my buttons.
All works perfectly, except for one thing which seems to belong to standard behaviour of the listener. I hope to be able to explain it without posting code since it's long.
If I click and hold a button, the onTouch method is called, as expected, and application sees button clicked.
If I click and hold a second one, the onTouch method (related to first button) is called, as expected, and application sees button clicked.
If I release only second one, if my finger on the first button stays ABSOLUTELY motionless, the onTouch event is not called and the second button is not logically released. The onTouch method gets called only if I move at least a pixel first finger, and only in that moment the second button gets released.
I know that it's very difficult to keep a finger exactly in the same position for more than one millisecond :-),  but sometimes it happens..I had to spend some time in order to understand the reason for this behaviour, and I didn't find a solution, have you got any suggests to workaround this problem?
Thank you very much.
Answer: Try this inside your onTouch
<code>PointF curr = new PointF(event.getX(), event.getY());
switch (event.getAction()) {
    case MotionEvent.ACTION_UP:
        float xDiff = Math.abs(curr.x-start.x);
        float yDiff = Math.abs(curr.y-start.y);
        if (xDiff < 5f && yDiff < 5f) {
        //insert here your code when button is click
        }
     break;
</code>
It's help for me avoid inaccuracy of push.
Comment: Hello, thank you but my problem is that the onTouch is not called :-) Maybe I'll have to create a different listener of the same class for each button


Is there a "player of the year" award for international basketball?

Question: The international governing bodies of some sports give an official "best player of the world" award. For example,

FIFA (association football): FIFA Ballon d'Or
FIH (field hockey): FIH Player Of The Year
IRB (rugby union): World Rugby Player Of The Year

Does FIBA, the international basketball federation, give a similar award?
Comment: Voting to reopen. Edits (pending) clarify the question as it was implicitly meant, referring to an equivalent POTY given by FIBA, and all but stated by @Pablo in comments. Please *don't* vote as "too broad" when there can be only one answer to whether a single group does a specific thing!
Comment: @nij with the comentaries and edition, it came clear to me that the governing body for basket is FIBA. Now looking a bit in google I found a recently new award they give (since 2005) "FIBA Europe Player of the Year Award " . Still dont know if there is the same award but for people of any nationality, which would be the equivalent of the golden ball in soccer
Answer: Given the lack of anyone finding any evidence, I'm going to go out on a not very big limb and say "No, FIBA does not give a 'best player in the world' award".
The closest that seems to exist is that FIBA Europe give a "Player of the Year" award. This is open to any player with European citizenship, but mostly goes to players in the NBA.
Answer: When in NBA a team wins a championship they are called the best in the world (world champions, because in NBA are playing the best players from different countries). So I guess when somebody is awarded as MVP (most valuable player), he is the best in the world.
Comment: The question was clarified some time ago to mean a FIBA award. The NBA, like other sports in the USA, call things "World" players, leagues, series, etc. because of exceptionalist social tradition, not anything to do with the origin of players.
Comment: But you cannot argue with the fact that in NBA there are the best players in the world
Comment: Some of them, yes. But if all players in the world were ranked, a substantial number of NBA players would be below some number of players from elsewhere.


Ordinal variables relation analysis

Question: I have a data set containing 10 subjects and students' grades in those subjects (e.g., A+, A, B+, B, C+, C, D+, D). I want to find out out if the grades in one subject are affecting the grades for other subjects. Should I go with regression analysis? If yes, then should I replace grades with some numbers before doing the regression?
<code>A+   A+   B+   A    A    A+   A+   A+  A+  A+
</code>
Above is 1 row of the data set. This row signifies grades of a particular student in 10 different subjects in the exam. I want to know if grade in any subject influences the grade of another.
Comment: What exactly would it mean for "the grades of one subject [to affect] the grades for other subjects"? I don't know how you could figure this out because I have no idea what it means.
Comment: I need to know if one subject grade has an impact over another subject grade. For instance grade of subject 1 has some impact or relation with grade in subject 6. This data is just a single student performance in 10 subject. I have 60000 students similar grades in those 10 subjects. So I would like to analyse to find soms insights.. Thanx
Comment: As you say you have ordinal data so why you are asking about regression?
Comment: See advice against cross-posting in http://stats.stackexchange.com/help/on-topic
Answer: "influences" sounds like some sort of causation. You cannot determine that from these data.
If you mean "are grades related to each other" then you might want cluster analysis.
If you want to look at each pair of subjects separately, you could run rank correlations among all pairs.
Comment: I would like to know if grade in one subject affects or have any relation with grades of other. This data is just 1 students grade in 10 subjects.. So my question is if grade in subject one has any influence over grade in subject 6 for instance. I have 60000 students data and their respective score in 10 subjects .  So if I can relate grades of students in different subjects to find some insights.

Ordinal variables relation analysis


Azure Bot Not Forwarding Messages From Teams Channel to Messages Endpoint

Question: I have created a Teams Bot using bot framework and have deployed all the resources in the clients environment. The Web App running the Bot Framework SDK is working and Tested, but when trying to hit the bot through the Teams Channel Link (or through a Teams App) no responses is received and the Web App never logs a hit to the message route.
I have confirmed all the settings are the same in both the clients Bot configuration (and accompanying app registration) as is in our development environment. The Web App works correctly when using the Test in Web Chat provided in the Azure portal and works when testing using a Azure Bot deployed in our dev environment pointed at the Web App in the client's environment. Any tips on how to proceed and get messages flowing from the Teams channel?
I have noticed that there are errors logged in the client's Azure bot "The tenant admin has disabled this bot" that do not appear in our dev environment. I have looked at the logs in web-based Teams and get an 403 error with a response body containing a 209 error indicating "Write Blocked on this Thread". I am hoping someone here knows why this is occurring. I assume it may be an Entra configuration that is blocking the bot? Again, the Web App running the bot is working as expected the only issue is that Teams message will not go through the Bot service only in the Clients environment.
Comment: Are you using MS Teams free service?
Answer: As per my earlier communication with Microsoft, they have highlighted that "This behavior is by design in the new Teams client. unpublished Teams bot app chat windows are disabled in both new and old Teams App" While bot services for the team channel link were working in the old Teams or Teams classic ( Recently this was also disabled ), unfortunately, this feature is not supported in the latest Teams client. Consequently, the chat window for such chatbots will be disabled by default so you should publish your app in O365 ( Manage App ). Then only you can do the testing in the Teams App.
Reference:

MS Bot Chat Window Disabled
Answer: For anyone who comes across this, the issue was resolved by having a tenant admin create a new Azure Bot service and setup the Teams channel on their end. I'm not sure what was happening, but creating the resource from scratch fixed the error.


Erro ao ativar WP_DEBUG

Question: Estou com um problema no meu site em WordPress.
Quando defino no wp-config.php, meu site fica normal:
define('WP_DEBUG', false);

Mas quando defino
define('WP_DEBUG', true);

O site dá erro de página não encontrada. E eu estava precisando debugar porque estou com um outro problema para resolver...
Tem algum problema do wp-debug ficar setado como true num servidor Windows?
Estou usando meu website num servidor Windows.
Comment: Por curiosidade, conseguiu solução ou achou o problema?
Comment: Se em algum momento topar de novo com a solução, ia ser legal se deixasse registrada aqui. Valeu!
Comment: A sua reposta me ajudou porque a usei como referência para buscar outra resposta que pudesse me ajudar. Só que agora não lembro como resolvi, eu lembro que me baseei na sua resposta.
Answer: A constante WP_DEBUG exibe problemas e alertas relacionados à configurações, plugins e inclusive a segurança, portanto você não pode deixar ela ativa em um ambiente de produção.
Quando você define a WP_DEBUG para TRUE, certifique-se de limpar o cache e observar o log de erros de seu site, lá poderão ser exibidas informações sobre o erro 404 (que você alega ser o de página não encontrada).
Você também pode definir seu Wordpress para não trabalhar com URLs amigáveis, nas opções de link permanente, assim deverá evitar os erros 404 que aparentemente são de um problema com o rewrite de seu site. (certifique-se que seu .htaccess está sendo lido corretamente e você não possui AllowOverride None nas configurações do seu servidor).
Há um plugin que pode checar isso pra você:
https://wordpress.org/plugins/monkeyman-rewrite-analyzer/
Answer: Talvez fazendo o debug para um arquivo possa contornar o problema:
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_DISPLAY', false ); // não mostrar na tela
define( 'WP_DEBUG_LOG', true ); // escrever debug em um arquivo
@ini_set('display_errors',0);

Com a constante WP_DEBUG_LOG ativa, o debug vai ser gerado no arquivo /wp-content/debug.log. Esta constante é usada para ver erros de Ajax ou wp-cron que não são mostrados na tela durante a execução do site.
Tempos atrás, fiz um plugin para visualizar esse arquivo diretamente no backend do WordPress.
Se mesmo usando o debug direto para um arquivo seu site continuar sem funcionar por causa dessas constantes, então deve procurar nos logs de erro do seu servidor para ver se há alguma dica do que realmente está acontecendo. Esta solução que apresento é só uma alternativa para contornar o erro real (conflito WP_DEGUB com seu servidor), fiz uma pesquisa rápida e não encontrei nada relacionado.

Erro ao ativar WP_DEBUG


Windows command not finding script

Question: I am working on the password locker project in the Automate the boring stuff with Python book. I need to create a script and a bat file to run the program with a Windows command. When running the command, Windows informs me that it can't find my script ("pw") and to check the name & try again.
The folder where the script it located has been added to the Path system variable folder.
Here is my script file (pw.py):
<code>#! python3
# pw.py - An insecure password locker program.

PASSWORDS = {'email': 'f7nsdkfn2BDD3fkjTXjs6Fjsn',
             'blog': 'fdkNc32NskNskKslLI321n',
             'luggage': 12345}

import sys, pyperclip
if len(sys.argv) < 2:
  print("Usage: python pw.py [account] - copy account password")
sys.exit()

account = sys.argv[1]      # first command line arg is the account name

if account in PASSWORDS:
  pyperclip.copy(PASSWORDS[account])
  print("Password for " + account + " copied to clipboard")
else:
  print("There is no account named " + account)
</code>
Here is my bat file (MyName is my real name):
<code>@py.exe C:\Users\MyName\AppData\Local\Programs\Python\Python39\MyScripts\pw.py %*
@pause
</code>
And here are the path folders I have added to both the system and user variables:
<code>C:\Users\MyName\AppData\Local\Programs\Python\Python39\MyScripts
C:\Users\MyName\AppData\Local\Programs\Python\Python39
</code>
Could you help me fix this? Thank you!
Comment: Sadly, I believe your obfuscation is to blame. Does `MyName` actually contain a space? If so, or in any case, `"quote the filename"` ie,  use `py.exe "C:\Users\MyName\AppData\Local\Programs\Python\Python39\MyScripts\pw.py" %*` - and always best to report the *precise* (If obfuscated)  error message - saves us guessing.
Comment: `sys.exit()` is indented incorrectly, I assume. Doesn't that belong to the if-clause?
Comment: The issue came from the user (me). I was calling my .py file instead of my .bat in my Windows command. Thanks for the help! You asnwers helped me with troubleshooting.
Answer: Add double apostrophes and include the full python file path. The following worked for me:
<code>@"C:\Users\MyName\AppData\Local\Programs\Python\Python37\python.exe" "C:\Users\MyName\Documents\test.py" %*
@pause
</code>
Comment: I found how to fix the issue, and feel extremely silly. In the command file, I was calling for the .py instead of the .bat file. Can't believe I spend hours modifying codes and doing system restore for this.

Thanks for everyone who helped!

If someone else does this problem, the command might not work if the bat file end with * instead of one (this information is not written in the book).
Wrong code:
'@py.exe C:\Users\MyName\AppData\Local\Programs\Python\Python39\MyScripts\pw.py %*'

Good code
'@py.exe C:\Users\MyName\AppData\Local\Programs\Python\Python39\MyScripts\pw.py %1'
Comment: Great to hear that you were able to fix it!

Windows command not finding script


How can I express in polar form $z = \frac{1}{(x-3 + iy)^n}$?

Question: How can I express in polar form
$$z = \frac{1}{(x-3 + iy)^n} $$
$x$, $y$ and $n$ could be any number. $i$ is the imaginary unit.
Comment: What have you tried? What do you know about the polar form of $1/z$, given the polar form of $z$? Can you find the polar form of $z=(x-3+iy)^n$?
Comment: Try setting $x'=x-3$.
Comment: It would have been easy without the 3.
Comment: Welcome to Mathematics Stack Exchange! A quick [tour](https://math.stackexchange.com/tour) will enhance your experience. Here are helpful tips to [write a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question/9960#9960) and [write a good answer](https://stackoverflow.com/help/how-to-answer).  For equations, please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Answer: We first compute the polar form of $a = x-3+iy$, giving $r = \sqrt {(x-3)^2 + y^2}$ and $\theta = \tan^{-1} \left( \frac{y}{x-3} \right)$. Writing it as $re^{i \theta}$ and noting that $z = a^{-n}$, we obtain the polar form $r^{-n} e^{-in \theta}$ where $r$ and $\theta$ are the aforementioned constants in terms of $x$ and $y$.


Simply What does Pasting Lemma says

Question: Let me write definition of Pasting Lemma: Let $X=A \cup B$ where $A$ and $B$ are closed subsets of $X$. Let $g: A\to Y$ and $h:B\to Y$ be continuous function such that $g|A\cap B = h|A\cap B$. Define $f:X\to Y$ by $f\left( x\right) =\begin{cases}g\left( x\right) ,x\in A\\
h\left( x\right) ,x\in B\end{cases}$
then $f$ is continuous.
My request is can you summary the pasting lemma for me?
I looked some applications of pasting lemma and author says that $f$ is continuous since $g$ and $h$ are continuous. Does theorem say that like this? Is it enough to check $g$ and $h$ are continuous? Thank all of you for now.
Comment: For applications, it is not enough to check that $f$ and $g$ are continuous, because there are other hypotheses you must also check: You must check that $A$ and $B$ are closed; You must also check that $g \mid A \cap B = f \mid A \cap B$.
Comment: I know this may sound complicated, but this is quite intuitive. The theorem says that if you have two continuous functions which coincides in the interesction of its domains then it can be extended to the union. Do you undertand the proof, what do you need exactly? If you study homotopy theory, you will see many aplications of this lemma, which can help you to undestand it.
Answer: I think the best way to understand the pasting lemma is to understand why a "naive" version of it is false:

(Incorrect "theorem") Suppose $A,B$ are subspaces of a topological space $X$, and $f:A\rightarrow Y$, $g:B\rightarrow Y$ are continuous functions which agree on the intersection of their domains (that is, for $x\in A\cap B$ we have $f(x)=g(x)$). Then the "union" of $f$ and $g$ $$A\cup B\rightarrow Y: x\mapsto\begin{cases}
f(x) & \mbox{ if } x\in A\\
g(x), & \mbox{ if } x\in B\\
\end{cases}$$ (which makes sense since $f$ and $g$ agree on $A\cap B$) is again continuous.

To see why this is false, consider for example $A=[0,1]$, $B=(1,2]$, $f:[0,1]\rightarrow\mathbb{R}: x\mapsto 0$, and $g: B\rightarrow\mathbb{R}: x\mapsto 1$ (where all spaces involved have the usual topologies). The union of $f$ and $g$ is the function $$[0,2]\rightarrow\mathbb{R}: x\mapsto\begin{cases}
0 & \mbox{ if } x\le 1\\
1 & \mbox{ if } x>1\\
\end{cases}$$ which is not continuous.
So we have a naive idea that gluing together continuous functions should result in a continuous function, but a simple counterexample to the most obvious way of stating that. The correct pasting lemma is what we get when we realize what additional hypotheses we were missing in order to rule out counterexamples like the above - namely, that both $A$ and $B$ must be closed (this can actually be weakened somewhat, but that's not worth focusing on at first).

Simply What does Pasting Lemma says


Is it possible to use abitrary-length parameters in an ILE COBOL procedure?

Question: What I want to do is define an (AS400) ILE COBOL procedure that takes a PIC X(n) parameter, processes the string, and returns a result code to the calling program. My concerns are:
1) whatever length I select for the maximum string size, it's likely that some program will need to call it with a larger string, and
2) trailing spaces might be meaningful in terms of the result.
So, the procedure needs to be able to accept a parameter of an arbitrary length, and determine at run time what the actual length of the string is.
In reading the IBM docs, I'm inclined to believe that this can't be done. Am I right, or is there actually a way to accomplish this?
Comment: Have you considering using ILE C or ILE RPG?  The whole point to ILE is that you can have modules written in different languages linked into a single *PGM or *SRVPGM. Thus allowing you to use the best tool for the job; instead of using a hammer to drive a screw.
Comment: If I were permitted to use C, I would.
Answer: I'm not aware of any problem using arbitrary length arguments (other than learning how to do it). Just as with every language, you need to either define a variable-length field or receive the actual length in a second argument. The PIC will need to declare the maximum length allowed.
A variable-length argument will be like this:
01   VL-FIELD.
   05   i      PIC   S9(4)   COMP-4.
   05   data   PIC   X(n).

The i variable reports the length and PIC(n) will be coded as the maximum. You can't safely access any bytes beyond what i says.
Answer: You will need to know the length of the field in your CALLed program. So I hope that you know it in your CALLing program. So if you know the length there, you will be fine.
There are generally two ways to then proceed:

Prefix the data with the length (common definition for a VARCHAR in COBOL)
Pass the length as a separate parameter

The second can be more convenient if you don't want to toss your data around just to prefix it (if it isn't already).
Type of field for the length? Binary will be good. Which binary? From your description it sounds like "native binary" would suit best, rather than a binary field with a decimal limit to the PICture size. That is perhaps COMP-4, but I haven't checked for your COBOL.
How to do the definition for field?
01  THE-DATA.
    05  THE-LENGTH                      COMP-4 PIC S9(4).
    05  THE-STRING.
        10  FILLER OCCURS 0 TO 32767
            DEPENDING ON THE-LENGTH.
            15  FILLER                         PIC X.

Or
01  THE-LENGTH                          COMP-4 PIC S9(4).
01  THE-DATA.
    05  THE-STRING.
        10  FILLER OCCURS 0 TO 32767
            DEPENDING ON THE-LENGTH.
            15  FILLER                         PIC X.

In your program you just then use THE-STRING, in a MOVE or DISPLAY or whatever. Except CALL, which conveys nothing to the CALLed program except the address of the start of the data, :-)
You don't need a definition like that in the CALLing program, unless you want it. It is a convenient definition for the CALLed program, though there are other ways to do it, including that refuge of the scoundrel, reference-modification :-)
If you are able to compile with NOSTDTRUNC you will be able to use the above values, otherwise you'll need to define larger binary fields like PIC S9(6) at least.
Comment: Note that `COMP-5` is not a valid usage in the AS/400 line, but the ODO clause can be a good choice.
Comment: Thanks @user2338816. Do you have a binary which allows access to all the bits? Ours is COMP-5, our COMP-4 is identical to COMP and BINARY (they do decimal truncation) so looks exciting but does nothing. Lots of variation in COBOL on this. I'll change it to COMP-4 and let me know if that is wrong, please.
Comment: DB2 on i and varying-length fields in general will specify the varying prefix as COMP-4 which is equivalent to BINARY. COMP-4 can cover 2-, 4- and 8-bytes binary/integer values. The varying-length prefix, of course, will always be integer and will be 2 bytes.
Comment: @user2338816 Thanks. What is the maximum value of an unsigned two-byte COMP-4 field? I'm assuming it is the figure I've used, and if DB2 on i using COMP-4 for VARCHAR, I'm hoping it is correct :-) There's always the manuals, I suppose...
Comment: Two issues get involved. First, the `*NOSTDTRUNC` compile option can ensure that truncation happens at half-, full- or double-word boundaries. This helps overcome the issue of four decimal digits in `9(4)`. But `S9(4)` requires extra handling because 'unsigned' isn't supported. The 2-byte value must be manipulated into the low-order bytes of a 4-byte binary field in order to eliminate potential negative values. Make sense?
Comment: @user2338816 Thanks again. Very useful. I've never heard of a forced signed field for a binary, so learn something new every day.
Comment: COBOL in the midrange line doesn't have the usage base to compete with the RPG language series. It stays advanced in terms of ILE and general feature set; but various details slip by, probably because developers never ask. For COBOL developers, 2-byte binary usage is relatively rare and 4-byte rarely needs to use that bit. So it just seldom makes a difference.


How do you test an implementation of k-means?

Question: Disclaimer: I posted this question on Stackoverflow, but I thought maybe this is better suited for this platform.
How do you test your own k-means implementation for multidimensional data sets?
I was thinking of running an already existing implementation (i.e., Matlab) on the data and compare the results with my algorithm. But this would require both algorithms to work more than roughly the same, and the mapping between the two results probably is no piece of cake.
Do you have a better idea?
Answer: The k-means includes a stochastic component, so it is very unlikely you will get the same result unless you have exactly the same implementation and use the same starting configuration. However, you could see if your results are in agreement with well-known implementations (don't know about Matlab, but implementation of k-means algorithm in R is well explained, see Hartigan & Wong, 1979).
As for comparing two series of results, there still is an issue with label switching if it is to be run multiple times. Again, in the e1071 R package, there is a very handy function (;matchClasses()) that might be used to find the 'best' mapping between two categories in a two-way classification table. Basically, the idea is to rearrange the rows so as to maximise their agreement with columns, or use a greedy approach and permute rows and columns until the sum of on the diagonal (raw agreement) is maximal. Coefficient of agreement like the Kappa statistic are also provided.
Finally, about how to benchmark your implementation, there are a lot of freely available data, or you can simulate a dedicated data set (e.g., through a finite mixture model, see the MixSim package).
Comment: hi chi, thanks for the answer. When you want you can also answer the identical question at SO and I would accept it there as well. => http://stackoverflow.com/questions/4280371/how-do-you-test-a-implementation-of-k-means
Comment: (+1) The first paragraph quickly gets to the heart of the matter.
Answer: The mapping between two sets of results is easy to compute, because the information you obtain in a test can be represented as a set of three-tuples: the first component is a (multidimensional) point, the second is an (arbitrary) cluster label supplied by your algorithm, and the third is an (arbitrary) cluster label supplied by a reference algorithm.  Construct the $k$ by $k$ classification table for the label pairs: if the results agree, it will be a multiple of a permutation matrix.  That is, each row and each column must have exactly one nonzero cell.  That's a simple check to program.  It's also straightforward to track small deviations from this ideal back to individual data points so you can see precisely how the two answers differ if they differ at all.  I wouldn't bother to compute statistical measures of agreement: either there is perfect agreement (up to permutation) or there is not, and in the latter case you need to track down all points of disagreement to understand how they occur.  The results either agree or they do not; any amount of disagreement, even at just one point, needs checking.
You might want to use several kinds of datasets for testing: (1) published datasets with published k-means results; (2) synthetic datasets with obvious strong clusters; (3) synthetic datasets with no obvious clustering.  (1) is a good discipline to use whenever you write any math or stats program.  (2) is easy to do in many ways, such as by generating some random points to serve as centers of clusters and then generating point clouds by randomly displacing the cluster centers relatively small amounts.  (3) provides some random checks that potentially uncover unexpected behaviors; again, that's a good general testing discipline.
In addition, consider creating datasets that stress the algorithm by lying just on the boundaries between extreme solutions.  This will require creativity and a deep understanding of your algorithm (which presumably you have!).  One example I would want to check in any event would be sets of vectors of the form $i \mathbb{v}$ where $\mathbb{v}$ is a vector with no zero components and $i$ takes on sequential integral values $0, 1, 2, \ldots, n-1$.  I would also want to check the algorithm on sets of vectors that form equilateral polygons.  In either situation, cases where $n$ is not a multiple of $k$ are particularly interesting, including where $n$ is less than $k$.  What is common to these situations is that (a) they use all the dimensions of the problem, yet (b) the correct solutions are geometrically obvious, and (c) there are multiple correct solutions.
(Form random equilateral polygons in $d \ge 2$ dimensions by starting with two nonzero vectors $\mathbb{u}$ and $\mathbb{v}$ chosen at random.  (A good way is to let their $2d$ components be independent standard normal variates.)  Rescale them to have unit length; let's call these $\mathbb{x}$ and $\mathbb{z}$.  Remove the $\mathbb{x}$ component from $\mathbb{z}$ by means of the formula
$$\mathbb{w} = \mathbb{z} - ( \mathbb{z} \cdot \mathbb{x} ) \mathbb{x}.$$
Obtain $\mathbb{y}$ by rescaling $\mathbb{w}$ to have unit length.  If you like, uniformly rescale both $\mathbb{x}$ and $\mathbb{y}$ randomly.  The vectors $\mathbb{x}$ and $\mathbb{y}$ form an orthogonal basis for a random 2D subspace in $d$ dimensions.  An equilateral polygon of $n$ vertices is obtained as the set of $\cos(2 \pi k / n) \mathbb{x} + \sin(2 \pi k / n) \mathbb{y}$ as the integer $k$ ranges from $0$ through $n-1$.)
Comment: (+1) Your comments on the possible ways to generate relevant synthetic data are very welcome.
Answer: One very simple 'naive' approach would be to use simple synthetic data, for that every implementation should result in the same clusters.
Example in Python with import numpy as np:
test_data = np.zeros((40000, 4))
test_data[0:10000, :] = 30.0
test_data[10000:20000, :] = 60.0
test_data[20000:30000, :] = 90.0
test_data[30000:, :] = 120.0

For n_clusters = 4 it should give you a permutation of [30, 60, 90, 120]
Answer: Since k-means contains decisions that are randomly chosen (the initialization part only), I think the best way to try your algorithm is to select the initial points and let them fixed in your algorithm first and then choose another source code of the algorithm and fix the points in the same way. Then you can compare for real the results.


In Drupal 7 Views how do you set permissions via roles for an attachment display?

Question: I am trying to set roles permissions for my attachment view, but every time i set the roles permissions it affects the master display aswell. I want my attachment display only viewable to admin's of the site. Am i missing something or should is there another alternative to this issue?
Comment: this seems to be a possible views 3 bug as changing roles in one display affects the other even if you have setup the override. one solution i did was set my attachment access to "Permissions" and set my master to NONE for anonymous users.
Comment: By the way, the bug mentioned in the answer from duckx is https://drupal.org/node/1174588 There is a workaround, which is to override the access type as well as the permission.
Answer: From you screenshot you gave permission to anonymous user, authenticated users and instructor. So the attachment will be visible to all users. Choose only admin for the attachment and for the page it is attached you do not need to set permissions. You settings should look something like the image below

Make sure you always apply permissions to the current display and not to all display.


Laravel where statement and pagination

Question: I have an SQL search where I use Eloquent whereRaw, and than paginatate results.
Proplem: the results are paginated and if I navigate to the next page the results will  be gone and it will just "SELECT All " bacause laravel's pagination sends only ?page= GET request.
code:
<code>if (Input::has('city')) {
        $query .= ' and city = '.Input::get('city');
    }
    if (Input::has('area')) {
        $query .= ' and area = '.Input::get('area');
    }
    if (Input::has('sub_location')) {
        $query .= ' and sub_location = '.Input::get('sub_location');
    }
    if (Input::has('rent')) {
        $query .= ' and rent = '.Input::get('rent');
    }
    if (Input::has('price_min') && Input::has('price_max')) {
        $query .= ' and price < '.Input::get('price_max').' and price >'.Input::get('price_min');
    }

    $listings = ListingDB::whereRaw($query)->paginate(5);

    return View::make('page.index')->with('title','Home')->with('listings',$listings);
</code>
so when I navigate to the next page all the Input is gone because laravel generates pagination only with ?page= GET variable, how can I solve it?
thank you.
Answer: you can append you query string to the pagination link
<code>{!! $listings->appends(Input::all())->render() !!}
</code>
Answer: "Appending To Pagination Links
You may add to the query string of pagination links using the appends method. For example, to append &sort=votes to each pagination link, you should make the following call to appends:
{!! $listings->appends(['sort' => 'value'])->links() !!}
So in your case you need to add to pagination links like this if you have city and rent search applied then
{!! $listings->appends(['city' => 'london', 'rent' => 5000])->links() !!}
This will sort out your problem.

Laravel where statement and pagination


look for a char in a word. The char is the button clicked

Question: Someone from stackoverflow helped me with my code for buttons by giving me the right code that's also more appropriate... But the problem is I want to use this code in a hangman program, when someone clicks on the button it must scan a word and print either "Yes, the letter is in the word" or "NO, the letter is not in the word"
I came across some code in stackoverflow that does that, but I have no idea how to adapt that persons code to my button code
The code for creating buttons(as I got it):
public CharSearch(){

super(BoxLayout.Y_AXIS);
    for(char i = 'A'; i <= 'Z'; i++){
        String buttonText = new Character(i).toString();
        JButton button = getButton(buttonText);
        add(button);
    }
}

public JButton getButton(final String text){
    final JButton button = new JButton(text);
    button.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "You have clicked: "+text);
            //If you want to do something with the button:
            button.setText("Clicked"); // (can access button because it's marked as final)
        }
    });
    return button

and then the code I found (I'll also post the link):
if(original.indexOf(button)!=-1){
    JOptionPane.showConfirmDialog(panel, "Your word does contain" + button );
}
else{
    JOptionPane.showConfirmDialog(panel, "There is no" + button );
}

How can I check if a single character appears in a string?
Question is how do I make the two codes work together, I Have tried fusing them but then i get errors with the indexOf at
if(original.indexOf(button)!=-1){

I'll also post my full code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public final class CharSearch extends Box{
int i =0;
int error = 0;
static JPanel panel;
String original = "Dinosaur";
JLabel label = new JLabel();
String secret = new String(new char[original.length()]).replace('\0', '-');

public CharSearch(){

super(BoxLayout.Y_AXIS);
    for(char i = 'A'; i <= 'Z'; i++){
        String buttonText = new Character(i).toString();
        JButton button = getButton(buttonText);
        add(button);
    }
}

public JButton getButton(final String text){
    final JButton button = new JButton(text);
    button.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "You have clicked: "+text);
            //If you want to do something with the button:
            button.setText("Clicked"); // (can access button because it's marked as final)
        }
    });
    return button;

    if(original.indexOf(button)!=-1){
    JOptionPane.showConfirmDialog(panel, "Your word does contain" + button );
    }
 else{
    JOptionPane.showConfirmDialog(panel, "There is no" + button );
 }

}

public static void main(String[] args){
    EventQueue.invokeLater(new Runnable(){
        public void run(){
           JFrame frame=new JFrame();
            frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            frame.setContentPane(new CharSearch());
            frame.pack();
            frame.setVisible(true);
            new CharSearch();
        }
    });
}
}

Answer: Change button to button.getText() (assuming the text of the button is just like b or c), or possibly getName if you have them all named by their character (that may be better as it allows you to use different stuff for the text the button shows, like the button could be 'Choose c', but the name 'c', and it would still work)
Comment: sorry, even if change button to button.getText() it still gives me a problem with "indexOf()


how do I theme rounded corners in Panels 7.x-3.3

Question: I looked through older questions & answers and some examples about styling rounded corners and they seemed valid but when I look into the code in Panels 7.x-3.3 I see an entire function that dynamically generates rounded-corners and tells Drupal where to find the image files.
I have new image files for the rounded-corners. How do I over-ride this function without hacking the module itself?
Ex. (This function is in rounded_corners.inc)
/**
 * Generates the dynamic CSS.
 */
function _panels_rounded_corners_css($idstr) {
  $url = panels_get_path('plugins/styles/corners', TRUE);

  $css = <<<EOF

.t-edge, .b-edge, .l-edge, .r-edge, .wrap-corner {
  position: relative;
  /* hasLayout -1 ? For IE only */
  zoom: 1;
}
$idstr .t-edge {
  background: url($url/shadow-t.png) repeat-x 0 top;
  font-size: 1px;
}
$idstr .b-edge {
  background: url($url/shadow-b.png) repeat-x 0 bottom;
  font-size: 1px;
}
$idstr .l-edge {
  background: url($url/shadow-l.png) repeat-y 0 0;
}
$idstr .r-edge {
  background: url($url/shadow-r.png) repeat-y right 0;
}
$idstr .wrap-corner {
  background: #fff !important;
}
$idstr .wrap-corner .t-edge, $idstr .wrap-corner .b-edge {
  height: 11px;
}
$idstr .wrap-corner .l, $idstr .wrap-corner .r {
  position: absolute;
  top: 0;
  height: 11px;
  width: 11px;
  background-image: url($url/corner-bits.png);
}
$idstr .wrap-corner .l {
  left: 0;
}
$idstr .wrap-corner .r {
  right: 0;
  background-position: -11px 0;
}
$idstr .wrap-corner .b-edge .l {
  background-position: 0 -11px;
}
$idstr .wrap-corner .b-edge .r {
  background-position: -11px -11px;
}
$idstr .wrap-corner .r-edge {
  padding: 5px 24px;
}
$idstr div.admin-links {
  margin-top: -14px;
  margin-left: -12px;
}

$idstr .panel-separator {
  background: url($url/shadow-b.png) repeat-x 0 center;
  font-size: 1px;
  height: 30px;
}

$idstr .rounded-corner {
  margin-bottom: 1em;
}

EOF;

  return $css;
}

Comment: I found this snippet but do not know if this will work. https://drupal.org/node/218960#comment-790385 Need a nodeID?
Answer: The functionality you refer to predates common browser support for rounded corners, when images was the only reasonable solution.
Today, I would most likely no use it, but instead implement it with the modern CSS approach.
If you really want to modify the existing functionality though, it's called a Style. You can see this question for details about implementing ctools plugins: What are Ctools plugin (content type, access, etc), and how does one create them?
Comment: thanks Letharion for the link to your previous write-up about Ctools


Comparing topologies and metrics

Question: I have the space of continuous functions from $[0,1]$, $C([0,1])$, with 3 different metrics, $d_1$,$d_2$ and $d_\infty$, and the topologies induced by those metrics, $\tau_1$, $\tau_2$, $\tau_\infty$. I must to prove that $\tau_2$ is coarser than $\tau_\infty$.
I do not give the definition of every metric, because, before trying to solve this question I want to understand the relationship between the equivalence of metrics and comparing topologies. I mean, if $d \le \rho$, for any metrics $d$, $\rho$, what does this tell me about: comparing open balls with those metrics, comparing open sets in their respective topologies.
My teacher told me that, if $d \le \rho$ then $B_\rho(x, r) \subseteq B_d(x, \varepsilon)$ and $\tau_d \preceq \tau_\rho$. But this is not clear to me at all, neither in the matter of formal logic nor in intuition of what that says to me.
I hope I was clear and I would really appreciate it if you could help me to understand this issue.
Answer: Let $X$ be a set and endow it with two topologies $\tau_1$ and $\tau_2$, then $\tau_2$ is coarser then $\tau_1$ iff the identity map
$$I : (X,\tau_1) \longrightarrow (X,\tau_2) $$ is continuous. (Can you see why?)
Since you are working with metric spaces a function is continuous iff it's sequentially continuous, then if $d_1$ and $d_2$ are the metrics generating topologies $\tau_1$ and $\tau_2$ respectively with $d_2\leq d_1$, for any $x\in X$ take a sequence $x_n$ converging to $x$ in the $d_1$ metric, you get
$d_2(x,x_n)=d_2(I(x),I(x_n))\leq d_1(x,x_n)\longrightarrow 0$, so the identity map is continuous therefore $\tau_2$ is weaker then $\tau_1$
Answer: First we need to be clear what $d \le \rho$ and $\tau_1 \preceq \tau_2$ mean. From what your teacher says, $d \le \rho$ must mean that $d(x, y) \le \rho(x, y)$ for every $x$ and $y$ and $\tau_1 \preceq \tau_2$ means that every $\tau_1$-open set is also $\tau_2$-open (i.e., $\tau_1$ is coarser than (or equal to) $\tau_2$.
If $d \le \rho$ in the above sense, then $B_\rho(x, \epsilon) \subseteq B_d(x, \epsilon)$ for every $x$ and $\epsilon > 0$. Why? Answer: Because $y \in B_\rho(x, \epsilon)$ implies that $\rho(y, x) < \epsilon$, which (because $d \le \rho$) implies that $d(y, x) < \epsilon$ implying that $y \in B_d(x, \epsilon)$.
But if $B_\rho(x, \epsilon) \subseteq B_d(x, \epsilon)$ for every $x$ and $\epsilon > 0$ we must have $\tau_d \preceq \tau_\rho$. Why? Answer: if $A$ is $\tau_d$-open, then for every $x \in A$, there is an $\epsilon > 0$ such that $B_d(x, \epsilon) \subseteq A$, but then, because $B_\rho(x, \epsilon) \subseteq B_d(x, \epsilon)$, we have that $B_\rho(x, \epsilon) \subseteq A$. So for every point $x$ of $A$ there is $\epsilon > 0$ such that $B_\rho(x, \epsilon) \subseteq A$. So $A$ is $\tau_\rho$-open. We have shown that every $\tau_d$-open set is also $\tau_\rho$-open, so $\tau_d\preceq \tau_\rho$.
Comment: Much clearer! You are using the same radius $\epsilon$ for the open balls; is it still true for different radii, $\epsilon, r \gt 0$? Thank you so much.
Comment: Sorry, I corrected what must be a typo without mentioning it. It is not possible for every open $\rho$-ball to be contained in every open $d$-ball except in the trivial case when the space has only one point. If there are two points $x \neq y$, you can always find a $\rho$-ball around $x$ that includes $y$ (say the one with radius $r = 2\rho(x, y)$) and a $d$-ball around $x$ that does not contain $y$ (say the one with radius $\epsilon = d(x, y)/2$).

Comparing topologies and metrics


What is the meaning of the "callback=jQuery" query parameter in Http Request header?

Question: I'm trying to analysis a website login process.There exists a "callback=jQuery" in the GET request header I send to the server.Here is an example:
callback=jQuery17100013734368553252607_1378108363139&username=...
The number following jQuery varys every time.
So what does this mean exactly OR how to generate such numbers? Thank you!
Comment: it is used to over come same origin policy regarding requesting resources from a different domain using ajax
Comment: @ArunPJohny So generally how is the number `17100013734368553252607_1378108363139` generated?
Answer: Like Arun said...
What happens is that the server answer implements this callback with a 'function'...
Like this:..
jQuery17100013734368553252607_1378108363139('json_string_here')

and jquery generates this function, so it can be called:
function jQuery17100013734368553252607_1378108363139(string) {
   ...
}

so the answer calls this function... and you have access to the response...
Comment: Do you mean that `17100013734368553252607_1378108363139` is hard-coded?
Comment: no, jquery creates it, for every request, to avoid same function names for different ajax call's! this was just to explain waht is happening!
Comment: on client side yes! on server side, you have to bind it in your response, in PHP something like this: `echo $_GET['callback'] . '('data_here')';`


In Angular 4 How to re-inject a component created from the template

Question: I am building an app using Angular 4, and I would like to remove and re-insert a DOM element using a custom structural directive.
The template with the custom structural directive looks like this.

            <clr-icon
                [attr.shape]="(isSearchFormOpen | async) ? 'zoom-out' : 'zoom-in'">
            </clr-icon>

and the 'showIn' structural directive does the following.
@Input() set showIn(target: string) {
    console.log(this.templateRef);
    this.breakPoint.subscribe((breakPoint) => {
        if (target === breakPoint) {
            this.viewContainer.createEmbeddedView(this.templateRef);
        } else {
            this.viewContainer.remove();
        }
    })
};

The 'breakPoint' is a value returned every time the window gets resized, and depending on whether this value matches the input value of the directive, I would like to inject or eject the DOM element.
The issue is when the element is injected again after it's been removed from the view, the 'clr-icon' element is injected without the attribute binding I set up initially ('[attr.shape]="(isSearchFormOpen | async) ? 'zoom-out' : 'zoom-in'"), making the element itself invisible. It's only after I explicitly click inside the window that this attribute binding kicks in, making the element visible again.
How can I reinsert the DOM element without losing all property & attribute bindings?
Answer: You have to create an embedded view and store the reference to it. Then just insert or detach it. Something like this:
view = this.templateRef.createEmbeddedView(null);

@Input() set showIn(target: string) {
    console.log(this.templateRef);
    this.breakPoint.subscribe((breakPoint) => {
        if (target === breakPoint) {
            this.viewContainer.insert(this.view);
        } else {
            this.viewContainer.detach();
        }
    })
};

This solution is much more performant because it is simply attaches/removes the view DOM nodes to the host DOM node instead of creating and destroying the view each time which destroys/creates DOM nodes relevant for the view.
Comment: I somehow made it work by using ChangeDetectorRef.detectChanges(), but I think this is a much better solution. Thank you very much.


iterative sinus

Question: I saw this question online
"We define a series $\{a_i\}_{i=0}^\infty$ like so: $a_0 = 1, \; a_{n+1} = sin(a_n)$  prove that $a_n$ converges"
that is rather easy because if $\forall x>0 ,\;sin(x) < x$ that mean $a_n$ is monotonically decreasing and positive and thus converges.
It's pretty obvious $a_n$ converges to $0$, My question is, at what rate does $a_n$ converges to $0$.
Spoiler, I used my computer to show that the answer is probably $\frac{\alpha}{\sqrt{n}}$ where $\alpha \approx 1.732$ but I wasn't able to prove it mathematically
Comment: Spoiler?! LOL! I wonder if the 1000th person asking this question will get a bonus. https://math.stackexchange.com/questions/3215/convergence-of-sqrtnx-n-where-x-n1-sinx-n
Comment: How do you define rate of convergence?
Answer: By the Taylor approximation,
$$\frac{a_{n+1}}{a_n}\approx1-\frac{a_{n-1}^2}6$$ tends to $1$ and the convergence is sublinear.
As
$$\frac{a_{n+2}-a_{n+1}}{a_{n+1}-a_n}$$ tends to $1$, the convergence is said logarithmic, i.e. very slow.

iterative sinus


Invalid  jsp/* in filter mapping in eap 6.4

Question: I checked all the other url-pattern related issues but they do not solve my problem. so here it is:
I have a definition as follows in web.xml:
<code><filter-mapping>
  <filter-name>ManageFilter</filter-name>
  <url-pattern>/jsp/*.do</url-pattern>
</filter-mapping>
</code>
Exception throwed on start. Saying that :
<code> Invalid <url-pattern> /jsp/* in filter mapping
</code>
I have tried different version as follows :
<code> <url-pattern>jsp/*.do</url-pattern>
</code>
But it does not work. Same error is being raised.
How can I make it work? Or what is the working version of this url-pattern?
Thank you.
Full exception message :
<code>        15:32:52,179 ERROR [org.apache.catalina.core] (ServerService Thread Pool -- 81) JBWEB001097: Error starting context /E_LifePensionWeb: java.lang.IllegalArgumentException: JBWEB000278: Invalid <url-pattern> /jsp/*.do in filter mapping
            at org.apache.catalina.core.StandardContext.validateFilterMap(StandardContext.java:2030) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
            at org.apache.catalina.core.StandardContext.addFilterMap(StandardContext.java:1972) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
            at org.jboss.as.web.deployment.JBossContextConfig.processWebMetaData(JBossContextConfig.java:413) [jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
            at org.jboss.as.web.deployment.JBossContextConfig.applicationWebConfig(JBossContextConfig.java:267) [jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
            at org.apache.catalina.startup.ContextConfig.start(ContextConfig.java:369) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
            at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:162) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
            at org.jboss.as.web.deployment.JBossContextConfig.lifecycleEvent(JBossContextConfig.java:260) [jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
            at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:115) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
            at org.apache.catalina.core.StandardContext.start(StandardContext.java:3720) [jbossweb-7.5.7.Final-redhat-1.jar:7.5.7.Final-redhat-1]
            at org.jboss.as.web.deployment.WebDeploymentService.doStart(WebDeploymentService.java:163) [jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
            at org.jboss.as.web.deployment.WebDeploymentService.access$000(WebDeploymentService.java:61) [jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
            at org.jboss.as.web.deployment.WebDeploymentService$1.run(WebDeploymentService.java:96) [jboss-as-web-7.5.0.Final-redhat-21.jar:7.5.0.Final-redhat-21]
            at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) [rt.jar:1.7.0_80]
            at java.util.concurrent.FutureTask.run(FutureTask.java:262) [rt.jar:1.7.0_80]
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_80]
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_80]
            at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_80]
            at org.jboss.threads.JBossThread.run(JBossThread.java:122)
</code>
Comment: Try using `jsp/*` only
Comment: Let me explain it a bit further to make the big picture clear.
I have two filters, one is filtering all .do files and the other which I am having problems is handling the .do files only under a subfolder. So, the .do files which must be filtered by managefilter Filter class is staying under JSP subfolder. The issue is I can not give a subfolder and .do prefix et the same time to a url-pattern as it gives me the error Invalid url-pattern. Thanks.
Comment: I solved the issue by giving all the do files a seperate filter-mapping with full names.
But now the REQUEST object (httpsservletrequest) disappears during forward from action to jsp to filter. I think this has something to do with struts bean settings. Do you know anything about that?
Comment: Can you share the code and elaborate on your problem?
Comment: Hi, I asked a new question for that. https://stackoverflow.com/questions/56835084/forwarded-request-is-not-passed-and-an-empty-one-is-being-processed-jboss-eap-6
Answer: Issue is solved by giving all .do paths separately in web.xml
Thanks


Updating the value of a iterator tag in struts2

Question: I have a jsp in which I have a drop down as
<s:select name="newQuestion.CertificationId" list="certificationList"
          listKey="certificationId" listValue="certificationName"
          headerKey="" headerValue="Select Certification"
          label="Certification Name"
          onchange="getQuestionsList(this.value)" />

When the dropdown value changes I can getQuestionsList. In the javascript function I submit to an action class where I modify the value of a questionList which is displayed in my JSP via an iterator.
The values of the questionList contain all questions and when I select a value from the above drop down I need to populate only those questions which belong to the id selected in the drop down. (I query the DB to load the questions in action class.)
Initially when the page is loaded I have all questions in questionList but after selecting a value from drop down I have the updated questions in the action class.
For displaying the values of question list I use a iterator tag

  Question List

      Question Id
      Question Description

    <s:iterator value="questionList">

        <s:property value="questionId" />
        <s:property value="questionDesc" />

</s:iterator>

The div is initially hidden and on select of a value in drop down I need to display the values of questionList which is taking old values as the page is not reloaded.
When I again come back to this jsp I am not seeing the new value as it is not getting updated.
Any heads up please
Comment: if this is ajax, I think it won't be implicitly handled by Struts2's action unless you are using a plugin which support ajax.
Answer: Why don't you try Struts2 Jquery Plugin. Here is the showcase with code.
What you need is
<sj:select ...> tag.

Let me know if you still need an example.
Answer: You would need to make few changes to the code. Let me list them down:

Move the following part in your initial JSP to another jsp, say questionList.jsp. The below part should be the only thing which should be inside the newly created jsp.
  Question List

      Question Id
      Question Description

    <s:iterator value="questionList">

        <s:property value="questionId" />
        <s:property value="questionDesc" />

</s:iterator>

In your main page, you would need to replace the above code part with
<jsp:include page="questionList.jsp" flush="true"/>
Now deploy and see if everything is in place as before.
In your getQuestionsList() javascript function, make an ajax call to another action mapping say showQuestionList.action?certification=12. Here, 12 will be the id of the certification, which you will handle in the action. If you use certification as an action property, add a variable with the same name with getter and setter methods.
In your action method say showQuestionList(), retrieve the questionList and assign to the action variable.
On return of SUCCESS of the above method, the result should send only questionList.jsp. This will have the part to list just the necessary fields.
In the getQuestionsList() javascript function, after the ajax call being success, get the data and put it into the div with id questionDetails.
Show the div.


Plotting a numpy array with 256 columns used for k-means

Question: I have a numpy array with this shape: (109, 256) Every row is a frame and every column is a value of the frame's histogram (8 bits).
With k-means I cluster the histograms to get a resume of the frames. I want something like this:

Where every cluster should be a "scene" with similar histograms.
But how can I plot a representative graphic of the k-means process with 256 columns??
I'm trying with this typical example:
<code>plt.scatter(X[:,0],X[:,1], c=kmeans.labels_, cmap='rainbow')
</code>
But yeah, it shows only 2 columns and it doesn't represent the problem. Any help? I'm really new on Python and machine learning.
PD: my k-means code works well and it clusters the way I want, but I don't know how to represent it correctly.
Comment: can you explain why you have 256 columns ?
Answer: You always represent k-means clustering results on two axis. Those axis can be picked randomly. The only way you can include more attributes is by adapting the size of your points to another variables (for example the higher the income the bigger the point) or by having different color shades.
Otherwise, you seem to have done everything correctly, you have to stick to two variables for your axis and can't integrate more..
You can decide on creating more plots with different axis and create a grid (often this doesn't add much information though)


How setText in multiple TextView in onTick() method

Question: I have small question.
new CountDownTimer(12000, 2000) {
    public void onTick(long millisUntilFinished) {

    }
    public void onFinish() {

    }
}.start();

Here I would like setText to 6 different TextView(in one xml) with each onTick(). Any ideas how i can make this? Thanks
//edit
I would like have something like this
First tick
tv.setText("one")
Second Tick
tv2.setText("two")

Comment: try to use runonuithread
Answer: try using Array of TextViews like
TextView[] textViews = new TextView[6];
String[] value = new String[]{"one","two","three","four","five","six"};
int count = 0;

new CountDownTimer(12000, 2000) {

                    public void onTick(long millisUntilFinished) {
                        textViews[count].setText(value[count]);// you can set dynamic string variable also
                        count++;
                    }
                    public void onFinish() {

                    }
                }.start();

Comment: Thats what I was looking for. Thank you ;)
Answer: You could do something like this:
new CountDownTimer(12000, 2000) {
    int counter = 0;

    public void onTick(long millisUntilFinished) {
        switch (counter) {
            case 0:
                tv1.setText("");
                break;
            case 1:
                tv2.setText("");
                break;

            // ...

        }
        counter++;
    }
    public void onFinish() {
    }
}.start();

Answer: Check Below Answer,
   new CountDownTimer(12000, 2000) {

         public void onTick(long millisUntilFinished) {

               Activity_Name.this.runOnUiThread(new Runnable() {

                  @Override
                  public void run() {
                     tv1.setText("");
                     tv2.setText("");
                     tv3.setText("");
                     tv4.setText("");

                  }
               });

          }
          public void onFinish() {

          }
   }.start();

Comment: I would like setText ONCE per tick. In each next tick i would like setText to other TextView. Any option?
Comment: take one int variable and increase it in onTick method and use switch or if for setting value in textview


Jboss EAP 7.4.1 configuration issues

Question: I am trying to bring one of the environments EAP 7.0 to EAP7.4.1 and I have managed to migrate one of the environments successfully. However, on one of the environments, as soon as I start EAP after upgrade in the domain mode, the server runs out of memory with the error below:
<code>> "WFLYCTL0030: No resource definition is registered for address [
>     (\"host\" => \"somehost-server-1\"),
>     (\"server\" => \"server-1\"),
>     (\"core-service\" => \"platform-mbean\"),
>     (\"type\" => \"operating-system\") ]"
</code>
I have tried to copy the exact configuration as the other environment where EAP is running smoothly and find no difference. I couldn't find any help if I try to find this error, all I can see is that it has something to do with the Monitoring service of Jboss EAP. Can someone help?
Comment: Is your application a batch processing app using jberet? If so, can you give more details as to the jobs, amount of job executions, job repository, etc.
Comment: Yes I do around 21 batch jobs running in the application. I have configured the job repository to use JDBC so it uses my DB. And the amount of job executions vary from 1 to 2600. But there are several batch jobs where the job execution is above 1500.
Answer: I found the issue, apparently jberet was internally trying to fetch details about the job executions from the table(JDBC repository). And since there was a lot of rows in that table, the committed heap size would run out.
After I deleted rows from that table, the server looks stable and everything runs smoothly. I wonder how the server handles a large load since it is constantly trying to fetch that data. Is there an alternate to the solution?
Comment: This issue has been fixed in WildFly 25 and latest EAP version (see [WFLY-14946](https://issues.redhat.com/browse/WFLY-14946)).

Jboss EAP 7.4.1 configuration issues