How does Ruby Array #count handle multiple block arguments

Question: When I execute the following:
[[1,1], [2,2], [3,4]].count {|a,b| a != b} # => 1

the block arguments a, b are assigned to the first and the second values of each inner array respectively. I don't understand how this is accomplished.
The only example given in the documentation for Array#count and Enumerable#count with a block uses a single block argument:
ary.count {|x| x % 2 == 0} # => 3

Comment: It's called ["array decomposition"](https://docs.ruby-lang.org/en/2.1.0/syntax/assignment_rdoc.html#label-Array+Decomposition). That [entire doc](https://docs.ruby-lang.org/en/2.1.0/syntax/assignment_rdoc.html) is well worth a read. In this case, when, say, `[3, 4]` is passed to the block, Ruby computes `a, b = [3, 4]`. Try that in IRB or PRY and you'll see `a` is set to `3` and `b` is set to `4`. If the block variables were written `|a, (b, c)|` and `[3, [4, 5]]` were passed to the block the calculation would be `a, (b, c) = [3, [4, 5]]`, which results in `a #=> 3`, `b #=> 4` and `c #=> 5`.
Comment: Note that this is *exactly the same thing* as doing `hsh.each {|key, value|}` where `hsh` is some `Hash`, since `Hash#each`, like *all* implementations of `each` only ever `yield`s a single value per iteration, in this case a two-element `Array` whose first element is the key and second element is the value.
Answer: Just like assignments, there's a (not-so-) secret shortcut. If the right-hand-side is an array and the left-hand-side has multiple variables, the array is splatted, so the following two lines are identical:
a, b, c = [1, 2, 3]
a, b, c = *[1, 2, 3]

While not the same thing, blocks have something in the same vein, when the yielded value is an array, and there are multiple parameters. Thus, these two blocks will act the same when you yield [1, 2, 3]:
do |a, b, c|
  ...
end

do |(a, b, c)|
  ...
end

So, in your case, the value gets deconstructed, as if you wrote this:
[[1,1], [2,2], [3,4]].count {|(a,b)| a != b} # => 1

If you had another value that you are passing along with the array, you would have to specify the structure explicitly, as the deconstruction of the array would not be automatic in the way we want:
[[1,1], [2,2], [3,4]].each.with_index.count {|e,i| i + 1 == e[1] }
# automatic deconstruction of [[1,1],0]:
# e=[1,1]; i=0

[[1,1], [2,2], [3,4]].each.with_index.count {|(a,b),i| i + 1 == b }
# automatic deconstruction of [[1,1],0], explicit deconstruction of [1,1]:
# a=1; b=1; i=0

[[1,1], [2,2], [3,4]].each.with_index.count {|a,b,i| i + 1 == b }
# automatic deconstruction of [[1,1],0]
# a=[1,1]; b=0; i=nil
# NOT what we want

Comment: `(a, b) = [1, 2]` is documented, but not the implicit form without parentheses. I've opened a [ticket](https://bugs.ruby-lang.org/issues/15514).
Comment: _"If the right-hand-side is an array and the left-hand-side has multiple variables, the array is splatted"_ – this isn't documented, is it?
Comment: @Stefan It probably is somewhere. I don't remember where I read about it first. Maybe not in those words; but there is a clear difference in semantics of `a = [1, 2]` and `a, b = [1, 2]` - the first assigns the array, the second assigns its elements.
Comment: @Stefan I might miss something, but isn't at leat the deconstruction on assignment documented just above the section you linked to, i.e. [here](http://ruby-doc.org/core-2.6/doc/syntax/assignment_rdoc.html#label-Multiple+Assignment)?
Comment: @HolgerJust: No - `a, b = 1, 2` is documented there (with multiple lvalues being assigned multiple rvalues); but not `a, b = [1, 2]` (multiple lvalues being assigned a single array).
Answer:
I have looked at the documentation for Array.count and Enumerable.count and the only example given with a block uses a single block argument ...

Ruby, like almost all mainstream programming languages, does not allow user code to change the fundamental semantics of the language. In other words, you won't find anything about block formal parameter binding semantics in the documentation of Array#count, because block formal parameter binding semantics are specified by the Ruby Language Specification and Array#count cannot possibly change that.

What I don't understand is how this is accomplished.

This has nothing to do with Array#count. This is just standard block formal parameter binding semantics for block formal parameters.
Formal parameter binding semantics for block formal parameters are different from formal parameter binding semantics for method formal parameters. In particular, they are much more flexible in how they handle mismatches between the number of formal parameters and actual arguments.

If there is exactly one block formal parameter and you yield more than one block actual argument, the block formal parameter gets bound to an Array containing the block actual arguments.
If there are more than one block formal parameters and you yield exactly one block actual argument, and that one actual argument is an Array, then the block formal parameters get bound to the individual elements of the Array. (This is what you are seeing in your example.)
If you yield more block actual arguments than the block has formal parameters, the extra actual arguments get ignored.
If you pass fewer actual arguments than the block has formal parameters, then those extra formal parameters are defined but not bound, and evaluate to nil (just like defined but unitialized local variables).

If you look closely, you can see that the formal parameter binding semantics for block formal parameters are much closer to assignment semantics, i.e. you can imagine an assignment with the block formal parameters on the left-hand side of the assignment operator and the block actual arguments on the right-hand side.
If you have a block defined like this:
{|a, b, c|}

and are yielding to it like this:
yield 1, 2, 3, 4

you can almost imagine the block formal parameter binding to work like this:
a, b, c = 1, 2, 3, 4

And if, as is the case in your question, you have a block defined like this:
{|a, b|}

and are yielding to it like this:
yield [1, 2]

you can almost imagine the block formal parameter binding to work like this:
a, b = [1, 2]

Which of course, as you well know, will have this result:
a #=> 1
b #=> 2

Fun fact: up to Ruby 1.8, block formal parameter binding was using actual assignment! You could, for example, define a constant, an instance variable, a class variable, a global variable, and even an attribute writer(!!!) as a formal parameter, and when you yielded to that block, Ruby would literally perform the assignment:
class Foo
  def bar=(value)
    puts "`#{__method__}` called with `#{value.inspect}`"
    @bar = value
  end

  attr_reader :bar
end

def set_foo
  yield 42
end

foo = Foo.new

set_foo {|foo.bar|}
# `bar=` called with `42`

foo.bar
#=> 42

Pretty crazy, huh?
The most widely-used application of these block formal parameter binding semantics is when using Hash#each (or any of the Enumerable methods with a Hash instance as the receiver). The Hash#each method yields a single two-element Array containing the key and the value as an actual argument to the block, but we almost always treat it as if it were yielding the key and value as separate actual arguments. Usually, we prefer writing
hsh.each do |k, v|
  puts "The key is #{k} and the value is #{v}"
end

over
hsh.each do |key_value_pair|
  k, v = key_value_pair
  puts "The key is #{k} and the value is #{v}"
end

And that is exactly equivalent to what you are seeing in your question. I bet you have never asked yourself why you can pass a block with two block formal parameters to Hash#each even though it only yields a single Array? Well, this case is exactly the same. You are passing a block with two block formal parameters to a method that yields a single Array per iteration.
Comment: Ah, you're right, I remember that there was some discussion about checking the arity of the block. This is one of those cases where YARV makes some "unfair" optimizations that are not available to user code. If you wanted to do the same thing in user code, you would need to first convert the block to a proc so you can call `Proc#arity` or `Proc#parameters` on it, which would completely negate any performance advantage you would get from not constructing the array. Note, however, that there will also be another difference when you pass a lambda with `&`, I think.
Comment: Note also that this is really a YARV-specific optimization. E.g. JRuby already optimizes away the array in all of the more general cases, i.e. destructuring assignment, multiple value return, block parameter binding, etc.
Comment: Fun fact: YARV's `Hash#each` actually yields two values when the block takes multiple arguments (and an array otherwise). Probably for performance reasons to avoid the to-array/from-array conversion.
Comment: The whole parameter binding thing with regards to blocks, procs converted to blocks, and lambdas converted to blocks is a bit of a mess.


Fatal error - Class 'context_condition_node' in date_context module

Question: I'm debugging a site that has completely broken - not finding too much out there and hoping for some help. The error I see is:
Fatal error: Class 'context_condition_node' not found /sites/all/modules/contrib/date/date_context/date_context.module on line 56
Anyone seen this before?
Answer: It means this module is missing or registry is broken.
Can you check if the date module does exist?
If not you may try to download a copy of date module and put it in the exactly the folder.
Use Drush drush cc all to clear the cache.
In Drupal 7 you can also go to admin performance page to clear the cache. Sometimes this is still available by admin/config/development/performance.
If it still does not work, you may want to have a go with registry_rebuild module to rebuild the registry totally.
Comment: Yup it was a registry issue. I had to actually remove date module and re-add it for some reason, but now it's resolved. Thanks!


Is there a standard set of cadences designed for the seven modes?

Question: On Cadences for Modes and Modal Cadence Options, Dom, Richard, and I came up with a group of modal cadences.  Specifically (correct order from Ionian to Locrian):

Dom: ii-I, VII-i, II-i, II-I, VII-I, VII-i, [N/A]

Richard: V-I, VII-i, [II-i or vii-i], V-I, VII-I, VII-i, [N/A]

Me: [ii6-I or ii65-I], [ii6-i or ii65-i], [II-i or vii6-i], II6-I,  VII-I, VI-i, iii6-i(no5)

Since all three of us came up with different ideas, I am wondering: is there any standard set of cadences for each of the seven modes?
Comment: Each mode can have more than 1 cadence, no?
Comment: What do you mean by "standard" set of cadences?  There are certainly cadences which are more common and less common, as your list shows.  I don't know of any theoretical works on it, certainly none with any influence on composition.
Answer: There is not just one modal style. Do you mean Medieval modal, modal folk, modal jazz, modal rock? I'll address two.
In terms of standards, the clausula vera is the standard cadence in Medieval modal music. I think it is worth noting that even in this early style the mode could be chromatically altered to form a cadence. Your outline of cadences in the other two questions seem to require that the cadence be purely diatonic to maintain the quality of the mode. Within the Medieval that simply is not required. It's contrary to the style.

http://www.robertkelleyphd.com/clausula.htm
For other modal styles - basically modern styles of folk, rock, jazz with modal flavoring - @Dom and @Richard lay out essentially the same idea. Tritones are avoided in the chords and root progressions, use root progression of descending 5th or 4th, or use root progression by step like bVII i or bII i, use root position chords. Notice that with these cadences unique chord qualities are not required. bVII i and v i (with a minor dominant) are common to both Dorian and Aeolian. Your outline of cadences also has this requirement for uniqueness, but that isn't required by this style.
Here are some examles of the song Drill, Ye Tarriers...

https://www.sheetmusicdirect.com/se/ID_No/90044/Product.aspx
...and another arrangement...

https://www.partitionsdechansons.com/sheet-music/1754-england-drill-te-tarriers.html
We can see the modal quality in the melody from the lowered ^7 degree.
Between the two arrangements there is a fluidity in handling the cadences. V7 i, v i, and bVII i are all variously used.
Notice the ^6 degree is not used in the melody and it is not used in the two cadence chords. The ^6 is used in the repeated phrase "drill, ye tarriers..." in bVI before the cadence bVII i. Clearly the cadences do not need to contain unique modal tones, nor do they need to be modally pure.
From what I have seen in numerous folk songbooks this is very typical of how cadences are treated.

Siegmeister, Harmony & Melody. Vol II, Twentieth Century Melody p. 368. This textbook has about 25 pages devoted to the modes - excluding Locrian - in 20th century music. It specifically addresses the changed aspect of chord function in the various modes. Many musical quotes from real composers like Milhaud are included.


How to inherit from textbox and override keypress and keyup events?

Question: I want to create a new class inherits from System.Windows.Forms.TextBox and assign keypress and keyup events to my control.
Something like this :
    class CurrencyTextbox : TextBox
    {
        private void CurrencyTextbox_KeyPress(object sender, KeyPressEventArgs e)
        {
            char ch = e.KeyChar;

            if (!Char.IsDigit(ch) && ch != 8 && ch != 13)
            {
                e.Handled = true;
            }
        }

        private void CurrencyTextbox_KeyUp(object sender, KeyEventArgs e)
        {
            if (!string.IsNullOrEmpty(CurrencyTextbox.Text))
            {
                System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");
                Int64 valueBefore = Int64.Parse(CurrencyTextbox.Text, System.Globalization.NumberStyles.AllowThousands);
                CurrencyTextbox.Text = String.Format(culture, "{0:N0}", valueBefore);
                CurrencyTextbox.Select(CurrencyTextbox.Text.Length, 0);
            }
        }
    }

Comment: SLaks's answer works ! Many thanks to him. Now everytimes I want it I need to drag a textbox from toolbox into form then go to from.Designer.cs to replace "private System.Windows.Forms.TextBox TextBox1;" to "private CurrencyTextbox TextBox1;". Is there any way to add it to toolbox so I can use it like other controls.
Comment: I try to return the text of the currency textbox as number format. Eg : textbox2.text = currencytextbox1.text (currencytextbox1.text=999,999) then I would like textbox2.text = 999999 (no ","). I tried to override text get method but the app then crashed. Do you have any idea for it ? Thank in advance !
Answer: You should override the protected virtual void OnKeyUp(KeyEventArgs e).
Make sure to call base.OnKeyUp(e), or the event will not be raised.
You can also add a regular event handler by writing KeyUp += CurrencyTextbox_KeyUp
Comment: Thanks, it works ! Now everytimes I want it I need to drag a textbox from toolbox into form then go to from.Designer.cs to replace "private System.Windows.Forms.TextBox TextBox1;" to "private CurrencyTextbox TextBox1;". Is there any way to add it to toolbox so I can use it like other controls.
Comment: After you build your project, it should appear in the toolbox.  If it doesn't, check the toolbox options tab.  Also, try making the class `public`.
Comment: Thank SLaks, I try to return the text of the currency textbox as number format. Eg : textbox2.text = currencytextbox1.text (currencytextbox1.text=999,999) then I would like textbox2.text = 999999 (no ","). I tried to override text get method but the app then crashed. Do you have any idea for it ? Thank in advance !


Update method doesn't save to database in Grails

Question: I'm trying to write custom a custom controller that would allow me to handle tables with composite keys in Grails 3.3.8. One such table that I have is called AliasFrequencyDict and so I created a method like this in the controller:
@Transactional
def update(AliasFrequencyDict aliasFrequencyDict) {

    aliasFrequencyDict = AliasFrequencyDict.get( new AliasFrequencyDict(params) )

    if (aliasFrequencyDict == null) {
        notFound()
        return
    }

    try {
        aliasFrequencyDict.save(insert: false, flush: true, failOnError: true)
    } catch (ValidationException e) {
        respond aliasFrequencyDict.errors, view:'edit'
        return
    }

    request.withFormat {
        form multipartForm {
            flash.message = message(code: 'default.updated.message', args: [message(code: 'aliasFrequencyDict.label', default: 'AliasFrequencyDict'), aliasFrequencyDict.getPK()])
            redirect(action: 'show', params: params)
        }
        '*'{ respond aliasFrequencyDict, [status: OK] }
    }
}

This seems like it should work - when I change something in the edit view and submit, I am correctly redirected to the show action, I get the flash message informing about successful update, the URL is http://localhost:8080/aliasFrequencyDict/show?_method=PUT&version=&frequency=0&unit=Q&description=abc123&lang=PL, and yet nothing changes in the record in the database itself. Why is that so? What may be wrong here?
Comment: Is your project available on github? Useful to see other things going on here such as `getPK()`
Comment: @MikeW - it's not and regretfully I don't think it can be as I'm doing this in a corporate environment so I don't think I'm allowed to show it in its entirety :( As for the problem here, though, adding a line `aliasFrequencyDict.properties = params` seems to have solved the problem!
Comment: I would expect you to get a 404 there because I don't think `AliasFrequencyDict.get( new AliasFrequencyDict(params) )` is ever going to find a matching record.  Maybe there is something in `AliasFrequencyDict` that would make that make more sense but at a glance I am not sure what the intent there is.
Comment: My previous comment assumes that your `notFound()` method returns a 404 of course.
Comment: @JeffScottBrown - but that wasn't resulting in a 404, quite the contrary - a "successfully updated" message. Turns out the culprit was me not writing the params to the properties explicitly, like mentioned above. The `.get()` method way of looking for a record is based on this entry in the docs: http://docs.grails.org/3.0.2/guide/GORM.html#compositePrimaryKeys (as I mentioned, I'm using composite primary key here)
Comment: I had overlooked the composite key.  Glad you worked it out.
Answer: OK, turned out the issue was simpler than it looked like - writing the params to the properties explicitly before saving was enough to fix it! So we simply do this:
...
if (aliasFrequencyDict == null) {
            notFound()
            return
        }

aliasFrequencyDict.properties = params /* <===== here! */

try {
    aliasFrequencyDict.save(insert: false, flush: true)
...

...and it works!


The negation of $(P)$

Question: Let $(E,\mathcal{A},\mu)$ be finite measure space. Let $A\subset \mathbb{R}$ and the multifunction $F:E\to 2^{\mathbb{R}}$
We suppose that:
$$
 (P)~~:~~\exists N\in \mathcal{A} ~(\text{with }\mu(N)=0),\text{ such that: }\forall t\in E\smallsetminus N~:~F(t)\subset A
$$
Can we say that the negation of $(P)$ is :
$$
\exists N\in \mathcal{A} ~(\text{with }\mu(N)\neq 0) \text{ such that: } \forall t\in N~:~F(t)\nsubseteq  A
$$
If not, can you give me the negation of $(P)$. An idea please.
Comment: You needn't delete the previous question.
Comment: I apologize but it was contains many errors
Answer: I think it's good to think of the initial proposition in terms of $\mathcal B = \{N\in\mathcal A\,|\,\mu(N) = 0\}$.
Then the initial proposition is
$$
\exists N\in \mathcal{B}\text{ such that }\big( \forall t\in E\setminus N,~F(t)\subset  A\big).
$$
The negation is then simply
$$
\forall N\in \mathcal{B},\big( \exists t\in E\setminus N \text{  such that }F(t)\not\subset  A\big).
$$
Comment: I want to demonstrate a proposition of the same type as $ (P) $, for that I used the proof by absurd and I used the formula  :$$\exists N\in \mathcal{A} ~(\text{with }\mu(N)\neq 0) \text{ such that: } \forall t\in N~:~F(t)\nsubseteq  A$$
Is this formula wrong?
Comment: Yes, that is not the negation of $P$.
Comment: why no $(P)$ does not imply what I wrote?
Comment: I have shown what the negation of $P$ is.
Comment: Do you understand how to negate a proposition?
Answer: The negation of a forall is an exists, and vice versa. So "not all humans are mortal" is logically the same as "there is a human who is not mortal" and "there is no god who is mortal" is logically the same as "all gods are not mortal."
More formally, $$\neg(\exists x \in Y: f(x))~~\Leftrightarrow~~\forall x \in Y: \neg f(x),\\
\neg(\forall x \in Y: f(x))~~\Leftrightarrow~~\exists x \in Y: \neg f(x).
$$
In your particular case you have
$$
\neg(\exists N \in \mathcal A: \mu(N)=0~\wedge~\forall t\in N: F(t)\subset A)
$$
Distributing this gives
$$
\forall N \in \mathcal A: \mu(N)\ne 0~\vee~\exists t\in N: F(t)\not\subset A
$$
We could then rewrite that last part as $\mu(N) = 0 ~\rightarrow~ \exists t\in N: F(t)\not\subset A$ and then incorporate the "with $\mu(N) = 0$" into the "forall" clause, if you wanted to instead do like the other answer did and view  the original (P) as restricting focus to a set $\mathcal B = \mathcal A \cap \operatorname{ker} \mu$ : you can indeed see this as saying for all elements $N$ of $\mathcal B$ there is some $t$ in $N$ such that $F(t)$ is not a subset of $A$. In this way a domain restriction on an "exists", manifesting as a conjunction, becomes (on negation) an implication, which is a domain restriction on a "forall."

The negation of $(P)$


Pseudo-dice probability distribution

Question: Given the following data, is there an algorithmic way to generate a probability distribution?
Data: min, max, and average results of "die".
Known Trend: results will always be weighted towards lower values, as the gulf between the average and max is greater than the gulf between the average and min (e.g. min=10, avg=19.4 max=42)
Constraints:

Results are restricted to integer values
The probabilities of any two results should be as close to equal as possible.

Allowances: Rough approximations (+/-0.5) of a given average are acceptable.
Comment: Do you also require all integers between min and max to be possible? My intuition says that allowing gaps would make it much easier to satisfy the trend.
Answer: First, find $p_1,\ldots,p_{33}$ that satisfy the system
$$
\begin{cases}
p_1+p_2\cdots+p_{33}=1\\
10p_1+11p_2+\cdots+42p_{33}=19.4\cdot33,
\end{cases}
$$
s.t. $0\leq p_i\leq 1$ for all $i=1,\ldots,33$. Then sample $\{10,11,\ldots,42\}$ with cell probabilities $(p_1,p_2,\ldots,p_2)$.

Pseudo-dice probability distribution


Runbook - PowerShell to modify Azure AD Group

Question: I'm using ARM and have created an automation account, with a run book using the PowerShell code snippet below to modify Azure AD users so that their location is updated properly. All resources are within the same subscription and resource group as my Azure AD.
get-msoluser | where{$_.userPrincipalName -like "*@contoso.co.uk"} | set-msoluser -Usagelocation "GB"
When I run this in Azure, I get a failure as below:
The term 'get-msoluser' is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:2 char:1
+ get-msoluser | where{$_.userPrincipalName -like "*@contoso.co.uk."} | s ...
+ ~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (get-msoluser:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
When I run the PowerShell manually using "connect-msolservice" and enter my credentials it works fine.
I have a couple of questions:

Do I need to supply credentials so that the PowerShell knows which Azure AD to connect to?
What modifications do I need to make to ensure get-msoluser cmdlet is recognised?

Thanks
Comment: This [blog](https://blog.kloud.com.au/2016/08/24/schedule-office-365-powershell-tasks-using-azure-automation/) answered your question. Please see my answer.
Answer: You have to think about Azure Automation account as a fresh powershell install. it has got almost no modules in it. What you have to do first is install modules into it. Just follow that article and install the proper module, after that all the cmdlets from that module will be available to you in Azure Automation runbooks.
And you still need to authenticate against Azure AD (with proper rights) for your commands to work (else anybody could issue the same commands against your Azure AD, which is not something you would like). So you should start every runbook with the silent authentication commands. You can use Azure Automation
variables to store passwords (to not hardcode them into the runbook).
You can also use certificate auth, Azure Automation is capable of storing certificates for that.


Passing values from a custom view to Main View Controller - Swift

Question: I am working on a basic alarm app. This is how the main storyboard looks like

I have added a custom view controller as a separate xib file which looks like this

And this is how the interface looks like when it runs. (The main ViewController in background and the CustomAlertController in the foreground)

It contains a date picker. What I mean to do is that when a user clicks on the addButton in the Main story board the customAlertViewController will come up and the user can choose a date and time to add as an alarm. When the user taps on Add in the customAlertViewController the date and time are supposed to be passed back into an array and added to the tableView in the Main storyboard view controller.
This is the code I have written so far:
Code for TableView
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    let adate = alarmDate[indexPath.row].date
    print(adate)
    cell.textLabel?.text = String(adate)
    return cell
    }

Code in the Alarm class
import Foundation
class Alarm{
    var date : NSDate
    init (date : NSDate){
        self.date = date
    }
}

Code in CustomAlertViewController
You don't have to go through the entire code. I have tried using prepare for segue, but I guess that's not a doable solution when the CustomAlertviewcontroller is in a different storyboard(?)
The next approach I took was to somehow pass the date to an instance of Alarm class in the viewDidDisappear method, and subsequently append it to alarmDate array (declared in ViewController).
This is where I am getting stuck. The print statement in the viewDidDisappear outputs 1 to the console, obviously because the date has been appended. But once the CustomAlertViewController exits and the viewController is back, the alarmDate array resets and no value shows up in the table view. I have tried to work around this but to no avail.
I realise that if I had used a new view controller in the storyboard in place of a separate xib file, I could have achieved the same result easily.
class CustomAlertViewController: UIViewController {
    //MARK: - Properties
    @IBOutlet weak var customAlertView: UIView!
    @IBOutlet weak var alarmPicker: UIDatePicker!
    var destinationDate = NSDate()
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName : nibNameOrNil, bundle : nibBundleOrNil)
        self.modalPresentationStyle = .OverCurrentContext
    }
    convenience init(){
        self.init(nibName : "CustomAlertViewController", bundle: nil)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("NSCoding not supported")
    }

    //MARK: - Methods
    override func viewDidLoad() {
        super.viewDidLoad()
        print ("View loaded")
        self.customAlertView.layer.borderColor = UIColor.darkGrayColor().CGColor
        self.customAlertView.layer.borderWidth = 2
        self.customAlertView.layer.cornerRadius = 8
        view.backgroundColor = UIColor(white: 1, alpha: 0.7)
        view.opaque = false
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    override func viewDidDisappear(animated: Bool) {
        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("table") as! ViewController
        let alarm = Alarm( date : destinationDate)
        vc.alarmDate.append(alarm)
//        vc.alarmData.reloadData()
        print(vc.alarmDate.count)
    }
    // MARK: - Navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        let destinationVC = segue.destinationViewController as! ViewController
        let alarm = Alarm( date : destinationDate)
        destinationVC.alarmDate.append(alarm)
        destinationVC.alarmData.reloadData()
        print(destinationVC.alarmDate.count)
    }
    //MARK: - Actions
    @IBAction func cancelButton(sender: AnyObject) {
        self.presentingViewController!.dismissViewControllerAnimated(true, completion: nil)
    }
    @IBAction func addButton(sender: AnyObject) {
        //Code to correct the time zone difference
        let sourceDate = alarmPicker.date
        let sourceTmeZone = NSTimeZone(abbreviation: "GMT")
        let destinationTimeZone = NSTimeZone.systemTimeZone()
        let sourceOffset = sourceTmeZone!.secondsFromGMTForDate(sourceDate)
        let destinationOffset = destinationTimeZone.secondsFromGMTForDate(sourceDate)
        let interval : Double
        interval = Double(destinationOffset - sourceOffset)
        destinationDate = NSDate.init(timeInterval: interval, sinceDate: sourceDate)

        self.presentingViewController!.dismissViewControllerAnimated(true, completion: nil)
    }
}

I lack experience with Swift and would gladly appreciate any help.
PS I'm using Swift 2.3
Comment: The best way to accomplish this is by using a protocol and delegate to pass information between the view controllers. I would learn about protocols and delegation regardless because they're value concepts to know as you get better. There's plenty of resources both online and through stackoverflow on this. Here is one tutorial to get you started: http://www.iphonelife.com/blog/31369/swift-programming-101-mastering-protocols-and-delegates-part-2
Comment: You're welcome! I'd post code, but there are so many resources already out there that it would be redundant at this point. If you have a specific question though, I'd be happy to help! Also, you can probably accomplish this with notification center, but it's more of a "hacky" way. You could run into issues down the line with notification center for something like this. Protocols are the "proper" way I guess you could say. OR if you're using a navigation controller, you can use an "unwindSegue" function to accomplish the same thing. Good luck!
Comment: Thanks!. I'll look that up
Comment: @user3353890 Thanks! Finally figured out how to work with protocols. The tutorial was a great help
Comment: You're welcome! I'm glad it helped.
Comment: Well notification is not a good process. You can do this by protocols.
Answer: You could use a protocol:
protocol DateShare {
    func share(date: NSDate)
}

which you declare wherever you want outside of any controller scope.
then you add a
delegate: DateShare!

property in your CustomAlertVC. In the VC, when you init the CustomAlert, you add this line:
customAlert.delegate = self

And of course you add an extension that you conform to the DateShare protocol in your VC, as so:
extension ViewController: DateShare {
    func share(date: NSDate) {
         // do whatever you can for that the date can be displayed in table view
        alarmDates.append(date) // if I understood it all ?
    }
}

And finally you add this line in addButton(sender: _) scope:
@IBOutlet func addButton(sender: UIButton?) {
    // generate inputDate here
    delegate.share(date: inputDate)
}

This should make the trick.
Comment: No problem, if you want further explanations I can provide some to you :)
Comment: I just tried your code, but couldn't get it to work. I didn't understand how to get `customAlert.delegtae = self` to compile. What did you mean to do here? By customAlert did you mean the CustomAlertViewController? Where do I have to type the code?
Comment: Never mind. I have figured it out and made the necessary edits. Thanks for your help!


About solving a differential equation

Question: I have this differential equation :
$4xf'(x) = 2f''(0)x^2+f(2x)$
Do you have any idea to solve it ?
Thanks in advance
Comment: What do you know about $f$? If you know $f$ can be expressed as a power series, that would be a good place to start.
Answer: One family of solutions, by inspection (or if you prefer trying a likely polynomial given the homogeneous structure), is given by $f(x)=Ax^2+Bx^4$.

One could also consider a locally analytic solution $f= \sum_{n=0}^{\infty} c_nx^n$. Then one finds
$$\sum ( 4n - 2^n)c_n x^n = 4 c_2 x^2$$
Now comparing coefficients we have a general analytic-at-the-origin solution as given above, since $4n-2^n\neq 0$ unless $n=4$ and at $n=2$ we also have agreement.
Comment: Thanks Sharkos for your answer. I'm searching if there are other forms of solutions. More precisely, I wonder if there is a general form for all solutions and how can we find it.
Comment: It's generally hard to solve functional equations like this where the function appears with multiple arguments in complete generality, and I have no immediate ideas about showing that all solutions are analytic vs finding non-analytic ones. Good luck!

About solving a differential equation


Generate MVN data that has a specific mean and variance matrix

Question: As an example, say I want to create a matrix $Y$ with 2 covariates and 10 observations each ( a 10 x 2 matrix) with a specific variance matrix and mean vector. The goal is to simulate regression data.
I want to generate $Y\sim MVN(\mu,\Sigma)$.  As an example:
$\Sigma =\begin{bmatrix}1 & .1 \\ .1 & 1\end{bmatrix} , $ $\mu=\begin{bmatrix}10 & 4\end{bmatrix}$
I start by generating $X\sim MVN(\vec{0},\mathbb{I})$ and my mean and variance matrix:
x <- matrix( rnorm(20), 10, 2)
mu <- matrix(c(10,4), nrow = 2)
sigma <- matrix( c(1,.1,.1, 1), nrow = 2, ncol = 2)

If I understand correctly what I need to do is let $Y = \mu +BX$ where $B=U\Lambda^{\frac{1}{2}}$ such that $U$ is the matrix of eigenvectors and $\Lambda$ is the diagonal matrix of eigen values of $\Sigma$.  So I go to compute that:
eigen <- eigen(sigma)
u <- eigen$vectors
sqrtlambda <- sqrt(diag(eigen$values))
B = u %*% sqrtlambda

But this isn't quite what I want at all, as this has all of my dimensions wrong to get what I am looking for.
Final code missing:
mu <- matrix(rep(1,10),nrow = 10) %*% mu
Y = x %*% t(B) + mu

Comment: It was just a number I came up with off the top of my head, I was thinking something along the lines of two RV X's, each with 10 replicates.
Comment: My apologies. I misread your code. The problem is that when you write $BX$ in algebra $X$ is a column vector of length 2. When you created a matrix you made it with column dimension 10. You either need to transpose your `x` or you need to redo your algebra to work with row-vectors and then compute $XB^\prime$ instead.
Comment: Ah thank you!  The continual mix of block notation had me confused.  I promise this is all on the premise of trying to learn the algebra!
Answer: A relevant piece of code is:
n <- 10
p <- 2
mu <- c(10, 4)
Sigma <- matrix(c(1, .1, .1, 1), nrow = 2, ncol = 2)

ed <- eigen(Sigma, symmetric = TRUE)
ev <- ed$values
evec <- ed$vectors
Y <- drop(mu) + tcrossprod(evec * rep(sqrt(pmax(ev, 0)), each = p),
                           matrix(rnorm(n * p), n))
t(Y)


Left Outer Join and Null Value conversion

Question: I split my input data, with two selects with different where clauses, I then want to join them back together after some aggregation, with a left outer join.
This works fine, and the joined data from the left table have null values as expected. This would be okay if I could do a IsNull(lefttable.column,0), but IsNull is not supported as far as I can see, is there any alternative way to structure my statement?
Answer: You can use "IS NULL" operator (same as in TSQL)
If you want to project it as a column value you can use this expression
CASE WHEN lefttable.column IS NULL THEN 1 ELSE 0 END AS isNull


Prove that the unit ball in $X$ is not compact

Question:
Let $X$ bet the set of all sequences $\{a_n\}_{n=1}^\infty$ in
  $\mathbb R$ with $\lim_{n \to \infty} a_n = 0$. For any $\{a_n\},
 \{b_n\} \subset X$, we define a metric
$$d(\{a_n\}, \{b_n\}) = \sup\{|a_n - b_n|, n = 1,2,\dots \}$$
Prove that the unit ball $\{\{a_n\}\in X: d(\{a_n\}, 0) = \sup_{n \in
 \mathbb N} |a_n| \le 1\}$ in $X$ is not compact

I think this unit ball is both bounded and closed in metric space, so it is compact. But the question asks me to prove that it is not compact. Please help.
Comment: In general, in metric spaces, closed and bounded subsets need not be compact. That is something remarkable about $\mathbb{R}^n$ (with suitable metrics, e.g. the Euclidean metric). In particular, that characterisation does not hold in $X$.
Comment: @DanielFischer that begs the question, why is $\mathbb R^n$ so special? What properties should a metric space have to ensure that the Heine Borel theorem holds?
Comment: The correct generalization to other metric spaces is "complete and totally bounded". Plain old boundedness isn't useful, because every metric space is bounded in a metric that is equivalent to a given metric. The metric essentially provides *local* information, not really global.
Comment: In a metric space, the closed unit ball is compact if and only if the space is finite dimensional. One direction may be proved by the Riesz Lemma and the other one follows by Heine-Borel.
Comment: What book is this?
Answer: One of the more intuitive definitions/characterizations of compactness in a metric space $(X,d)$ is the following:
A set $K \subseteq X$ is compact if and only if every sequence $\{a_k\} \subseteq K$ has a convergent subsequence.
So in order to show that the unit ball in the space of all sequences is not compact, you have to find a sequence (of sequences) in the unit ball that does not contain a convergent subsequence.
Answer: If $K$ is a compact set in a Hausdorff space, the only closed discrete subsets of $K$ are the finite sets.
The infinitely many sequences $s_n$ where
$$
s_n(n)=1,\qquad \text{$s_n(m)=0$ for all $m\neq n$}
$$
form a closed, discrete, but infinite subset of the unit ball in the space of all convergent sequences, implying the latter is not compact.
Comment: I think you mean closed discrete subsets.
Comment: @MeesdeVries: Absolutely. Edited, thank you.
Answer: For $S\subseteq \mathbb N$ let
$$ a^{(S)}_n=\begin{cases}1&\text{if $n\in S$}\\-1&\text{if $n\notin S$}\end{cases}$$
Then for any sequence $a\in X$ we have $d(a,a^{(S)})<2$ for $S=\{\,n\in \mathbb N\mid a_n>0\,\}$. Hence
$$\tag1X=\bigcup_{S\subseteq \mathbb N} B(a^{(S)},2).$$
Consider a finite subcover $$\tag2B(a^{(S_1)},2)\cup \ldots \cup B(a^{(S_m)},2)$$
and let $T=\{\,n\in\mathbb N\mid 1\le n\le m, n\notin S_n\,\}$. Then $d(a^{(T)},a^{(S_n)})=2$ for $1\le n\le m$, so that $a^{(T)}$ is not covered by $(2)$.
Remark: Apparently $(1)$ doesn't even allow a countable subcover.
Answer: Consider 0= (0,0,0,……………) € l2
Consider the closed ball, B [0,1].
Clearly B [0,1] is a closed and bounded subset of l2 . (Any closed ball in a metric space is a closed set and diam B[0,1]
Comment: It is not true that a closed and bounded subset of a metric space is compact; this property is one of the things that makes $\Bbb R^n$ special. The above is a standard counterexample. The general version is that complete and totally bounded subsets of a metric space are compact.


Share application ios?

Question: I do not know exactly is called in iOS terms.
Well I have a share button in my app. On the click of the button I want to open a list of installed apps through which I can share my app store link.
For eg: Through msg, email, whatsapp, facebook etc.
The app store link will be string with some message attached to it.
For eg: Download the latest : some URL or app store URL
Comment: `UIDocumentInteractionController`? Or maybe `UIActivityViewController`?
Comment: I just need to send a string to other apps.
Comment: Thnx @maddy exactly what i needed to search
Answer: This link solves my problem.
Add the following code on your button press:
<code>NSString *textToShare = @"Guys, Check this website";
NSURL *myWebsite = [NSURL URLWithString:@"http://www.9gag.com/"]; //any URL

NSArray *objectsToShare = @[textToShare, myWebsite];

UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];

NSArray *excludeActivities = @[UIActivityTypeAirDrop,
                               UIActivityTypePrint,
                               UIActivityTypeAssignToContact,
                               UIActivityTypeSaveToCameraRoll,
                               UIActivityTypeAddToReadingList,
                               UIActivityTypePostToFlickr,
                               UIActivityTypePostToVimeo];

activityVC.excludedActivityTypes = excludeActivities;

[self presentViewController:activityVC animated:YES completion:nil];
</code>

Share application ios?


Check my work: line integral of $\langle e^z,e^{x-y},e^y\rangle$ over a triangular path

Question:
Calculate the line integral of $F=\langle e^z,e^{x-y},e^y\rangle$ over the closed path $C$ connecting the points $ABCA$, where $A = (2,0,0), B = (0,4,0)$ and $C = (0,0,6)$.

To do this, I parameterized each line segment, then calculated $F(r(t))$ and $r'(t)$ for each segment. I then took the integral for each, and summed up the total. I ended up with a complicated answer of:
$$\frac{e^{10}+2e^6-3}{3e^4}+\frac{3e^4}{2}-\frac{65}{6}$$
I'm wondering if I did something wrong. The usual trend with these questions is that it turns out to work nicely. Does anyone get a different answer for this than I did?
Comment: the third component of vector $F$ is a complex?
Comment: Sorry, but your complicated answer _is_ correct.  Generally, only the low-numbered line integral problems in a textbook section have "nice" (i.e., integral or rational number) values.  One very quickly graduates to messier evaluations (particularly when transcendental functions or less simple paths are involved)...
Comment: @juliogodoy Whoops, that was supposed to be a y. Fixed!
Answer: for the segment $AB$, we have:
$$r(t)=A+(B-A)t=(2,0,0)+(-2,4,0)t=(2-2t,4t,0)$$
$$r'(t)=B-A=(-2,4,0)$$
then the integral of line in this segment is:
$$\int_0^1(e^0,e^{2-6t},e^{4t})\cdot(-2,4,0)dt=\int_0^1-2+4e^{2-6t}dt=-2+\frac{2}{3}(e^2-e^{-4})$$
now for the $BC$ segment, we have:
$$r(t)=B+(C-B)t=(0,4,0)+(0,-4,6)t=(0,4-4t,6t)$$
$$r'(t)=(0,-4,6)$$
then
$$\int_0^1(e^{6t},e^{4t-4},e^{4-4t})\cdot(0,-4,6)dt=\int_0^1-4e^{4t-4}+6e^{4-4t}dt=$$
$$=\left[-e^{4t-4}-\frac{3}{2}e^{4-4t}\right|_0^1=\left[e^{4t-4}+\frac{3}{2}e^{4-4t}\right|_1^0=e^{-4}+\frac{3}{2}e^4-\frac{5}{2}$$
For $CA$, we have:
$$r(t)=C+(A-C)t=(0,0,6)+(2,0,-6)t=(2,0,6-6t)$$
$$r'(t)=(2,0,-6)$$
then
$$\int_0^1(e^{6-6t},e^2,e^0)\cdot(2,0,-6)dt=\int_0^1 2e^{6-6t}-6dt=-6+\frac{1}{3}\left[ e^{6-6t}\right|_1^0=$$
$$=-6+\frac{1}{3}(e^6-1)=\frac{e^6}{3}+\frac{-19}{3}$$
the final result is:
$$=-2+\frac{2}{3}(e^2-e^{-4})+e^{-4}+\frac{3}{2}e^4-\frac{5}{2}+\frac{e^6}{3}+\frac{-19}{3}$$
God bless you.
Comment: I agree up to your last integral evaluation:  $ \ -6 \ - \ \frac{1}{3} \ = \ -\frac{19}{3} \ $ This will then make the sum of your constant terms equal to $ \ - \frac{65}{6} \ $ , which _is_ what **dubbler26** had found.
Comment: Thank you guys for the help! I appreciate it.
Comment: @RecklessReckoner thanks a lot, i fix the problem
Comment: @dubbler26 you're welcome
Comment: Almost there: you should have either $ \ \frac{e^6}{3} \ - \ \frac{ 19}{3} \ $ or  $ \ \frac{e^6}{3} \ + \ \frac{-19}{3} \ $ .
Comment: @RecklessReckoner thanks again


How can I add the android support library to my netbeans project

Question: specifically I just want to import ActionBarActivity to my net beans project... you would think that this would be a simple enough task, however that does not seem to be the case. I would be so grateful if there was a fairly simple way to do this... And please bear in mind I am on lesson one of the first android app tutorial on the android developers website so probably wont understand if you give me a hugely complex and technical answer.
Comment: I believe the Jar file is in your sdk folder, should you have installed the support libraries using the sdk manager
Answer: Copy the required file (eg. android-support-v13.jar) from the SDK directory into the libs folder in your project. Eg. from android-sdk/extras/android/support/v13.
First of all make sure to install the support lib with SDK manager.
Comment: This answer is wrong. This works for library that doesn't have resources. For appcompat v7 this doesn't work (and I still don't have any solution to import a library with resources)
Answer: Open project properties, select "JAR Libraries", choose "Custom location", browse to desired directory and press open. You'll have your jar in "Referenced JRA libraries" below. Now just press OK.
PS.
It's do not download libraries manually, instead use SDK manager.
Open "Tools"->"Android SDK manager" and install desired library.


Why do we need Tokenzier if we have Vectorizer

Question: In the ML learning textbook I am working through, it says, that for NLP we construct a feature vector from the Text via the Bag of Words model.
For that, we are using
from sklearn.feature_extraction.text import CountVectorizer
count = CountVectorizer(ngram_range=(1,1))
docs = np.array(["The sun is shining",
                 "The weather is sweet",
                 "The sun is shining and the weather is sweet"])
bag = count.fit_transform(docs)

From this we can get an array with the number of words for each Sentence and a dictionary to look up the indices of each word in this array
Now later, the book says, we also need a Tokenizer like this
def tokenizer(text):
     return text.split()

(or optional with a stemmer)
which simply takes a text, and splits it into an array, where each element contains a word.
I don't really get why we need to do this though, since if we apply the tokenizer first, we just have a long array of words, and not as in the example of the CountVectorizer, an array of sentences
Answer: A CountVectorizer first tokenizes the text, then count tokens. It therefore needs to have a Tokenizer, as you can see for example in sklearn.feature_extraction.text.CountVectorizer, which takes a tokenizer as argument :
class sklearn.feature_extraction.text.CountVectorizer(input=u'content',
encoding=u'utf-8', decode_error=u'strict', strip_accents=None,
lowercase=True, preprocessor=None, tokenizer=None, stop_words=None,
token_pattern=u'(?u)\b\w\w+\b', ngram_range=(1, 1), analyzer=u'word',
max_df=1.0, min_df=1, max_features=None, vocabulary=None, binary=False,
dtype=<type 'numpy.int64'>)


Verify the differentiablity of trace and determinant function

Question: $f: \text{GL}_n(\mathbb R) \times \mathbb M_n(\mathbb R) \to R, f(A,B) = \text{tr}(A^{-1}B)$
$g: \mathbb M_n(\mathbb R) \to \mathbb M_n(\mathbb R), g(A) = \det(A)$
Are $f,g$ differentiable? (Use the definition of differentiation)
We need to find a linear continuous application $L$ such that:
$$f(A+H, B+H) = f(A,B) + L_{(A,B)}(H,H) + ||(H,H)|| \epsilon(H,H),$$ where $\epsilon(H,H) \to 0$, as $(H,H) \to (0,0)$
What is the relation between: $\text{tr}((A+H)^{-1}(B+H))$ and $\text{tr}(A^{-1}B)$?
Same question for $\det(A+H)$ and $\det(A)$.
Answer: Hint
Use the series expansion for $(I+X)^{-1} = I - X + o(X^2)$
Answer: Hint: you can use the fact that determinants are just linear combinations in $\mathbb{R}^{n^2}$. Show for $\mathbb{R}$, then apply induction.
Similarly, trace is just a sum of projections, i.e., a composition of continuous functions.


ngx-bootstrap , Component Modal, The selector "modal-content" did not match any elements

Question: I have Angular 7 "ngx-bootstrap": "^3.1.4" and "bootstrap": "^4.3.1"
Are these compatible at all?
I trying to open component in modal as this question: ngx-bootstrap How to open a modal from another component?
However I'm getting this error:

ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[DialogBoxComponent -> BsModalRef]:
    StaticInjectorError(Platform: core)[DialogBoxComponent -> BsModalRef]:
      NullInjectorError: No provider for BsModalRef!
  Error: StaticInjectorError(AppModule)[DialogBoxComponent -> BsModalRef]:

I have imported ngx in my module as:
        import { BrowserModule } from "@angular/platform-browser";
    import { NgModule } from "@angular/core";
    import { HttpClientModule } from "@angular/common/http";

    import { AppComponent } from "./app.component";
    import { AppHeaderComponent } from './app-header/app-header.component';
    import { AppFooterComponent } from './app-footer/app-footer.component';
    import { AppRoutingModule } from './app-routing.module';
    import { PoliciesComponent } from './policies/policies.component';
    import { AddComponent } from './add/add.component';
    import { ReactiveFormsModule } from '@angular/forms';
    import { ModalModule } from 'ngx-bootstrap';
    import { ModalContentComponent } from './modal-content/modal-content.component';

    @NgModule({
      declarations: [AppComponent, AppHeaderComponent, AppFooterComponent, PoliciesComponent, AddComponent, ModalContentComponent],
      imports: [
        ModalModule.forRoot(),
        HttpClientModule,
        BrowserModule,
        AppRoutingModule,
        ReactiveFormsModule

      ],
      providers: [],
      bootstrap: [AppComponent, ModalContentComponent]
    })
    export class AppModule { }

    import { Component } from '@angular/core';
    import { BsModalRef } from 'ngx-bootstrap/modal';

    @Component({
      selector: 'modal-content',
      templateUrl: './modal-content.component.html',
    })

    export class ModalContentComponent {
      title: string;
      closeBtnName: string;
      list: any[] = [];

      constructor(public bsModalRef: BsModalRef) { }

      ngOnInit() {
        this.list.push('PROFIT!!!');
      }
    }

import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core';
import { PoliciesService } from './policies.service';
import { Policy } from 'src/models/policy';
import { Gender } from 'src/models/gender';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
import { ModalContentComponent } from '../modal-content/modal-content.component';

@Component({
  selector: 'app-policies',
  templateUrl: './policies.component.html',
  styleUrls: ['./policies.component.scss']
})
export class PoliciesComponent implements OnInit {
  gender = Gender;
  policies: Policy[];
  bsModalRef: BsModalRef;

  constructor(private policiesService: PoliciesService, private modalService: BsModalService) { }

  ngOnInit() {
    this.policiesService
      .getAll()
      .subscribe(p => this.policies = p);
  }

  deleteClicked(id: number) {
    this.policiesService
      .delete(id)
      .subscribe(() => this.deleteFrom(this.policies, id));
  }

  private deleteFrom(arr: Policy[], id: number) {
    arr.splice(arr.findIndex((p: Policy) => p.policyNumber === id), 1);
  }

  openModalWithComponent() {
    const initialState = {
      list: [
        'Open a modal with component',
        'Pass your data',
        'Do something else',
        '...'
      ],
      title: 'Modal with component'
    };
    this.bsModalRef = this.modalService.show(ModalContentComponent, { initialState });
    this.bsModalRef.content.closeBtnName = 'Close';
  }
}

Comment: Can you show where `BsModalRef` is being used?
Comment: @JasonWhite I solved my first issue, I don't know what was the issue. Now I have another issue: The selector "modal-content" did not match any elements
    at DefaultDomRenderer2.push../node_modules/@angular/platform-browser/fesm5/platform-browser.js.DefaultDomRenderer2.selectRootElement
Answer: I had an error where I added ModalContentComponent.
It should be added as below to module:
providers: [],
  entryComponents: [ModalContentComponent],
  bootstrap: [AppComponent]
})


Fail to update apk when updating from titanium app to Android SDK

Question: I have recently built an already existing app from ground up using the Android SDK. The previous version was a titanium mobile app, I have used the same keystore as the titanium app. The difference is that I have removed all uses-featurewhich was unnecessary but automatically generated in titanium.
When I upload the apk I get an error from the developer console which I find quite cryptic and I can't update the apk. I'm guessing this has something to do with titanium building the app with the NDK which I have no experience of.
Error:

This configuration cannot be published for the following reason(s):
  It is forbidden that a device upgrading from API levels in range 8-19 to API levels in range 20+ should downgrade from version 10 to version 3, which would occur when
  Screen layouts containing any of [small, normal, large, xlarge] and
  Native platforms containing any of [armeabi, armeabi-v7a, x86] and
  Features containing all of [android.hardware.LOCATION, android.hardware.location.GPS, android.hardware.location.NETWORK, android.hardware.TOUCHSCREEN, android.hardware.WIFI].

Titanium manifest:
<?xml version="1.0" ?><manifest android:versionCode="3" android:versionName="1.3" package="xx.xxx.xxx" xmlns:android="http://schemas.android.com/apk/res/android">
<supports-screens android:anyDensity="false"/><uses-sdk android:minSdkVersion="8"/>

<application android:debuggable="false" android:icon="@drawable/appicon" android:label="xxxxxx" android:name="xxxxxx">

    <activity android:configChanges="keyboardHidden|orientation" android:label="XXXXXX" android:name=".XXXXX" android:theme="@style/Theme.Titanium">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>

    <activity android:configChanges="keyboardHidden|orientation" android:name="org.appcelerator.titanium.TiActivity"/>
    <activity android:configChanges="keyboardHidden|orientation" android:name="org.appcelerator.titanium.TiTranslucentActivity" android:theme="@android:style/Theme.Translucent"/>
    <activity android:configChanges="keyboardHidden|orientation" android:name="org.appcelerator.titanium.TiModalActivity" android:theme="@android:style/Theme.Translucent"/>
    <activity android:configChanges="keyboardHidden|orientation" android:name="ti.modules.titanium.ui.TiTabActivity"/>
    <activity android:name="ti.modules.titanium.ui.android.TiPreferencesActivity"/>

    <service android:exported="false" android:name="org.appcelerator.titanium.analytics.TiAnalyticsService"/>

</application>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

New SDK Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="xxx.xxx.xxx" >
<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="19" />
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/Theme.Custom" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".DetailsActivity"
        android:label="@string/details"
        android:parentActivityName=".MainActivity"/>
</application>

EDIT: the new app is built using Android Studio, and the rest of the declarations are in gradle where Versioncode is : 10 and minSDK is 8
Answer: You have no android:versionCode in your new Manifest.xml.
Comment: Read bottom Edit, versionCode is injected by gradle
Comment: Have you checked that Android Studio actually injects it correctly. You can check by doing: aapt dump badging  dinapp.apk|grep versionCode
Comment: versionCode 10 , I'm guessing that it wants to downgrade because the NDK specifically says which platforms are optimized for which version.


Reading array values in PHP and assigning to individual string

Question: I have a PHP array which gives this result:
Array
(
  [count] => 1
  [0] => Array
  (
    [sn] => Array
    (
      [count] => 1
      [0] => Smith
    )
    [0] => sn
    [givenname] => Array
    (
      [count] => 1
      [0] => John
    )
    [1] => givenname
    [mail] => Array
    (
      [count] => 1
      [0] => firstname.lastname@example.com
    )
    [2] => mail
    [count] => 3
    [dn] => CN=John Smith,OU=IT Admin,DC=mylocaldomain,DC=local
  )
)

How do I go about extracting the Email address from this array result into a single string?
I need to able to reference the Email address, but can't find a way to pull that information out.
The meat of the LDAP code is along the lines of:
$dn = "OU=IT Admin,DC=mylocaldomain,DC=local";
$ds = $ldapconnectionstring;
$person = "johnsmith";
$filter="(|(sn=$person*)(samaccountname=$person*))";
$justthese = array("ou", "sn", "givenname", "mail");
$sr=ldap_search($ds, $dn, $filter, $justthese);
$info = ldap_get_entries($ds, $sr);

echo '
'; print_r($info); echo '
';

I've googled this to death, read the PHP documentation about arrays, and read various similar posts here, but nothing seems to work for me.
I need to end up with:
 echo $email;

and get back:
 firstname.lastname@example.com

Comment: `$email = $info[0]['mail'][0];`
Comment: The dump tells you the EXACT array construct/path you need to follow to get to the email address...
Answer: Basic DUMP analysis 101:
Omitting the irrelevant parts of the dump:
 Array                                            <-- $array
[0] => Array                                      <-- [0]
        [mail] => Array                           <-- ['mail']
                [0] => firstname.lastname@example.com    <-- [0]

giving you
$array[0]['mail'][0];

Comment: Many thanks, much appreciated.  Sorry stack overflow doesn't allow me to mark both answers as correct!  :)
Answer: All you need to do is read what print_r() shows you.
(Array) [0](Array) > [mail](Array) > [0](string) => email@example.com

$info = ldap_get_entries($ds, $sr);
$email = $info[0]['mail'][0];
echo $email;

See the section Accessing array elements with square bracket syntax on these docs http://docs.php.net/manual/en/language.types.array.php


I have added Git plugin in Jenkins after that all my jobs are throwing exception stating failed to load

Question: Before installing Git plugin in my Jenkins all my jobs were working properly. After installing the Git plugin, my Jenkin get restart and after that my jobs are not displaying in dashboard. When I check in system log, I found issue stating "Failed to load struct, Failed to load x job, Failed to load Y job..... And so on".

How can I resolve this?
Comment: Things not a helpdesk. [How to ask good question](https://stackoverflow.com/help/how-to-ask). Did you at least look in the logs for errors and what did it say?
Comment: Agreed with Ian, we will need more info like logs to assist on this forum.
Comment: Try uninstalling the Git plugin, to see if that at least fixes things.
Comment: Please provide some logs to look into the issue.
Answer: You need to upgrade Jenkins to the latest version. This will solve the problem.


Finding the Norm of an element in a field extension

Question: If I have a field extension of $\mathbb{Q}$ given by $\mathbb{Q}(\alpha)$ and the only thing I know about the primitive element $\alpha$ is it's minimal polynomial $p(x) = a_0 + a_1x + ... + x^n$ such that $p(\alpha) = 0$ how can I find the norm of an element $\beta \in \mathbb{Q}(\alpha)$?
I've got partial notes that seem to claim that I can define a linear map $T_\beta$ such that when I take the determinant of the associated matrix I'll end up with the norm of $\beta$ but I can't find the rest of my notes and I was hoping someone knows how to construct the matrix for $T_\beta$
EDIT: $\beta$ is given as  $\beta = b_0 + b_1\alpha + ...$ with $\{\alpha^i\}$ forming a power basis for $\mathbb{Q}(\alpha)$
Comment: Related (but slightly more specific): [This question](http://math.stackexchange.com/questions/504000)
Comment: @ccorn ; it's related but they've chosen a root of p($\alpha$) whereas I'm looking for a way to find the norm without making that choice.
Comment: **Worked example** in [this answer](https://math.stackexchange.com/a/504008/242).
Answer: Let $\beta = q(\alpha)$ where $q(X) = \sum_{i=0}^{n-1} b_i X^i$ and all $b_i\in\mathbb{Q}$.
Represent $p(X) = \prod_{i=1}^n(X-\alpha_i)$ where the $\alpha_i$ are $\alpha$ and its conjugates. Then $\beta_i=q(\alpha_i)$ are $\beta$ and its conjugates.
By definition of the norm,
$$N(\beta) = \prod_{i=1}^n \beta_i = \prod_{i=1}^n q(\alpha_i) = \operatorname{Res}(p,q)$$
where $\operatorname{Res}$ is the polynomial resultant. It can be expressed solely in terms of the rational coefficients $a_0,\ldots,a_{n-1}$ of $p$ and $b_0,\ldots,b_{n-1}$ of $q$. It has indeed a representation as a determinant of a Sylvester matrix. It can be computed recursively in a way similar to the euclidean GCD algorithm. Writing out the resultant as a polynomial expression for general $q$ and $n\geq 3$ yields unwieldy expressions however.
Comment: Pari/GP's `polresultant(1+x+x^2+x^3+x^4,1+23*x)` yields `268181`.
Comment: Wolfram Alpha [agrees](http://www.wolframalpha.com/input/?i=Resultant%5B1%2Bx%2Bx%5E2%2Bx%5E3%2Bx%5E4%2C1%2B23*x%2Cx%5D).
Comment: I'm trying to understand your answer so I've tried a concrete example. Let $\alpha$ solve $1 + x + x^2 + x^3 + x^4 == 0$ and then let $\beta \in \mathbb{Q}(\alpha)$ be given by $\beta = 1+23\alpha$. So from what I understand I have $q(X) = 1+23X$ and $p(X) = 1+X+X^2+X^3+X^4$ and I should look at  Res($p,q$) which I get to be 1 (using mathematica to calculate the resultant of the polynomials defined above) whereas mathematica says "AlgebraicNumberNorm[1 + 23 $\alpha$]] = 268181". I think I've missed something in your answer.
Comment: I've figured out what I was doing wrong in mathematica. I tried to define the Polynomials and then call "Resultant[Q[x],P[x],x]" and for some reason it doesn't like that and returns 1. I've got it working now.
Comment: Thanks for your help by the way. Is there a good reference for information about the resultant? I've been reading wikipedia/mathworld but would love to see something more in depth.
Comment: Lang's Algebra: it has a chapter on polynomials. Succinct and very succulent. =)
Comment: @AvatarOfChronos Try chapter 1.3 of _Polynomials_ by Victor V. Prasolov. I'd actually refer you the whole book though!
Comment: many thanks for the references.
Answer: Think of the linear map from $\mathbb Q(\alpha)$ into itself given by
   $$T_\beta(\gamma) = \beta \gamma $$
the norm of $\beta$ is just the determinant of the matrix associated to this linear map, for instance if you write
   $$ \beta \alpha^j = a_{0j} + a_{1j}\alpha + \dots + a_{(n-1)j} \alpha^{n-1}\quad \quad j = 0,1,\dots,n-1 $$
then the matrix associated to $T_\beta$ relative to the base $\{1,\alpha,\dots,\alpha^{n-1}\}$,  is
$$ M_\beta = \begin{pmatrix} a_{00} &\dots&a_{0(n-1)}\\\dots\\a_{(n-1)0} &\dots&a_{(n-1)(n-1)}\end{pmatrix}$$
you can see that the characteristic polynomial of this matrix is
$$ \det (M_\beta - XI_n) = (-1)^n\prod_{i=1}^n (X-\beta^{(i})$$
where $\beta^{(i}$ is the $i$-th conjugate of $\beta$. Putting $X=0$, we get that norm of $\beta$ in the extension $\mathbb Q(\alpha)/\mathbb Q$ is
$$ N_{\mathbb Q(\alpha)/\mathbb Q}\beta = \prod_{i=1}^n \beta^{(i} = \det M_\beta $$


Find the limit in $\mathbb R^2$

Question: Let $x_1 = y_1 = 0$ and
$$
(x_{n+1}, y_{n+1}) = \bigg(\bigg(1-\frac{2}{n}\bigg)x_n -\frac{y_n}{n} + \frac{4}{n}, \bigg(1-\frac{1}{n}\bigg)y_n - \frac{x_n}{n} + \frac{3}{n}\bigg).
$$
Find the $\lim_{n \to \infty} (x_n, y_n)$.
Unfortunately, I have no idea how to solve this problem. Expressions like
$$
x_{n+1} - x_n = -3\frac{x_n}{n} - \frac{1}{n}\sum_{k = 1}^{n-1} \frac{x_k}{k} + \frac{H_{n-1}}{n} + \frac{3}{n},
$$
that can be derived from the definition of a sequence do not seem to be helpful. $H_n$ is $n$-th partial sum of Harmonic series.
Would be happy to see some suggestions.
Comment: Hi when you say that $x_0=y_0=0$ it means that is the limit of the sequences $x_n,y_n$?
Comment: Sorry, of course $x_1 = 0, y_1 = 0$. It has nothing to do with the limit
Comment: Well no problem, also the first notation was fine. The point is that we know where the sequence start but not yet where is going. I was just demanding a clarification in order to fully understand the question, let me think!
Answer: It's easy to prove that:
$$
\pmatrix{x_{n+1}-1 \\ y_{n+1}-2} = \pmatrix{x_{n}-1 \\ y_{n}-2} -\frac{1}{n}\cdot \pmatrix{2 & 1\\ 1&1}\cdot\pmatrix{x_{n}-1 \\ y_{n}-2} = \pmatrix{1-\frac{2}{n} & -\frac{1}{n}\\ -\frac{1}{n}&1-\frac{1}{n}}\cdot\pmatrix{x_{n}-1 \\ y_{n}-2}
$$
For the sake of simplicity, we denote
$$\pmatrix{z_{n}\\ t_{n}} :=\pmatrix{x_{n}-1 \\ y_{n}-2}$$
Then
$$
\pmatrix{z_{n+1} \\ t_{n+1}} = \underbrace{\pmatrix{1-\frac{2}{n} & -\frac{1}{n}\\ -\frac{1}{n}&1-\frac{1}{n}}}_{=:\mathbf{A}_n}\cdot\pmatrix{z_{n}\\ t_{n}} \tag{1}
$$
The matrix $\mathbf{A}_n\in \mathbb{R}^{2\times 2}$ is diagonalizable:
$\mathbf{A}_n = \mathbf{P}^{-1} \cdot \mathbf{D}_n \cdot \mathbf{P}$ with
$$\mathbf{D}_n := \pmatrix{1-\frac{3+\sqrt{5}}{2n} & 0\\ 0&1-\frac{3-\sqrt{5}}{2n}}
\hspace{0.5cm}\text{and}\hspace{0.5cm}\mathbf{P} := \pmatrix{\frac{1+\sqrt{5}}{2} & 1\\ \frac{1-\sqrt{5}}{2}&1}  \tag{2}$$
Interestingly, the matrix $\mathbf{P}$ does not depend on $n$.
We can then deduce the closed form expression for $z_n$ and $t_n$ from $(1)$ and $(2)$:
$$\begin{align}
\pmatrix{z_{n} \\ t_{n}} &= \left(\prod_{i=1}^n \mathbf{A}_i \right) \cdot \pmatrix{z_{0} \\ t_{0}} \\
&= \left(\prod_{i=1}^n  \mathbf{P}^{-1} \cdot \mathbf{D}_i \cdot \mathbf{P} \right) \cdot \pmatrix{z_{0} \\ t_{0}} \\
&= \mathbf{P}^{-1}\pmatrix{\prod_{i=1}^n\left(1-\frac{3+\sqrt{5}}{2i}\right) & 0\\ 0&\prod_{i=1}^n\left(1-\frac{3-\sqrt{5}}{2i}\right)}\mathbf{P}\cdot\pmatrix{z_{0} \\ t_{0}}
\end{align}$$
And the closed form expression for $\pmatrix{x_n \\ y_n}$:
$$\color{red}{\pmatrix{x_{n} \\ y_{n}} = - \mathbf{P}^{-1}\pmatrix{\prod_{i=1}^n\left(1-\frac{3+\sqrt{5}}{2i}\right) & 0\\ 0&\prod_{i=1}^n\left(1-\frac{3-\sqrt{5}}{2i}\right)}\mathbf{P}\cdot\pmatrix{1 \\ 2} + \pmatrix{1 \\ 2} }  $$

For the limit of $x_n$ and $y_n$, just notice that the terms $\left(1-\frac{3+\sqrt{5}}{2i}\right)$ and $\left(1-\frac{3-\sqrt{5}}{2i}\right)$ are in $(0,1)$ and decreasing for all $i \ge 2$.
By consequence, the two products $\prod_{i=1}^n\left(1-\frac{3+\sqrt{5}}{2i}\right)$ and $\prod_{i=1}^n\left(1-\frac{3+\sqrt{5}}{2i}\right)$ are decreasing to $0$ when $n$ tends to $+\infty$.
From that, we can conclude
$$\color{red}{\pmatrix{x_{n} \\ y_{n}} \xrightarrow{n \to +\infty }   \pmatrix{1 \\ 2} }  $$

Find the limit in $\mathbb R^2$


Media with WYSIWYG not converting media tags to markup

Question: I just installed the Media module v 7.x-2.0-alpha3 along with WYSIWYG, CKEditor, and Image Resize Filter. (The site has many other modules active.)  The site also uses Display Suite, and its view modes are used for different types of images. My use case is for images embedded in the Filtered HTML text format, not as separate entities in a content type.
When an image is first embedded, its source code is like this:
[[{"fid":"161","view_mode":"default","fields":{"format":"default","field_file_image_alt_text[und][0][value]":"f asdfasdf"},"type":"media","attributes":{"alt":"alt text","class":"media-element file-default"}}]]

From my reading, I found that checking "Convert Media tags to markup" at mysite/admin/config/content/formats/filtered_html is required. I have verified that is active.
Instructions at https://www.drupal.org/node/1599070 include "Image resize filter" is AFTER "Convert Media tags to markup" and my filters are in that order.
If I double-click an embedded image in the CKEditor and make it a captioned image, then the Media tags are converted to markup. If a caption isn't added, the Media tags do not get converted.
Based on my configuration, can anyone suggest why the conversion is not occurring?
Comment: I have the same problem. Do you have any solution for that problem now?
Comment: I too have the same issue and its driving me mad.
Comment: schulle877, I have not found a solution for this yet.
Comment: The image resize filter should be after media tags for markup. Check that the filter is allowing images tags also.
Comment: Just in case that you have done anything and it still does not working: make sure that all double quotes (`"`) are properly opened and closed in the node's body field, otherwise you wiil get unrendered items (`[[{"type":"media","view_mode":"media_original","fid":"995"}}]]`). Perhaps this a media's module bug!
Answer: I was having this same problem and have solved it. My problem was not rendering the text in the correct format in the template. So if you are using a custom theme, .tpl or whatever you need to make sure you render it correctly. I had it like this:
<?php print $node->field_main_body['und'][0]['value'] ;?>

Changing this to proper rendering using field_view_field fixed it for me:
<?php print render(field_view_field('node', $node, 'field_main_body', array('label'=>'hidden'))) ;?>

Hope that's helpful
Comment: In my case, this was the cause. I was printing the value instead of the rendered markup.
Comment: I'd upvote a thousand times more if I could. Wow what a pain it was to figure this out. I even asked in another thread like half a year ago and got no response. You'd think with all the minds behind drupal you wouldn't need some special way to render to handle media tags... in this day and age. Thanks a ton
Answer: Might be worth checking that your "Limit html tags" isnt limiting your img tags
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient [reputation](http://drupal.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](http://drupal.stackexchange.com/help/privileges/comment).
Comment: I need to have 50 rep points to comment on a post? How do you suggest i leave comments/ request more info, without answering, if i cant comment ?
Comment: The list of allowed HTML tags does allow img tags.
Answer: If you updated Media, WYSIWYG and CTools module with latest stable version, then run update.php The embeded image source code will automatically convert to image.


definition of the directed colimit of a functor

Question: Let $(\Lambda,\le )$ be a directed set, which we can understand as a small category: The set of all objects is $\Lambda$ and for $\lambda,\lambda '\in \Lambda$ there exists an unique morphism $i_{\lambda,\lambda '}:\lambda\to \lambda '$ iff $\lambda\le \lambda '$. Otherwise we don't have any morphisms.
Let $R-$MOD be the category of $R$-modules, $F:(\Lambda,\le )\to R$-MOD a functor. The directed colimit of $F$ is
$$\operatorname{colim}\limits_{\lambda} F:=\coprod\limits_{\lambda\in \Lambda}F(\lambda)/\sim ,$$where $v\sim F( i_{\lambda,\lambda '})(v)$ for $v\in F(\lambda),\; \lambda\le \lambda '$.
My question: is $\sim$ really an equivalence relation? This realtion isn't symmetric, or am I wrong?
Best
Answer: EDIT : [I will assume that by $\coprod\limits_{\lambda\in \Lambda}F(\lambda)$ you mean $\bigoplus\limits_{\lambda\in \Lambda}F(\lambda)$ using the general notation for coproduct (and not the disjoint union, which would be wrong).] Actually for directed colimits it doesn't matter.
Then you have to quotient by the equivalence relation that is generated by $v\sim F( i_{\lambda,\lambda '})(v)$ (which you have to show is a congruence).
Comment: As for the "disjoint union" part, it's my mistake : for *directed* colimit it doesn't matter. It's just bad practive, because for general colimits you will take the direct sum.
Comment: ok, the professor in lecture states that this relation is already an equvalence relation, but this seems to be wrong, right? And we definited the colimit with the disjoint union. I don't know, why this should be wrong
Comment: Strictly speaking, I guess you could call it wrong. But generally people implicitly symmetrize their relations in the definitions, so I wouldn't consider it *wrong*, just maybe somewhat misleading.
Comment: thank you, your answer is very helpful!


Bug with switch in foreach

Question: Here is code I have problem with - simple foreach iterating array. Sometimes element from array can has key "mailto" - in such case it should do some task. But for some reason first element with "0" key enters "mailto" case too.
<?php
    foreach (
        array(
            " this shouldnt appear, it's without mailto as key - 1",
            " this shouldnt appear, it's without mailto as key - 2",
            "mailto" => " this should appear ",
            " this shouldnt appear, it's without mailto as key - 3",
        ) as $type => $text
    ) {
        echo "#$type#\n";
        switch ($type) {
            case "mailto":
                echo ">$type< $text\n";

                break;

            default:
                break;
        }

    }

Output:
#0#
>0<  this shouldnt appear, it's without mailto as key - 1
#1#
#mailto#
>mailto<  this should appear
#2#

Why first element appears?
Comment: You may need to escape `,` (comma) which is specified within every value, as this is conflicting with value seperator inside array. you can use forward slash for escaping
Comment: Even with letter-only text bug still occurs.
Comment: This is one of the cases where I think the PHP authors really should have created distinct array types, index-based and associative, like in Python and Ruby.
Answer: As the other answers pointed out: switch compares by value, it doesn't do type & value comparing. The fact that a string constant == 0 evaluates to true is just one of those PHP oddities/quirks, I guess. That said: You could either use "real", hard coded keys, or you could use a cast:
foreach($theArray as $type => $text)
{
    echo "#$type#\n";
    switch ((string) $type)
    {//cast key to string
        case "mailto":
            echo ">$type< $text\n";
            break;
        default:
            break;
    }
}

Job done.
That said, you really needn't concatenate strings you echo. In fact, it's better not to. I'd just echo the values as comma-separated constants + variables:
echo '#', $type, '#', PHP_EOL;// use X-platform constant
switch ((string) $type)
{
    case 'mailto':
        echo '>', $type, '< ', $text, PHP_EOL;
        break;
}

will be marginally faster
Comment: I found your solution the most convenient for my needs, thanks.
Answer: Your switch statement is doing a == comparison which means that php is typecasting the string mailto to a integer which equals 0.  So the case statement evaluates as true.
Since you are only using one value, change it to an if statement and use the strict comparison ===
Comment: Well I'm using only one value for sake of simplicity in this example, but in real script there are other types. Converting to if-statement is only solution?
Answer: The switch/case construct is implemented using the == equal operator.
Now if you try this:
>> "mailto" == 0
true
>> "mailto" == 1
false
>>

You can see how PHP makes it wrong.
"mailto" is cast into an integer value of 0 for the equality test.
Answer: Well it appears to be easily fixed by adding another case to your switch statement, like so:
switch ($type)
{
    case 0:
        break;
    case 'mailto':
        echo ">$type< $text\n";
        break;
    default:
        break;
}

I suspect the issue with 0 being compared to 'mailto' coming up as true has to do with PHP's loose type comparison. When you compare an integer with a  string in PHP with only two equals (==) it returns true.
Another fix to force the comparison to be done as a string and therefore avoid having to add this additional case is to cast the $type to a string, like so:
switch ((string) $type)
{
    case 'mailto':
        echo ">$type< $text\n";
        break;
    default:
        break;
}

Answer: The problem is that the non-type comparison of == in switch() causes 0=="mailto" to be true.
If you need to add other case statements and want to keep the original structure, you can force the first key to be a 1, and avoid the issue.
foreach (
    array(
        1=>" this shouldnt appear, it's without mailto as key - 1",
        " this shouldnt appear, it's without mailto as key - 2",
        "mailto" => " this should appear ",
        " this shouldnt appear, it's without mailto as key - 3",
    ) as $type => $text
) {

Otherwise, just switch to a simple if using strict comparison ===
foreach (
    array(
        " this shouldnt appear, it's without mailto as key - 1",
        " this shouldnt appear, it's without mailto as key - 2",
        "mailto" => " this should appear ",
        " this shouldnt appear, it's without mailto as key - 3",
    ) as $type => $text
) {
    echo "#$type#\n";
    if($type === 'mailto'){
            echo ">$type< $text\n";
    }
}

Bug with switch in foreach


Deserializar array de objetos C#

Question: Boa noite! Estou com o seguinte script em minha View:
$('form').submit(function(e){
        e.preventDefault();

        var resposta = new Array();
        var x = 0;
        var y = 0;
        $(".resposta").each(function () {
                var dados = new Array();
                dados[x] = $(this).children("input[name^='idQuestao']").serialize();
                dados[++x] = $(this).children("input[name^='idQuestionario']").serialize();
                dados[++x] = $(this).children("input[name^='idCampanha']").serialize();
                dados[++x] = $(this).children("input[name^='idFuncionario']").serialize();
                dados[++x] = $(this).find("input[name^='idOpcao']").serialize();

                if(dados[x] === "")
                {
                    dados[x] = $(this).find("select[name^='idOpcao']").serialize();
                }

                if(dados[x] === "")
                {
                    dados[x] = $(this).find("textarea[name^='descricao']").serialize();
                }

                resposta[y] = dados;
                x = 0;
                y++;
        });

        $.ajax({
        type: "POST",
        url: '/Questionario/Create/?questionario=' + JSON.stringify(resposta),
        success: function(result) {
        },
        error: function(result) {
        }
        });
    });

No meu Controller eu estou tentando receber da seguinte forma:
public ActionResult Create(string questionario)
        {
            try
            {
                var intermediateJson = JsonConvert.DeserializeObject<string>(questionario);
                var oPerson = JsonConvert.DeserializeObject<List<QuestionarioViewModel>>(intermediateJson);

                return View();
            }
            catch(Exception ex)
            {
                return View();
            }
        }

e estou recebendo o seguinte erro: "Unexpected character encountered while parsing value: [. Path '', line 1, position 1."
Essa é a string que o controller está recebendo:
"[[\"idQuestao=1\",\"idQuestionario=1\",\"idCampanha=2\",\"idFuncionario=1\",\"descricao=teste\"],[\"idQuestao=2\",\"idQuestionario=1\",\"idCampanha=2\",\"idFuncionario=1\",\"descricao=teste\"],[\"idQuestao=3\",\"idQuestionario=1\",\"idCampanha=2\",\"idFuncionario=1\",\"idOpcao=2\"],[\"idQuestao=4\",\"idQuestionario=1\",\"idCampanha=2\",\"idFuncionario=1\",\"idOpcao=6\"],[\"idQuestao=5\",\"idQuestionario=1\",\"idCampanha=2\",\"idFuncionario=1\",\"idOpcao=11\"],[\"idQuestao=8\",\"idQuestionario=1\",\"idCampanha=2\",\"idFuncionario=1\",\"descricao=teste\"]]"

Já tentei várias formas, o que estou fazendo errado?
Comment: Tente trocar os `[ & ]` por `{ & }`, pois no JSON, [ e ] não são caracteres válidos para chaves. Você pode usar o `X = X.Replace("[", "{").Replace("]", "}")` neste caso.
Comment: @T. Borges Se alguma resposta lhe foi útil, se puder marque-a como aceita `√`, assim quando outros usuários visualizarem sua questão verão que já tem uma resposta correta e aceita por você.
Answer: Você esta enviando um array com array o formato do seu JSON esta ficando [ [], [] ] considerando este formato o JsonConvert espera que você faça o DeserializeObject para uma lista de lista, exemplo, List<List<>>.
Portanto se você fizer como no exemplo abaixo ele vai parar de dar o erro.
var intermediateJson = JsonConvert.DeserializeObject<List<List<string>>>(questionario);

Mas pelo que entendi do objetivo do seu código você não precisa destes 2 array, então poderia mandar só o array dados e converter direto para List<QuestionarioViewModel>

Porem acredito que tenha algumas melhorias que podem ser feitas para simplificar.
Opção 1: Enviar o json como data no post e não por parâmetro na url
Para deixar a função mais segura seria melhor enviar os parâmetros no data do post, como no exemplo abaixo:

Opção 2: Serializar o Form e enviar inteiro
Se a sua View e tipada como List e os inputs são gerados pelo Razor, você pode gerá-los como lista e no final só serializar o form e passar no post, recebendo direto no seu objeto. Para isso você precisa que a propriedade Name dos inputs crie uma sequencia ficando name='[0].idQuestao' por exemplo.
Para que isso aconteça sua view deve criar os inputs como no exemplo abaixo:
@for (var i = 0; i < Model.Count; i++)
{

        @Html.HiddenFor(model => model.i].idQuestao)
        @Html.EditorFor(model => model.Itens[i].idOpcao)

}

E o seu script ficaria assim:

E o controller assim:
[HttpPost]
public ActionResult Create(List<QuestionarioViewModel> respostas)
{

}

Answer: Para facilitar a manutenção do código, recomendo que faça duas alterações, uma no controller e outra na view.
Na view, ao invés de serializar em formato de array coloque em um objeto, crie um modelo no c# para transitar os dados como por exemplo:
public class Resposta {
    public int IdQuestao {get;set;}
    public int IdQuestionario {get;set;}
    public int IdCampanha {get;set;}
    public int IdFuncionario {get;set;}
    public int IdOpcao {get;set;}
    public string Descricao {get;set;}
}

No controller altere o método para receber uma lista de Resposta
public ActionResult Create(List<Resposta> questionario)
{
    //Nesse momento você já deve possuir toda a lista populada
    try
    {
        return View();
    }
    catch(Exception ex)
    {
        return View();
    }
}

Na view você deve fazer a seguinte alteração:
$('form').submit(function(e){
    e.preventDefault();

    var resposta = new Array();
    var x = 0;
    var y = 0;
    var dados = [];
    $(".resposta").each(function () {
        var objResposta = {
            IdQuestao: $(this).children("input[name^='idQuestao']").val(),
            IdQuestionario: $(this).children("input[name^='idQuestionario']").val(),
            IdCampanha: $(this).children("input[name^='idCampanha']").val(),
            IdFuncionario: $(this).children("input[name^='idFuncionario']").val(),
            IdOpcao: $(this).find("input[name^='idOpcao']").val(),
            Descricao: $(this).find("textarea[name^='descricao']").val()
        }

        dados.push(objResposta);
    });

    $.ajax({
        type: "POST",
        url: '/Questionario/Create',
        data: JSON.stringify(dados)
        success: function(result) {
        },
        error: function(result) {
        }
    });
});

Deserializar array de objetos C#


set theory (concept of infinity)

Question: Let $S$ be a set. $f$ be a function on $S$ into real line $\mathbb{R}$.
Let us define $Af$ as a function from $\mathbb{R}$ into power set of $S$, $PS$
$Af(x) = \{s\mid f(s) \leq x\}$
Question: Is $S$ in the range of $Af$?
(as an example we can chose $S=\mathbb{R}$ and $f(x) = x$)
Thanks
PS: I'm having some technical difficulties in proving few results. It boils down to above. (and related in infinity)
Comment: for finite it is trvial. im unable to understand when S is infinite
Comment: What do we know about $S$, is it finite or something?
Answer: $S$ is in the range of $Af$ iff $f$ is bounded from above.
If $f$ isn't bounded from above, there is for every $x\in \mathbb{R}$ a $s_x\in S$ with $f(s_x)>x$ and so $s_x\notin Af(x)$ and so $S\neq Af(x)$ which means $S$ isn't in the range.
If $f$ is bounded from above, there is a $x\in \mathbb{R}$ with $f(s)\leq x$ for all $s\in S$ and so $S=Af(x)$  which means $S$ is in the range.
Comment: +1. A concrete example which might help the OP: let $f(x)=x$, and let $S=\mathbb{R}$. Then $Af(x)=\{s: s\le x\}$, and this is never all of $\mathbb{R}$, since $\mathbb{R}$ has no maximal element. By contrast, if we took $S=(0, 1)$, then $Af(1)=S$. So this is what boundedness gets us.
Comment: thanks. i was trying to define probability spaces starting from cdfs and random variables. above puts that in risk as in some cases i will not have sample space in the sigma algebra. so seems i cant go much further.  thanks
Comment: but if i assume /infinity/ belongs to R then I can get over this issue. Because then Af (infinity)  = S and hence S will be in the image of Af. Am I going in right direction plz?

set theory (concept of infinity)


App settings attributes missing in "Settings" app of device - iOS

Question: I had made a settings.bundle file in my project with some attributes in it. It was working fine and I could find all attributes in device's "Settings" app until I moved the file from one folder to another in my project hierarchy. Now, "Settings" app does show my app name in it, but there are no attributes in it.
Edit:
I have cleaned, build my project several times. Also deleted app from device, reinstalled it but the problem is still there.
I need to know the problem and reason why it has happened.
Thanks in advance.
Comment: I did it several times.. clean project, rebuild but didn't make any difference
Comment: Delete the app and then install it
Comment: Check if `Settings.bundle` is present in the `Copy Bundle Resources` build phase.
Answer: You can't put the Settings bundle wherever you want.  It needs to be in the top level diretory of your app's bundle.
from the manual:

A Settings bundle has the name Settings.bundle and resides in the
  top-level directory of your app's bundle.


What is this electrical thing in my piano?

Question:
What is the bar with the red freehand circle? You can see it has a cord coming out to the right.
I'm unable to try plugging it in and seeing what it does because it's an incompatible cord with my locale.
The piano is a Baldwin Acrosonic. I don't know how old it is.
Comment: The general shape and placement suggests a heater.
Comment: From what I can glean while skimming eBay and some piano stores' listings,  there's no such thing as an Acrosonic with electronics.  My bet is it's an aftermarket or home-built addon.  First thing to do is give us a photo of the cord & plug so those of us in the engineering world :-) can guess what locale and voltage this comes from.
Comment: Yup - doesn't look like a pickup [imho], looks more like an anti-condensation heater for cold weather - a smaller version of the things you used to see in wardrobes. But as @DaveEngineer & Carls say, a close-up pic of the wire/plug/socket would give us a better chance.
Answer: Closer inspection revealed the words "DAMPP CHASER". Some Googling revealed that it must be a Piano Life Saver dehumidifier, made by Dampp-Chaser.
Answer: Exactly --- it's a dehumidifying appliance.  It creates some heat to keep the air drier inside the instrument body.
There are also "humidifiers", but they do the opposite thing, and typically have plastic piping and a water reservoir and are most often found on grand pianos instead of console/studio models.
Comment: As a slight clarification, its purpose is to protect a piano is stored in conditions where temperature and humidity can cycle (e.g. a building which is used a few hours a week, and is unheated when not in use).  If the air were warm and humid when the heat was switched off, and then very slowly cooled, then when the temperature reached the new point, moisture could condense on everything.  Condensation on strings could induce rust.  Adding the heater will ensure that whenever the air is at the dew point, the piano will always be a tiny bit above that, so condense will happen elsewhere.
Comment: That is a helpful clarification, although there are places where the humidity is fairly constant (such as (sub)tropical regions) where these might be necessary in most pianos.

I have also seen these devices attached to grand pianos, but due to the relative openness of the piano case, I'm not sure they are quite as effective; if you're thinking of buying a grand, make sure you have a good HVAC system that keeps the RH relatively low (swamp coolers are OK for people but not pianos).
Comment: There may be places where humidity never gets very low, but that doesn't mean its "constant". Small changes in temperature can cause a certain level of absolute humidity to go from being slightly under 100% relative humidity to slightly over. Keeping the piano slightly warmer than its environment would ensure that its relative humidity would always be slightly lower than the surrounding air (and thus below 100%). It may not be possible to protect a grand piano *while it's in use*, but it could still be protected when it's not in use.
Comment: @supercat there's not only the question of keeping the humidity constant but of keeping it sufficiently high to prevent the sound board and pin block from cracking, or at least to prevent the pins from loosening.  At my university, such heaters were hung with wicks that reached down into buckets of water.  These were permanently installed in the practice rooms. They were definitely I'm operation when the pianos were in use.
Answer: I had a Dampp Chaser installed in my piano in the late 1970's. The entire thing consisted of a rectangular tank that sat in the bottom of the piano. The tank had a bar across the top that was heated. There were pads that were hung over that bar the ends of which hung in the water. You put water in the tank, it was absorbed by the pads and would humidify the inside of the piano. The second part was the heating bar as shown in the picture. That was used to dehumidify the piano. There was a sensor that controlled which function happened when. You had to put water in the tank weekly during dry times. I used to say I was watering my spinet trying to grow a baby grand.


websocket messages a nifi cluster to kafka without duplicates

Question: In a current project im working on, Im using a one flume server in order to initiate a connection with socket-io websocket that sends events, when consumes the messages it writes them into a kafka topic.
I want to use a nifi cluster with ConnectWebSocket processor in order to consume the messages from the websocket and finally insert them into a kafka topic.
Can nifi cluster lead to a duplicate messages in the topic as a result of more than one broker in the cluster handling the same event?
Thanks in advance :)
Answer: After I checked it, I saw that with the default configurations there will be duplications because all the nodes will perform the same processes.
But there is an option to configure the ConnectWebSocket scheduling to Execute only the primary node and in case it shuts down for some reason, another node will do the work instead.
That solved my problem in order to write events only once in a stable way.


How to make Catel recognise all MultiSelectTreeView properties?

Question: I am a fairly novice Visual Basic developer trying to use the MultiSelectTreeView control (https://github.com/ygoe/MultiSelectTreeView) in a MVVM application I am developing. To become familiar with using them together, I translated the MultiSelectTreeView demo to VB, and started implementing viewmodels using Catel.
What I found is that Catel seems to make some MultiSelectTreeView properties unavailable. On running the test using Catel, the demo window opens and mostly behaves as expected, but the immediate window shows a number of errors like:

System.Windows.Data Warning: 40 : BindingExpression path error: '(Controls:MultiSelectTreeView.HoverHighlighting)' property not found on 'object' ''MultiSelectTreeView' (Name='TheTreeView')'. BindingExpression:Path=(Controls:MultiSelectTreeView.HoverHighlighting); DataItem='MultiSelectTreeView' (Name='TheTreeView'); target element is 'MultiSelectTreeViewItem' (Name=''); target property is 'HoverHighlighting' (type 'Boolean')

Similar messages are present for the MultiSelectTreeView  IsKeyboardMode and ItemIndent properties. Setting these properties in code or directly in the MainWindow XAML has no effect, and the MultiSelectTreeView's HoverHighlighting effect no longer works if Catel is used.
I have uploaded my test project to GitHub (https://github.com/AnotherKiwi/MultiSelectTreeViewDemoVB). The master branch contains the VB translation of MultiSelectTreeView demo, with all features working. In the ImplementingMainWindowViewModel branch I have started implementing a viewmodel using Catel. Most features of the demo work, except the ones involving the properties mentioned above.
I would really appreciate it if someone could provide guidance on why Catel seems to be interfering with these MultiSelectTreeView properties!
Some further information added after the answer from @Geert:
The declaration of the MultiSelectTreeView control in MainWindow.xaml is as follows
    <controls:MultiSelectTreeView
            x:Name="TheTreeView"
            ItemsSource="{Binding RootNode.Children}"
            AllowEditItems="{Binding AllowEditItems}"
            VerticalRulers="{Binding VerticalRulers}">

            <controls:MultiSelectTreeView.ContextMenu>
                ...
            </controls:MultiSelectTreeView.ContextMenu>

                ...

            <controls:MultiSelectTreeView.ItemContainerStyle>

            </controls:MultiSelectTreeView.ItemContainerStyle>

            <controls:MultiSelectTreeView.Resources>

                <HierarchicalDataTemplate DataType="{x:Type vm:TreeItemViewModel}" ItemsSource="{Binding DataContext.Children}">
                    <StackPanel Orientation="Horizontal">
                        <Image Source="{Binding DataContext.ImageSource}" Width="16" Height="16" SnapsToDevicePixels="True"/>
                        <TextBlock Text="{Binding DataContext.DisplayName}" VerticalAlignment="Center" Padding="4,0,2,0"/>
                    </StackPanel>
                </HierarchicalDataTemplate>
            </controls:MultiSelectTreeView.Resources>
        </controls:MultiSelectTreeView>

I have tried applying the advice given in @Geert's answer, but when I run the application the MultiSelectTreeView is not displayed. I'm very new to WPF and I'm probably not modifying the appropriate XAML statements. Some more help with this would be really appreciated!
Answer: Note that items in an itemscontrol get a new DataContext (which is the item), so you cannot bind directly to the VM inside an ItemTemplate.
If you need to bind to the vm, you should do something like this:
<ItemsControl x:Name="myItemsControl" ItemsSource="{Binding MyItems}">
  <ItemsControl.ItemTemplate>
    <DataTemplate>
        <TextBlock Content="{Binding ElementName=myItemsControl, Path=DataContext.SomePropertyOnTheVm}" />
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>

Comment: Thanks @Geert...could you please help me pinpoint the portion of my XAML that needs to be modified (since I don't have an ItemsControl)? is it the  block?
Comment: Would you expand on your comment please @Geert?