Interpreting a backtrace when crashing on the device but not the simulator

Question: My app crashes when I run it on my iPhone 4, but it doesn't when I run it on the simulator. I imagine it's something about I'm using more memory than allowed.
I don't have any idea of the error message. The error is just (lldb) and when I tap bt, I get the code below...
I would be very grateful if somebody threw me some light on how to begin understanding this error message, because for me is like Chinese (and of course I'm not Chinese)
(lldb) bt
* thread #1: tid = 0x7396a, 0x37db5ce2 libsystem_platform.dylib`OSSpinLockLock$VARIANT$up + 2, queue = 'com.apple.spritekit.textureOp, stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
    frame #0: 0x37db5ce2 libsystem_platform.dylib`OSSpinLockLock$VARIANT$up + 2
    frame #1: 0x2fa9da68 SpriteKit`SKSpinLockSync(int*, void () block_pointer) + 92
    frame #2: 0x2fa63a48 SpriteKit`-[SKTexture loadImageData] + 300
    frame #3: 0x2fa6735a SpriteKit`-[SKTexture load] + 126
    frame #4: 0x37c79d06 libdispatch.dylib`_dispatch_client_callout + 22
    frame #5: 0x37c8be72 libdispatch.dylib`_dispatch_barrier_sync_f_invoke + 26
    frame #6: 0x2fa672ae SpriteKit`-[SKTexture _loadOnTextureQueue] + 122
    frame #7: 0x2fa98cf0 SpriteKit`SKCSprite::prepareForRendering() const + 1168
    frame #8: 0x2faaaf0c SpriteKit`SKCRenderer::preprocessSpriteImp(std::__1::vector<SKCRenderer::SpriteRenderInfo, std::__1::allocator<SKCRenderer::SpriteRenderInfo> >&, SKRenderQuadPool&, SKCSprite const*, _GLKMatrix4 const&, float, unsigned int&, bool) const + 124
    frame #9: 0x2faab9a4 SpriteKit`SKCRenderer::preprocessSpriteImp(std::__1::vector<SKCRenderer::SpriteRenderInfo, std::__1::allocator<SKCRenderer::SpriteRenderInfo> >&, SKRenderQuadPool&, SKCSprite const*, _GLKMatrix4 const&, float, unsigned int&, bool) const + 2836
    frame #10: 0x2faa73b4 SpriteKit`SKCRenderer::preprocessAndSubmitSpriteInternal(std::__1::vector<SKCRenderer::SpriteRenderInfo const*, std::__1::allocator<SKCRenderer::SpriteRenderInfo const*> >&, std::__1::vector<SKCRenderer::SpriteRenderInfo, std::__1::allocator<SKCRenderer::SpriteRenderInfo> >&, SKRenderQuadPool&, SKCSprite const*, _GLKMatrix4 const&) + 52
    frame #11: 0x2faa5e7c SpriteKit`SKCRenderer::preprocessAndSubmitSprite(SKCSprite const*, _GLKMatrix4 const&) + 152
    frame #12: 0x2faa973e SpriteKit`SKCRenderer::submitScene(SKScene*) + 186
    frame #13: 0x2faabf5c SpriteKit`SKCRenderer::renderScene(SKScene*) + 148
    frame #14: 0x2fa71120 SpriteKit`-[SKView _renderContent] + 1072
    frame #15: 0x37c79d06 libdispatch.dylib`_dispatch_client_callout + 22
    frame #16: 0x37c8be72 libdispatch.dylib`_dispatch_barrier_sync_f_invoke + 26
    frame #17: 0x2fa70cc2 SpriteKit`-[SKView renderContent] + 82
    frame #18: 0x2fa6e662 SpriteKit`__29-[SKView setUpRenderCallback]_block_invoke + 130
    frame #19: 0x2fa90dda SpriteKit`-[SKDisplayLink _callbackForNextFrame:] + 254
    frame #20: 0x00216a66 libglInterpose.dylib`-[DYDisplayLinkInterposer forwardDisplayLinkCallback:] + 270
    frame #21: 0x2f8509ce QuartzCore`CA::Display::DisplayLinkItem::dispatch() + 98
    frame #22: 0x2f850778 QuartzCore`CA::Display::DisplayLink::dispatch_items(unsigned long long, unsigned long long, unsigned long long) + 344
    frame #23: 0x3243576c IOMobileFramebuffer`IOMobileFramebufferVsyncNotifyFunc + 104
    frame #24: 0x2e0e8a74 IOKit`IODispatchCalloutFromCFMessage + 248
    frame #25: 0x2d3c6e20 CoreFoundation`__CFMachPortPerform + 136
    frame #26: 0x2d3d19de CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 34
    frame #27: 0x2d3d197a CoreFoundation`__CFRunLoopDoSource1 + 346
    frame #28: 0x2d3d014e CoreFoundation`__CFRunLoopRun + 1398
    frame #29: 0x2d33ac26 CoreFoundation`CFRunLoopRunSpecific + 522
    frame #30: 0x2d33aa0a CoreFoundation`CFRunLoopRunInMode + 106
    frame #31: 0x32019282 GraphicsServices`GSEventRunModal + 138
    frame #32: 0x2fbde048 UIKit`UIApplicationMain + 1136
    frame #33: 0x00067b5c superBeeLand`main(argc=1, argv=0x27dbbc64) + 116 at main.m:16
(lldb)

Answer: I have finally found an answer to this.
Well, the first clue is that the error is EXC_BAD_ACCESS. That almost always means I'm trying to access memory where there's not an object. Maybe a corrupted pointer, or an object gone away (been deallocated or lost the reference to it).
Going farther down the trace, it appears to be related to texture loading in some way. So I started by looking at any place where I were trying to load/preload textures, create sprites, etc. But it looks like it may be inside the prerender/render loop, which may mean it's not me explicitly loading textures, but Sprite Kit trying to load textures dynamically when needed.
I've tried removing some of the sprites until it doesn't crash, to narrow down which one is giving you the issue and I've finally found it was my hero movement. For his animation, I use a @propertie int _imgNum ; And add it to a [NSString stringWithFormat:@"image%d",_imgNum]; so the _imgNum is the number of the image.
I initialize _imgNum at the beginning of the scene and increment it everytime I use it (in didSimulatePhysics() and in touchedMovedWithEvent()).
Sometimes the app don't find the image and that's when it crash, but I still don't get why can't load images.
I'll better show the code.
        if(_imgNum >= 1 && _imgNum <= 12 )
    {
        [[self childNodeWithName:@"hero"]runAction:[SKAction setTexture:[SKTexture textureWithImageNamed:[NSString stringWithFormat:@"heroRunnning%d",_imgNum]]]];
        _imgNum++;
        if(_imgNum >= 12)
        {
            _imgNum = 1;
        }
    }

Answer: It seems that [SKAction setTexture:] has a bug.  I was getting the same com.apple.spritekit.textureOp bad_access error on the main thread.  My app was crashing on older hardware (pre iPad mini) and all of the simulators.
Set the spriteNode's texture instead of using the SKAction on it.
spriteNode.texture = [SKTexture textureWithImageNamed:@"imageName"];

Answer: I had the problem because I was using this:
SKAction* changeTextTo_Los = [SKAction runBlock:^{
    [myNode removeFromParent];
}];

This caused a crash since he wanted to access the object after running the block or some reason. This was of course not possible because it was removed already.


Probability of two random papers being submitted in alphabetical order

Question: I thought up this scenario and was curious if anyone could see the computation for the probability of this particular event.

A class has $k$ students and each student turns in his/her homework on a table at the beginning of class in random order.
What is the probability that in the stack of $k$ papers, exactly two appear in alphabetical order?
Comment: There are $k!$ such arrangements with $(k-2)!$ of those having two in alphabetical order. So, $(k-2)!/k!$, but this seems too straightforward.
Comment: If the letters are, say,  $ABCDEF$, is $CFEDAB$ considered as $AB$ being in alphabetical order ?
Comment: Yes, the two are allowed to occur in order at location in the stack.
Comment: I may have misinterpreted the question. Do $ZAYB$ and $ZAYC$ satisfy the criterion ?
Comment: Those would not. I am requiring that it must be $ZALQN\cdots ORTSB\cdots EF\cdots$ so the $EF$ is the "success"
Comment: Then my interpretation was right. Try to finish it, if you can't, I'll do it  a bit later. Watching the Australian Open.
Comment: Suggested edit: "exactly two _adjacent papers_ appear"
Answer: Firstly, we shall count no two consecutive letters being sequential.
Assuming an unrestricted number of $A,B,C,...$ and that $A$ is not allowed to follow $Z$,
Let's say the first letter is $P$, then 25 choices for second $(R)$, say, 25 ways for the next and so on.
Thus P(no two are sequential) $= \dfrac{26\cdot25^{k-1}}{26^k} = \left(\dfrac{25}{26}\right)^{k-1}$
Can you try and modify it to P(exactly $2$ are sequential) ? Start with the first two being sequential, and develop it...
PS
Suppose the first two have sequential alphabets. This can happen in $26\cdot1$ way (with $A$ after $Z$ also treated as sequential). The next letter now has $25$ choices, as have each of subsequent letters, so $26\cdot1\cdot25^{k-2}$ ways.
The pair that is sequential could occur starting at any of $(k-1)$ points,
thus $Pr = \dfrac{(k-1)26\cdot25^{k-2}}{26^k}$
Comment: I would have thought with $3$ papers, the probability no pair are sequential is $\frac{3}{6}$.  I do not see how to get that from your expression.
Comment: I seem to have misinterpreted the question as no consecutive letters being sequential, have asked OP for a clarification. The wording was actually "in alphabetical order"


Unexplained Infinite Loop in Excel VBA

Question: I'm writing a subroutine that is meant to remove unwanted rows from a worksheet via Loop.
I am using Cells.Find to locate the string "Total", and then passing the Cells.Find().Row value for my Rows().EntireRow.Delete statement. I only want the subroutine to delete the row if the String is in column 2, so I am also using Cells.Find().Column and then an IF statement to delete the line if Cells.Find().Column = 2
What's really weird: If the initial segment of the If statement is TRUE, then the loop executes without issue in expected number of iterations. If the initial segment is FALSE, it loops infinitely. Here is the original code:
Sub Clean_Placeholder()
Dim row_bound, column_bound As Long
Dim rngFound As Range

holder_ws.Activate
WorkbookArea (*This item sets the last_row and Last_column variables*)
row_bound = last_row
column_bound = last_column
Set rngFound = Cells.Find(What:="Total", After:=Range("A1"), LookAt:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)
Do While Not rngFound Is Nothing
    row_bound = Cells.Find(What:="Total", After:=Range("A1"), LookAt:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False).Row
    column_bound = Cells.Find(What:="Total", After:=Range("A1"), LookAt:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False).Column
    If column_bound = 2 Then
        Rows(row_bound).EntireRow.Delete Shift:=xlToUp
    End If
    Set rngFound = Cells.Find(What:="Total", After:=Range("A1"), LookAt:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)
Loop

End Sub

As is, the code loops forever because the (If column_bound = 2) statement is FALSE. However, if I change the IF statement to something that is TRUE, the code works perfectly. E.G., If the word "Total" is present in column 16, (If column_bound = 16) would work as expected.
I'm really confused as this doesn't seem to make logical sense, but I am sure that I am not thinking of something.
Please let me know if you need more details.
Comment: If you don't delete the Total row, then the loop will find it repeatedly. I think normally one would use `Find` and `FindNext` here.
Comment: What is the point of `WorkbookArea` and setting `row_bound` and `column_bound`?
Comment: @BigBen Thanks, putting that way makes it click in my head. I can take a look at your recommendation.
Answer: Delete Matching Rows using Find and FindNext

It might be worth looking into Range.AutoFilter which could be used to do the same more efficiently and with less code.

Sub DeleteEntireRows()

    Const SEARCH_PATTERN As String = "*ToTal*" ' contains
    Const IS_TESTER As Boolean = True

    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!

    Dim rg As Range:
    With ws.Range("B2")
        Set rg = .Resize(ws.Rows.Count - .Row + 1)
    End With

    Dim cell As Range: Set cell = rg.Find( _
        SEARCH_PATTERN, rg.Cells(rg.Cells.Count), xlFormulas, xlWhole)

    If cell Is Nothing Then
        MsgBox "No match found using the pattern """ & SEARCH_PATTERN _
            & """ in the range """ & rg.Address(0, 0) & """ of worksheet """ _
            & ws.Name & """!", vbExclamation
        Exit Sub
    End If

    Dim FirstRow As Long: FirstRow = cell.Row

    Dim urg As Range

    Do
        If urg Is Nothing Then
            Set urg = cell
        Else
            Set urg = Union(urg, cell)
        End If
        Set cell = rg.FindNext(cell)
    Loop While cell.Row <> FirstRow

    With urg.EntireRow
        If IS_TESTER Then
            MsgBox "You were about to delete the following rows:" _
                & vbLf & vbLf & .Address(0, 0) & "." & vbLf & vbLf _
                & "Set ""IS_TESTER"" to 'False' to do it for real.", _
                vbInformation
        Else
            .Delete xlShiftUp
            MsgBox "Total rows deleted.", vbInformation
        End If
    End With

End Sub

Unexplained Infinite Loop in Excel VBA


What would non recursive enumerability means?

Question: Edit : I think that this article is the answer i was waiting for, i stubble upon it by chance while investigating automatic proof verification and lambda calculus :
http://plato.stanford.edu/entries/mathematics-constructive/
Original post :
Due to negative feed back, as of 15/04/2016, i delete the original post, only leaving collected links and article. Thank you for reading, i guess mathematic community is a closed one, not very open to self learners.
edit : I found this related question
Proving that the set of natural numbers is well-ordered
edit : another related question : Proving the so-called "Well Ordering Principle"
edit : here is another one, that point towoard Z being suffiscient Prove the principle of mathematical induction in $\sf ZFC $
edit : here is a discussion about constructives approaches
https://mathoverflow.net/questions/30643/are-real-numbers-countable-in-constructive-mathematics
Comment: What theory adds an axiom declaring that any infinite set of integers is enumerable? No theory does that, none has to: it's a theorem of ZFC. Of course the enumeration won't in general be computable. Of course it's false that "any subset of the integers is recursively enumerable". The article doesn't state that at all, not even "somehow".
Comment: Your algorithm relies on the existence of the order restricted to the set you want to enumerate. I doesn't help that you know the order on all the naturals. At any step you don't want to list the least element not listed thus far, you want to list the least element in your subset that hasn't been listed thus far.
Comment: In Peano arithmetic (PA), the induction axiom is equivalent to the principle you cite, but first-order PA doesn't (can't) talk about all subsets of $\Bbb N$, only about each subset definable in PA (by a formula). In ZFC, however, the full statement is simply a theorem: the integers are well-ordered. In fact I don't think choice is needed; ZF should prove this, thanks to Regularity. Any subset of a well-ordered set is itself well-ordered (by the same/superset's ordering, restricted to the subset).
Comment: http://plato.stanford.edu/entries/mathematics-constructive/ I think my only problem is that ZFC is overwhelming in all google search. There exists alternatives, but it seems that for some reason very few people have the ability to hear about them.
Comment: Also i found an interesting discussion here : http://mathoverflow.net/questions/30643/are-real-numbers-countable-in-constructive-mathematics
Answer: You are conflating recursively enumerable (r.e.) and enumerable (countable). There are lots of sets which are countable but not r.e. - for example (as you mention) the set of indices of Turing machines which do not halt on input 0 (say). This set is countable, even though it is not r.e. You write e.g.

There is no bijection from the set of all N, and . . . any non recursively enumerable set

and cite the diagonal argument as proof - however, all a diagonal construction shows is that there is no recursive bijection between $\mathbb{N}$ and the set of all programs that do not terminate. There are lots of such bijections, they just aren't recursive.
I suspect that you are implicitly assuming some principle like "every thing which exists is recursive." While philosophically interesting, this is deeply at odds with classical mathematics, which indeed proves that there is a rich universe of non-recursive entities.


How to find the range of the following function?

Question: I have following function $$f(x_1,x_2)=\frac{(x_1,x_2)}{x_1+x_2+1}$$ where domain of $f$ is $\{(x_1,x_2)|x_1+x_2+1>0\}$. How to find the range of this function?
Comment: What's the numerator?
Comment: @MarkMcClure is it clear now?
Comment: Yes, it's more clear! So, $f:\mathbb R^2 \to \mathbb R^2$?
Comment: @MarkMcClure yes that is right
Answer: Let $D$ be the domain of $f.$ For $b>-1,$ let $L_b$ be the line $x+y=b.$ Then $D=\bigcup_{b>-1}L_b.$
Now if $(x,y) \in L_b, b>-1,$ then
$$f(x,y) =\frac{(x,y)}{b+1}.$$
Because $x/(b+1)+y/(b+1) = (x+y)/(b+1) = b/(b+1),$ we see that $f(L_b)\subset L_{b/(b+1)}.$ In fact $f$ is a bijection between $L_b$ and $L_{b/(b+1)}.$ Thus
$$\tag 1 f(D) = \bigcup_{b>-1}f(L_b) = \bigcup_{b>-1}L_{b/(b+1)}.$$
Observe $b\to b/(b+1)$ maps $(-1,\infty)$ bijectively onto $(-\infty,1).$ Thus the union on the right of $(1)$ is the set $x+y<1.$
Comment: No, the *range* is the set of points below the line joining $(0,1)$ and $(1,0).$
Comment: Thank you so much for your answer. So it means that all the points that are below the line joining $(1.5,0)$ and $(0,1.5)$ are the domain of the function?


Interpreting output from lmer

Question: This probably has been asked many a times, but I cannot find the answer. I'm trying to interpret the output that I get from lmer.
My code is as follows:
Model1<- lmer(DV ~ Eduy_IMP + Gender + Age + APOEdich_IMP +
     predictor + Time:Factor2:Factor1*predictor +
     (1 + Time|Study), Data)
summary(Model1, ddf="Kenward-Roger")

DV = Dependant variable; Factor2 has levels 1,2,3; Factor1 has levels 0, 1.
Here is my Output:

My Question: I need to be able to report a coefficient for the predictor in the following groups: Predictor in each of the individual levels of Factor1 and Factor2. How do I get this?  I even tried having different data sets and running the above code, but I cannot get a coefficient for these.
My aim is to see the influence of the predictor on the DV in Factor1 and Factor2.
Comment: Hi, there are blind and visually impaired users of this
site who interact with it using screen readers. The screen
readers can't handle the equation in your screenshot.
Please edit the post to include the equation as LaTeX. If
it helps, we have some
[resources on using LaTeX on Cross Validated](https://stats.meta.stackexchange.com/a/1605/155836).
Answer: I think in order to get there you would have to include the factors as main effects themselves. Currently, you only use factors in an interaction term. I am not even sure if this is sound (including an interaction without the corresponding main effects), but I am no expert. Nevertheless, this is why you only get coefficients for the interaction or more specifically for the different contrasts.
Model1 <- lmer(DV ~ Eduy_IMP + Gender + Age  + Factor1 +
            Factor2 + APOEdich_IMP + predictor +
            Time:Factor2:Factor1*predictor +
            (1 + Time|Study), Data)
summary(Model1, ddf="Kenward-Roger")

Answer: It appears you are using ":" or colons for the interaction between Factor1 and Factor2. In R, that will estimate the interaction only but not the main/conditional effects. To estimate both the main/conditional effects and the interaction, use the asterisk or "*"

Interpreting output from lmer


Is the function order guaranteed?

Question: let x = 0;
function a() {
    console.log("called a()");
    for (let i=0; i<123456789; ++i) {
        x += Math.sqrt(2);
    }
    console.log("x = "+x);
}
function b() {
    x = undefined;
    console.log("called b()");
}
setTimeout(b, 20);
a();

output:
called a()
x = 174594265.7306214
called b()

b should have been called sooner, but it waited until the function a completed.
I know js uses only one thread, but the processor could have switched between executing a and b during a's execution. Does the processor always execute only one function at a time (if there is no await inside)? In nodejs and in website javascript?
EDIT:
Here is an await example:
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
let x = 0;
async function a() {
    console.log("called a()");
    await sleep(1000);
    for (let i=0; i<123456789; ++i) {
        x += Math.sqrt(2);
    }
    console.log("x = "+x);
}
function b() {
    x = undefined;
    console.log("called b()");
}
setTimeout(b, 20);
a();

output:
called a()
called b()
x = NaN

notice how x becomes NaN, since b is executed during a
Comment: `but the processor could have switched between executing a and b during a's execution.` No it couldn't. JavaScript runs (in a) task loop. One task at a time.
Comment: with `setTimeout` you give *the minimum* time to wait. The thread still has to be idle to run your task, so if something is already running, the execution of `b` would be delayed further.
Comment: RE the edit - still only a single function gets executed at once. Async functions can be paused/unpaused and will continue from where they left off. In the mean time other functions can run. If something modifies *the same state the async function works with*, then the code just continues using that new state.
Comment: `b is executed during a` - to be more specific, `b` is executed before the `await` in `a` returns. Javascript can **wait** in parallel but cannot execute code in parallel since it is singlethreaded
Answer:
b should have been called sooner, but it waited until the function a
completed.

No. b should be called after your synchronous code has executed because that's when a function passed to setTimeout is called.
Callback function of setTimeout is scheduled to run after the delay you specify as a second argument to setTimeout. This delay is the minimum amount of time it will take to run the callback function scheduled using setTimeout.
Once the timer expires, that callback function is put in a task queue and from there it is pushed to the call stack BUT it is only pushed once the call stack is empty.
In your case, call stack will be empty when your script has finished its execution.

I know js uses only one thread, but the processor could have switched
between executing a and b during a's execution

That's not possible with only 1 thread. In Javascript, only one thing executes at a given time, unless you use another thread.

Does the processor always execute only one function at a time (if
there is no await inside)

Yes. Even with await, function is paused until the promise is settled. Once the promise settles, that function continues execution and at that time, nothing else executes.
Edit

notice how x becomes NaN, since b is executed during a

No, there is no interference here. Function a is executed synchronously until the following statement
await sleep(1000);

While the function a is paused, waiting for the promise returned by sleep(...) to settle, during this time, function b is executed because its timer has expired and the call stack is empty.
Since both functions assign to same variable x, value of x is NaN because its value before function a resumes is undefined and performing addition on undefined leads to NaN.

Is the function order guaranteed?


WCF RIA Services, EntitySet always empty?

Question: A quick question here about the new WCF Ria services beta:
If I do this in code-behind:
EntitySet e = MyContext.Employees
It seems that the entityset is always empty at runtime? I.e. if I want to loop through the Employee entityset.
Also, if I'm getting the Enumerator for the entityset, I'll get an error telling me that the enumerator either is empty or hasn't started yet. Is there any way at all to grab a collection of entities from the context and iterate through them?
Thanks in advance!
Answer: Have you checked within the Completed event call back? Remember that within Silverlight all the calls are asynchronous. Even if you see sample code where the ItemsSource is assigned before the call back, it is relying to the fact that Employees is an ObservableCollection for the data binding.
<code>LoadEmployeeCommand()
{
    // The Load method initiates the call to the server
    LoadOperation<Employee> loadOperation = domainContext.Load(domainContext.GetEmployeesQuery());
    // The EntitySet is still empty at this point
    employeeDataGrid.ItemsSource = domainContext.Employees;
    loadOperation.Completed += EmployeeLoadOperationCompleted;
}

private void EmployeeLoadOperationCompleted(object sender, EventArgs e)
{
    // Don't need to reassign now but at this point the collection should be populated
    employeeDataGrid.ItemsSource = domainContext.Employees;
}
</code>
Comment: Hi Martin, sorry for the delayed comment here.

Even though I'm using the completed event, it dosn't fire at all. It just skips the loadOperation.Completed and stops there. Shouldn't I be able to step into the completed method?

Thanks again :)
Comment: I'd set a seperate break point in the completed event handler as "stepping" into it doesn't make sense when it is asynchronous. Provided you hit the break point you can then check the LoadOperation.HasError property and LoadOperation.Error if set.


latest product with add-to-cart in magento

Question: I'm new for Magento. I need to display latest added product in home page. I'm using following code in 2columns-left.phtml

<?php echo $this->getChildHtml('breadcrumbs') ?>

        <?php echo $this->getChildHtml('global_messages') ?>
        <?php echo $this->getChildHtml('content') ?>
        <?php
            $productsCollection = Mage::getModel("catalog/product")->getCollection()
                               ->addAttributeToSort("entity_id","DESC")
                               ->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInSiteIds())
                               ->setPageSize(6)
                               ->setCurPage(1);
            foreach ($productsCollection as $product) {
                $model = Mage::getModel('catalog/product')->load($product->getId());
                echo $model->getName().'
';
                echo $model->getPrice().'
';
                echo $model->getImageUrl().'
';
                echo "

";
            }
        ?>

It's working fine. But I can't correct code for add-to-cart option.
I found fllowing code from addtocart.phtml with script,
<?php $_product = $this->getProduct(); ?>
<form action="<?php echo $this->getSubmitUrl($_product) ?>" method="post" id="product_addtocart_form">
<?php $buttonTitle = $this->__('Add to Cart'); ?>
<?php if($_product->isSaleable()): ?>

        <?php if(!$_product->isGrouped()): ?>
        <?php echo $this->__('Qty:') ?>
        <input type="text" name="qty" id="qty" maxlength="12" value="<?php echo $this->getProductDefaultQty() * 1 ?>" title="<?php echo $this->__('Qty') ?>" class="input-text qty" />
        <?php endif; ?>
        <button type="button" title="<?php echo $buttonTitle ?>" class="button btn-cart" onclick="productAddToCartForm.submit(this)"><?php echo $buttonTitle ?></button>
        <?php echo $this->getChildHtml('', true, true) ?>

<?php endif; ?>
</form>

But, if I click add-to-cart, going to home page.
Help me.
Comment: No need to redirect. If just add into cart is Enough.
Answer: Call a block on home page through static block  with content value as
{{block type="catalog/product_list" name="product_listing" template="catalog/product/latest.phtml"}}
or you can directly call this block on cms home , paste this
{{block type="catalog/product_list" name="product_listing" template="catalog/product/latest.phtml" }}
in your cms home page content.
create a file in folder frontend/theme_folder/default/template/catalog/product as latest.phtml.
Paste the below code in it  as :
Latest Products
<?php
$_productCollection = Mage::getResourceModel('reports/product_collection')
                    ->addAttributeToSelect('*')
                    ->setVisibility(array(2,3,4))
                    ->setOrder('created_at', 'desc')
                    ->setPage(1, 4);
?>
 <?php $_iterator = 0; ?>

            <?php  foreach($_productCollection as $_product) : ?>
            <li class="item<?php if( ++$_iterator == sizeof($_productCollection) ): ?> last<?php endif; ?>">
                <?php // Product Image ?>
                       <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image"><img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(135); ?>" width="135" height="135" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />

<a href="<?php echo $_product->getProductUrl(); ?>"><?php echo $_product->getName(); ?>

                                 <?php echo $this->getPriceHtml($_product, true) ?>
                                <?php if($_product->isSaleable()): ?>

<button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><?php echo $this->__('Add to Cart') ?></button>

                                <?php else: ?>

<?php echo $this->__('Out of stock') ?>

                                <?php endif; ?>

        <?php endforeach;  ?>

Thats it you will be able to see the latest 4 product on home page. you can increase the number of product by increasing the  ->setPage(1, 4);  to your required number of product on home page.
Comment: Thanks. But add-to-cart button is not working. It's just going to product page.
Comment: No need to redirect. If just add into cart is Enough.
Comment: u can go with ajax
getIdBySku($p); ?>
   load($productid); ?>

init(); ?>
   addProduct($my_product, array('qty' => $ar)); ?>
   save(); ?>
   setCartWasUpdated(true); ?>


How do I customize an article URL alias?

Question: In Drupal 6 there is a possibility to customize URL alias by the help of [AUTOMATED ALIAS SETTINGS], but this will affect all the articles. I need to restructure my URL alias only for few paid articles.
Can we able to add /pro/ somewhere in the url only for few articles like as follows,
Original article url parameters:
www.example.com/{article}/{channel}/{year}/{month}/{nid}/{article_title}
Customised article URL:
www.example.com/pro/{article}/{channel}/{year}/{month}/{nid}/{article_title}
Comment: i think you are looking for https://www.drupal.org/project/pathauto module
Comment: @Smalution : Thank you for your help, I have a question here, can we able to change article url only for few articles?
Comment: yes it provide the facility to set url for individual node
Answer: There are so many module for this you can check
Pathauto
Path redirect
Global Redirect


Teaching rhythm to a beginner

Question: I'm teaching viola to a beginner high school student.
His progress with technique and reading are pretty good, but one thing he has trouble with is rhythm and tempo. He tends to want to work on expression and tone quality a lot -- which is understandable; a lot of beginner violinists tend to be more self-conscious about their tone (and these are probably the ones that end up excelling later on, given they don't become discouraged and quit). This is his first exposure to music performance, though, so tempo is more important than he thinks -- and he's struggling to grasp it or to appreciate its importance, as enthusiastic as he is about learning music in general.
I've tried a few things so far -- tapping to a metronome, counting subdivisions, playing a straight 16ths melody on top so that he'd know when he can guess intuitively from the chord change when his note comes in -- I've had moderate success with the last one, but he tends to rush ahead, especially during rests.
Are there any other tricks that I might try? I think it just hasn't "clicked" for him. Once it does, I'm sure he can pay more attention to it and either improve quickly with a metronome or at least over time with practice.
Answer: When I was in choir in high school, a technique that clinicians and teachers from different events I was involved with used was just singing the rhythm.
Pick a note for the student to play that is in a comfortable playing position and have them play the rhythm (without changing notes) throughout the piece.  If the piece is accompanied then play the accompaniment part while they do this; this is so that the student can internalize the rhythm of the piece in actual context.
This was a huge help to me in pieces with complex rhythmic lines (Daemon Irrepit Callidus was a really tough one for me early on.)  Another tip is to encourage your student to "play the rests".  Help them to realize that "Music is the silence between the notes" (Claude Debussy).  Have them do the aforementioned exercise but, on the rests, mute the strings and either play the rest as though it were another note with a pitch or have them subdivide the rest into regular beats (quarters, eights, sixteenths, depending on the piece) and have them play those.  This will emphasize the importance of the rests in the music.
Rhythm was a huge struggle for me in my musical youth and I hope this will help your student as it helped me.
Comment: +1 for "singing the rhythm". Check out Sheila Chandra's "Vocal Percussion" pieces for a cool way to do it.
Comment: Playing the rests is HUGE. A college professor published "The Addition Method," and among the techniques used were subdividing counted rhythms using breath-impulses, and whispering/speaking a different pitch for rests.
Answer: When I was starting to learn the piano, my teacher told me to practice every scale I knew so far, every day, with a metronome set at a different tempo each time.
After a month, he gave me some sheets that were just scales, but with different rhythms each, and he told me to do the same thing, practice everyday with a different tempo on the metronome.
It helped a lot!
The scales are a good way to practice rhythm, he said, because the student does not need to pay attention to the notes (since scales are almost built-in in the hands of a pianist, I don't know how is it with a violinist) so he can focus all his attention to the rhythmical aspect of the music.
I hope it helps.
Comment: I would think scales are equally "built in" for any instrument (or at least should be), so this is a good answer for violin as well.
Answer: A technique to concentrate entirely on the rhythm is to put away the instrument entirely, and clap the rhythm along with a metronome. You should also clap along to emphasize what would be the correct rhythm. You can vary this technique with the  methods you have already tried with counting sub divisions etc.
Comment: If they don't like clapping, try a single drumstick on a textbook.
Comment: The thing I don't like about clapping/tapping, despite its popularity, is that there is no concept of duration to the notes. It's sufficient when trying to count out something in the midst of a busy rehearsal, but as a general practice, especially for students, I'm not a fan.
Answer: I think using his inner hearing more will help:
Let him sing a simple four phrase song, something he knows really well, such as Frere Jacques. After that he can progress through a scale of difficulty:

sing alternating phrases with you
sing alternating phrases out loud/in his head, while you tap the pulse
sing two consecutive phrases out loud, then two in his head
sing the song according to cards you hold up for each phrase:green for sing, red for singing your head, yellow for tap the pulse or rhythm, progressing to combinations of green/yellow and red/yellow
repeat this with you changing the card shown mid-phrase
sing the entire song in thinking voice and indicate when finished
sing simple songs where more words can be missed out each time, such as "Bingo", "Chest Chest Knee Toe" etc
-repeating simple 4/4 rhythms by clapping, only using crotchets and quavers at first,then introduce crotchet rests

At first keep a pulse for him, then experiment with weaning him off it. It's worth doing this vocally so that technique considerations don't create an extra obstacle for him, and things always embed more easily with voice first.
I've had success with these activities with much younger children; hopefully they'll work for someone older too. They are used by teachers of Kodaly methodology.
Answer: Make him play exercises. The emotional content of the music here is a distraction for your student when he is getting his tempo right. Therefore, the exercises you prescribe must be as devoid of this as possible. The best example for such an exercise would be ( as @victor suggested ) scales. You can give arpeggios and make up patterns that go up and down scales for your student to play.
  Let him start his practice sessions everyday by rigorously playing these, giving attention only to tempo, before moving on to anything else. And let him do this while trying to get faster and more and more accurate each day. This may seem tedious and perhaps boring, but your student will himself embrace this approach, when he sees that it ultimately makes his tunes themselves more evocative, controlled and beautiful.

Teaching rhythm to a beginner


How to consume REST web service with ActiveMQ in Mule

Question: I have a requirement where I need to expose a REST web service in Mule .. I have the following flow in Mule :-

   <flow name="MainService" doc:name="MainService">
        <http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8082" doc:name="HTTP"/>
        <logger message="RequestLog :- #[message.payloadAs(java.lang.String)]" level="INFO" doc:name="RequestLogger"/>
         <jms:outbound-endpoint queue="NewQueue" connector-ref="Active_MQ" doc:name="JMS" exchange-pattern="request-response"/>
    </flow>

    <flow name="testFlow1" doc:name="testFlow1" initialState="started">
       <jms:inbound-endpoint connector-ref="Active_MQ" address="jms://tcp:NewQueue" doc:name="JMS" exchange-pattern="request-response" disableTemporaryReplyToDestinations="true" responseTimeout="90000"/>
        <jersey:resources doc:name="REST">
            <component class="com.test.services.schema.maindata.v1.Impl.MainDataImpl"/>
        </jersey:resources>
    </flow>

Now I want whenever the service is triggered from a rest client the request should first enter into an ActiveMQ queue NewQueue in MainService flow and in testFlow1 flow it will get the request from  NewQueue and will execute it ..
Now there are 2 methods in this webservice :-

The first method is insertDataOperation which is triggered from
rest client as a POST method and it accept the JSON request on it's
body ..
The second method is retrieveDataOperation which has is
triggered from rest client as a GET method which has request in the
url like the following :-
http://localhost:8082/getData/retrieve/?id=21 where the value is in
id ..

Now when ever I trigger the value I get the following exception :-
INFO  2014-08-10 20:23:56,622 [[test].connector.http.mule.default.receiver.02] org.mule.lifecycle.AbstractLifecycleManager: Initialising: 'Active_MQ.dispatcher.2028594834'. Object is: EeJmsMessageDispatcher
INFO  2014-08-10 20:23:56,622 [[test].connector.http.mule.default.receiver.02] org.mule.lifecycle.AbstractLifecycleManager: Starting: 'Active_MQ.dispatcher.2028594834'. Object is: EeJmsMessageDispatcher
ERROR 2014-08-10 20:23:56,709 [ActiveMQ Session Task-1] org.mule.exception.DefaultMessagingExceptionStrategy:
********************************************************************************
Message               : Failed to invoke JerseyResourcesComponent{testFlow1.component.1820680768}. Component that caused exception is: JerseyResourcesComponent{testFlow1.component.1820680768}. Message payload is of type: String
Code                  : MULE_ERROR--2
--------------------------------------------------------------------------------
Exception stack is:
1. null (java.lang.NullPointerException)
  org.mule.module.jersey.JerseyResourcesComponent:116 (null)
2. Failed to invoke JerseyResourcesComponent{testFlow1.component.1820680768}. Component that caused exception is: JerseyResourcesComponent{testFlow1.component.1820680768}. Message payload is of type: String (org.mule.component.ComponentException)
  org.mule.component.AbstractComponent:144 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/component/ComponentException.html)
--------------------------------------------------------------------------------
Root Exception stack trace:
java.lang.NullPointerException
    at org.mule.module.jersey.JerseyResourcesComponent.doInvoke(JerseyResourcesComponent.java:116)
    at org.mule.component.AbstractComponent.invokeInternal(AbstractComponent.java:122)
    at org.mule.component.AbstractComponent.access$000(AbstractComponent.java:57)
    + 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
********************************************************************************

ERROR 2014-08-10 20:23:57,746 [ActiveMQ Session Task-2] org.mule.exception.DefaultMessagingExceptionStrategy:
********************************************************************************
Message               : "Message with id "ID:ANIRBAN-PC-50216-1407682432183-1:1:6:1:1" has been redelivered 1 times on endpoint "jms://tcp:NewQueue", which exceeds the maxRedelivery setting of 0 on the connector "Active_MQ". Message payload is of type: ActiveMQTextMessage
Code                  : MULE_ERROR--2
--------------------------------------------------------------------------------
Exception stack is:
1. "Message with id "ID:ANIRBAN-PC-50216-1407682432183-1:1:6:1:1" has been redelivered 1 times on endpoint "jms://tcp:NewQueue", which exceeds the maxRedelivery setting of 0 on the connector "Active_MQ". Message payload is of type: ActiveMQTextMessage (org.mule.transport.jms.redelivery.MessageRedeliveredException)
  org.mule.transport.jms.redelivery.JmsXRedeliveryHandler:81 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/transport/jms/redelivery/MessageRedeliveredException.html)
--------------------------------------------------------------------------------
Root Exception stack trace:
org.mule.transport.jms.redelivery.MessageRedeliveredException: "Message with id "ID:ANIRBAN-PC-50216-1407682432183-1:1:6:1:1" has been redelivered 1 times on endpoint "jms://tcp:NewQueue", which exceeds the maxRedelivery setting of 0 on the connector "Active_MQ". Message payload is of type: ActiveMQTextMessage
    at org.mule.transport.jms.redelivery.JmsXRedeliveryHandler.handleRedelivery(JmsXRedeliveryHandler.java:81)
    at org.mule.transport.jms.MultiConsumerJmsMessageReceiver$JmsWorker.preProcessMessage(MultiConsumerJmsMessageReceiver.java:512)
    at org.mule.transport.AbstractReceiverWorker$1$1.process(AbstractReceiverWorker.java:117)
    + 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
********************************************************************************

Now I guess the request need to be inserted into the ActiveMQ queue NewQueue should be String format in case of insertDataOperation as the request is on BODY .. and I am not sure for retrieveDataOperation which carries value id in url ...
Please let me know how to fix the exception for both the cases ... Please help
Answer: The most prominent problem is that you only send the payload of the HTTP request via the JMS endpoint, which is of course not enough for the Jersey to be happy.
You need to serialize the whole Mule message to XML (so it's properties are carried over too) ...
<xml:object-to-xml-transformer acceptMuleMessage="true" />

... then send it over JMS, then deserialize it before the Jersey component.
TBF I don't know if this will work but that's probably the closest to a working solution you will be.
Comment: OHHHH ..Wonderful ... It works David Thanks .. What's the exact reason ?? Why it require to accept the whole Mule message ?? Does it need to accommodate message id and correlation id etc etc ?
Comment: The HTTP endpoint creates a truckload of properties (see: http://www.mulesoft.org/documentation/display/current/HTTP+Transport+Reference#HTTPTransportReference-HTTPProperties), some of which are essential for a REST API to work. That's why you need to carry them across JMS.
Answer: So as per David's suggestion need to add :-
<mulexml:object-to-xml-transformer acceptMuleMessage="true" doc:name="Object to XML"/>

UPDATED WORKING FLOW :-
<jms:activemq-connector name="Active_MQ" brokerURL="tcp://localhost:61616" validateConnections="true" doc:name="Active MQ"/>

<flow name="MainService" doc:name="MainService">
<http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8082" doc:name="HTTP"/>
<logger message="RequestLog :- #[message.payloadAs(java.lang.String)]" level="INFO" doc:name="RequestLogger"/>
<mulexml:object-to-xml-transformer acceptMuleMessage="true" doc:name="Object to XML"/>
<jms:outbound-endpoint queue="NewQueue" connector-ref="Active_MQ" doc:name="JMS" exchange-pattern="request-response"/>
</flow>

<flow name="testFlow1" doc:name="testFlow1" initialState="started">
 <jms:inbound-endpoint connector-ref="Active_MQ" address="jms://tcp:NewQueue" doc:name="JMS" exchange-pattern="request-response" disableTemporaryReplyToDestinations="true" responseTimeout="90000"/>
 <mulexml:xml-to-object-transformer doc:name="XML to Object"/>
 <jersey:resources doc:name="REST">
   <component class="com.test.services.schema.maindata.v1.Impl.MainDataImpl"/>
 </jersey:resources>
</flow>


Retrieving Current Value from Telerik RadGrid EditFormItem

Question: I have an ASP form created using Telerik's RadGrid control, already binding values from the database and displaying them, with the ability to add and delete entries from the table. I need to add editing functionality, but I've finally run into a block, and I can't find a way past it.
The ASP page contains both the RadGrid and the SqlDataSource I need to use:
<asp:SqlDataSource ID="ContactsSqlDataSource" runat="server"
                   ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
                   SelectCommand="etc..."
                   UpdateCommand="UPDATE Contacts
SET Salutation=@Salutation,
    FirstName=@FirstName,
    etc...
WHERE ClientContactID=@ClientContactID" CancelSelectOnNullParameter="False"
                   onupdating="ContactsSqlDataSource_Updating">
    <UpdateParameters>
        <asp:Parameter Name="Salutation" Type="String" />
        <asp:Parameter Name="FirstName" Type="String" />
        etc...
        <asp:Parameter Name="ClientContactID" Type="String" />
    </UpdateParameters>
    <SelectParameters>
        <asp:QueryStringParameter Name="GroupID" QueryStringField="ID" />
    </SelectParameters>
</asp:SqlDataSource>
etc...
<telerik:RadGrid ID="ContactsRadGrid" runat="server"
                 AutoGenerateColumns="False" AutoGenerateDeleteColumn="True" CellSpacing="0"
                 DataSourceID="ContactsSqlDataSource" GridLines="None"
                 Skin="Windows7" onitemcommand="ContactsRadGrid_ItemCommand"
                 onitemdatabound="ContactsRadGrid_ItemDataBound"
                 AllowAutomaticUpdates="True">
    <MasterTableView DataSourceID="ContactsSqlDataSource"
                     DataKeyNames="etc...">
        <Columns>
            etc...
        </Columns>
        <EditFormSettings EditFormType="Template">
            <FormTemplate>
                <asp:HiddenField ID="ClientIDHiddenField" runat="server"
                                 Value='<%# Bind("ClientContactID") %>' />
                etc...
                <asp:TextBox ID="SalutationTextBox" runat="server" Text='<%# Bind("Salutation") %>' TabIndex="1" />
                etc...
                <asp:TextBox ID="FirstNameTextBox" runat="server" Text='<%# Bind("FirstName") %>' TabIndex="2" />
            </FormTemplate>
        </EditFormSettings>
    </MasterTableView>
</telerik:RadGrid>

In my code behind, I have:
protected void ContactsRadGrid_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
    RadGrid grid = sender as RadGrid;
    GridDataItem dataItem = e.Item as GridDataItem;
    GridEditFormItem editItem = e.Item as GridEditFormItem;
    if (e.CommandName == "Delete")
    {
        etc...
    }
    else if (e.CommandName == "Update")
    {
        ContactsSqlDataSource.Update();
    }
}

protected void ContactsSqlDataSource_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
    GridEditFormItem editItem = (ContactsRadGrid.EditItems[0] as GridDataItem).EditFormItem;
    string salutation = Convert.ToString(editItem.GetDataKeyValue("Salutation"));
    string firstName = Convert.ToString(editItem.GetDataKeyValue("FirstName"));
    etc...
    string clientContactID = Convert.ToString(editItem.GetDataKeyValue("ClientContactID"));

    e.Command.Parameters["@Salutation"].Value = salutation;
    e.Command.Parameters["@FirstName"].Value = firstName;
    etc...
    e.Command.Parameters["@ClientContactID"].Value = clientContactID;

    e.Command.Connection.Open();
    e.Command.ExecuteNonQuery();
    e.Command.Connection.Close();
}

This is where I finally got to in order to stop getting errors on the SQL execution, however there's one major problem: the values being pushed onto the parameters are the old values, the ones that were already in the database, not the values I've entered in the EditFormItem. If I hardcode something onto a parameter (eg, append ".com" onto email), the alteration is correctly reflected in both the database and the table after the "Save" button in the edit form is clicked. Without the manual edit, no changes occur, because the database is simply being updated with the values that were already present.

How can I get the current values in the edit form?
(I'm not opposed to getting this done in some way other than the DataSource_Updating event, that's just the solution I came up with which was closest to correct. I do need to stick with the RadGrid, though.)
Answer: I managed to find a resolution to this issue. In the first part of  ContactsSqlDataSource_Updating, I now have:
string salutation = (editItem.FindControl("SalutationTextBox") as TextBox).Text;
string firstName = (editItem.FindControl("FirstNameTextBox") as TextBox).Text;
etc...
string clientContactID = (editItem.FindControl("ClientIDHiddenField") as HiddenField).Value;

The database now updates correctly.


Is the converse of the first Hilbert-Bernays Derivability Condition true?

Question: The first Hilbert-Bernays Derivability Condition is (⊢P) → (⊢◻P). What I'd like to know is, is the converse true? That is, is (⊢◻P) → (⊢P) valid?
I know from Löb's Theorem that ⊢(◻P → P) is not valid in general (and when it is, it suffices to prove P), but I'd like to know whether it's also true that (⊢◻P) → (⊢P) isn't valid in general.
Answer: There are some unclear aspects to the question, so I'll make the following plausible assumptions: (1) You use both "true" and "valid" to mean the same thing, namely "true in the standard model of arithmetic". (2) $\square$ refers to a formalization of provability in the same theory, say $T$, that $\vdash$ refers to. (3) $T$ is a recursively enumerable theory, and its formalization is done straightforwardly (not with any Feferman-style tricks).
Under these assumptions, if $T$ is true (or even just $\Sigma^0_1$-correct), for example, if $T$ is Peano atrithmetic (PA), then $\vdash\square P$ does imply $\vdash P$, simply because "$P$ is provable" is a $\Sigma^0_1$ statement, so if $T$ proves it then it must be true.
On the other hand, if we merely assume that $T$ is consistent, then we might well have $\vdash\square P$ but not $\vdash P$.  For example, let $T$ be PA plus the sentence formalizing "PA is inconsistent". This $T$ is consistent, by the second incompleteness theorem.  But it proves that $\square(0=1)$ (i.e., it proves its own inconsistency) without also proving $0=1$ (i.e., without actually being inconsistent).
Comment: Can you explain or point me to some sources explaining what $\Sigma^0_1$ means?
Comment: @Trismegistos $\Sigma^0_1$ formulas (in the language of first-order arithmetic) are the formulas obtainable from atomic formulas and their negations by the connectives $\land$ and $\lor$, existential quantification $(\exists x)$, and *bounded* universal quantification $(\forall x<y)$.
Comment: I have a question. Let $T$ be PA. If $T \vdash \square P$ implies $T \vdash P$, then by deduction theorem, $T \vdash \square P \rightarrow P$, and thus $T \vdash \lnot P \rightarrow \lnot \square P$. Now if $P := 0 = 1$, then $T \vdash 0 \neq 1 \rightarrow \lnot \square (0 = 1)$, and since $T \vdash 0 \neq 1$, we have $T \vdash \lnot \square (0 = 1)$. Thus, $T$ proves its own consistency. Doesn't this violate Gödel's second incompleteness theorem?
Comment: I just realised an error in my argument. Deduction theorem does not guarantee $T \vdash \square P \rightarrow P$. I'll leave my original comment in case future readers fall into the same logical fallacy as me.


amchart Trend Lines change theme

Question: I have sum issues with Trend Lines chart.
when change chart.theme , it does not affect (chart.theme="patterns";)
please help me.
this is my sample.
<code>[http://jsfiddle.net/qncgx096/1/]
</code>
Answer: if you use API-fashioned way to create you chart you need to initiate the chart instance with the theme like following:
<code>chart = new AmCharts.AmSerialChart(AmCharts.themes.patterns);
</code>
Ensure you don't overwrite these default settings with your graph settings like you are currently doing it in your fiddle.

amchart Trend Lines change theme


Keeping TOC layers unchecked on first load in ArcGIS JavaScript API

Question: I am using NLiu's TOC widget for displaying the layers. It is working perfectly, however, I wanted to keep all layers unchecked when it is loading on the browser (for performance reason). I tried to find a way on its javascript files but not succeed.
Any clue to do so?
Answer: Set the layer's visible layers to none:
<code>layer.setVisibleLayers([])
</code>


Profile2 template for profile type?

Question: I have alredy created profile2 type with machine name "user" and now i would to overide template, can someone explain me how i have to name my new tpl? i ve copied existing, and tried some rename variants, but i didnt find solution.
In google i didnt find solution too.
Here is link for module https://drupal.org/project/profile2
Answer: To theme a custom template for profile2, try the following:

copy profile2.tpl.php from your module folder, to your theme's template folder
rename the file profile2--machine_name.tpl.php (profile2--user.tpl.php)
adjust the template as desired
clear the cache
Comment: I tried this variant before question, but now i found my problem. Profile machine name cant "user", becouse on this machine name doesnt work any tpl (aslo globaly profile2.tpl,php).

Profile2 template for profile type?


using wysiwyg Editor text with angular2

Question: I'm trying to use wysiwyg in my project angular2
when I add my code in index.html page (on the root page, it works)
but when I try to use it in a child view html it doesn't get the css or (and) javascript code to get my wysiwyg correctly
<!doctype>

    <base href="/">
    <title>Arkloud Adservio</title>
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0"/>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
          integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
          integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

    <link rel="stylesheet" href="src/css/app.css">
    <link rel="stylesheet" href="src/css/loginCss.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="/css/froala_editor.css">
    <link rel="stylesheet" href="/css/froala_style.css">
    <link rel="stylesheet" href="/css/plugins/code_view.css">
    <link rel="stylesheet" href="/css/plugins/colors.css">
    <link rel="stylesheet" href="/css/plugins/emoticons.css">
    <link rel="stylesheet" href="/css/plugins/image_manager.css">
    <link rel="stylesheet" href="/css/plugins/image.css">
    <link rel="stylesheet" href="/css/plugins/line_breaker.css">
    <link rel="stylesheet" href="/css/plugins/table.css">
    <link rel="stylesheet" href="/css/plugins/char_counter.css">
    <link rel="stylesheet" href="/css/plugins/video.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.3.0/codemirror.min.css">

<my-app>Loading...</my-app>

    <form>
      <textarea id='edit' style="margin-top: 30px;" placeholder="Type some text">

Textarea

The editor can also be initialized on a textarea.

      </textarea>

        <input type="submit">
    </form>

in this case it works (I put my wysiwyg in my index.html)
but when i put this on another view component it doesn't work

        <form>
          <textarea id='edit' style="margin-top: 30px;" placeholder="Type some text">

Textarea

The editor can also be initialized on a textarea.

          </textarea>

            <input type="submit">
        </form>

Answer: I agree with @mayur to use angular2 and tinyMCE.
If you need more guidance on the HOW based on @mayur's answer:
directives/tiny.directive.ts:
import {Directive} from '@angular/core';
declare var tinymce: any;
// Tinymce directive
@Directive({
    inputs: ['htmlEditor'],
    selector: '[htmlEditor]'
    })

export class EditorDirective{
    constructor(){
        tinymce.init({
            selector: 'textarea', //change this to a specific class/id
            schema: 'html5',
        });
    }
}

app.component.ts:
import { Component } from '@angular/core';
import {EditorDirective} from './directives/tiny.directive';

@Component({
    selector: 'my-app',
    directives: [EditorDirective],
    templateUrl: '<textarea [htmlEditor]></textarea>'    //having [htmlEditor]="Form.find('Text')" caused an error for me, your mileage may vary
    })
export class AppComponent {

}

main.ts:
import { bootstrap }    from '@angular/platform-browser-dynamic';
import { AppComponent  } from './app.component';
bootstrap(AppComponent);

index.html:

        <my-app>Loading...</my-app>

hope this helps
Comment: This is not working on router pages. what we need to do for router pages ?
Comment: Wouldn't the app module need to have the directive imported?
Comment: I haven't updated this since Angular 2 official release; will try get back to it at some point!
The biggest change would be as @Jon said, the app module needing to import the directive instead of in the component.
Comment: EditorDirective should be present in declarations in app.module.ts @chris.currin
Comment: Is this module compatible with AOT compilation ? There are no d.ts files for typescript. Have you built with AOT ?
Answer: https://www.tinymce.com/
If angular 2 Use Tinymce .. Why tinymce?
 //.ts
 import {EditorDirectory} from '/../directives';
 @Component({
 selector: 'Foo'
 directives: [EditorDirectory],
 template: '<textarea [htmlEditor]="Form.find('Text')"></textarea>'
 })

 // Tinymce directive
 @Directive({
 inputs: ['htmlEditor'],
 selector: '[htmlEditor]'
 })

 tinymce.init({
    selector: '.tinymce-editor',
    schema: 'html5',
  });

Index.html

Remaining can read from Tinymce
Comment: In package.json angular file add in dependencies // "dependencies": {"tinymce": "4.3.12"} }, and then in terminal add npm install tinymce
Comment: I download tinymce then i should add files within my project !
How to get tinymce ?
Comment: How to use this after angular 2 official release? @mayur
Answer: Here is the full explanation with steps.

Install:
npm install --save tinymce

In file give the path for tinymce script files
"scripts": [
    "../node_modules/tinymce/tinymce.js",
    "../node_modules/tinymce/themes/modern/theme.js",
    "../node_modules/tinymce/plugins/link/plugin.js",
    "../node_modules/tinymce/plugins/paste/plugin.js",
    "../node_modules/tinymce/plugins/table/plugin.js"
 ],

Run the following command it will copy the styles inside the assests folder.
xcopy /I /E node_modules\tinymce\skins src\assets\skins

Create directive for tinymce so it will be used anywhere in the application.
 import { Directive,
      EventEmitter,
      Input,
      Output, ElementRef,OnInit,
      AfterViewInit,  OnDestroy } from '@angular/core';

    declare var tinymce:any

    @Directive({
      selector: '[htmlEditor]'
    })
    export class SimpleTinyMceDirective implements OnInit,OnDestroy{

      private htmlContent:any;
      private editor;
      @Output() private htmlEditorKeyUp : EventEmitter<any> = new EventEmitter();

      constructor(private el:ElementRef){

      }

      ngOnInit(){
         tinymce.init({
          selector: '#' + this.el.nativeElement.id,
          plugins: ['link', 'paste', 'table'],
          skin_url: 'assets/skins/lightgray',
          setup: editor => {
            this.editor = editor;
            editor.on('keyup', () => {
              const content = editor.getContent();
              this.htmlEditorKeyUp.emit(content);
            });
          },
        });
      }

      ngOnDestroy() {
        tinymce.remove(this.editor);
      }
    }

save it as simple-tinymce.directive.ts
Now inside the app.module.ts file
import * as tinymce from 'tinymce'; //"importing tinymce"
import {SimpleTinyMceDirective} from './common/simple-tinymce/simple-tinymce.directive'; //import the directive your path of directive may be different than mine.

You can use like below inside the component template
<textarea  id="description" class="form-control" name="description" placeholder="Enter the description" required [(ngModel)]='description' #description='ngModel'
    (htmlEditorKeyUp)="onHtmlEditorKeyUp($event)" htmlEditor></textarea>

You can fetch inside the component.ts like below
onHtmlEditorKeyUp(content:any):void{
    console.log(content);
}

Answer: I followed the answers but i couldn't get this working, maybe because i'm using routing and the dom element where to apply the directive is not already available. I just moved the tinymce.init code from the constructor to the ngOnInit function and now it works as expected:
directives/tiny.directive.ts:
import {Directive, OnInit} from '@angular/core';
declare var tinymce: any;

// Tinymce directive
@Directive({
    inputs: ['htmlEditor'],
    selector: '[htmlEditor]'
})
export class EditorDirective implements OnInit { }

ngOnInit(){
    tinymce.init({
        selector: 'textarea', //change this to a specific class/id
        schema: 'html5',
    });
}

using wysiwyg Editor text with angular2


Smooth Animation with Python Turtle Graphics and Stamps

Question: Is it possible to get a smoother animation effect using Turtle Graphics and the stamp() method than what the code below gives?
One attempt I made was to only clear the first stamp using stamper.clearstamps(1) inside move_blocks, and to only draw the new block each time, but the result looked the same. I think the problem might be that stamping calls Screen.update() in the background, although I haven't confirmed this.
import turtle

def move_blocks():
    stamper.clearstamps()
    new_block = blocks[-1].copy()
    new_block[0] += 20
    if new_block[0] > 250:
        new_block[0] = - 250
    blocks.append(new_block)
    blocks.pop(0)

    for block in blocks:
        stamper.goto(block[0], block[1])
        stamper.stamp()

    screen.update()
    turtle.ontimer(move_blocks, 100)

screen = turtle.Screen()
screen.setup(500, 500)
screen.tracer(0)  # Turn off automatic animation

stamper = turtle.Turtle("square")
stamper.penup()

blocks = [[0, 0], [20, 0], [40, 0], [60, 0]]

for block in blocks:
    stamper.goto(block[0], block[1])
    stamper.stamp()

move_blocks()
turtle.done()

Any help much appreciated.
Answer:
I think the problem might be that stamping calls Screen.update() in
the background, although I haven't confirmed this.

This appears to be true, and is easily confirmed, but not necessarily the whole problem.  Below is my rework of your code to optimize it by removing only the defunct stamp ID, but it looks no better than yours.  You can see I've commented out screen.update() which makes no difference:
from turtle import Screen, Turtle

def move_blocks():
    new_block = blocks.pop(0)
    new_block[0] = blocks[-1][0] + 20

    if new_block[0] > 250:
        new_block[0] = -250

    blocks.append(new_block)

    stamper.goto(new_block)
    stamper.clearstamp(ids.pop(0))
    ids.append(stamper.stamp())

    # screen.update()
    screen.ontimer(move_blocks, 100)

screen = Screen()
screen.setup(500, 500)
screen.tracer(0)  # Turn off automatic animation

stamper = Turtle('square')
stamper.hideturtle()
stamper.penup()

blocks = [[0, 0], [20, 0], [40, 0], [60, 0]]
ids = []

for block in blocks:
    stamper.goto(block)
    ids.append(stamper.stamp())

# screen.update()

move_blocks()

screen.exitonclick()

Trying to be clever, I wanted to do a comparison of drawing vs. stamping but the result is the same, the fill operations trigger a screen.update() and get us right back where we started:
from turtle import Screen, Turtle

CURSOR_SIZE = 20

def move_blocks():
    filler.clear()

    new_block = blocks.pop(0)
    new_block[0] = blocks[-1][0] + 20

    if new_block[0] > 250:
        new_block[0] = -250

    blocks.append(new_block)

    for block in blocks:
        fill(block)

    # screen.update()
    screen.ontimer(move_blocks, 100)

def fill(position):
    filler.goto(position)

    filler.begin_fill()
    for _ in range(4):
        filler.forward(CURSOR_SIZE)
        filler.left(90)
    filler.end_fill()

screen = Screen()
screen.setup(500, 500)
screen.tracer(0)  # Turn off automatic animation

filler = Turtle()
filler.hideturtle()
filler.penup()

blocks = [[0, 0], [20, 0], [40, 0], [60, 0]]

for block in blocks:
    fill(block)

# screen.update()

move_blocks()

screen.exitonclick()

Finally, I did an implementation that is under the control of tracer() and programmer initiated screen.update() calls.  I simply reshape the cursor and move it for comparison purposes.  You can see the difference when screen.update() is commented out this time.
from turtle import Screen, Turtle

CURSOR_SIZE = 20
CURSOR_LENGTH = 80
STEP_SIZE = 1

def move():
    x = turtle.xcor() + STEP_SIZE

    if x - CURSOR_LENGTH/2 > 250:
        turtle.setx(-250 - CURSOR_LENGTH/2)
    else:
        turtle.forward(STEP_SIZE)

    screen.update()
    screen.ontimer(move, 5 * STEP_SIZE)

screen = Screen()
screen.setup(500, 500)
screen.tracer(0)  # Turn off automatic animation

turtle = Turtle()
turtle.shape('square')
turtle.shapesize(stretch_len=CURSOR_LENGTH/CURSOR_SIZE)
turtle.penup()

screen.update()

move()

screen.exitonclick()

However, this implementation points out that the earlier poor visual performance is also due to a large step size -- if you change STEPSIZE = CURSOR_SIZE, then you have the same step size, and the same performance, as your original.
Comment: Thanks for this. I'd love to know more about your interest in Turtle Graphics - you seem to be a true aficionado and maestro, which is quite rare. do you have any books, blogs,  repos etc. please?


$p_1+\cdots+p_k=1$, can those be written as rational numbers $p_1=n_1/m,~p_2=n_2/m,~\ldots,~p_k=n_k/m$?

Question: I'm now thinking about a question that:

If $0<p_1,~p_2,~\ldots,~p_k<1$(further assume these $p_i$ are rational numbers) and $p_1+\cdots+p_k=1$, then there exists
  $m\in\Bbb Z$ and $n_1,~\ldots,~n_k\in\Bbb Z$ such that
  $p_1=n_1/m,~p_2=n_2/m,~\ldots,~p_k=n_k/m$?

Is it true or false? How to prove this?
Comment: You are assuming that the $p_i$ are rational? Are you in effect asking whether a finite number of rationals can be put over a common denominator?
Comment: @LordSharktheUnknown Yes, $p_i$ are rational. Yes, you're right.
Answer:
If $0<p_1,~p_2,~\cdots,~p_k<1$ (...) and $p_1+...+p_k=1$

Neither of these conditions is necessary.

assume these $p_i$ are rational numbers (...)
   then there exists
  $m\in\Bbb Z$ and $n_1,~\cdots,~n_k\in\Bbb Z$ such that
  $p_1=n_1/m,~p_2=n_2/m,~\cdots,~p_k=n_k/m$?

Yes. Let $\,p_i = a_i / b_i\,$ in irreducible form, then take for example $\,m=\operatorname{lcm} \,\{b_i \mid i=1,2,\cdots,k\}\,$ and $\,n_i = a_i m / b_i\,$, where $\,n_i \in \mathbb{Z}\,$ because $\,b_i \mid m\,$. The representation is not unique unless you add more conditions, such as $\,\gcd \,\{n_i \mid i=1,2,\cdots,k\}=1\,$.
Answer: Let $p_i = \frac{n_i}{m_i}$ for $i = 1 \dots k$, multiply by $\frac{\prod_{j \neq i,j=1}^k m_j}{\prod_{j \neq i,j=1}^k m_j} = \frac{m_1 \dots m_{i-1} m_{i+1} \dots m_k}{m_1 \dots m_{i-1} m_{i+1} \dots m_k}$ so that $$p_i = n_i \frac{\prod_{j \neq i,j=1}^k m_j}{\prod_{j=1}^k m_j} =  1 - \sum_{j \neq i}^k p_j = \frac{r_i}{m}$$
where $$m = \prod_{j=1}^k m_j = m_1 \dots m_k, \qquad r_i = \prod_{j=1}^k m_j - \sum_{j \neq i}^k n_j \prod_{l \neq j,l=1}^k m_l$$


how to parse data in yaml from column to row

Question: My final data after parsing from a yaml file is like this in text file :
        - id: 200
          addr: 10.242.57.129/27
        - id: 210
          addr: 10.242.57.161/25
        - id: 300
          addr: 10.244.26.1/24

I wanted to convert to this and save it as txt with shell scripting ( bash):
200,10.242.57.125,27
210,10.242.57.162,25
300,10.244.26.11,24

Can anyone help for that?
Need to get the command shell for this (with awk, grep , sed , ...).
I used the following code but it doesn't work:
grep -F -e "id:" | cut -c 14-16 -e "addr:" | cut -c 16-35 ip.txt | paste -d , - -

Answer: Given that the question is also tagged powershell, let me offer a native PowerShell solution that uses the switch statement, whose features resemble that of awk:
switch -Regex -File file.txt {
  '\bid: (\d+)'            { $id = $Matches.1  }
  '\baddr: ([\d.]+)/(\d+)' { '{0},{1},{2}' -f $id, $Matches.1, $Matches.2  }
}

The automatic $Matches variable is used to access what the branch-conditional regexes matched.

The -f operator is used to format the output strings.
Answer: Using GNU sed
$ sed -E '/-/{N;s~[^0-9]*([0-9]+)\n[^0-9]*([0-9.]+)/([0-9]+)~\1,\2,\3~}' input_file
200,10.242.57.129,27
210,10.242.57.161,25
300,10.244.26.1,24

Answer: This might work for you (GNU sed):
sed 'N;s/[^0-9.\n/]//g;y/\n\//,,/' file

Append the next line.
Remove all but id and address.
Replace the newline and / with ,'s.


Como aplicar regex , utilizando C# em um arquivo pdf?

Question: <code>    private static string BuscaComparacao (string url)
        {
            Regex r =new Regex("\S+\D{3}[.]\D{3}\S+\D)";
        var result = r.Matches(url);
        return result[0].ToString();

        }
</code>
o codigo nao encontra os dados q eu mandei buscar.
Comment: Deixa eu ver se entendi, você está passando uma URL para o método. Certo?
Comment: Que informação está a ser pesquisada? Precisa detalhar mais a sua questão.
Comment: a expressao regular ta certa, mas ele diz que Message = "analisando \"\\s+\\d{3}[.]\\d{3}\\s+\\d)\" - Número excessivo de )'s."
Comment: Não lhe falta um parêntesis no início da expressão? _new Regex("(\S+\D{3}[.]\D{3}\S+\D)"_? Ou o parêntesis no fim está a mais?
Comment: sim, corrigi, mas nao ta retornando nada, sera que ta dando erro por ser enviada a url de um pdf
Comment: O que pretende obter com a expressão regular?
Comment: 042.964 3 (unidade concendente e codigo verificador)
Comment: isto C:\\AnexosEmail\\26342018013427.pdf
Comment: agora esta saindo dando a execção Message = "Argumento especificado estava fora do intervalo de valores válidos.\r\nNome do parâmetro: i" seria por que ele precisa do iis pra ler o pdf?
Comment: Sendo um caminho para um ficheiro, o que pretende com a expressão regular? Obter o nome do ficheiro? Da pasta?
Comment: obter um dado dentro do arquivo
Comment: @mateusandrade Isso é impossível. O que você está fazendo é aplicar a regex ao texto `C:\\AnexosEmail\\26342018013427.pdf`
Comment: teria que converter o pdf pra texto primeiro?
Comment: Para isso terá que utilizar uma biblioteca externa, do tipo **Docotip.pdf** ou **ITextSharp**. Da forma que está a fazer apenas está a aplicar a expressão regular no URL em si e não dentro do ficheiro.
Comment: Utilize esta biblioteca, é de fácil uso e aí depois já poderá pesquisar no texto o que precisa. https://www.codeproject.com/Articles/14170/Extract-Text-from-PDF-in-C-100-NET
Answer: Resolvido da seguinte forma
<code>PdfReader reader = new PdfReader(arquivo);
var page = PdfTextExtractor.GetTextFromPage(reader,1);
var exp = @"\s+\d{3}[.]\d{3}\s+\d";
Regex r =new Regex(exp);
var result = r.Matches(page);
return result[0].ToString();
</code>
obrigado @joaomartins


Proof that spanning set is greater than linearly independent subset

Question: Let G be a set that generates V containing n vectors and H be a linearly independent subset of V containing m vectors. Prove that $m \le n$.
My attempt:
We will use a proof by induction with base case $m=0$.
$m=0$ implies that $H =∅$ and since m cannot be less than $0$, $m \le n$.

Our induction hypothesis is that the theorem holds for some $n>0$. We need to show that it holds for $m+1$, ie. $m+1 \le n$.

Suppose the opposite, that $m+1 \ge n$ $\implies m>n$ which cannot be true but I am not sure how to prove it.
Any help is appreciated!
Answer: If $G = \{ v_1, \cdots, v_n\}$ generates $V$, then $n \geq\dim V $ by the definitions of basis and dimension. If $H = \{w_1, \cdots, w_m \}$ has $m$ linearly independent vectors, again by the definitions of basis and dimension we have $m \leq \dim V$. So $m \leq \dim V \leq n$, as we wanted to prove.
Comment: If I am correct, I think this fact is used in proving the definition of a basis as a least linear independent subset so this would be a cyclical proof.


How to encode Chinese text in QR barcodes generated with iTextSharp?

Question: I'm trying to draw QR barcodes in a PDF file using iTextSharp. If I'm using English text the barcodes are fine, they are decoded properly, but if I'm using Chinese text, the barcode is decoded as question marks. For example this character '测' (\u6D4B) is decoded as '?'. I tried all supported character sets, but none of them helped.
What combination of parameters should I use for the QR barcode in iTextSharp in order to encode correctly Chinese text?
Comment: you may try using different font as in [link](http://kuujinbo.info/cs/itext_cjk.aspx) and use [this](http://sourceforge.net/project/shownotes.php?group_id=72954&release_id=368247) font
Comment: I'm not trying to draw Chinese text, I'm trying to encode Chinese text in a QR barcode.
Answer: iText and iTextSharp apparently don't natively support this but you can write some code to handle this on your own. The trick is to get the QR code parser to work with just an arbitrary byte array instead of a string. What's really nice is that the iTextSharp code is almost ready for this but doesn't expose the functionality. Unfortunately many of the required classes are sealed so you can't just subclass them, you'll have to recreate them. You can either download the entire source and add these changes or just create separate classes with the same names. (Please check over the license to make sure you are allowed to do this.) My changes below don't have any error correction so make sure you do that, too.
The first class that you'll need to recreate is iTextSharp.text.pdf.qrcode.BlockPair and the only change you'll need to make is to make the constructor public instead of internal. (You only need to do this if you are creating your own code and not modifying the existing code.)
The second class is iTextSharp.text.pdf.qrcode.Encoder. This is where we'll make the most changes. Add an overload to Append8BitBytes that looks like this:
static void Append8BitBytes(byte[] bytes, BitVector bits) {
    for (int i = 0; i < bytes.Length; ++i) {
        bits.AppendBits(bytes[i], 8);
    }
}

The string version of this method converts text to a byte array and then uses the above so we're just cutting out the middle man. Next, add a new overload to the constructor that takes in a byte array instead of a string. We'll then just cut out the string detection part and force the system to byte-mode, otherwise the code below is pretty much the same.
    public static void Encode(byte[] bytes, ErrorCorrectionLevel ecLevel, IDictionary<EncodeHintType, Object> hints, QRCode qrCode) {
        String encoding = DEFAULT_BYTE_MODE_ENCODING;

        // Step 1: Choose the mode (encoding).
        Mode mode = Mode.BYTE;

        // Step 2: Append "bytes" into "dataBits" in appropriate encoding.
        BitVector dataBits = new BitVector();
        Append8BitBytes(bytes, dataBits);

        // Step 3: Initialize QR code that can contain "dataBits".
        int numInputBytes = dataBits.SizeInBytes();
        InitQRCode(numInputBytes, ecLevel, mode, qrCode);

        // Step 4: Build another bit vector that contains header and data.
        BitVector headerAndDataBits = new BitVector();

        // Step 4.5: Append ECI message if applicable
        if (mode == Mode.BYTE && !DEFAULT_BYTE_MODE_ENCODING.Equals(encoding)) {
            CharacterSetECI eci = CharacterSetECI.GetCharacterSetECIByName(encoding);
            if (eci != null) {
                AppendECI(eci, headerAndDataBits);
            }
        }

        AppendModeInfo(mode, headerAndDataBits);

        int numLetters = dataBits.SizeInBytes();
        AppendLengthInfo(numLetters, qrCode.GetVersion(), mode, headerAndDataBits);
        headerAndDataBits.AppendBitVector(dataBits);

        // Step 5: Terminate the bits properly.
        TerminateBits(qrCode.GetNumDataBytes(), headerAndDataBits);

        // Step 6: Interleave data bits with error correction code.
        BitVector finalBits = new BitVector();
        InterleaveWithECBytes(headerAndDataBits, qrCode.GetNumTotalBytes(), qrCode.GetNumDataBytes(),
            qrCode.GetNumRSBlocks(), finalBits);

        // Step 7: Choose the mask pattern and set to "qrCode".
        ByteMatrix matrix = new ByteMatrix(qrCode.GetMatrixWidth(), qrCode.GetMatrixWidth());
        qrCode.SetMaskPattern(ChooseMaskPattern(finalBits, qrCode.GetECLevel(), qrCode.GetVersion(),
            matrix));

        // Step 8.  Build the matrix and set it to "qrCode".
        MatrixUtil.BuildMatrix(finalBits, qrCode.GetECLevel(), qrCode.GetVersion(),
            qrCode.GetMaskPattern(), matrix);
        qrCode.SetMatrix(matrix);
        // Step 9.  Make sure we have a valid QR Code.
        if (!qrCode.IsValid()) {
            throw new WriterException("Invalid QR code: " + qrCode.ToString());
        }
    }

The third class is iTextSharp.text.pdf.qrcode.QRCodeWriter and once again we just need to add an overloaded Encode method supports a byte array and that calls are new constructor created above:
    public ByteMatrix Encode(byte[] bytes, int width, int height, IDictionary<EncodeHintType, Object> hints) {
        ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L;
        if (hints != null && hints.ContainsKey(EncodeHintType.ERROR_CORRECTION))
            errorCorrectionLevel = (ErrorCorrectionLevel)hints[EncodeHintType.ERROR_CORRECTION];

        QRCode code = new QRCode();
        Encoder.Encode(bytes, errorCorrectionLevel, hints, code);
        return RenderResult(code, width, height);
    }

The last class is iTextSharp.text.pdf.BarcodeQRCode which we once again add our new constructor overload:
    public BarcodeQRCode(byte[] bytes, int width, int height, IDictionary<EncodeHintType, Object> hints) {
        newCode.QRCodeWriter qc = new newCode.QRCodeWriter();
        bm = qc.Encode(bytes, width, height, hints);
    }

The last trick is to make sure when calling this that you include the byte order mark (BOM) so that decoders know to decode this properly, in this case UTF-8.
//Create an encoder that supports outputting a BOM
System.Text.Encoding enc = new System.Text.UTF8Encoding(true, true);

//Get the BOM
byte[] bom = enc.GetPreamble();

//Get the raw bytes for the string
byte[] bytes = enc.GetBytes("测");

//Combine the byte arrays
byte[] final = new byte[bom.Length + bytes.Length];
System.Buffer.BlockCopy(bom, 0, final, 0, bom.Length);
System.Buffer.BlockCopy(bytes, 0, final, bom.Length, bytes.Length);

//Create are barcode using our new constructor
var q = new BarcodeQRCode(final, 100, 100, null);

//Add it to the document
doc.Add(q.GetImage());

Answer: Looks like you may be out of luck. I tried too and got the same results as you did. Then looked at the Java API:

"*CHARACTER_SET the values are strings and can be Cp437, Shift_JIS and
  ISO-8859-1 to ISO-8859-16. The default value is ISO-8859-1.*"

Lastly, looked at the iTextSharp BarcodeQRCode class source code to confirm that only those characters sets are supported. I'm by no means an authority on Unicode or encoding, but according to ISO/IEC 8859, the character sets above won't work for Chinese.
Answer: Essentially the same trick that Chris has done in his answer could be implemented by specifying UTF-8 charset in barcode hints.
var hints = new Dictionary<EncodeHintType, Object>() {{EncodeHintType.CHARACTER_SET, "UTF-8"}};
var q = new BarcodeQRCode("\u6D4B", 100, 100, hints);

If you want to be more safe, you can start your string with BOM character '\uFEFF', like Chris suggested, so it would be "\uFEFF\u6D4B".
UTF-8 is unfortunately not supported by QR codes specification, and there are a lot of discussions on this subject, but the fact is that most QR code readers will correctly read the code created by this method.


Add custom config to ckeditor

Question: I'd like to customise the CKEditor config, by using the removePlugins setting to disable the elementspath plugin, so that body p etc. isn't displayed in the status bar (here's a similar, old question for D7).
I created the following CKEditor plugin, which returns an additional setting via the getConfig() method.  It has no effect on my editor fields (I've verified the plugin ID is being matched).
What's the right approach - if not this - for a config change, given I'm not loading a new plugin JS file or adding buttons?
<?php

/**
 * @file
 * Definition of \Drupal\ckeditor_remove_elementspath\Plugin\CKEditorPlugin\RemoveElementsPath
 */

namespace Drupal\ckeditor_remove_elementspath\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginInterface;
use Drupal\Component\Plugin\PluginBase;
use Drupal\editor\Entity\Editor;

/**
 * Defines the "Remove Elements Path" plugin.
 *
 * @CKEditorPlugin(
 *   id = "remove_elements_path",
 *   label = @Translation("Remove elements path"),
 *   module = "ckeditor_remove_elementspath"
 * )
 */
class RemoveElementsPath extends Pluginbase implements CKEditorPluginInterface {

  /**
   * {@inheritdoc}
   */
  function getDependencies(Editor $editor) {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  function getLibraries(Editor $editor) {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function isInternal() {
    return false;
  }

  /**
   * {@inheritdoc}
   */
  public function getFile() {
    return false;
  }

  /**
   * {@inheritdoc}
   */
  public function getButtons() {
    return [ ];
  }

  public function getConfig(Editor $editor) {
    return [
      'removePlugins' => 'elementspath',
    ];
  }

}

Answer: I had a look at the CKEditor API docs and the other classes I might extend - it didn't seem to be any of:

CKEditorPluginButtonsInterface
CKEditorPluginContextualInterface
CKEditorPluginCssInterface

…though perhaps CKEditorPluginConfigurableInterface, if I wanted to configure the settings form per text format?
Then, I found a module called ckeditor_config, so I adapted it's plugin class, which extends CKEditorPlugin/Internal:
/**
 * @file
 * Definition of \Drupal\ckeditor_remove_elementspath\Plugin\CKEditorPlugin\RemoveElementsPath
 */

namespace Drupal\ckeditor_remove_elementspath\Plugin\CKEditorPlugin;

use Drupal\ckeditor\Plugin\CKEditorPlugin\Internal;
use Drupal\editor\Entity\Editor;

/**
 * Defines the "Remove Elements Path" plugin.
 *
 * @CKEditorPlugin(
 *   id = "remove_elements_path",
 *   label = @Translation("Remove elements path from CKEditor status bar")
 * )
 */
class RemoveElementsPath extends Internal {

  /**
   * {@inheritdoc}
   */
  public function getConfig(Editor $editor) {
    // Get default config.
    $config = parent::getConfig($editor);

    $config['removePlugins'] = 'elementspath';

    return $config;
  }

}

Edit: And here's my module if anyone finds it useful.

Add custom config to ckeditor


Attaching random string from an array to a button

Question: I am trying to make a random string from an array in my strings.xml file to appear on a random button in a linear layout.  I inflate the button, choose a random string from my file, and them attach the random string to the button, then repeat for three buttons.  everything works fine, I can see that it is attaching random strings every time, but the problem is that the button displays the name that I would use to refer to the string, not the strings actual value.  For example if I have a string with a name of: string and value of: "Hello World", it just displays "string" as my button text.
    private void loadButtons()
    {
<code>   LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

   for (int row = 0; row < guessRows; row++)
   {
         random = new Random();
         Resources res = getResources();

         String[] truthString = res.getStringArray(R.array.truthArray);
         String truth = truthString[random.nextInt(truthString.length)];

         Button newGuessButton = (Button) inflater.inflate(R.layout.guess_button, null);

         newGuessButton.setText(truth);

         buttonLayout.addView(newGuessButton);

   }
</code>
Comment: What you have tried? Show us some code.
Comment: Show the code! Looks like a resource problem
Answer: Are you sure you're setting the string array correctly? Individual strings in an array shouldn't have name tags, the only name should be the array name. See the docs, and make sure you're declaring it properly.
Comment: oh I see, originally I had a ton of strings, and I thought that by adding them to the array I just had to use the item and the name of the string already made, but where I was entering the name, I needed to enter a new value.


"{...} is not a function" although never called as a function

Question: If I create a JSON object immediately before an anonymous function call, I get TypeError: ({x:0, y:0}) is not a function in Firefox, or Uncaught TypeError: {(intermediate value)(intermediate value)} is not a function in Chrome.
However, I never called a as a function. Also, when I put a semicolon after the object definition, this error does not occur.
According to http://inimino.org/~inimino/blog/javascript_semicolons I don't see why I would, in theory, need a semicolon there. However, for some reason it is still required. Why?

let a = { x: 0, y: 0 }

(() => {
    console.log('test')
})()
Comment: Just always use semicolons. You just gave a good example why you shouldn't omit them.
Comment: Specifically, that guide states _"In front of a leading ( or [ at the start of the line. This prevents the expression from being interpreted as a function call or property access, respectively."_ which is the situation you have right here. The opening paren causes the interpreter to read it as a function call.
Comment: @benni: i guess you missed one of the cars where you did always use them: "In front of a leading ( or [ at the start of the line. This prevents the expression from being interpreted as a function call or property access, respectively."
Comment: it cannot be emphasized enough. always use semicolons!!!!!
Comment: @Benni this is a situation when it would be considered "necessary" anyway just always use them
Comment: I'm usually following the NPM coding style (https://docs.npmjs.com/misc/coding-style.html), which explicitly states that I should never use semicolons except necessary. Also, even if I decided that I'm going to use them in the future, I would love to know, why the interpreter does not like what I did.
Answer: As other's have said, the two statements are being read as a single, non-sensical statement. My peeve here is that no-one has properly answered why this happens here and not in other cases.
You quote the NPM style guide here: https://docs.npmjs.com/misc/coding-style.html
It says

In front of a leading ( or [ at the start of the line. This prevents the expression from being interpreted as a function call or property access, respectively.

So your issue is because the second statement starts with ( or [, and this confuses the parser. In these cases a semi-colon is needed. Why would the parser be confused by ( or [? Because for instance { x: 0, y: 0}["x"] would be valid code. And the same for { x: 0, y: 0}(), it's perfectly valid, it will just crash. But the parser cannot know if it makes sense or not, it has to apply the same rules everywhere.
Note that the npm style guide then says to put the semi-colon on the line with the ( in cases like this. So you would write:
let a = { x: 0, y: 0 }

;(() => { // semi-colon at start of this line
    console.log('test')
})()

The reason for this is that if you were to put it after the first statement and later edit your code, you would re-introduce the problem. For instance end up like this:
let a = { x: 0, y: 0 };

let b = { x: 1, y: 1 }

(() => { // this will fail
    console.log('test')
})()

Answer: You haven't terminated your assignment to x, so the engine is seeing you call a function:
// Wrong:
let {x: 0, y:}()();

You should use semi-colon to terminate:

let a = { x: 0, y: 0 }; // terminate this line with a semi-colon ;

(() => {
    console.log('test')
})()

The reason why is, without the semi-colon, the two statements will be read as one,
 in turn making no sense.
Comment: @Matsemann was this meant to be on the other answer - this one actually explains the need for the semi colon as was the question by the OP and I don't see how it should be closed as a typo when OP is specifically asking about why there is the need for the colon
Comment: @Matsemann Excuse me? "rep farming"..? You might think and work that way, but i don't. It not simply a typo error - if you bother to read OPs question - it is _why_ semi-colon is required. Please keep your unwitting angst for somewhere else.
Comment: (The post is edited now) But why would the two statements be read as one here, but not if it was `42\n"hello"`. That's the question, everyone understands it's being read as two statements, the interesting part is why in some cases and not in others.
Comment: > "if you bother to read OPs question - it is why semi-colon is required."
Exactly, I did read the question and pointed out that you didn't answer it, at least not before editing.
Answer: instead raises a TypeError, JavaScript tries to interpret it as
let a = { x: 0, y: 0 }(
    () => {console.log('test')}
)()

Details refer to:
https://flaviocopes.com/javascript-automatic-semicolon-insertion/
Answer: Always use semicolon ,since Javascript compiler compile the code line by line from top to bottom ,so in your case it is interpreted as

let a = { x: 0, y: 0 } (() => { console.log('test') })()

and compiler is unable to determine where the line terminates and also the func is  executed at the same time which makes no sense to the compiler.
That's why you are getting TypeError as you mentioned.
To fix this use semicolon after defining your object like this

let a = { x: 0, y: 0 } ;
(() =>  console.log('test') )();

You can also remove curly braces to refactor your code (just a little advice) since your function is not returning any value (using es6 property).


Center JTextField (not the text inside the field!)

Question: How can I center a JTextField.
NOTE! I do not want to center the text in the JTextField (which is achieved using setHorizontalAlignment(JTextField.CENTER), but rather I want to center the actual JTextField in the space it is in, just as jLabel.setHorizontalAlignment(SwingConstants.CENTER) would do.
Comment: You have to use proper layout for that. Post your code if you cant get.
Comment: FlowLayout.CENTER - not sure, but something like that if you are using flowlayout
Comment: I am using null layout. There must be a way with null layout.
Comment: Are you using any layout? Using GridBagLayout with appropriate [GridBagConstraints](http://docs.oracle.com/javase/6/docs/api/java/awt/GridBagConstraints.html#anchor) can do this. The `setHorizontalAlignment` behaves the same way for both `JTextField` and `JLabel`, both have their content aligned accordingly. You probably do not notice it in `JLabel` due to the gray colour of the background panel.
Answer: I recommend using GridBagLayout for this.
panel.setLayout(new GridBagLayout());
GridBagConstraints center = new GridBagConstraints();
center.anchor = GridBagConstraints.CENTER;
center.fill = GridBagConstraints.NONE;
panel.add(textField, center);

Answer:
Null Layout: This indicates no Layout. Items must be manually positioned and arranged. This layout should only be used if the window
  will not and cannot be resized, as the item in the window will stay
  where they are placed...   http://www.tech-recipes.com/rx/1205/java-null-layout-manager-swing/

http://www.tech-recipes.com/rx/1205/java-null-layout-manager-swing/
http://docs.oracle.com/javase/tutorial/uiswing/layout/none.html

The first link used .setLocation(x, y) to position the controls and the second link used .setBounds(...). You'll need to do the centering yourself
Comment: I'm not the downvoter, but never use the null layout, it's bad practice!
Comment: if you see my comment I recommended FlowLayout but the OP choose to use null layout. I don't know why this is downvoted. There is also warning in my post regarding the limitation....


Alter the exposed filters of a view, based on the view result

Question: I have a view that displays matching nodes, based on contextual arguments.
I'd like to create an exposed filter that filters by node title, displaying a drop down (select) menu with options for every node in the result set.
I can modify / set the contents of the exposed filter using hook_form_alter, but the views query hasn't executed when this hook is called, so I don't have access to the result set.  If I use hook_views_post_execute then I have access to the result set, but the exposed filters form has already been rendered.
I know that I could write an EntityFieldQuery to select the nodes and set them within hook_form_alter, but that isn't very DRY as I would effectively be re-writing (and executing) the same query that Views will be executing anyway.
What's the best practice way to achieve what I'm looking for?
Answer: Since this has gone unanswered, I decided to get creative and it's very easy with Entity Reference, Views Reference Filter and optional Rules.

Add an entity reference field to the content type that will reference its own node. So node/5's field will reference node/5. This can be done with Rules
automatically. Old nodes can be updated with VBO if needed.
In your view, Add > Entity Reference with the exact same filters
etc. That should be automatic. Remove unwanted fields. Save the view.
Go back to your regular view, add an exposed filter (only for that pane) for the entity reference field we just created with (reference filter) written beside it.
In the exposed filter's settings, choose the Entity Reference view we just created. If it's just using contextual filters, don't worry about sending arguments.

The logic: The view will process the entity reference view first and provide its results to the first view as an exposed filter. I just tested it and it works perfectly. Takes about five minutes.
Answer: The closest solution to this with core Views is to use the Summary option of a Contextual filter, but use it in a separate Views Display of type Attachment.
In your case to show title it may be the Title contextual filter, or node ID contextual filter set to display the title instead of the ID (use Relationship if necessary, I haven't tested this).
The Attachment will display along with the results, but because of the Contextual filter set to Summary it will work like an Exposed filter, showing all the options from the results set.
You may need to tweak the appearance of the Summary to make it look more like a drop-down or something you had in mind, by default it will be a list of links.