How to determine whether an indirect effect is statistically significant using Bayesian statistics?

Question: I've used bayesian estimation to test the indirect effects within a model and identified 95% credible intervals.
I'm typically used to using the Sobel's z test to identify significant mediation, what is the Bayesian alternative?
Answer: You would look at the 95% credible interval for the ab effect (the product of the two slopes involved in the indirect effect). At each iteration of the MCMC, you can compute the product of the estimates of the two slopes, then obtain the 95% credible interval for this posterior distribution of the product of the two slopes.


move imported svg with svg.js

Question: I'm trying to import an svg snippet with svg.js and then offset it, but it seems like any transformation method I try to use don't work with imported svg.
The code I have:
var lang = SVG('lang').size(400,400)
var swe = lang.svg('<svg id="swe" width="65" height="40.625" preserveAspectRatio="xMidYMid meet" zoomAndPan="magnify" version="1.0" contentScriptType="text/ecmascript" contentStyleType="text/css" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg"><rect width="100%" height="100%" fill="navy"/>' +
'<g transform="scale(4.0625)">' +
'    <rect x="5" width="2" height="10" fill="gold"/>' +
'    <rect y="4" width="16" height="2" fill="gold"/>' +
'</g></svg>')

swe.dx(100).dy(50) <-- this line does nothing.

Nor does any other method that are supposed to translate work, like x(), transform() or move()
I have tried making a rectangle and importing into that which also doesn't work:
var flag = lang.rect(65, 40.625)
var swe = flag.svg(<svg code>)
swe.dx(100).dy(50)

I can't find anything in the docs that make me any wiser. Is there anyone who has experience with this?
Comment: Think of an SVG as an image. If you want to transform an image you must use CSS or DOM. It does not matter what you do inside the image. It will not change where it is rendered on the page. Right now, you are **only** manipulating what is happening inside the image.
Answer: First of all: a rect-element cant have any children so your last approach is nonsense.
Furthermore it is not allowed to transform an svg element so transform won't work either. x and y properties on the other hand only work on nested svgs but not on the root svg.
You can create a group, import the svg there and move the group. Or you can loop through all children of your root svg and move them (you can loop through children with the children().each() method.
Answer: There are two ways to move your graphic around. The first would be to simply use CSS to reposition the "lang" div tag.
If you really want to move your graphic around inside the svg document  with svg.js function calls you could do something like the following.
var lang = SVG('lang').size(800,800)
var swe = lang.svg('<svg id="swe" preserveAspectRatio="xMidYMid meet" zoomAndPan="magnify" version="1.0" contentScriptType="text/ecmascript" contentStyleType="text/css" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg">' +
'<g transform="scale(1)" id="my_flag">' +
'    <rect width="65" height="40.625" fill="navy"/>' +
'    <rect x="15" width="5" height="40.625" fill="gold"/>' +
'    <rect y="15" width="65" height="5" fill="gold"/>' +
'</g></svg>')

var flag = SVG.get("my_flag");
flag.move(5,5);

Notice that I gave the group an id. I also moved the navy background into the group so it would move around with everything else.
This example will not work with SVG.js v3 (SVG.get function is deprecated for this use).
Answer: You have to create a group for it first and then import it into the group. Like this:

var draw = SVG('drawing').size(400, 400);
var casing = draw.group();
casing.svg('<g><rect x="100" y="100" width="50" height="50" style="fill: blue" /> </g>');
casing.move(50, 50);
casing.animate({
  duration: 4000
}).rotate(360).loop();

Answer: By the code you posted, you're creating a SVG document with SVG() and imported another SVG document into it, which doesn't make any sense at all.
You should import your SVG document into your div tag first:
document.getElementById('lang').innerHTML = (yourSvgCode);

Then you can use SVG.get() to get SVG document.
var swe = SVG.get('swe');

After that, you should be able to manipulate elements in the document. Use swe.children() or other reference method you can find on SVG.js to get your SVG elements.

move imported svg with svg.js


Specific inequality

Question: Let $x,y,z$ be different real numbers . Prove that:
$$\frac{x^2y^2+1}{(x-y)^2}+\frac{y^2z^2+1}{(y-z)^2}+\frac{z^2x^2+1}{(x-z)^2} \geq \frac{3}{2}$$
Comment: Maybe you think a=x,b=y,c=z
Comment: sorry i 've check
Comment: I find the min happen when $z=0$ and $x=-y$
Answer: Hint :
We have Dao Hai Long inequality :
$$\sum \frac{a+b}{a-b}.\frac{b+c}{b-c}=-1$$
So :
$$\sum \frac{(a+b)^2}{(a-b)^2} \geq 2$$
So:
$$\sum \frac{ab}{(a-b)^2} \geq \frac{-1}{4}  (1)$$
Then :
$$\sum \frac{1-ab}{a-b}=-1$$
So:
$$\sum \frac{(1-ab)^2}{(a-b)^2} \geq 2 (2)$$
From (1) and (2) we have solution
Comment: Can you please share references for the Dao Hai Long inequality? Thank you :-).
Comment: http://www.mediafire.com/view/?72wnw73ctccezl6 page 203
Answer: By AM-GM
$$\sum_{cyc}\frac{x^2y^2+1}{(x-y)^2}=\sum_{cyc}\frac{x^2y^2}{(x-y)^2}+\sum_{cyc}\frac{1}{(x-y)^2}\geq2\sqrt{\sum_{cyc}\frac{x^2y^2}{(x-y)^2}\sum_{cyc}\frac{1}{(x-y)^2}}.$$
Thus, it remains to prove that
$$\sum_{cyc}\frac{x^2y^2}{(x-y)^2}\sum_{cyc}\frac{1}{(x-y)^2}\geq\frac{9}{16}$$
or
$$\left(\sum_{cyc}(x^2y+x^2z-2xyz)\right)^2\sum_{sym}\left(7x^4y^2-5x^3y^3-5x^4yz+2x^3y^2z+x^2y^2z^2\right)\geq0.$$
Hence, it remains to prove that
$$\sum_{sym}\left(7x^4y^2-5x^3y^3-5x^4yz+2x^3y^2z+x^2y^2z^2\right)\geq0.$$
Indeed, let $x+y+z=3u$, $xy+xz+yz=3v^2$, where $v^2$ can be negative, and $xyz=w^3$.
Hence, $$\sum\limits_{sym}x^4y^2=(x^2+y^2+z^2)(x^2y^2+x^2z^2+y^2z^2)-3x^2y^2z^2=$$
$$=-3w^6+A_1(u,v^2)w^3+B_1(u,v^2);$$
$$\sum_{cyc}x^3y^3=27v^6-27uv^2w^3+3w^6;$$
$$\sum_{cyc}x^4yz=27u^3w^3-27uv^2w^3+3w^6$$ and
$$\sum_{cyc}x^3y^2z=9uv^2w^3-3w^6.$$
Thus, our inequality it's just $f(w^3)\geq0$, where $f$ is a concave function,
which says that it's enough to prove our inequality for an extremal value of $w^3$,
which happens for equality case of two variables.
Since the last inequality is homogeneous and even degree,
it's enough to assume $y=z=1$, which gives $(x-1)^4\geq0$.
Done!

Specific inequality


How to set the device name (as friendly name) in Airwatch/Workspace ONE via Rest-API

Question: I am looking to change the Device Name and Friendly Name of iOS devices to a different value via the Rest-API. I am able to change the Friendly Name like this:
$requestHeaders = @{
   'Accept' = 'application/json'
   'Authorization' = $auth
   'aw-tenant-code' = $wsoApiKey
}
$body = @{
   'DeviceFriendlyName' = $WsoDeviceName
}
$body = ConvertTo-Json $body
$uri = $wsoApiUri + $WsoDevice.Id.Value
Invoke-RestMethod -Uri $uri -ContentType "application/json; charset=utf-8" -Headers $requestHeaders -Body $body -Method Put

But I can't seem to find the correct attribute to change the Device Name, neither in the local API help (at server.local/api/help), nor in vmwares documentation.
Sending a PUT-request to change the DeviceName or DeviceReportedName shows no changes whatsoever. The code for that looked like:
$body = @{
    'DeviceName' = $WsoDeviceName
}

I am aware of the possibility to set the Friendly Name as Device Name via the web interface. Maybe there is a way to activate that option via API, that I did not find? In this case it would get the job done.
Would be glad, if someone could point me in the right direction.
Best regards
Holewasch
Answer: I was able to accomplish this using a custom MDM command. In the example below, I specifically use the POST /devices/commands method while searching by a serial number for the device.
$MdmCommandXml = [xml]@'
<dict>
  <key>RequestType</key>
  <string>Settings</string>
  <key>Settings</key>
  <array>
    <dict>
      <key>DeviceName</key>
      <string></string>
      <key>Item</key>
      <string>DeviceName</string>
    </dict>
  </array>
</dict>
'@

$Auth = ""
$WsoApiKey = ""

$BaseUrl = "https://as<yourhostnumber>.awmdm.com/API/mdm"
$SerialNumber = ""
$Uri = "${BaseUrl}/devices/commands?command=CustomMdmCommand&searchBy=Serialnumber&id=${SerialNumber}"
$NewDeviceName = "NewDeviceName"

$MdmCommandXml.SelectSingleNode('//key[.="DeviceName"]/following-sibling::*[1]').InnerXml = $NewDeviceName

$RequestHeaders = @{
    'Accept' = 'application/json'
    'Authorization' = $Auth
    'aw-tenant-code' = $WsoApiKey
 }
 $Body = @{
    'CommandXml' = $MdmCommandXml.OuterXml
 }
 $Body = ConvertTo-Json $Body
 Invoke-RestMethod -Uri $Uri -ContentType "application/json; charset=utf-8" -Headers $RequestHeaders -Body $Body -Method Post

Comment: I had to modifiy it slightly to get it to work with (my version of) powershell, but otherwise worked like a charm. Thank you very much
Answer: I am looking to implement the above solution, in order to rename device friendly names. See attached script below. When passing your specified uri value, the cmd output is this :
'Invoke-RestMethod : Cannot validate argument on parameter 'Uri'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.'

This suggests that my uri variable is not being populated. I am wondering if access to this functionality has been changed with a recent update to the API?
$MdmCommandXml = [xml]@'
<dict>
  <key>RequestType</key>
  <string>Settings</string>
  <key>Settings</key>
  <array>
    <dict>
      <key>DeviceName</key>
      <string></string>
      <key>Item</key>
      <string>DeviceName</string>
    </dict>
  </array>
</dict>
'@
$server = "https://xxxxx.awmdm.com/"
$client_id = "client_id"
$client_secret = "client_secret"
$access_token_url="token_url"
$body = @{
    grant_type    = "client_credentials"
    client_id     = $client_id
    client_secret = $client_secret
}
try {
    $response = Invoke-WebRequest -Method Post -Uri $access_token_url -Body $body -UseBasicParsing
    $response = $response | ConvertFrom-Json
    $oauth_token = [string]$($response.access_token)
} catch {
    $ErrorMessage = $PSItem | ConvertFrom-Json
    Write-Log "Failed to create OAuth Token for: $env with following ErrorCode: $($ErrorMessage.errorCode) - $($ErrorMessage.message)" -ForegroundColor Red
}
$header_v1 = @{
    "Authorization" = "Bearer " + $oauth_Token;
    "Accept" = "application/json;version=1";
    "Content-Type" = "application/json"
}

$header_v3 = @{
    "Authorization" = "Bearer " + $oauth_Token;
    "Accept" = "application/json;version=1";
    "Content-Type" = "application/json"
}

$WsoApiKey = "WsoApiKey"
$BaseUrl = "https://xxxxx.awmdm.com/API/mdm"
$SerialNumber = "R52N30M3T3P"
$Uri = "${BaseUrl}/devices/commands?command=CustomMdmCommand&searchBy=Serialnumber&id=${SerialNumber}"                                                #$Uri = "${BaseUrl}/devices/commands?command=CustomMdmCommand&searchBy=Serialnumber&id=${SerialNumber}"
$NewDeviceName = "NewDeviceFriendlyName"
$uri = $wsoApiUri + $WsoDevice.Id.Value
$MdmCommandXml.SelectSingleNode('//key[.="DeviceName"]/following-sibling::*[1]').InnerXml = $NewDeviceName
$test = $MdmCommandXml.SelectSingleNode('//key[.="DeviceName"]/following-sibling::*[1]').InnerXml;
 $Body = @{
    'CommandXml' = $MdmCommandXml.OuterXml
 }
 $Body = ConvertTo-Json $Body

 Invoke-RestMethod -Uri "$server/api/mdm/devices/search?" -Method Get -Headers $header_v1
 #Invoke-RestMethod -Uri $Uri -ContentType "application/json; charset=utf-8" -Headers $header_v1 -Body $Body -Method Get
 Invoke-RestMethod -Uri $uri -ContentType "application/json; charset=utf-8" -Headers $header_v1 -Body $Body -Method Post

Best Regards,
Liam
Comment: It looks like you're combining the script in my answer with the script in the original question, which is causing conflicts. Most notably, you're changing the value of `$uri` to `$uri = $wsoApiUri + $WsoDevice.Id.Value` on line 50, yet `$wsoApiUri` is not being defined in your version of the script you posted. I would suggest using only the code from my answer and not any code from the original question.


How to copy data based on count in range?

Question: I am trying to build in the following code in order to count  how many cells in a row have data. Based on the count I then need to Copy cells by the same number as the count. For instance if the count was 3 then I need to copy the data 3 times.
n = Worksheets("Sheet1").Range("C2:P2").Cells.SpecialCells(xlCellTypeConstants).Count
The data to be copied three times would be located in Sheet1 A2:B2 and needs to be copied to Sheet2 A2:B2
I would need to continue this until I reach an empty row in sheet1
Many thanks for any help or assistance.
Comment: What does "Copy three times" mean. How could the count of cells in `A2:B2` be three? What does `C2:P2` have to do with this? Can you share some sample data and explain a little clearer. The site `ozh.github.io/ascii-tables/` will help format data (choose excel after pasting your sample data in the top box) in a way that can be pasted here nicely.
Comment: I am counting the number of cells that contain data in the range C2:P2, based on that result I need to copy what ever text that is in A2:B2
Comment: The 'three times" was just an example of the result of the count
Comment: OK. But then "Copy it three times". You say you want to copy it into `Sheet2!A2:B2`. How can you copy something that is two cells into a range that is two cells... .three times.
Comment: Would it go into `A2:B2`, then `A3:B3`, then `A4:B4`. Then when we read the next row in `Sheet1` we start pasting however many times into `A5:B5`.. etc?
Comment: You are correct, if i need to copy three times then the text should then copy into A2:B2, A3:B3 and A4:B4. Hope this explains it better
Answer: To do this you will want to loop through each row that contains data in Sheet1. You will then want to count the number of populated columns in C:P through that row. Then paste that for however many times into Sheet2.
This will look something like:
Sub duplicateData()
    Dim rngReadRows As Range
    Dim rngWrite As Range
    Dim rngCell As Range
    Dim timesToPaste As Integer
    Dim pasteCount As Integer
    Dim arrMonth() As Date

    'Set up the rows that we will read from
    Set rngReadRows = Sheet1.Range("A2:A10").Rows

    'Set up the first cell/row we will write to
    Set rngWrite = Sheet2.Range("A2")

    'Now loop through each row from which we will read
    For Each rngReadRow In rngReadRows.Rows

        'figure out how many times we need to paste this thing
        timesToPaste = Application.WorksheetFunction.CountA(rngReadRow.Offset(, 2).Resize(1, 13))

        'redim the date array to the size we need
        ReDim arrMonth(1 To timesToPaste)

        'Fill the array
        i = 1
        For Each rngCell In Sheet1.Range("C1:P1").Cells
            If rngReadRow.Cells(1, rngCell.Column).Value <> "" Then
                arrMonth(i) = rngCell.Value
                i = i + 1
            End If

        Next rngCell

        'Loop however many number of times
        For pasteCount = 1 To timesToPaste

            'Paste it
            rngReadRow.Resize(1, 2).Copy Destination:=rngWrite

            'Get the date
            rngWrite.Resize(1, 1).Offset(, 2).Value = arrMonth(pasteCount)

            'Increment to next row
            Set rngWrite = rngWrite.Offset(1)
        Next pasteCount
    Next rngReadRow
End Sub

Comment: Thnaks and this makes sense to an amateur like me. However geting a runtime error 424 at Set rngWrite = Sheet2.Range("A2")
Comment: So.. here I'm using the codename of the worksheets. IN VBE insure that you have the View>>Project Explorer pane open. You can see the `Sheet1`, `Sheet2` name of each Tab name (the tab name is the part in the parentheses) the code name is the part outside. Sometimes if you have deleted tabs and saved and all that you'll see `Sheet23 (Sheet2)` or something silly like that. So tab name "Sheet2" is actually codename `Sheet23`. Change as needed. I'm suspecting you don't have a `Sheet2` codename in your workbook.
Comment: You are correct I just had to change to Sheet3 in your code! When I now run it shows no errors but what seems to be happening is that it seems to be counting all rows rather than just one row at a time as the total number of populated columns I have in my test sheet is 11 and it seems to copy the data in A2:B2 11 times rather than just the three times which is the total number of populated colums for row A2
Comment: Oh yea... I totally goofed that up. One sec and I will fix.
Comment: Switched up the `for each` loop to iterate `.Rows`. Also switched the `rngReadRow.Resize(1, 2).Copy` to refer to the correct variable.. totally hosed that. Should be working now, just have to flip out your sheet numbers again.
Comment: Works fantastic - thank you so much. For my own learning, why do we only read from Sheet1.Range("A2:A10").Rows? Also I have an additional task I need to do to this but I will try some more based on what i have learned from you. Thanks again!
Comment: That is another line of code you will have to change. Change `A10` to whatever row your data ends on. I just put it at 10 to test so my computer wasn't chugging rows that weren't populated.
Comment: i could try a find last row perhaps?
Comment: Absolutely. That would definitely be my next step if this were my code.Something like `lastRow = Sheet1.Range("A2").End(xlDown).Row`. Then..  `Set rngReadRows = Sheet1.Range("A2:A" & lastRow).Rows`
Comment: Perfect Genius! This might be difficult but is it possible to add this? Currently in Sheet1 C1:P1 contains dates, can we search in C2:P2 to see if there is any text and if there is can we copy the date from C1:P1 that corresponds with the column where the text was found in C2:P2. For instance if text was found in Cell C2 and Cell D2 then can we copy the dates from C1 and D1 into Sheet2 in cells C1 and C2 and so on moving onto search C3:P3 and copy dates into Sheet2   underneath the last copied data in Column C until we meet an empty row?
Comment: @JohnMc I've updated the code to bring in the column headers. Probably there is a cleaner way of doing this, but this will get you in the ballpark. If you have any other things you are trying to work through, please open a new question. You'll probably get faster responses since it won't be just me looking at it.


Alter default value for field settings (allowed_formats)

Question: Please how can I alter the default field settings whenever a new field is added?
NB I am not asking how to set the default whenever a new entity is added.  This is about changing the pre-populated values on the page "Administration->Structure->Content types->XXX->Manage fields->Add field when a field is added"
NB This question is for D8.  In D7 the answer is to use hook_field_info_alter.
Specifically I am using the module allowed_formats, and I would like every new text_with_summary or text_long field to have defaults of:

Allowed formats = "Basic HTML" only
Form display settings "Hide the help link About text formats." and "Hide text format guidelines." enabled.

The defaults need to work even if the new field is created in code.  In particular it's important to work for the Body field that is created automatically on a new content type.
I'm struggling because looking at the code, the defaults come from the public static function TextWithSummaryItem::defaultFieldSettings and there doesn't seem to be any hook.
Comment: In D8 the field structure is stored in config entities. For example when the node module creates the body field for a new content type you can use `hook_field_config_presave()` to change the settings before they are saved. Or `hook_entity_form_display_presave()` for the settings in the form mode.
Comment: https://api.drupal.org/api/drupal/core%21modules%21comment%21comment.module/function/comment_field_config_create/8.3.x is an example of how comment.module controls the default settings for new config fields. The isSyncing check is important.
Comment: Form display is indeed a good question. All entities have $entity->original available, which is the original unaltered entity that you can use to detect changes. In this case you could get the new and old compoents, do an array_diff() to get only those that were added, then check their type. Adding a new field adds it to default display automatically, editing another form display  might not work in the same way as the form is displayed and saved, so maybe you need a form alter for that
Comment: You can use these entity hooks for the field, view mode and form mode config entities https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/group/entity_crud/8.3.x
Comment: @4k4 thanks for the response.  Please can you explain which of hooks on that page?  The hooks look like they are for hooking changes on an entity, i.e. content.  I am trying to hook changes on a field, i.e. structure.
Comment: The Better Formats module will do this. It will let you set formats per field that should be available, or not.
Comment: @4k4 that sounds like it should be the answer. I'd actually suggest to use the create hook, as the field config entity might be displayed in the UI before being saved, then you don't know anymore if it is a default or not.
Comment: @Kevin Allowed formats does the same. The question is about controlling the default settings of allowed formats on a new field.
Comment: @Berdir, great example for the UI part, my example was for the body field added in `node_add_body_field()`, (I admit this was the easier part, didn't had the time to investigate a full answer, but you can go ahead if you want)
Comment: Thanks @Berdir for a great example.  I've got the field config working.  I'm still not sure about the form display - it seems that no new entity is created in this case because one form_display entity controls all the fields on an entity.  I can hook presave, but as you point out how do I know if it is a default or not.
Comment: In fact I'm not sure hook_entity_form_display_presave even gets called.  I've had another go with some code in my answer, but it's still not working.
Comment: @Berdir thanks again.  I'm sorry you have lost me somewhat.  Which hook is it please that you are suggesting I add the array_diff code too?
Answer: Thanks to @Berdir and @4k4 who helped me out several times - I just followed their ideas, tested and wrote up the answers.
This first hook alters the field settings.  I've included a second example for image settings.
<code>/**
 * Implements hook_ENTITY_TYPE_create() for 'field_config'.
 */
function MYMODULE_field_config_create(FieldConfigInterface $field) {
  if ($field->isSyncing()) return;

  switch ($field->getType()) {
    case 'image':
      $field->setSettings(['file_directory' => 'images', 'max_resolution' => '1080x1080']);
      break;

    case 'text_with_summary':
    case 'text_long':
      $field->setThirdPartySetting('allowed_formats', 'basic_html', 'basic_html');
      break;
  }
}
</code>
This second hook alters the form display settings.  The array_diff_key command is used to determine which fields are new.
<code>/**
 * Implements hook_ENTITY_TYPE_presave().
 *
 * Override field form display defaults used when a field is added to a content type.
 */
function MYMODULE_entity_form_display_presave(EntityFormDisplay $display) {
  $fields = $display->getComponents();
  $origFields = (isset($display->original)) ? $display->original->getComponents() : [];
  foreach (array_diff_key($fields, $origFields) as $newField => $settings) {
    switch ($settings['type']) {
      case 'text_textarea_with_summary':
      case 'text_textarea':
        $settings['third_party_settings']['allowed_formats'] = ['hide_help' => '1', 'hide_guidelines' => '1'];
        $display->setComponent($newField, $settings);
        break;
    }
  }
}
</code>
Comment: You can't do all in one hook, the field is added to the default form mode on submit anyway, so you can hook into this when this is happening. The create hook is  only to prepare the entity for the form, nothing is saved at this point, because you don't know whether the user submits the form.
Comment: @Neograph734 Thanks for the advice.  My original question was not fully answered and I was trying to indicate which parts were answered and which not.  I have now moved that information into the question as you suggest, so hopefully it's clearer now.
Comment: @AdamS, this is the presave hook for the form mode i've mentioned in the first comment. When the field config form gets submitted, it will update the default form mode config entity. And this is the same for the body field added by new content types (second part of your question). So this hook would take care of both parts, UI and non UI. And for the diff part see Berdir's comment.
Comment: Please do not ask new questions in answers. If you have found an answer to your question, leave the working part here and ask the other issue as a new separate question (provide a link to this issue for reference if needed). If your question is not yet answered, edit your latest findings in the original question and wait for a complete answer. That way we can keep all combinations of questions ans answers relevant. Thanks :)
Comment: @4k4 thanks again I am learning a lot from you.  Please could you tell me what hook I need for the second part?  I need a hook where I can distinguish which field is newly created and only alter settings on that one.


Prove convergence with the $\epsilon$-$N$ method

Question: Prove (with the $\epsilon$-$N$ method) that the sequence $(3n^3 +2)/n^3$ converges. Determine the limit first. Can someone help me with this? I have seen many examples but it I still don't get it. If someone can explain step by step (especially why we need to use the $N$?) I would be very very thankful.
Answer: As this is likely to be a homework, just few hints:
$$
    a_n := \frac{3n^3 +2}{n^3} = 3 + \frac{2}{n^3}
$$
As $n$ increases, the term $2/n^3$ clearly becomes smaller and smaller. Now for any $\epsilon > 0$, find $N$, such that for all $n > N$, $| a_n - 3 | < \epsilon $.
Answer: Well, you can rewrite $\frac{3n^3 + 2}{n^3}$ as $3 + \frac{2}{n^3}$. Now observe what happens if you put in larger and larger $n$. What can you say about the term $\frac{2}{n^3}$ then? And what does that tell you about the limit?
To formally prove that some $c$ that you have determined previously is actually the limit, you will have to show that for every $\epsilon > 0$ there is an $N$ such that for every $n \geq N$ you have $\left|\frac{3n^3 + 2}{n^3} - c\right| < \epsilon$. In other words, show that you can make all values of the sequence after a certain starting point lie arbitrarily close to the limit, provided that you pick a suitable starting point. Hint: This is the same as showing that all values of $\frac{2}{n^3}$, $n \geq N$ are $< \epsilon$, for an arbitrary epsilon, if you pick $N$ large enough.
Comment: I think I am starting to understand. I only got 2 examples in the book where I stared for 2 days and still I didn't get it. Thanks both of you for your effort to help people!
Comment: @Jeoren Once you've solved it, you could post your solution as an answer. That way, you'll get feedback, and also earn some reputation points.
Answer: Proof: Let $\epsilon > 0$ be given. You want to find a $N$ such that if $n\geq N (>0)$, then $\lvert a_n - 3\lvert < \epsilon$. Consider what you want:
$$
\lvert a_n - 3 \lvert = \left\lvert \frac{2}{n^3}\right\lvert = 2 \frac{1}{n^3}.
$$
Hence you just need to find a $N$ such that if $n> N$, then $2\frac{1}{n^3} < \epsilon$. Note that this $N$ will be dependent on $\epsilon$ in some way.
Just to show an example. Say that $\epsilon = 0.1$. Then what would $N$ need to be for $n> N$ to imply that $\frac{2}{n^3} < 0.1$? Well, we would need that
$$
\begin{align}
2 &< 0.1\cdot n^3 \Rightarrow \\
\frac{2}{0.1} = 20 &< n^3 \Rightarrow \\
\sqrt[3]{20} &< n.
\end{align}
$$
So for any $n> N = \sqrt[3]{20}$ you have the desired conclusion.
...
$\square$


Is LDA just selecting the minimum Mahalanobis distance?

Question: I have a question regarding Linear Discriminant Analysis (LDA). I know that LDA chooses the coefficients of a linear model, which maximize the separability of classes - that is the ratio of "between-class scatter" and "within-class scatter". Finding the coefficients can be done by solving a generalized eigenvalue problem.
Assume now a LDA classifier which is already trained and should be used to predict new observations.
From my tests (experimenting with different data sets) it looks like a new observation is always put into the class which has the closest mean value to that new point. That would mean that LDA just predicts the class based on the class which has the smallest Mahalanobis distance to the new point.
Question: Is that true? If not: can someone show a small counterexample (I wasn't able to construct one)? If yes: Why should we then solve a generalized eigenvalue problem if instead we could just compute all distances and take the smallest one?
Answer: As you probably already know LDA assumes equal covariance matrices for both classes. So the first counter example might be a scenario where the two classes have different covariance matrices. LDA would assume them to be equal and compute the wrong distances.
But assuming the variance-covariance matrices are equal in both classes:

Why should we then solve a generalized eigenvalue problem if instead we could just compute all distances and take the smallest one?

The solution returns a hyperplane separating the classes. A boundary. Once you know this boundary it is a lot easier to check if the observation is above it (belong to 1st class) or below it (belong to the 2nd class) compared to computing the Mahalanobis distance to the averages of both classes and choosing the smaller one.


Given two adjacency matrices, how can I find if they're isomorphic?

Question: Matrix 1:
\begin{matrix}
0&1&1&0\\
1&0&1&0\\
1&1&0&1\\
0&0&1&0
\end{matrix}
Matrix 2:
\begin{matrix}
0&1&1&1\\
1&0&0&0\\
1&0&0&1\\
1&0&1&0
\end{matrix}
I've looked on google to find out how to do this, but I can't find an answer that makes sense to me. As far as I can tell, there is no efficient algorithm to do this, so you need to check all the permutations... but I don't even know how to start. Any help would be great, Thanks.
Comment: Draw the graphs...
Answer: As isomorphims have to preserve degree, there are only 2 possible ones, the first given by
$$ \phi_1 \colon 1\mapsto 3, 2 \mapsto 4, 3 \mapsto 1, 4 \mapsto 2 $$
and
$$ \phi_2 \colon 1\mapsto 4, 2 \mapsto 3, 3 \mapsto 1, 4 \mapsto 2 $$
$\phi_1$ maps the first matrix to (that means the following matrix has $a_{\phi_1^{-1}(i), \phi_1^{-1}(j)}$ as $(i,j)$-th entry.
$$
\begin{pmatrix}
0&1&1&1\\
1&0&0&0\\
1&0&0&1\\
1&0&1&0
\end{pmatrix}
$$
and so $\phi_1$ is an isomorphism.
Answer: I think there is a better way of finding a solution to your question.
As the question is given in MATRIX form. I think it's better to do total solution in Matrices.
Concept : Matrix  M be the matrix we get by multiplying adjacency matrix and its TRANSPOSE (A').
<code>  Matrix M will be = [a ij] : where a ij is the number of edges from Vi to Vj if i is not equal to j and a ii is the number of edges incident to i(V is the vertices set of the given matrix).
</code>
So if we find Matrices M1 and M2 for the two given matrices..and checking whether identical terms are there are not. If identical numbers are there in Matrices, then both graphs are ISOMORPHIC.
and from these matrices (if they are ISOMORPHIC)we find which element of first graph points to which element of second graph.


Views Block Question

Question: I created a view that is a block.  I then wanted to create another block for that view but with different criteria.  When creating the second block, it was identical to the first block created and when I lets say change the fields, the first original block gets changed as well.  So it seems anything I do to the new block changes the first block as well.
What is the purpose of being able to create a second block but it is the exact same as the first?  I think the only difference it can have is a display name?  Can anyone explain this to me or give me an example of the purpose of this functionality?
Answer: Change the "For" setting in the header whenever changing almost anything.
If you want the setting to change on both displays choose "All displays":

If you want the setting to change on only one display choose "This block (override)"
Comment: @klo009 yes, just click on the +add button and select block, then just change the filter of content type and use the above answer.
Comment: I was not paying attention.  So easy.  Can I ask you if it would be ideal to have 1 view with blocks of different content.  Example I have 3 block views and they are all the same only difference is the content type being displayed.  Can I use 1 view and create 3 blocks of different content for that view? @chrishappy
Answer: You can create another view block within same view with a difference to change the fields on both views can be done. The process is when you create a fields on second view just use override this display for each field on second view and if you want to delete some fields from second view that is being carried over from first view is by opening the popup by clicking the field in second view and select override this display option with in popupp and then remove. If you escape the step of overriding the field in second view and remove the field from second view the field will also be removed from first also.

Views Block Question


is it possible to run chrome in debug mode?

Question: Firstly I'm really not sure if this is a question for Super-User or Stack-Overflow. It may certainly useful for other developers but it's not a specific code question.
In Google Chrome is there a way to look at render engine exceptions or general debugging info? I have some code which i'm 99% certain is crashing the render/repaint engine for chrome but (i'm on a mac) in the Console.app I don't get notifications for the exception. I'm wondering if theres a way of forcing chrome to be much more verbose in it's logging? Perhaps it's a webkit thing rather than chrome specific.
Let me know if this really isn't for stack overflow and I'll remove/close the question like I said I'm aware it's not code specific.
Comment: Have you read this: http://www.chromium.org/developers/how-tos/debugging#TOC-Single-process-mode?
Answer: Yes!
You can start chrome from the command line on a mac. See a previous question here
something like this:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome
You can also pass a flag to make chrome output to a log file by appending:
--enable-logging --v=1
This should write a log file chrome_debug.log which lives somewhere in your ~/.config/ directory.
Then you can tail that log. My command for that is:
$ tail -F ~/.config/chromium/chrome_debug.log
Your path to the log file may be different.
Hope that helps!
Answer: In a similar way as Rimian's answer, in Windows you can also start Chrome from command line enabling logging. Just open CMD and type:
cd C:\Program Files\Google\Chrome\Application
chrome --enable-logging --v=1

The log file chrome_debug.log is in C:\Users\<USERNAME>\AppData\Local\Google\Chrome\User Data. Notice you have to replace  for your username.
Answer: I am not completely sure whether I understood it correctly but maybe you want to check out chromium.org HOW-TO for mac rather than windows. you have two possibilities to debug the renderer process
a) Run Chrome in a single process
or
b) Attach XCode's debugger to a renderer process after launch
They are described in detail here. Hope that helps
EDIT: updated the link
Comment: Broken link. Thank why it is always a good idea to add the relevant pieces of information inside the answer.
Comment: @GilbertoTorrezan thanks for noticing (the structure of the urls has changed, the correct link was in the suggestions though)... still I did not want to just like copy paste the whole block there


Proper way to hold 3 chamber ocarina?

Question: I've picked up the multi-chamber ocarina, after playing tenor recorder for years.
I have a 'regular' triple alto A ocarina.
My question is, what's the proper way to hold the thing so that I can switch between chambers smoothly?
I can't find much info online about technique for multi-chambered ocarinas. Thanks.
Answer: I myself have never played a multi-chamber ocarina, but a while ago I wanted to buy one and did some research on the topic and on the miscellanea of playing it.
At that time, I remember finding this video that seemed very informative of the basic technique of dealing with switches between chambers. Here he uses a double ocarina, but the idea is the same if you are playing a triple one.

Proper way to hold 3 chamber ocarina?


Tao Analysis 1 Exercise 3.4.2

Question: Let $f: X \rightarrow Y$ be a function from $X$ to $Y$. Let $S$ be a subset of $X$, and $U$ be a subset of $Y$.
(iii) In general, what's the relation between $f^{-1}f^{-1}(U)$ and $U$?
Need help for 3.4.2 (iii). My solutions to part(i) and part(ii) are in general that there are no relation except in certain cases such as when f is bijective.
For part(iii), I thought it might be something similar but I tried to think of a couple of counterexamples and they all failed in some way or another so I thought that it may be the case that for (iii) both sets are always the same. I tried to proof it as below but got stuck and am not sure how to proceed. If f is injective, then clearly it works but in general im not sure how to proceed.
Let $x$ be an element of $f^{-1}(f(f^{-1}(U)))$, then there must exist $y \in f(f^{-1}(U))$, such that $f(x) = y$. For such $y$ to exist, there must also exist some $z \in f^{-1}(U)$, such that $f(z) = y$.
Comment: Please don't post unsearchable images of text and equations.
Answer: Presumably you know about the relationship between  $f^{-1}(f(S))$ and $S$ as in the previous exercises. What happens when $S = f^{-1}(U)$ in that scenario?
I'll leave the details to you.
Comment: I dont think its equivalent though,  since there are some cases where (i) is true, and i feel like $S=f^{-1}U$ is precisely such a case.
Comment: ah nvm i think i got part(i) and part(ii) wrong which is why i didnt understand what you meant
Answer: They are the same set for an arbitrary $f$.
The inclusion $f^{-1}(U)\subseteq f^{-1}(f(f^{-1}(U)))$ is a consequence of what you already have seen in (i).
Conversely, let $x\in f^{-1}(f(f^{-1}(U)))$. Thus, $f(x)\in f(f^{-1}(U))$ so there exists $z\in f^{-1}(U)$ such that $f(x)=f(z)$. Now, since $z\in f^{-1}(U)$ then $f(z)\in U$, hence $f(x)\in U$. Therefore, $x\in f^{-1}(U)$.
Comment: ah i got part(i) wrong so i wasn't able to see the inclusion in that direction.
Could i also check that for part(ii),  the relation is that $f(f^{-1}U) \subseteq U$

For the converse part, I understand now, it was sufficient to show that $f(z)=f(x)$ even if $z$ and $x$ are different since that allows us to say that $f(x) \in U$ and conclude that the pre-image of $U$ under $f$ will contain $x$

Tao Analysis 1 Exercise 3.4.2


Login failed for "IIS AppPool\ASP.NET v4.0" - SQL Server Web

Question: I'm trying to migrate a website from SQL Server 2008 Express to SQL Server Web, and the website is having trouble accessing the database.  In truth, Express was only ever used by running the website from Visual Studio's builtin web server, so I'm not sure about the configuration working all that well under full-blown IIS 7.  At any rate, when I try to access a page that uses Linq to Entities (requiring the website to connect to the database), I get the error "Login failed for 'IIS AppPool\ASP.NET v4.0'".  So, I opened SQL Server Management Studio, and I attempted to add a login for the user, but I just get a message stating "Windows NT or user group '*****\Asp.Net v4.0' not found".  This happens even after I ask Management Studio to check the name of the user, which it does successfully.  Can someone tell me what I'm doing wrong?  Also, I'm open to alternative suggestions as well...  Everything's running on the same server, so there are no remote connections.  For this reason, I'd love to use Windows Authentication if at all possible.
Answer: IIS 7 is trying to use the IIS application pool identity to access your SQL database.
So you must first grant the IIS 7 apppool access to SQL server.
To do that, go in SQL Server Management Studio -> Server Instance -> Security -> Logins -> New Login
Login name will be "IIS APPPOOL\ASP.NET v4.0". This is because everytime you create an application pool in IIS7, it will create an identity which uses the same name as your app pool. In your case, you are using the default app pool which comes with asp.net 4.
Then on your database, go to Security -> Logins -> New login , give it a alias name, then select your user object you added in your previous step (IIS APPPOOL\ASP.NET v4.0) then give it db_owner (or whatever your needs are) schemas/role privileges.
Comment: Do not use the 'Search...' button to validate the login name because it will replace 'IIS APPPOOL\ASP.NET v4.0' by 'PC-NAME\ASP.NET v4.0' (which won't work).
Comment: @kimphamg:  Thanks for the reply.  I tried that, but after entering the login name you suggested, Management studio says "Windows NT or user group '[Server Name]\Asp.Net v4.0' not found".  Also, since the website hasn't been able to access sql server, I can't seem to find the database in the object explorer of Management Studio.  I don't think it's been attached yet...
Comment: Should I create a local user on the server called "Asp.Net v4.0"?
Comment: Is that necessary?
Comment: Wait, are you using IIS 7 or IIS 7.5 ?
Comment: It's IIS 7.5...
Comment: You do not need to create a user, because your app pool already created it. Also make sure you execute SQL Server Management Studio as Administrator
Comment: Thanks kimphamg, I'll try that.  Also, about your other suggestion to add the new sql server user's privelages to the database...  Should I attach the database using Management Studio?  Is that something which IIS would normally take care of?  Sorry, I guess these are kind of newbie questions...
Comment: Yes, attach your database to SQL server using Management Studio. It is much easier to manage your database this way! Also look at IIS to see which application pool your website uses. By looking at your error, your app pool seems to be 'ASP.NET v.4.0'.
Comment: @kimphamg:  It worked!  I created a sql server login and granted it permissions on the necessary databases.  Thanks!
Answer: EDIT: Please don't do this -- I wasn't thinking when I originally wrote this answer.
For more details why my original answer isn't a good idea please review the link in the comments below.

Another solution is to go into IIS and edit the application pool itself to use the identity "LocalSystem."  This can be found by
right click the app pool
-> advanced settings
-> click Identity's '...' button (right below "Process Model")
-> select "LocalSystem" under the Built-in account drop-down.
Doing it this way you don't need to set up a new user in your database.
Answer: Simply follow as in pictures below and make sure you select your database while mappin user.
enter image description here
enter image description here
Answer: Follow this steps as in image and make sure to choose your database in last image.
Click below steps to view image:
step:1
step:2
step:3


Reduzir tamanho do arquivo de Log

Question: Estou em uma saga com meu banco de dados, hoje tenho um arquivo mdf de 11GB e um log de 77GB.
Já pesquisei em diversos forum, apliquei alguns procedimentos de redução via Management(shrink) e via comando como o SHRINKFILE, o banco de dados já se encontra como simple. mas nada o faz reduzir, preciso de ajuda.
Answer: Você precisa fazer backup do seu log de transação (arquivo ldf) e depois executar um shrink. O backup dos logs de transação precisa ser feito da mesma maneira que você faz o backup do banco (arquivo mdf). Caso você não faça, então acontecerá esse comportamento que você está observando.
Exemplo de um comando para fazer backup dos logs de transação:
BACKUP LOG [Mobius] TO  DISK = N'G:\Microsoft SQL Server\MSSQL.1\MSSQL\Backup\log.trn' WITH NOFORMAT, NOINIT,  NAME = N'Mobius-Log de Transações  Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO

O mesmo pode ser feito pela interface:

Um detalhe: o backup dos logs de transação pode ser feito com o banco online e sendo acessado.
Caso você não precise de log de transações, altere o Recovery Mode (ou modo de recuperação) para Simple (simples). Neste cenário, os logs não serão gerados e, assim, você não precisa fazer backup.

Note, entretanto, que tudo depende do tipo de banco que você está lidando. Exemplo: é recomendável que um banco de um software ERP tenha log de transações ativos. Um possível cenário seria um backup completo todos os dias e backup das transações de hora em hora.
Já um banco de uma aplicação mais simples, pode ter apenas o backup completo sem a necessidade dos logs de transação.
A vantagem dos logs feitos de hora em hora (por exemplo), é a possibilidade de restaurar um backup até uma determinada hora. Neste caso, basta restaurar o backup completo e, em cima dele, restaurar os backups de hora em hora dos logs de transação até a hora desejada.
Answer: Já faz um tempo que desenvolvi esse script para diminuir o log de dados das bases.
Denrto o cursor tem uma linha pra cada versão. A versão 2008 também funciona para 2012
declare @cmd nvarchar(4000)
declare @bd varchar(100)
declare @file nvarchar(100)
declare @size nvarchar(100)
declare pap_log cursor read_only forward_only for

SELECT
    db_name(sf.dbid) as [Database_Name],
    sf.name as [File_Name],
    (sf.size/128.0 - CAST(FILEPROPERTY(file_name(fileid), 'SpaceUsed') AS int)/128.0) AS 'Available_Space_MB'

FROM    master..sysaltfiles sf
WHERE   groupid = 0
and db_name(sf.dbid) not in('model')
ORDER BY    Available_Space_MB  DESC

open pap_log
fetch next from pap_log into @bd,@file,@size
while @@fetch_status = 0
begin
/*2005*/
--set @cmd='backup log '+@bd+' with no_log ;use '+@bd+';dbcc shrinkfile(['+@file+'],0);'
/*2000*/
--set @cmd='backup log '+@bd+' with no_log ;use '+@bd+';dbcc shrinkfile('+@file+',0);'
/*2008*/
set @cmd='use '+@bd+';dbcc shrinkfile('+@file+',0);'
exec sp_executeSQL @cmd
declare @filepath varchar(100)
print ''
print @bd
print rtrim(ltrim(@file+' '+@size))
select @filepath=filename from master..sysaltfiles where name=@file
print @filepath
print ''
fetch next from pap_log into @bd,@file,@size
end
close pap_log
deallocate pap_log

Answer: Teste o seguinte:

Faça uma cópia do seu banco;
Execute dump tran SEUBANCO with no_log dbcc shrinkdatabase (SEUBANCO,0)

Outra opção seria desatachar o banco e tentar atachar somente com o arquivo MDF na pasta.
Comment: ele não deixa atachar sem o arquivo de log,

sobre a linha de comando, apresenta o seguinte erro
Sintaxe incorreta próxima à palavra-chave 'tran'.
Comment: apenas complementando, eu alterei para simple para efetuar os testes, até então estava full e com backup também full diário, não tenho backup separado de logs, e a base começou a crescer dessa maneira de uns dias para cá
Comment: Acredito que no próximo backup o `log` vai diminuir.
Answer: Peguei o mesmo problema recentemente e resolvi desta forma:

Óbvio: Fazer enquanto ninguém estiver usando a base de dados

Backup Full.
Botão direito na base e depois detach.
Acessar o
diretório que fica o arquivo do banco de dados, geralmente é:
C:\Program Files\Microsoft SQL
Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA pode mudar dependendo da
versão;
Renomear o arquivo de log que tem a extensão .ldf;
No Management Studio, clicar com o botão direito em database, Attach,
seleciona o arquivo do banco de dados, remove a linha do log que
aparece em baixo e clica  OK.
Answer: Se você tiver certeza de que não precisará do log, ou seja, quer somente reduzir o tamanho do arquivo de log, pode fazer o procedimento abaixo:
1 - Verifique o nome do seu arquivo de log executando o código abaixo:
-- Mostra as informações de seus arquivos
USE [NomeDoBanco]-- Alterar nome do banco
GO
EXECUTE sp_helpfile
GO

2 - Execute o comando abaixo, colocando o nome do seu arquivo de log:
USE [NomeDoBanco];

-- Obs.: Só é possível truncar o log se o banco estiver no modo Simple
ALTER DATABASE [NomeDoBanco] SET RECOVERY SIMPLE WITH NO_WAIT;

-- Limpa o arquivo de log.
DBCC SHRINKFILE (NomeDoArquivo_log, 1); -- Atenção: Colocar o nome do arquivo de log e tamanho que se quer reduzir

-- Volta o Banco para o modo FULL se for o caso
ALTER DATABASE [NomeDoBanco] SET RECOVERY FULL WITH NO_WAIT;

Reduzir tamanho do arquivo de Log


server not reachable by IP

Question: I have a strange problem in our local environment. Our file server is not reachable by IP, probably since I updated it to windows server 2016.
I can reach the server by \name and by \name.domain.local but not by \IP.
We have a local AD and DNS @ domain functional level 2012 R2.
I added a secondary network card to the server which uses DCHP instead of the fixed on the original card. But the problem is the same on that IP. All google results is about the opposite problem, IP works but not server name.
What is going on with our server/network?
Comment: Problem solved, I removed the server from the AD and re added it. In the same time I removed DFS and SMB 1. One, to me unknown, of those did the trick!
Answer: You actually connect the server every time with an IP, while \\name and \\name.domain.local are actually resolved using DNS or WINS before making the connection. Therefore, the most reasonable explanation would be that the IP address of your server has changed. It might for example be that your server had a static IP but during your update it has started using DHCP.
Try nslookup name.domain.local to get the actual IP of the server (or log in & use ipconfig).
Comment: Server:         ab-ad-2.trivector.local
Address:       192.168.26.212

Name:          trifile.trivector.local
Addresses:  192.168.26.203
                     192.168.27.31. Accessing both those IP with \\ip in explorer gives the error "Host unreachable"(free translation from swedish)
Answer:
Problem solved, I removed the server from the AD and re added it. In
  the same time I removed DFS and SMB 1. One, to me unknown, of those
  did the trick! – niklas.unnhem Oct 23 '17 at 12:41

This action was not necessary. Next time check if Netlogon service is running. Just yesterday I did the same - upgraded 2012 to 2016 and for some freaky reason Netlogon service was disabled. Eneable it and then start it. No restart required.

server not reachable by IP


iOS - NSFileManager file not exist

Question: I am hosting my in-app purchase content with Apple. I have managed to download the contents and right now I want to save it in device.
[[NSFileManager defaultManager] removeItemAtPath:dstPath error:nil];
[[NSFileManager defaultManager] copyItemAtPath:srcPath toPath:dstPath error:nil];

This code above is how I move the content downloaded to my desired location.
It seems to work fine and when I try to display the content it works. But when I stop and run the app again the files does not exist.
What am I missing?
My code:
- (void)processDownload:(SKDownload *)download
{
    NSString *path = [download.contentURL path];

    path = [path stringByAppendingPathComponent:@"Contents"];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *files = [fileManager contentsOfDirectoryAtPath:path error:&error];

    NSMutableArray *stickersDownloadedArray = [[NSMutableArray alloc] init];

    for (NSString *file in files)
    {
        NSString *fullPathSrc = [path stringByAppendingPathComponent:file];

        NSString *fileName = [fullPathSrc lastPathComponent];
        NSString *fullPathDst = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@", fileName]];

        [fileManager removeItemAtPath:fullPathDst error:nil];
        [fileManager moveItemAtPath:fullPathSrc toPath:fullPathDst error:nil];

        NSLog(@"fullPathDst: %@", fullPathDst);
        NSLog(@"file: %@", file);
        NSLog(@"key: %@", download.transaction.payment.productIdentifier);

        [stickersDownloadedArray addObject:fullPathDst];
    }

    [[NSUserDefaults standardUserDefaults] setObject:stickersDownloadedArray
                                              forKey:download.transaction.payment.productIdentifier];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

An example of fullPathDst is
/firstname.lastname@example.com

Comment: Where are you saving the data to? Could you print the `dstPath` and show it to us?
Comment: @Sulthan I have updated my answer
Comment: @Sulthan the file exists as long as I don't stop and run the app again.
Comment: Usually the sandbox path changes on application updates (e.g. new version downloaded from app store). However, every deploy from Xcode is also an update that changes the sandbox. You can't save absolute URLs.
Comment: @Sulthan Thank you. its working now.
Comment: How do you know it seems to work fine when you're ignoring all errors???
Answer: An app's sandbox changes at different times. You must never store full paths to files. Only store a relative path.
In your case, only store the path relative to the Documents folder. When you reload the relative path when the app starts up, you recalculate the full path again.
Comment: I initially thought this gave me the clue to fixing this issue for me (changed from the `path` method to `relativePath`, but the issue is intermittent and it did come back fairly quickly.  FWIW, the only thing that seems to help consistently for my dev. env. is to restart the iPhone I am testing on.  It always works for a number of iterations after restarting completely.  Deleting app, signing out of sandbox, etc. do not help everytime.

iOS - NSFileManager file not exist


Fixed Effects OLS Regression: Difference between Python linearmodels PanelOLS and Statass xtreg, fe command

Question: I'd like to perform a fixed effects panel regression with two IVs (x1 and x2) and one DV (y), using robust standard errors. In Python I used the following command:
result = PanelOLS(data.y, sm2.add_constant(data[['x1', 'x2']]), entity_effects=True).fit(cov_type='robust')
result

resulting in:
                          PanelOLS Estimation Summary
================================================================================
Dep. Variable:                      y   R-squared:                        0.0008
Estimator:                   PanelOLS   R-squared (Between):             -0.0212
No. Observations:               34338   R-squared (Within):               0.0008
Date:                Tue, May 05 2020   R-squared (Overall):           3.076e-05
Time:                        11:29:40   Log-likelihood                -4.647e+05
Cov. Estimator:                Robust
                                        F-statistic:                      13.569
Entities:                        1304   P-value                           0.0000
Avg Obs:                       26.333   Distribution:                 F(2,33805)
Min Obs:                       0.0000
Max Obs:                       75.000   F-statistic (robust):             71.477
                                        P-value                           0.0000
Time periods:                      88   Distribution:                 F(2,33805)
Avg Obs:                       390.20
Min Obs:                       0.0000
Max Obs:                       499.00

                             Parameter Estimates
==============================================================================
            Parameter  Std. Err.     T-stat    P-value    Lower CI    Upper CI
------------------------------------------------------------------------------
const       5.472e+05     6478.7     84.469     0.0000   5.346e+05   5.599e+05
x1            -758.82     70.912    -10.701     0.0000     -897.81     -619.83
x2            -322.77     60.629    -5.3238     0.0000     -441.61     -203.94
==============================================================================

F-test for Poolability: 1337.3
P-value: 0.0000
Distribution: F(530,33805)

Included effects: Entity

Because the results seamed a bit off I tried to replicate them with Stata, using:
xtreg y x1 x2, fe vce(robust)
resulting in:
Fixed-effects (within) regression               Number of obs      =     34338
Group variable: ID                              Number of groups   =       531

R-sq:  within  = 0.0008                         Obs per group: min =         1
       between = 0.0010                                        avg =      64.7
       overall = 0.0004                                        max =        75

                                                F(2,530)           =      7.99
corr(u_i, Xb)  = -0.0205                        Prob > F           =    0.0004

                                   (Std. Err. adjusted for 531 clusters in ID)
------------------------------------------------------------------------------
             |               Robust
           y |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
          x1 |  -758.8212   202.0153    -3.76   0.000     -1155.67   -361.9723
          x2 |  -322.7749   219.6023    -1.47   0.142    -754.1727    108.6229
       _cons |   547249.1    22976.5    23.82   0.000     502112.9    592385.3
-------------+----------------------------------------------------------------
     sigma_u |  1266542.2
     sigma_e |  183793.32
         rho |  .97937616   (fraction of variance due to u_i)
------------------------------------------------------------------------------

The results are different. Especially the difference in p-value for x2, the average and min observations seem to be off. I do not understand what I am doing wrong in the Python version. Is the command I'm using correct? Have I missed a fundamental difference within the two models?

EDIT: as @Jesper for President pointed out there are some differences in the way Stata and Python interpret the data. Here is what I found out so far: My time variable is dates. As some dates are missing, Python seems to fill up the missing ones (Stata Obs per group max: 75 vs. Python Time Periods: 88). Further, Stata's vce(robust) does not seem to do the same like Pythons cov_type='robust'. By reading the manuals, I understand that both are including White-Sandwich estimator of variance. Nevertheless, while the results without robust standard errors are almost identical (difference in observations is the same like for robust SE), including them leads to the difference in p-values presented here. Can anybody help me to further understand the problem?
Comment: What is the reason you deleted your original version of this question?
Comment: It was the suggested solution to either edit the post or create a new one. As I read your comment I realized that my previous post was not well structured, so I rearranged it in a new post for better understanding and deleted the old one
Comment: It's unclear who might have suggested that--it's almost always better to edit a post rather than create a new one, unless the new one is so radically different that none of the comments, answers, or previous edits is relevant.  This enables us to keep track of changes rather than having to read through a new (and long) post all over again, trying to figure out how it has been changed.
Comment: I do not know Python and I am not a stata expert, but if I remember correctly the fe-option in stata do not add time-fixed effects. This does however seem to be the case for the PythonOLS command although that may depend on the exact construction of the MultiIndex DataFrames object.
Comment: It also seems strange to me that Python report 1304 entities and stata 531 groups. You seem to have some entities with 0 observations. Try to figure out what these entities  are.
Comment: thanks @JesperforPresident! As mentioned in my edits, the only difference I could find was that Python seems to complete missing dates. Nevertheless that does not explain where Python takes the 1304 from (Stata's 531 is correct). The differences in the results seem to result from differences in the robust std errors. From reading through the manuals I can't find the differences. So if anybody knows the difference that would be of great help.
Comment: Cutting it very short: clustering standard errors on individual implies that the relevant sample size for std.'s are the number of individuals (entities in python language and groups in stata language). So if you take Python std. 70.912 and multiply it with sample size 1304 and divide with stata sample size 531 you get the number  174 which is not the same as the stata std. error 202 but it is way closer. So perhaps if you clean your data so you have the same number of entities as you have groups and then compare standard errors.
Comment: I've tried the same for a completely balanced data set and I observe the same difference in the SE between Stata and Python.
Answer: If anybody has a similar question, I found my mistake. According to the linearmodels manual the robust SE used (White's robust covarinace) is not robust for fixed effects. Instead clustered covariance is required. Stata seems to adapt that automatically. Therefore the correct command is:
from linearmodels import PanelOLS
fe_mod = PanelOLS(df.y,sm2.add_constant(df[['x1' , 'x2']]), entity_effects=True)
fe_res = fe_mod.fit(cov_type='clustered', cluster_entity=True)
print(fe_res)

This leads to:
                              PanelOLS Estimation Summary
================================================================================
Dep. Variable:                      y   R-squared:                        0.0008
Estimator:                   PanelOLS   R-squared (Between):             -0.0212
No. Observations:               34338   R-squared (Within):               0.0008
Date:                Tue, May 05 2020   R-squared (Overall):           3.076e-05
Time:                        18:04:12   Log-likelihood                -4.647e+05
Cov. Estimator:             Clustered
                                        F-statistic:                      13.569
Entities:                        1304   P-value                           0.0000
Avg Obs:                       26.333   Distribution:                 F(2,33805)
Min Obs:                       0.0000
Max Obs:                       75.000   F-statistic (robust):             8.0007
                                        P-value                           0.0003
Time periods:                      88   Distribution:                 F(2,33805)
Avg Obs:                       390.20
Min Obs:                       0.0000
Max Obs:                       499.00

                             Parameter Estimates
==============================================================================
            Parameter  Std. Err.     T-stat    P-value    Lower CI    Upper CI
------------------------------------------------------------------------------
const       5.472e+05  2.296e+04     23.840     0.0000   5.023e+05   5.922e+05
x1            -758.82     201.83    -3.7597     0.0002     -1154.4     -363.23
x2            -322.77     219.40    -1.4712     0.1413     -752.80      107.25
==============================================================================

F-test for Poolability: 1337.3
P-value: 0.0000
Distribution: F(530,33805)

Included effects: Entity

Which is close enough to the Stata version for me to trust the results.


React native toolbar comes below the status bar

Question: I currently have a toolbar -
I want the green color toolbar on my statusbar and on the left side I need the back button. Here is my code -
<View style={{ height: 24 }} >
                <StatusBar backgroundColor="rgba(0, 0, 0, 0.2)" translucent />
                <Toolbar
                    rightElement={{
                        menu: {
                            icon: "more-vert",
                            labels: ["Settings"]
                        }
                    }}
                    onRightElementPress={this.settingsShow}
                />
                <View style={styles.footer}>
                    //...
                </View>
            </View>

Comment: Here is a sample `export const Root = StackNavigator({
      Login: {
        screen: LoginStack,
      },
    },{
      mode: 'modal',
      navigationOptions: {
             header: null//Will hide header for all screens of current stack navigator,
       },
      initialRouteName: 'Login',
    })` the `header: null` will remove the white header
Comment: First wrap the `StatusBar` and `Toolbar` in `View` and try `` and see
Comment: No now it is coming left top corner below the white toolbar
Comment: Do you need the white toolbar? is it from the navigation? share the updated code also
Comment: I dont know where it comes from...
Comment: Super thank you works now
Comment: If it fixed your issue, let me know. I will post as an answer so it will helpful to others @Julia
Comment: Yes sure it helped me
Answer: Removing the White header from navigation, follow this sample one
export const Root = StackNavigator({
    Login: {
      screen: LoginStack,
     },
   },
    { mode: 'modal',
      navigationOptions: {
        header: null//Will hide header for all screens of current stack navigator, },
        initialRouteName: 'Login',
    })


*Quarter Note* = invisible?

Question: I pulled up a new song on piano and started looking over the sheet music when I saw Quarter Note = invisible. Does anyone know what this means? And what it changes to the sheet music?
Comment: I grantee that was an export error in whatever software created it (maybe the component was marked invisible). There's a couple other glaring issues like measure 16 where the decrescendo and the triplet marks overlap when there's plenty of space for both.
Comment: Can you post an image or a link to the actual music that shows the text you are asking about?
Comment: Yes here you go: https://docs.google.com/viewer?a=v&pid=sites&srcid=ZGVmYXVsdGRvbWFpbnxxdWVsbGF0YWxvfGd4OjYzZjZkOGNlNjBjNjJhOTQ
Comment: Well, there's  Largo,  Andante,  Allegro, Presto,  so I propose that "invisible" is wicked awesome fast (like the baseball term "radio ball" for a pitch so fast you hear it but don't see it)
Answer: I think we can only guess, because it is not a normal marking.
Looking at other transcriptions, it appears that there is no fixed tempo for the piece, and that it is played with rubato, a specific way of speeding up and slowing down. This makes me think that the marking in question is meant to indicate that the tempo for the piece is not clear, and "invisible" might be a mistranslation.
I suggest looking for a different transcription.
Comment: Seems it could be a mistranslation of 'variable'.
Answer: My guess is that this is breakage of the sixth wall (the computer case) and the intent was to have the tempo specification be invisible rather than "invisible".

*Quarter Note* = invisible?


ReactJS events - this.props.onSubmit(this.state....)

Question: The following code snippet is from a simple Todo list which stores information on a local EOS blockchain and has a frontend web interface built on ReactJS. The question is related to ReactJS, specifically the event handler code snippet
saveTodo(e) {
  e.preventDefault();
  this.props.onSubmit(this.state.description)
  this.setState({ description: "" })
}

The full program can be found here...https://github.com/eosasia/eos-todo/blob/master/frontend/src/index.jsx
In the body of the event handler saveTodo(e), there is a line  this.props.onSubmit(this.state.description). I would like to know what exactly is going on here?
I am new to ReactJS, and it looks to that the above line of code is somehow setting a property (props) by calling a built-in function onSubmit() with an argument retrieved from the state object. Is this correct? I don't see how onSubmit() was assigned to props anywhere in this code, but somehow we are able to use it like so:  this.props.onSubmit(this.state.description) …. What's going on here?
Thank you kindly.
P.S. pardon the terminology. I'm not sure if "event handler" or "event listener" is the right word.
Answer: The TodoForm component takes a property "onSubmit".
That line is simply calling this property (that was passed to it by its parent) and passing in the description ( taken from the state of TodoForm ).
For example:
<TodoForm onSubmit={(description) => alert(description)} />

Read more about props in react here.
Comment: Thanks Mathew, in your example, you are implementing the function, which results in an alert(description). However, on the full code in the link, there seems to be no implementation of the function. what happens after this.props.onSubmit(this.state.description) gets called?                                                                                render() {
    return(

 ............

    )
Comment: @kamiss In the full code in the link, if you look in the render function of TodoList, you see that `` So in this case, the onSubmit property is set to be the `addNewTodo` function that is declared in TodoList. If you look, `addNewTodo(description)` takes that same description argument that is passed into the property.
Comment: Thank you Mathew, i finally understood it!


Is this differentiation correct?

Question: $J(x,y')=\int_1^2 xy'(x)+(y'(x))^2dx = \int_1^2{f(y,y^\prime,x)}$
Need to find $\frac{d}{dx}(\frac{\partial f}{\partial y^\prime})$
$\frac{\partial f}{\partial y^\prime}=x+2y'(x)$
$\frac{d}{dx}(\frac{\partial f}{\partial y^\prime})=1$
Is this correct, or what is the right solution?
Comment: I guess this is calculus of variations? And the integrand is what you are considering as $f(y,y^\prime, x)$? I think you meant to type ${d\over dx}({\partial f\over\partial y^\prime})$ rather than ${d\over dx}({\partial f\over\partial y})$.
Comment: Yes, that is true. For that part I got x from the first term in the sum and brought down the exponent in the second part of the sum. i.e. analogous to $5x+x^2$ differentiated as 5+2x
Comment: When you do ${d\over dx}(x + 2y^\prime)$, you need to remember that $y^\prime$ is a function of $x$, so the result is $1 + 2y^{\prime\prime}(x)$.
Answer: When you do ${d\over dx}(x + 2y^\prime)$, you need to remember that $y^\prime$ is a function of $x$, so the result is $1 + 2y^{\prime\prime}(x)$.
Comment: Then it would be product rule: $(x)(2y^{\prime\prime}(x)) + (1)(2y^\prime(x))$.
Comment: Ok, and I am curious, what would happen if $\partial f/ \partial y$ was x*2y'(x) instead?
Comment: Would this be 2y'(x)*1*2y"(x)?

Is this differentiation correct?


Block: DRUPAL_NO_CACHE not working

Question: I have a block that displays an item fetched from the database at random. The block has DRUPAL_NO_CACHE as cache parameter. However, when visiting the page as anonymous user with the cache on, the item never changes.
Some code:
<code>function foo_block_info() {
  $blocks = array();

  $blocks['foo'] = array(
    'info' => t('Foo'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

function foo_block_view($delta = '') {
  if ($delta == 'foo') {
    $block = array(
      'content' => theme(
        'foo_block',
          array(
            'item' => entity_get_controller('foo')->get_random_foo(),
          )
        ),
    );
    return $block;
  }
}

function foo_theme($existing, $type, $theme, $path) {
  return array(
    'foo_block' => array(
      'template' => 'foo-block',
      'arguments' => array(
        'item' => NULL,
      ),
    ),
  );
}
</code>
I suspect it's a Drupal Core bug, I've checked the forums but can't really find a solution for Drupal 7.
I know I could insert the item in the DOM with AJAX, but that's a last resort.
Answer: If you are caching the whole page (which is off by default in D7) then BLOCK_NO_CACHE will not make a difference on a block. Because while the block is not cached, the page is.
I think what you may want is the esi api module it allows you to use ajax to render the blocks.
Comment: As Jeremy said, block caching applies when there is *no* page cache or when a page cache needs to be rebuilt. Remember that a page cache entry is for a specific URL, but you might be displaying the same cached block on every/multiple pages.
Comment: In what situations would DRUPAL_NO_CACHE or it's D6's variant be useful? When the cache is off there wouldn't be a reason to set the block cache to DRUPAL_NO_CACHE anyway (since it's not cached).
Comment: I may be wrong, but block cache is independent of page cache. If you really need to have no caching for the block you should specify it. Otherwise you get DRUPAL_CACHE_PER_ROLE

Block: DRUPAL_NO_CACHE not working


Is Migrate module supposed to be used for imports too?

Question: I am in need of an entity import functionality so I started to write my own. But then I started to think if I'm not reinventing the wheel and it occurred to me that maybe Migrate module will be used for this(beside it's main purpose)?
I mean, since all entity fields are objects with their own specifications regarding data they work with, Migrate will probably handle all of this. So am I correct to assume this or should I continue to work on my module? Because right now I started to think about the field objects(FieldDefinition for core fields and FieldInstanceConfig for field API fields) and I would need to write a lot of data handlers for each type of field and data-type it's working with(boolean, text, file/image, float,...) which will be a lot of work.
On the other hand Migrate would probably have all this data-handlers already in place so they could be reused?

By entity import I mean creating data from csv, xls, xml... files.
Comment: Are you working on Drupal 8? If yes, Migrate module has no package for 8.
Comment: Yes D8, that's why this is tagged by '8', though I know it can easily be overlooked. And by import I mean creating entities from files like csv, excel and such. I've edited the original post to make it clear.
Answer: Of course! That's why we split migrate_drupal and migrate. The latter is the API, it has the destinations, like the entities you are asking for. Handbook page is at https://drupal.org/node/2127611 useful article at http://webikon.com/cases/migrating-to-drupal-8
Comment: So in order to present my custom entity import UI to the user with option to select which columns he want's to import from lets say CSV file and to which entity fields to map them I would have to write some sort of UI module that would export such settings into a migrate configuration file and only after that run it?
Comment: Yes please. We are much interested in such a UI; it's somewhat planned for contrib.
Comment: Is there sandbox project for this?
Comment: The IMP sandbox focuses on core parts. We do not yet have ventured into contrib; core has priority.
Answer: Also github.com/larowlan/default_content for module provided entities


How to disable anchor tag click when clicked on bootstrap toggle button inside it

Question: I am new to BootstrapToggle and I am using Bootstrap toggle button inside an anchor tag like this :

Here is the code snippet :

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">

   Hello World

   <input type="checkbox" data-toggle="toggle" data-on="Accepted" data-off="Rejected" data-onstyle="success">

Now If I toggle the button the anchor tag alert also gets called. I want only my
button to be toggled If I change it not the anchor tag alert should be called in that case.
Any help would be appreciated.
Comment: remove `onclick="alert();"` and put `href="javascript:void(0);`
Comment: But what If I also want to call javascript method on anchor click as well
Answer: Instead of this:

use

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">

   Hello World

   <input type="checkbox" data-toggle="toggle" data-on="Accepted" data-off="Rejected" data-onstyle="success">

Comment: Thanks Mayank but what If I also want to call a method on anchor click as well.
Comment: Then use `onclick`, the above solution is for dealing with `href`
Comment: but in that case onclick triggers also if I toggle the button.
Comment: So what is the issue ?
Comment: The issue is that I dont want onclick to trigger if I toggle the button and dont want button to toggle if I click on the anchor link
Answer: I would suggest you to use as i had encounter the same problem.

Comment: Thanks Kavish but What I I also want to call a javascript method on anchor click as well
Answer: It is a strange solution to wrap the button with the anchor, but if this is what you want...
You can try something like that

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">

   Hello World

   <input type="checkbox" data-toggle="toggle" data-on="Accepted" data-off="Rejected" data-onstyle="success">

Comment: Thanks Kordi but What I really want is the onclick method on anchor tag not on toggle button and when we click on the toggle button that anchor click must not be invoked
Comment: @Lakhtey, I think you are contradicting yourself. You are saying that you don't want the anchor click to be invoked, and this is the solution that kavish and Mayank suggested. But then you said that you want the javascript to be called. A bit confusing to be honest.
Comment: basically What I want is a onclick on my anchor tag but dont want to trigger that onclick when button gets toggled. OnClick should be called only when the span text inside anchor tag is clicked. Hope now you get my point
Comment: Why do you want to wrap the toggle button with the anchor?
Comment: Thats a template I am following


Drupal base_url incorrectly writing extra subdomain

Question: We have a basic drupal multi-site installation on a RHEL (RedHat) server.
For some reason when viewing the site, the asset URLs (CSS/JS) all point to the wrong subdomain.
Our site URL: http://drupal.sandbox.domain.com the drupal index page loads up with asset URLs being written as: http://drupal.sandbox.sandbox.domain.com.
Why would drupal add in the extra .sandbox subdomain?
The .htaccess file has been left as the default, also attempted to set RewriteBase to /, but there was no change. The sites/default/settings.php file has the base_url set to: $base_url = 'http://drupal.sandbox.domain.com' but Drupal is overwriting this somewhere. Setting the $base_url to the IP of the server causes the assets to be linked to the correct location (using the IP rather than the actual domain), but this is not ideal.
I've tested using the same configuration on an Ubuntu Server without any problems. I'm not sure exactly how to track down the cause of this problem.
How would I go about debugging this and discovering what is causing the overwritten URLs?
Answer: This is not a Drupal-specific problem. This can easily be checked by creating a standalone PHP page and using the same code to test. Being that the variable is overwritten immediately after it is set shows that PHP/Apache is the one doing the overwriting.
It is possible for Apache to overwrite input and output. See: What would cause PHP variables to be rewritten by the server?


Selenium evaluating a subset of the DOM

Question: I'm trying to evaluate the subset of a DOM element with selenium. First i find a parent element, after that I use FindElement on the parent to look for a child element. But I'm getting unexpected behavior here. The elements returned are not part of the parent.
I looked at the documentation but i don't get the results they do. https://www.selenium.dev/documentation/webdriver/elements/finders/
var scavengeContainers = context.Driver.FindElements(ElementData.ScavengeOptions);
This returns 4 elements, now I want to categorize them.
for (int i = 0; i < scavengeContainers.Count; i++)
{
    Log.Information("Getting scavenge data for {ele}",scavengeContainers[i].GetAttribute("innerHTML"));
    var readyScav = scavengeContainers[i].FindElement(By.XPath(ElementData.ReadyScavenge.Xpath));`

    if (scavengeContainers[i].FindElement(ElementData.WaitingScavenge) != null)
        scavengeModel.Levels[i] = new ScavengeLevel() { CompletionTime = GetScavengeQueueTime(scavengeContainers[i]), Id = i, Bought = true };
    else if (readyScav != null)
         scavengeModel.Levels[i] = new ScavengeLevel() { CompletionTime = DateTime.Now, Id = i, Bought = true };
    else
         scavengeModel.Levels[i] = new ScavengeLevel() { Bought = false, Id = i };
            }

I can verify the elements html with the print statement for innerHTML. This makes me sure that i have 4 different elements. However readyScav ID is always the same, even though it shouldn't be found in some of them. Is this just broken or am i using the wrong ? I have currently worked around it by looking for class in the innerHTML of the parent, instead of finding the element from the parent. However i still like to know what i am doing wrong here.
The find element code
scavengeContainers[i].FindElement(ElementData.WaitingScavenge)
is a bit diffrent from normal but this just translates to an extension function for readability.
public static IWebElement? FindElement(this IWebElement webElement, ElementData data)
{
    try
    {
        return webElement.FindElement(By.XPath(data.Xpath));
    }
        catch(NoSuchElementException)
    {
        Log.Debug("element {@elementData} was not found", data);
    }
    return null;
}

Comment: show the locator that fails to look up the child elements as you expect
Comment: The issue is not that he wont find it, the issue is that it will find it even when its not there. If one of the elements in the array contains the locator then it will find it for all. Meaning it doesn't search the scavengeContainers[i] for children, it searches the dom again. Printing the innerHTML however does give me unique html as i see it when looking at the website.
Comment: So what is the XPath you are using
Comment: "//*[contains(@class,\"act_btn\")]"
Answer: You shouldn't start your locator from // when you look up from the specific element. When you do so, the search context is ignored and the element is getting searched from the top of the DOM.
Try .//*[contains(@class,\"act_btn\")]

Selenium evaluating a subset of the DOM


How can I set values for certain keys within multidimensional arrays to null?

Question: I want to unset an array value but not the key
Before:
Array
(
    [0] => Array
        (
            [id] => 45
            [type] => 1
            [lgsize] => 10
            [lgid] => 9
            [rank] => 4
            [winprize] => 3000
        )
[1] => Array
        (
            [id] => 46
            [type] => 1
            [lgsize] => 10
            [lgid] => 9
            [rank] => 4
            [winprize] => 2000
        )
)

After:
Array
(
    [0] => Array
        (
            [id] => 45
            [type] => 1
            [lgsize] => 10
            [lgid] => 9
            [rank] => 4
            [winprize] =>
        )
[1] => Array
        (
            [id] => 46
            [type] => 1
            [lgsize] => 10
            [lgid] => 9
            [rank] => 4
            [winprize] =>
        )
)

Comment: unset($array[0][winprize]); unset($array[1][winprize]); doesn't work. it removes the key.
Comment: `$array[1]['winprize'] = ""`
Comment: execute these two commands :
unset($array[0][winprize]);
unset($array[1][winprize]);
Comment: @B.Desai so easy.
Comment: Do you want to set the value to `null` or an empty string? Since you use the work *unset* it suggests the former.
Answer: I assume that your array length can be increased
Do it like below:-
foreach($array as &$arr){ // iterate over array
   $arr['winprize'] = ''; // empty value of desired key
}

Output:-https://eval.in/847434
Comment: When you iterate by reference it is better to unset value variable after the loop.
Answer: Another way is using sizeof function
for($i = 0; $i < sizeof($array); $i++) {
  $array[$i]['winprize'] = '';
}

Comment: Two things: a) how about using `count()` instead of the alias function (see http://php.net/manual/en/function.sizeof.php), and b), the array might not be 0-indexed, and the keys might not be sequential.
Answer: In looping please leave it blank.
e.g.
$array[0]['winprize'] = '';

Answer: Alternatively, you could also use array_map():
<?php

$data = array(
    array(
        'id' => 45,
        'type' => 1,
        'lgsize' => 10,
        'lgid' => 9,
        'rank' => 4,
        'winprize' => 3000,
    ),
    array(
        'id' => 46,
        'type' => 1,
        'lgsize' => 10,
        'lgid' => 9,
        'rank' => 4,
        'winprize' => 2000,
    ),
);

$cleaned = array_map(function (array $element) {
    // only set null as value if the key actually exists
    if (array_key_exists('winprize', $element)) {
        $element['winprize'] = null;
    }

    return $element;
}, $data);

var_dump($cleaned);

For reference, see:

http://php.net/manual/en/function.array-map.php
http://php.net/manual/en/function.array-key-exists.php

For an example, see:

https://3v4l.org/EskKq


Adicionar classe Tamanho a Produto

Question: Preciso fazer algo que quando for cadastrar um produto, faça igual uma pizza tenha tamanhos e cada tamanho seu preço.
Então criei uma classe Tamanho.
public class Tamanho implements Serializable {
@Id
@GeneratedValue
private Long idTamanho;
private String tamanho;
private Double valorTamanho;
private Long produto;

e fiz a chamada dela dentro de minha classe Produto
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Tamanho> tamanhos;

Agora bateu a dúvida como q eu vou adicionar na tela de cadastro pra quando a pessoa clicar em adicionar um tamanho o sistema gerar um campo para o usuario digitar um novo tamanho e assim gravar.
Atualmente estou fazendo assim:

Cadastro de Produtos

                                <mp:input id="nome" label="Nome" value="#{produtoBean.prod.nomeProduto}"/>

                                <mp:input id="desc"
                                          label="Descrição" value="#{produtoBean.prod.descricaoProduto}"/>

                                <mp:input id="valor" type="number" label="Valor" value="#{produtoBean.prod.valorProduto}">
                                    <f:convertNumber pattern="#,##0.00"></f:convertNumber>
                                </mp:input>

Categoria

                                <h:panelGroup layout="block" styleClass="selection">
                                    <h:selectOneRadio layout="pageDirection" id="categoria" converter="categoriaConverter" label="Categoria" value="#{produtoBean.prod.categoriaProduto}">
                                        <f:selectItems
                                            value="#{loginBean.pessoaAtual.categorias}"
                                            var="categoria" itemValue="#{categoria}"
                                            itemLabel="#{categoria.tituloCategoria}"/>
                                    </h:selectOneRadio>
                                </h:panelGroup>

Ingredientes

                                <h:panelGroup layout="block" styleClass="selection">
                                    <h:selectManyCheckbox
                                        id="ingrediente"
                                        converter="ingredienteConverter"
                                        label="Ingrediente"
                                        layout="pageDirection"
                                        value="#{produtoBean.prod.ingredientesProduto}">

                                        <f:selectItems
                                            value="#{ingredienteBean.listarIngrediente()}"
                                            var="ingrediente" itemValue="#{ingrediente}"
                                            itemLabel="#{ingrediente.nomeIngrediente}"/>

                                    </h:selectManyCheckbox>
                                </h:panelGroup>

Foto

                                    <mp:input hidden="hidden" type="hidden" id="imagemProduto" value="#{produtoBean.prod.imagemProduto}"></mp:input>

                                    <mp:image id="imagem" circle="true" width="150" height="150" value="../imagens/#{produtoBean.prod.imagemProduto}" />

                                <mp:button update=":form1:listaProduto" value="Salvar" action="#{produtoBean.salvar}"></mp:button>

Comment: Veja se te ajuda: http://pt.stackoverflow.com/questions/27982/campos-dinamicos-com-jsf-e-ajax-n%C3%A3o-renderizando-mascara
Comment: deu certo..obrigado
Comment: Se funcionou coloque a resposta e a marque como correta, dessa forma vc ajudará outros com a mesma dúvida
Answer: Criei uma tabela:

                                            <h:outputText value="#{tam.tamanho}"></h:outputText>

                                            <h:outputText value="#{tam.valorTamanho}">
                                                <f:convertNumber pattern="#,##0.00"></f:convertNumber>
                                            </h:outputText>

                                            <mp:button value="Remover" update="listaTamanhos" action="#{tamanhoBean.removerTamanho(tam)}"/>

                                    <mp:input id="tituloTamanho" label="Tamanho" value="#{tamanhoBean.tamanho.tamanho}"/>
                                    <mp:input id="valorTamanho" type="number" label="Valor" value="#{tamanhoBean.tamanho.valorTamanho}">
                                        <f:convertNumber pattern="#,##0.00"></f:convertNumber>
                                    </mp:input>
                                    <mp:button value="Adicionar" update="listaTamanhos, tituloTamanho, valorTamanho" action="#{tamanhoBean.adicionarTamanho()}"/>

Nela eu adicionava os valores do tamanho, depois era só pegar o valor da tabela e setar dentro do produto.

Adicionar classe Tamanho a Produto


X-Drupal-Cache http header

Question: Examining for http headers, I mentioned the header "X-Drupal-Cache HIT".
I use varnish reverse proxy.
Is it necessary for this header to appear? Can I make it be ommited? If yes, how? Would that have negative implications?
Answer: To change drupal http-header information check out drupal_set_header() (D6) or
drupal_add_http_header() (D7).
Looking at the documentation for _drupal_bootstrap_page_cache, it seems the header shows 'HIT' if the page is displayed from cache, and 'MISS' in the case it is not.
Check out Set X-Drupal-Cache header during page_cache_fastpath and Implement better cache headers for reverse proxies for more information about the X-Drupal-Cache header. It seems to be a Drupal 7 or Pressflow only thing.
Comment: I think there is no specific info about at these links.

X-Drupal-Cache http header


Getting payment configuration from PayPal lib

Question: I'm using PayPal in my monodroid application. I used the libraray that has been shared in this topic: http://forums.xamarin.com/discussion/comment/15331/#Comment_15331
But i have a problem at getting PaymentConfirmation object at OnActivityResult method. This is my code:
protected override void OnActivityResult (int requestCode, Result resultCode, Intent data)
    {
        if (resultCode == Result.Ok ) {
            var confirm =  data.GetParcelableExtra ("com.paypal.android.sdk.paymentConfirmation") ;

            PaymentConfirmation pc = (PaymentConfirmation)confirm;
        if (confirm != null) {
            try {
                //Log.Info ("paymentExample", confirm.ToJSONObject ().ToString (4));
                // TODO: send 'confirm' to your server for verification.
                // see https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
                // for more details.\
            } catch (JSONException e) {
                Log.Error ("paymentExample", "an extremely unlikely failure occurred: ", e);
            }
        }
    }else if (resultCode == Result.Canceled ) {
        Log.Info ("paymentExample", "The user canceled.");
    }else {
        Log.Info ("paymentExample", "An invalid payment was submitted. Please see the docs.");
    }
}

at the third line of the method. Compiler can not cast confirm to PaymentConfirmation. Do I need any other classes or codes in order to use data.GetParcelableExtra?
Comment: Try `confirm.JavaCast();` instead, not sure if that will help though.
Answer: As written in a comment JavaCast should be used in this case. I think this happens when the binding generated for the type, does not contain a GetType method. Hence .NET does not know what to cast it to.
So your line:
PaymentConfirmation pc = (PaymentConfirmation)confirm;

will need to be:
PaymentConfirmation pc = confirm.JavaCast<PaymentConfirmation>();


Discrete vs. Continuous variables

Question: This might seem silly but I am unable to find a clear answer:
I need to define whether two variables are either discrete or continuous: "total work" and "sleep". The description of these variables are as follows:
total work - minutes worked per week
sleep - minutes sleep at night, per week
The data given for these variables are all integers (no decimals) which inclines me to think both variables are discrete. Additionally to me it seems you can only sleep or work a finite amount of time in this case, given the constraint of "per week" as well as "per night"but maybe that is irrelevant as to whether they are discrete/continuous? Any help?
Comment: Answers & comments so far suggest it might be futile, or at least perplexing, to try to determine whether the variables are in some sense *truly* discrete or continuous. As you say, you need to define them as discrete or continuous: edit your question to explain to what end.
Answer: If your data values are all integers, this means that the "total work" and "sleep" are both being measured in whole minutes (i.e., part minutes are not being recorded).  In view of this, your data is discrete.  This is an example where a notionally continuous variable is being "discretised" by measurement limitations.
Comment: Are data are always discrete to some level of precision. The underlying construct being measured is clearly continuous.
Comment: Yes, that is correct.  Since our measuring instruments always have finite precision, we can go down only to a certain non-zero unit of measurement.  If this is sufficiently fine then we might use continuity as a good approximation, but if the measurements are quite crude, we might prefer a discrete model.

Discrete vs. Continuous variables