text:
Q: Is it possible to extract the full output for the statistical tests performed in gtsummary? Background/aim
I am using gtsummary to present tables that also include statistical tests performed by the package. I want to supplement the table with additional information about the statistical test in my manuscript text. For example, gtsummary has tested mean differences between groups with anova and I want to report the F value and degrees of value of the test in the text. Is there any way to extract this information from the gtsummary object or do I have to run the statistical tests again separately and extract it from there? I.e., run a aov() and copy paste from output?
Example situation with anova as the statistical test
library(tidyverse)
library(gtsummary)
theme_gtsummary_mean_sd()

gtTable <- mtcars %>%
  select(cyl, mpg) %>%
  tbl_summary(by = cyl) %>%
  add_p()

oneWay <- aov(mpg ~ cyl, data = mtcars)
summary(oneWay)
#>             Df Sum Sq Mean Sq F value   Pr(>F)
#> cyl          1  817.7   817.7   79.56 6.11e-10 ***
#> Residuals   30  308.3    10.3
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Table

A: This should be possible, but unfortunately it is not current possible with the aov() results. I will make it possible in the next release, and you can follow this GitHub Issue to track the progress of the release. https://github.com/ddsjoberg/gtsummary/issues/956
Here is an example using a t-test, where it currently is possible.
library(gtsummary)
packageVersion("gtsummary")
#> [1] '1.4.2'

tbl <-
  trial %>%
  select(age, trt) %>%
  tbl_summary(by = trt,
              missing = "no") %>%
  add_p(all_continuous() ~ "t.test")

# report any statistics in `tbl$table_body` with `inline_text()`
tbl$table_body
#> # A tibble: 1 x 18
#>   variable test_name var_type   var_label row_type label stat_1 stat_2 test_result
#>   <chr>    <chr>     <chr>      <chr>     <chr>    <chr> <chr>  <chr>  <list>
#> 1 age      t.test    continuous Age       label    Age   46 (3~ 48 (3~ <named lis~
#> # ... with 9 more variables: estimate <dbl>, statistic <dbl>, parameter <dbl>,
#> #   conf.low <dbl>, conf.high <dbl>, p.value <dbl>, estimate1 <dbl>,
#> #   estimate2 <dbl>, alternative <chr>

# the columns about the t-test come from `t.test(...) %>% broom::tidy()`
t.test(age ~  trt, data = trial) %>% broom::tidy()
#> # A tibble: 1 x 10
#>   estimate estimate1 estimate2 statistic p.value parameter conf.low conf.high
#>      <dbl>     <dbl>     <dbl>     <dbl>   <dbl>     <dbl>    <dbl>     <dbl>
#> 1   -0.438      47.0      47.4    -0.209   0.834      184.    -4.57      3.69
#> # ... with 2 more variables: method <chr>, alternative <chr>

# t-statistic
inline_text(tbl, variable = "age", column = "statistic") %>% style_sigfig()
#>       t
#> "-0.21"
# degrees of freedom
inline_text(tbl, variable = "age", column = "parameter") %>% style_number()
#>    df
#> "184"

Created on 2021-08-10 by the reprex package (v2.0.1)


text:
Q: How can I rerender a repeater I want to rerender the contents of a repeater using jquery but it doesn't seem to be working any ideas?
Visualforce code:

<apex:Form >
<apex:pageBlock Title="Cases">
<apex:actionFunction name="rerenderDevelopmentPanel" rerender="DevelopmentPanel" />

  <apex:pageBlockSection title="Development" collapsible="true" columns="3">

     <apex:outputPanel id="DevelopmentPanel">
        <apex:repeat value="{!CasesMap['Development']}" var="listvalue" id="DevelopmentRepeater">

               {!listvalue.CaseNumber}

{!listvalue.Subject}

{!listvalue.Description}

        </apex:repeat>
        </apex:outputPanel>

  </apex:pageBlockSection>

Controller code:
public class CaseController
{
public static Map<String, List<Case>> getCasesMap()
{
    Map<String, List<Case>> casesMap = new Map<String, List<Case>>();
    List<Case> developmentCases = new List<Case>();
    List<Case> testingCases = new List<Case>();
    List<Case> roadblockedCases = new List<Case>();
    List<Case> doneCases = new List<Case>();
    for(Case caseItem : [select Id, Subject, Description, Status, CaseNumber from Case])
    {
        if(caseItem.Status == 'Development')
        {
            developmentCases.add(caseItem);
        }
        if(caseItem.Status == 'Testing')
        {
            testingCases.add(caseItem);
        }
        if(caseItem.Status == 'Roadblocked')
        {
            roadblockedCases.add(caseItem);
        }
        if(caseItem.Status == 'Done')
        {
            doneCases.add(caseItem);
        }

        System.debug('status:' + caseItem.Status + ' Id:' + caseItem.Id);
    }
    casesMap.put('Development', developmentCases);
    casesMap.put('Testing', testingCases);
    casesMap.put('Roadblocked', roadblockedCases);
    casesMap.put('Done', doneCases);
    return casesMap;
}

Not all the code is here but you get the idea. The Javascript function gets called and both alert 1 and 2 fire but the rerender of the repeater doesn't seem to happen. I was expecting it to call the controller's getCasesMap function again and rebuild the cases on the screen. Instead nothing happens.
Thanks and any help is appreciate.
-Adam

A: You can see both alert(1) and alert(2) since there may not any script errors. Which means yes it's calling to your actionFunction as well. But the problem is you don't have an action parameter in your actionFunction. without action parameter it won't call the controller and so framework doesn't think of a rerender. So simply add it and try.
<apex:actionFunction action="{!getCasesMap}" name="rerenderDevelopmentPanel" rerender="DevelopmentPanel"/>

I'm assuminig that you need to call the controller method at page loading and for that using this actionFuntion. If not I don't see a special usage of having an actionFunction here(in the posted portion of your code). But for this case also may be you should try the action parameter of the page itself.

A: First up, your question doesn't have an action parameter in the <apex:actionFunction> tag which means no controller code is getting called; if that is the case (and it's not a posting issue) then hopefully @highfive will answer and can be voted up, if it's not the case then here's some things to try.
I'm assuming you just missed the action parameter while posting in which case the issue might just because of the page structure you've got in place. Maybe try the following (added ID to the <apex:pageBlockSection>:
<apex:actionFunction name="rerenderDevelopmentPanel" rerender="section.DevelopmentPanel"  action="{!getCasesMap}"/>

<apex:pageBlockSection title="Development" collapsible="true" columns="3" id="section">

    <apex:outputPanel id="DevelopmentPanel">

If that fails you might have better luck putting the <apex:actionFunction> right next to the panel itself:
<apex:pageBlockSection title="Development" collapsible="true" columns="3" id="section">

    <apex:actionFunction name="rerenderDevelopmentPanel" rerender="section.DevelopmentPanel" action="{!getCasesMap}"/>
    <apex:outputPanel id="DevelopmentPanel">

Finally, sounds silly but I've done it before, make sure that something being rerendered is actually being changed by the controller :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: What are the differences between the difficulty levels in Tomb Raider? I would like to know:

*

*Do the quantity of enemies increase in the harder difficulties?

*Does the salvage or XP received change?

*Are there any enemy AI behavior changes? Do they become "smarter"?

*Are stealth attempts harder? Are you more easily detected?

*Any other difficulty changes?

A: I've completed the game on hard and played around with other difficulties.
The only differences appear to be:

*

*Quick time events are, er, quicker. You have less time to hit that one button.

*Damage done to you by enemies is higher - on hard a single rifle burst can kill you.

*Non head-shot damage appears to be lower.
On my hard playthough I fully upgraded all the guns and skills just before the point of no return (the game warns you when you reach it), but that was with all treasures found and all challenges complete.
On Xbox there don't appear to be any achievements related to difficulty.

A: I've been playing on normal and got to a battle that I just couldn't beat (I died probably 100 times in this one part!), so scaled down to easy for that scene. The main difference I noticed was that it aims a bit for you. It's very subtle, but when I pull out my bow and press on the trigger to find the "red" target, it's much more likely to already be lined up for me while on easy mode. The bad guys can still move out of the way, but I don't have to waste time lining it up in the first place (something I'm not terribly good at).
In the non-combat zones, I haven't noticed any difference at all. I don't think the playthrough is different on different levels - just the way the guns / controls handle seems to be different.


text:
Q: Image not centered using patternImage in Swift In my app I display a background image on a UILabel using patternImage like so:
self.boxBackground = UIImage(named: "emptyBox")
self.backgroundColor = UIColor(patternImage: boxBackground)

The UILabel is a custom class so this is set in the init method and boxBackground is the UIImage I'm using. The image is the exact dimensions of the custom UILabel (40x46).
This was working fine with the image displaying centered until recently when Xcode updated (Swift 5). Now it tiles slightly above and to the left so the image looks like it has been moved 5 points diagonally up to the left. The weird thing is that if there is text in the UILabel it displays correctly, as soon as the text is removed it goes back to the off-centered/tiled look.
Am I doing something wrong here or is this a bug?


text:
Q: ndarray that updates its data on demand I would like to have a system, where I have a "Data class" that has some arrays and a "Selection class" that has the same array names whose data are just a mere view on a subset of the arrays from the Data class. which ones should be determined by the instance of the selection class. If one changes something in the instance of the Selection class it should get mapped back to the corresponding Data class and to make things really difficult, not only should the arrays from the selection class be real ndarrays (so al the methods should work), they should also be only views on teh original data or only be created on demand.
The scaffold I have created so far is
import numpy as np

class DataObj():
    def __init__( self, Data_dict ):
        self.arrays = [ n for n,d in Data_dict.iteritems() ]
        for n,d in Data_dict.iteritems():
            setattr( self, n, d )

class Darray(np.ndarray):
    def __new__(cls, input_array, SelObj, *args, **kwargs):
        obj = np.asarray(input_array[ SelObj.selA, SelObj.selB ]).view(cls)
        obj.SelObj = SelObj
        return obj

    def __array_finalize__(self, obj):
        if obj is None: return

    def __getitem__(self, index):
        return super(Darray, self).__getitem__(index)

class SelObj():
    def __init__(self, DataObj, selA, selB):
        self.selA = selA
        self.selB = selB
        self.DataObj = DataObj

        for n in DataObj.arrays:
            Darr = Darray( getattr( self.DataObj, n), self )
            setattr( self, n, Darr )

### creating some objects
DObj  = DataObj({ "X":ones((10,20)),
                  "Y":zeros((10,20)),
                  "Z":arange(10*20).reshape(10,20) })

SObj1 = SelObj( DObj, array([1,3,4]), slice(None,None,2) )
SObj2 = SelObj( DObj, array([4,5,7]), slice(None,2,None) )
SObj3 = SelObj( DObj, array([1,3,4]), slice(None)        )

This works, but now If a do
SObj1.X = 10

it looses the connection and just has a 10 instead of the original array. Even when I do something that actually makes sense like
SObj1.X[0,0] = 10.

this will not appear in the DObj ( because with input_array[ SelObj.selA, SelObj.selB ] I created a copy of the array ). Ans now every SObj will have it's own data which will eventually clog up memory.
I know what I want will not be easy but I would still like to do it. I was also looking into properties and making every Darray a property of SObj; doing the slicing on demand whenever the property is called. However then things like
SObj1.X[0,0] = 10.

will not work anymore, since the property already slices and an additional slice is not mapped back anymore.
I would be very grateful for any hints that would point towards a solution of this structure.
David

A: If you want an expression like
SObj1.X = 10

to change values of some distant sources, you should override __setattr__ method in your SelObj class. Like this:
class SelObj():
    def __init__(self, DataObj, selA, selB):
        self.selA = selA
        self.selB = selB
        self.DataObj = DataObj

        for n in DataObj.arrays:
            Darr = Darray( getattr( self.DataObj, n), self )
            setattr( self, n, Darr )

    def __setattr__(self, name, value):
        setattr(self.DataObj, name, value) # updates the source of the data
        super(SelObj, self).__setattr__(name, value) # updates the representation


text:
Q: Ruby gem sample_form I am using Rails 4.1.6 & Ruby 2.1.5
I want drop-down for all date ie. 1st drop-down should be for Month, 2nd drop-down should be for Date & Last drop-down will be for Year.
M using daterangepicker-bs3 & sample_form gem.
i written in _form.hatml.haml
= f.input :date_of_birth,order: [:month,:year]

So now Month & Year is coming in drop-down. I want date also in drop-down between of month & year, ie. month, date, year format.
For this I tried in same way:
= f.input :date_of_birth,order: [:month,:date,:year]

after putting date, it shows error

"stack level too deep"

Can anyone help me?

A: It looks like a simple spelling error. You want :day, not :date.


text:
Q: How do I base64 encode a string efficiently using Excel VBA? I need to encode a 100KB+ string as base64 in VBA. Are there any built-in functions or COM objects available which will do this as a pure VBA approach is either complex or doesn't scale well at these volumes (see links from dbb and marxidad)?

A: As Mark C points out, you can use the MSXML Base64 encoding functionality as described here.
I prefer late binding because it's easier to deploy, so here's the same function that will work without any VBA references:
Function EncodeBase64(text As String) As String
  Dim arrData() As Byte
  arrData = StrConv(text, vbFromUnicode)

  Dim objXML As Variant
  Dim objNode As Variant

  Set objXML = CreateObject("MSXML2.DOMDocument")
  Set objNode = objXML.createElement("b64")

  objNode.dataType = "bin.base64"
  objNode.nodeTypedValue = arrData
  EncodeBase64 = Replace(objNode.Text, vbLf, "")

  Set objNode = Nothing
  Set objXML = Nothing
End Function

A: You can use the MSXML Base64 encoding functionality as described at www.nonhostile.com/howto-encode-decode-base64-vb6.asp:
Function EncodeBase64(text As String) As String
  Dim arrData() As Byte
  arrData = StrConv(text, vbFromUnicode)

  Dim objXML As MSXML2.DOMDocument
  Dim objNode As MSXML2.IXMLDOMElement

  Set objXML = New MSXML2.DOMDocument
  Set objNode = objXML.createElement("b64")

  objNode.dataType = "bin.base64"
  objNode.nodeTypedValue = arrData
  EncodeBase64 = Replace(objNode.Text, vbLf, "")

  Set objNode = Nothing
  Set objXML = Nothing
End Function

A: This code works very fast. It comes from here
Option Explicit

Private Const clOneMask = 16515072          '000000 111111 111111 111111
Private Const clTwoMask = 258048            '111111 000000 111111 111111
Private Const clThreeMask = 4032            '111111 111111 000000 111111
Private Const clFourMask = 63               '111111 111111 111111 000000

Private Const clHighMask = 16711680         '11111111 00000000 00000000
Private Const clMidMask = 65280             '00000000 11111111 00000000
Private Const clLowMask = 255               '00000000 00000000 11111111

Private Const cl2Exp18 = 262144             '2 to the 18th power
Private Const cl2Exp12 = 4096               '2 to the 12th
Private Const cl2Exp6 = 64                  '2 to the 6th
Private Const cl2Exp8 = 256                 '2 to the 8th
Private Const cl2Exp16 = 65536              '2 to the 16th

Public Function Encode64(sString As String) As String

    Dim bTrans(63) As Byte, lPowers8(255) As Long, lPowers16(255) As Long, bOut() As Byte, bIn() As Byte
    Dim lChar As Long, lTrip As Long, iPad As Integer, lLen As Long, lTemp As Long, lPos As Long, lOutSize As Long

    For lTemp = 0 To 63                                 'Fill the translation table.
        Select Case lTemp
            Case 0 To 25
                bTrans(lTemp) = 65 + lTemp              'A - Z
            Case 26 To 51
                bTrans(lTemp) = 71 + lTemp              'a - z
            Case 52 To 61
                bTrans(lTemp) = lTemp - 4               '1 - 0
            Case 62
                bTrans(lTemp) = 43                      'Chr(43) = "+"
            Case 63
                bTrans(lTemp) = 47                      'Chr(47) = "/"
        End Select
    Next lTemp

    For lTemp = 0 To 255                                'Fill the 2^8 and 2^16 lookup tables.
        lPowers8(lTemp) = lTemp * cl2Exp8
        lPowers16(lTemp) = lTemp * cl2Exp16
    Next lTemp

    iPad = Len(sString) Mod 3                           'See if the length is divisible by 3
    If iPad Then                                        'If not, figure out the end pad and resize the input.
        iPad = 3 - iPad
        sString = sString & String(iPad, Chr(0))
    End If

    bIn = StrConv(sString, vbFromUnicode)               'Load the input string.
    lLen = ((UBound(bIn) + 1) \ 3) * 4                  'Length of resulting string.
    lTemp = lLen \ 72                                   'Added space for vbCrLfs.
    lOutSize = ((lTemp * 2) + lLen) - 1                 'Calculate the size of the output buffer.
    ReDim bOut(lOutSize)                                'Make the output buffer.

    lLen = 0                                            'Reusing this one, so reset it.

    For lChar = LBound(bIn) To UBound(bIn) Step 3
        lTrip = lPowers16(bIn(lChar)) + lPowers8(bIn(lChar + 1)) + bIn(lChar + 2)    'Combine the 3 bytes
        lTemp = lTrip And clOneMask                     'Mask for the first 6 bits
        bOut(lPos) = bTrans(lTemp \ cl2Exp18)           'Shift it down to the low 6 bits and get the value
        lTemp = lTrip And clTwoMask                     'Mask for the second set.
        bOut(lPos + 1) = bTrans(lTemp \ cl2Exp12)       'Shift it down and translate.
        lTemp = lTrip And clThreeMask                   'Mask for the third set.
        bOut(lPos + 2) = bTrans(lTemp \ cl2Exp6)        'Shift it down and translate.
        bOut(lPos + 3) = bTrans(lTrip And clFourMask)   'Mask for the low set.
        If lLen = 68 Then                               'Ready for a newline
            bOut(lPos + 4) = 13                         'Chr(13) = vbCr
            bOut(lPos + 5) = 10                         'Chr(10) = vbLf
            lLen = 0                                    'Reset the counter
            lPos = lPos + 6
        Else
            lLen = lLen + 4
            lPos = lPos + 4
        End If
    Next lChar

    If bOut(lOutSize) = 10 Then lOutSize = lOutSize - 2 'Shift the padding chars down if it ends with CrLf.

    If iPad = 1 Then                                    'Add the padding chars if any.
        bOut(lOutSize) = 61                             'Chr(61) = "="
    ElseIf iPad = 2 Then
        bOut(lOutSize) = 61
        bOut(lOutSize - 1) = 61
    End If

    Encode64 = StrConv(bOut, vbUnicode)                 'Convert back to a string and return it.

End Function

Public Function Decode64(sString As String) As String

    Dim bOut() As Byte, bIn() As Byte, bTrans(255) As Byte, lPowers6(63) As Long, lPowers12(63) As Long
    Dim lPowers18(63) As Long, lQuad As Long, iPad As Integer, lChar As Long, lPos As Long, sOut As String
    Dim lTemp As Long

    sString = Replace(sString, vbCr, vbNullString)      'Get rid of the vbCrLfs.  These could be in...
    sString = Replace(sString, vbLf, vbNullString)      'either order.

    lTemp = Len(sString) Mod 4                          'Test for valid input.
    If lTemp Then
        Call Err.Raise(vbObjectError, "MyDecode", "Input string is not valid Base64.")
    End If

    If InStrRev(sString, "==") Then                     'InStrRev is faster when you know it's at the end.
        iPad = 2                                        'Note:  These translate to 0, so you can leave them...
    ElseIf InStrRev(sString, "=") Then                  'in the string and just resize the output.
        iPad = 1
    End If

    For lTemp = 0 To 255                                'Fill the translation table.
        Select Case lTemp
            Case 65 To 90
                bTrans(lTemp) = lTemp - 65              'A - Z
            Case 97 To 122
                bTrans(lTemp) = lTemp - 71              'a - z
            Case 48 To 57
                bTrans(lTemp) = lTemp + 4               '1 - 0
            Case 43
                bTrans(lTemp) = 62                      'Chr(43) = "+"
            Case 47
                bTrans(lTemp) = 63                      'Chr(47) = "/"
        End Select
    Next lTemp

    For lTemp = 0 To 63                                 'Fill the 2^6, 2^12, and 2^18 lookup tables.
        lPowers6(lTemp) = lTemp * cl2Exp6
        lPowers12(lTemp) = lTemp * cl2Exp12
        lPowers18(lTemp) = lTemp * cl2Exp18
    Next lTemp

    bIn = StrConv(sString, vbFromUnicode)               'Load the input byte array.
    ReDim bOut((((UBound(bIn) + 1) \ 4) * 3) - 1)       'Prepare the output buffer.

    For lChar = 0 To UBound(bIn) Step 4
        lQuad = lPowers18(bTrans(bIn(lChar))) + lPowers12(bTrans(bIn(lChar + 1))) + _
                lPowers6(bTrans(bIn(lChar + 2))) + bTrans(bIn(lChar + 3))           'Rebuild the bits.
        lTemp = lQuad And clHighMask                    'Mask for the first byte
        bOut(lPos) = lTemp \ cl2Exp16                   'Shift it down
        lTemp = lQuad And clMidMask                     'Mask for the second byte
        bOut(lPos + 1) = lTemp \ cl2Exp8                'Shift it down
        bOut(lPos + 2) = lQuad And clLowMask            'Mask for the third byte
        lPos = lPos + 3
    Next lChar

    sOut = StrConv(bOut, vbUnicode)                     'Convert back to a string.
    If iPad Then sOut = Left$(sOut, Len(sOut) - iPad)   'Chop off any extra bytes.
    Decode64 = sOut

End Function


text:
Q: Output a field to multiple json fields Is there a way using, Jackson annotations, to have a have given field serialised to 2 json fields.
Like the reverse of @JsonAlias which deserialises multiple json field to the one field.
Eg
class Foo {
    @SomeAnnotation("field2")
    String field1;
}

serialising as:
{
    "field1" : "xyz",
    "field2" : "xyz"
}

Is there a something like @SomeAnnotation?
——
Note: This is not a "should" I do this (it's an imposed requirement), it's a "how" I do this (elegantly).

A: A simple solution to this may be to just add two getters for field1:
class Foo {
    private String field1 = "blah";

    public String getField1() {
        return field1;
    }

    public String getField2() {
        return field1;
    }
}

Jackson will create a field for each getter, following the javabeans naming convention:
{"field1":"blah","field2":"blah"}

An alternative to this may be @com.fasterxml.jackson.annotation.JsonAnyGetter, which can afford you even more flexibility:
class Foo {
    private String field1 = "blah";

    public String getField1() {
        return field1;
    }

    @JsonAnyGetter
    public Map<String, Object> getAny() {
        Map<String, Object> m = new HashMap<>();
        m.put("field2", this.field1);
        m.put("field3", this.field1.toUpperCase());

        return m;
    }
}

Producing:
{"field1":"blah","field3":"BLAH","field2":"blah"}


text:
Q: Program to view and edit fixed width text files? I'm looking for a program that can view and edit text files that contain data in a fixed width format.
The files contain no carriage returns.
I've tried viewing them in excel but the import process makes me insert a break line at every column. The text has 3 columns total, with 15, 12, and then 30 characters in each.
Does anyone know how I can view these files without opening them in notepad where they look like just a jumble of text?
Thanks

A: You could look at:

*

*Record Editor

*OpenFileAid

*Filred

The RecordEditor will display the file in Table format:

But you can change to a Text-Edit view (View >>> Text View (Highlighted fields):

It is probably best to not make changes in text view though

A: If it is a fixed width, notepad should be able to do it fine and I use it for something similar - I am unsure why you are having these problems but I can take a guess.
You are probably using a fancy font of some sort. Go in to Format > Font and choose Lucida Console as the font, or System\any other fixed width font and you should not have any problems.
You may also want to look at other tools such as Notepad++ (available on Ninite for easy installation) or Notepad2

A: The key point everyone is overlooking is the files contain no carriage returns. That is, it sounds like the text files are just one long line that cycles through three fields of length 15, 12, and 30.
You can probably use any text editor with a fixed width font, if you turn on word wrap and resize the window to be exactly 57 characters wide. You probably also want a text editor with overtype mode, so the fields will stay lined up as you edit.
(Edit: As I commented on Mush's answer, WordPad might work with the following setup. Go to View, Options, Text. Select "Wrap to ruler" and check Ruler so the ruler is visible. Then drag the right margin triangle in the ruler until you get the text to wrap at exactly the 57 characters you need. Also, press the Insert key on the keyboard to turn on overtype mode.)
A hex editor might work, if you can set it to exactly 57 characters per line. I have XVI32 on my computer, but even at the smallest font size and with the address column turned off, I could only fit about 45 characters per line on my 1024 × 768 screen. If your screen resolution is larger you may be able to squeeze in the 57 characters you need. The problem is XVI32 always shows both the hex data and text data, but it sounds like you're looking for a similar editor, but just need the text view.

A: Hopefully this isn't a stupid question, but did you try Wordpad?


text:
Q: How to import GraphQL query as a string instead of an object I created a .gql file for my query and I'm importing it like this:
const query = require("@/hello.gql");

However, if I log the query variable to the console, it shows an object, not a string. What can I do so that my imported query is just a string?

A: When querying your server using apollo-client, the provided query parameter has to be an object of the type DocumentNode, which is an AST representation of the query. In other words, if you use apollo-client, you can't just pass it a query as a string, you have to parse it first. This is commonly done using the graphql-tag library. It can also be done automatically through webpack by utilizing a loader like graphql-tag's loader or graphql-loader. If you utilize a loader like that, then any .gql files you import will automatically be parsed into DocumentNode objects for you.
If you're not using apollo-client, there's no need to utilize those loaders. If you still want to store you queries in separate files and import them as strings, you should utilize a different loader, for example, raw-loader.

A: Because, you are only importing the query, not using it.
You can use apollo to use that query like this
const yourQuery= require("@/hello.gql");

data(){
 return {
    queryResponse: []
  }
}

apollo: {
    queryResponse: {
      prefetch: true,
      query: yourQuery
    }
  }

Whit this, you are fetch the query and save the response in queryResponse

A: Now raw-loader is deprecated, you can load them like this.
In the webpack config
 module: {
  rules: [
    {
      test: /\.gql/,
      type: "asset/source",
    },
  ],
},

Then import
import myGraphQlQuery from "myGraphQlQuery.gql"


text:
Q: How to handle log drains in one-off dynos? We're aggregating our logs to papertrail using heroku's log drains. Everything works great, except, I'm not sure how to set up logging from one-off dynos, which we use to run scripts.
I thought the drain configuration would apply to one-off dynos, but I'm not seeing the output I'd expect from jobs we run using the heroku scheduler. In an attempt to figure out what's going on, I tried running
# heroku run bash --app myapp
# babel-node
> var logger = require('bunyan/my_configured_logger');
> logger.info('YO');

I'd expect this to result in logs being shipped to papertrail, but no dice. So then, I tried the simpler command line
> logger "YO"

and this didn't work either. So, either my tests are misguided, or drain configuration doesn't apply to one-off dynos. I think the former is more likely.
How can I test log drains (configured for a remote papertrail syslog) are working correctly?

A: Try
heroku run:detached --app myapp babel-node -- -e 'var logger = require("bunyan/my_configured_logger"); logger.info("YO");'

The key here is to run the dyno in detached mode, so that stdout and stderr go to the Heroku log drain instead of the console. That means you can't run bash interactively, so you have to pass the JavaScript to evaluate on the node command line.


text:
Q: Elasticsearch index created with fieldtype mapping integer, recognized as "string" in Kibana 4 I have created an index in elasticsearch 1.7 like this:
    curl -XPUT 'http://localhost:9200/test' -d '
{
    "test" : {
        "properties" : {
            "user" : {"type" : "string", "index" : "not_analyzed"},
            "message" : {"type" : "string", "null_value" : "na"},
            "syslogtimestamp" : {"type" : "date"},
            "transact" : {"type" : "integer"},
            "subscriber" : {"type" : "integer"},
            "pid" : {"type" : "integer"},
            "acquirertime" : {"type" : "float"}
        }
    }
}
'

I am populating it with data from logstash like this:
filter {
  if [type] == "test" {
    grok {
      match => { "message" => "%{TEST}" }
    }
geoip {
      source => "clientip"
      target => "geoip"
      database => "/etc/logstash/GeoLiteCity.dat"
      add_field => [ "[geoip][coordinates]", "%{[geoip][longitude]}" ]
      add_field => [ "[geoip][coordinates]", "%{[geoip][latitude]}"  ]
    }
    mutate {
      convert => [ "[geoip][coordinates]", "float"]
    }

}
}

Pattern:
TEST %{MONTH:month} (?:(\s+|)) %{INT:day} %{TIME:time} (?<hostname>[a-z0-9_-]+) (?<application>[a-zA-Z0-9-_]+\.(cgi|pml|pfml)):(?:\s+)\[(?:(\s+|))%{INT:pid}\] %{IPORHOST:clientip} (?:\s+\()(?<acquirer>[a-zA-Z0-9_-]+)(?:(\s|))\) (?<event>[a-zA-Z0-9]+)(?:\s+)id=%{INT:transact}(?:\s+)sub=%{INT:subscriber}

So I am trying to get the field "transact" mapped in elasticsearch as an integer. However, when I look up the fields i Kibana 4, all of my fields are "string" types. How can this be?

A: You should look into ES index templates here: https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templates.html
You can have either logstash pass them on or feed them directly to elasticsearch via curl or config.


text:
Q: PolicyVerificationInInterceptor Inbound policy verification failed: These policy alternatives can not be satisfied WSS4J + CXF Client I'm implementing web service client in Java which uses Apache CXF 3.1.1 + wss4j 2.2.1 for WS-Security running in JBOSS EAP 6.3 environment.
I've setted following properties in WSS4JInInterceptor for signature verification in the following way:
org.apache.cxf.endpoint.Client client =  org.apache.cxf.frontend.ClientProxy.getClient(service);
org.apache.cxf.endpoint.Endpoint cxfEndpoint = client.getEndpoint();

Map<String,Object> inProps = new HashMap<String,Object>();

inProps.put(WSHandlerConstants.ACTION,WSHandlerConstants.SIGNATURE + " " + WSHandlerConstants.TIMESTAMP + " ");
inProps.put(WSHandlerConstants.SIG_PROP_FILE, merlin.properties");
inProps.put(WSHandlerConstants.DEC_PROP_FILE, "merlin.properties");
WSS4JInInterceptor wssIn = new WSS4JInInterceptor(inProps);

cxfEndpoint.getInInterceptors().add(wssIn);
try {
result = call service...
}

In this way I got this exception:
[org.apache.cxf.ws.policy.PolicyVerificationInInterceptor] Inbound policy verification failed: These policy alternatives can not be satisfied:
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}AsymmetricBinding
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}InitiatorToken
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}X509Token
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}WssX509V3Token10
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}RecipientToken
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}AlgorithmSuite
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}Basic128
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}Layout
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}Strict
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}IncludeTimestamp
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}OnlySignEntireHeadersAndBody
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}SignedParts
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}SupportingTokens
{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}WssX509v3Token10

The policy section of the wsdl exposed server-side is below:
<wsp:Policy wsu:Id="ExamplePolicy">
<sp:AsymmetricBinding>
<wsp:Policy>
<sp:InitiatorToken>
<wsp:Policy>
<sp:X509Token sp:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/Once">
<wsp:Policy>
<sp:WssX509V3Token10/>
</wsp:Policy>
</sp:X509Token>
</wsp:Policy>
</sp:InitiatorToken>
<sp:RecipientToken>
<wsp:Policy>
<sp:X509Token sp:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/Once">
<wsp:Policy>
<sp:WssX509V3Token10/>
</wsp:Policy>
</sp:X509Token>
</wsp:Policy>
</sp:RecipientToken>
<sp:AlgorithmSuite>
<wsp:Policy>
<sp:Basic128/>
</wsp:Policy>
</sp:AlgorithmSuite>
<sp:Layout>
<wsp:Policy>
<sp:Strict/>
</wsp:Policy>
</sp:Layout>
<sp:IncludeTimestamp/>
<sp:OnlySignEntireHeadersAndBody/>
</wsp:Policy>
</sp:AsymmetricBinding>
<sp:SignedParts>
<sp:Body/>
</sp:SignedParts>
<sp:SupportingTokens>
<wsp:Policy>
<sp:X509Token sp:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/Never">
<wsp:Policy>
<sp:WssX509v3Token10/>
</wsp:Policy>
</sp:X509Token>
</wsp:Policy>
</sp:SupportingTokens>
</wsp:Policy>
</wsdl:definitions>

A: You are using the non-policy aware WSS4JInInterceptor class. You need to use the PolicyBasedWSS4JInInterceptor class instead. Note that this is configured differently to the WSS4JInInterceptor. See here: http://cxf.apache.org/docs/ws-securitypolicy.html


text:
Q: Error: invalid or unqualified - VBA copy paste I'm trying to copy a column of data from one sheet into an empty sheet containing only the matching "tickers" for a large list...once this is done I'm looking to delete all duplicates or do not copy them at all.
A) Could someone help figure out why I'm getting an error when setting the "Ticker"
B) What would the most efficient method be for removing the duplicates?
Dim BottomRow As Long
Dim TopRow As Long
Dim col As Integer
Dim Ticker As String
Dim RngY As Range

TopRow = 6

For col = 4 To 3 + (2 * 26) Step 2

Ticker = .Cell(TopRow - 1, col - 3).Value
BottomRow = .Cells(.Rows.Count, col).End(xlUp).row
.Range(.Cells(TopRow, col), .Cells(BottomRow, col)).Copy

Worksheets("TSX-CleanDate").Activate
RngY = Worksheets("Source").Range("3A:3XFD").Find(Ticker, lookat:=xlPart)

.Cells(4, RngY).Paste

Next

A: The reason you are getting an error when setting Ticker is because you are not referencing any worksheet in your code.
Ticker = .Cell(TopRow - 1, col - 3).Value

That .Cell part would only work if your code was in a With block, but since it's not, you need to fully qualify the worksheet like so (also, you should be using Cells instead of Cell):
Ticker = Sheets("Sheet1").Cells(TopRow - 1, col - 3).Value

As for part B, check out this answer.


text:
Q: how to bind mx4j to an ipaddress rather than localhost in jetty? I am using mx4j in jetty to have a web console to my jmx bean. However, mx4j by default only bind to localhost. I don't know how to set to by to the ipaddres of my machine rather than localhost. Here is my code:
MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
MBeanContainer mBeanContainer=new MBeanContainer(mbeanServer);
mBeanContainer.setManagementPort(1500);
mBeanContainer.start();
server.getContainer().addEventListener(mBeanContainer);
// server is Jetty Server

Thanks

A: I found the answer. YOu need to setup HttpAdapter with XSTL translator like this
HttpAdaptor adapter = new HttpAdaptor();
ObjectName name = new ObjectName("Server:name=HttpAdaptor");
mbeanServer.registerMBean(adapter, name);
adapter.setPort(1500);
adapter.setHost("MyIpAddress");
adapter.setProcessor(new XSLTProcessor());
adapter.start();


text:
Q: XSLT to remove specific unicode contained within an unordered list I have some XML that I'm importing into InDesign. The issue arises with multi-level bulleted lists, which do not format correctly in the document.
The problem is easier to visualise in InDesign. The two screenshots show the same imported XML in different views. The highlighted red areas are the parts I want to remove with XSLT (caused by unwanted unicode
).
InDesign story editor view
InDesign layout view
Here is the imported XML:
<?xml version="1.0" encoding="UTF-8"?>
<STORY StoryCode="454789" DatePublished="18/06/2019 07:50">
   <Story_text>

List 1

            level 1

level 2

level 2

level 1

            level 1

                  level 2

level 3

level 1

level 1

   </Story_text>
</STORY>

And here is my current XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="no" />

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="ul/li">
        <xsl:element name="li{count(ancestor::li) + 1}">
            <xsl:apply-templates select="@*|node()"/>
        </xsl:element>
    </xsl:template>

    <xsl:template match="li/ul">
        <xsl:copy><xsl:text>
</xsl:text><xsl:apply-templates/></xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Template #2 is necessary so that each bullet level can be mapped to a specific InDesign paragraph style (e.g.  to bullet 1 style,  to bullet 2 style etc.). Shoutout to user Tim C for his help here.
Template #3 is necessary to fix a quirk where the the first bullet from a level 2 or above list does not appear on a new line. Because InDesign only allows 1 paragraph style to be applied per new line, without this template, bullets of different levels appear in the same line and get mapped to the same paragraph style (image of InDesign result without template #3).
I have tried the following XSLT:
<xsl:template match="ul/li/ul/text()">
    <xsl:value-of select="translate(., '
', '')" />
    <xsl:apply-templates/>
</xsl:template>

[This gets close but ultimately fails if there are several consecutive bullets of the same level (see InDesign story editor image). I guess because all paragraph separators contained within the
 ...
 get stripped rather than just the ones I want removed.]
And
<xsl:template match="ul/li/ul/text()">
   <xsl:value-of select="substring(., 1, string-length(.)-X)" />
</xsl:template>

[Where X ≤2 nothing changes, when X>2 the result is the same as the above method]
I think what I want to achieve is if a
 ...
 (with at least one parent
) contains ≥2
, delete the final
, but I can't figure out how to translate this into XSLT.
I'd massively appreciate any help/pointers in the right direction.
EDIT
I realise that the imported XML example above is somewhat misleading in terms of line breaks, so here is a more accurate depiction (including the
 paragraph separator):
<?xml version="1.0" encoding="utf-8" standalone="yes"?><STORY StoryCode="454789" DatePublished="18/06/2019 07:50"><Headline>Bullet XML test SO</Headline>

<Standfirst>
placeholder
</Standfirst>

<Story_text>
List 1

level 1

level 2

level 2

level 1

level 1

level 2

level 3

level 1

level 1

</Story_text>

</STORY>

Here is the XML after being transformed with my current XSLT, I've marked the paragraph separators I want to remove.
<?xml version="1.0" encoding="utf-8" standalone="yes"?><STORY StoryCode="454789" DatePublished="18/06/2019 07:50"><Headline>Bullet XML test SO</Headline>

<Standfirst>
placeholder
</Standfirst>

<Story_text>
List 1

<li1>level 1

<li2>level 2</li2>

<li2>level 2</li2>

</li1>
    [TO DELETE]
<li1>level 1</li1>

<li1>level 1

<li2>level 2

<li3>level 3</li3>

</li2>
    [TO DELETE]

</li1>
    [TO DELETE]
<li1>level 1</li1>

<li1>level 1</li1>

</Story_text>

</STORY>


text:
Q: Problems with Instagram API on followers count I am currently running a script to have a live count of followers but it randomly stops working for a while and when I refresh the page, the number drops to 0 until I refresh it again randomly. Not sure what I am doing wrong, is there maybe a way to get the count of followers without going through an API?
EDIT: Actually found out why. The script is making too many requests so it passes the limits set by IG, is there another way to pull the amount of followers? Or limit the requests sent by the script?
Here is the code I use to pull the number from the API

var myCounter = new flipCounter('flip-counter', {value:0,auto:false});
var token = 'ACCESS_TOKEN';
var ref = false;
var tt;
function refs(){
$.ajax({

url: 'https://api.instagram.com/v1/users/self',

dataType: 'jsonp',

type: 'GET',

data: {access_token: token},

success: function(data){

var follows = data['data']['counts']['followed_by'];
if(!ref){
myCounter.incrementTo(follows, 3, 100);
ref=true;
}else{
myCounter.setValue(follows);
}
clearTimeout(tt);
tt=setTimeout(function(){
 refs();
},3000);
},

error: function(data){

console.log(data);

}

});
}
refs();
</script>


text:
Q: Reading a File Character by character in iOS Basically i have a concern, which needs to be solved using Objective C alone. (i have tried with C)

*

*Is there any appropriate way in objective C to read character by character (till EOF) from a file, which is placed in document directory. So, I will append a escape character before all inverted comma's in a file and A special character (say /) before each line.
Replace
(type == "Project")
with
/(doc.type == \"Project\")
if u feel my approach is not correct is there any other method to accomplish this task in an efficient way?

A: Get all the lines from your file, make your changes such as replacing characters or adding more text, and then save the file.
NSString *objPath = [[NSBundle mainBundle] pathForResource:@"textfile" ofType:@"txt"];
NSData *objData = [[NSData alloc] initWithContentsOfFile:objPath];

NSString *objString = [[NSString alloc] initWithData:objData encoding:NSUTF8StringEncoding];
NSMutableArray *lines = [NSMutableArray arrayWithArray:[objString componentsSeparatedByString:@"\n"]];

for (int i = 0; i < lines.count; i++) {
    NSString *oneLine = [lines objectAtIndex:i];
    if (oneLine.length < 2) {
        continue;
    }
    oneLine = [NSString stringWithFormat:@"/%@", oneLine];
    oneLine = [oneLine stringByReplacingOccurrencesOfString:@"`" withString:@"\`"];

    [lines replaceObjectAtIndex:i withObject:oneLine];
}
NSString *finalString = [lines componentsJoinedByString:@"\n"];
//save the file

A: You can use NSFileHandle and invoke readDataAtLength: with a value of 1.


text:
Q: Linux security implications for sudo, su to service account & add secondary group to admin Tomcat? I have a named account to login to a Linux host.  Tomcat is running under a Service Account named "tomcat"
I periodically need to do admin functions like modify tomcat-users.xml
which is configured as
-rw-------. 1 tomcat tomcat   1671 Mar 25 20:50 tomcat-users.xml

I want to audit changes.  Should I

*

*Give named users sudo with entitlements to edit file

*Give named users entitlement to su to the tomcat account and make any needed changes (either via sudo or giving admins the tomcat password)

*Add permissions to allow members of the tomcat group to edit the file and add tomcat as a secondary group to named users.

using sudo would open up potential config errors that would give named users more access than I intended and would allow them to use sudo -i and bypass auditing.  Changing the file permissions expands who can read the file seems risky.
I'm really looking for risks & advantages/disadvantages I have not covered above to help decide the approach to take and not just opinions and "I do it this way".

A: The only working way to have an audit trail you can trust is to work with a least privilege policy, i.e., deny access by default.
If you go with sudo access, you can certainly limit what users can and can't do; but you also need to be aware of the caveats that might apply.
In this case, you requirement is to grant access to a group of users to edit a specific file.
Best practices dictate that each user has a personal account.
It's not required to make those users belong to any group, as this is covered by sudo already.
Assuming your users belong to the operators group, a sudorule would look like:
Cmnd_Alias TOMCAT_COMMANDS = sudoedit /path/to/tomcat-users.xml
Host_Alias TOMCAT_HOSTS = foo.example.com, bar.example.com

Defaults log_host
Defaults log_output
Defaults syslog_badpri=alert
Defaults syslog_goodpri=notice
Defaults:%operators editor=/usr/bin/rvim

%operators TOMCAT_HOSTS = (tomcat)PASSWD: TOMCAT_COMMANDS

This ensures they can't scape the editor, as they are forced to use rvim, and provides some sane defaults to log their activities. You can further harden the sudo policy, and you can add more functionality to it. This is an example.
Another way to accomplish something similar is to version control changes to that file, and have it managed using a configuration management system.
RBAC to these kind of systems is a broad topic, as it is auditing.
It's up to you to collect and analyse the logs generated.


text:
Q: Generate list of objects named recursively My goal is to get a list of Objects named recursively dynamically. This is the code I tried.
I want the object_list to be [Object_0, Object_1, Object_2, Object_3, Object_4]
object_list = []

class Object(object):
    size = ""
    price = ""

def create_object_list(object_list):
    for num in range(5):
        Object_%s = Object() %num
        object_list.append(Object_%s)
    return object_list

This is the error:
Object_%s = Object() %num
SyntaxError: can't assign to operator

A: Having seen the comments on the page, the real answer is just use a list and don't try and give the objects names to denote their place in the list. What you are trying to do is an antipattern. You don't need to set the "name" of the object as if you want to access object_n you can get it via objects[n]. Additionally you can keep things simple use a dict or a namedtuple instead of your custom class.
from random import random

objects = []

for i in range(5):
    obj = {'size': random(), 'price': random()}
    objects.append(obj)

print(objects[0])
print(objects[3]['size'])
print(objects[1]['price'])

For the specific error in the question:
You can't use % in a variable name as it is an operator. See here for what you can use in a name:
https://docs.python.org/2/reference/lexical_analysis.html#identifiers
>>> variable_name = 1
>>> variable_%name = 2
  File "<input>", line 1
SyntaxError: can't assign to operator
>>>

There are several other problems in the code in your question that will probably bite you:

*

*Your Object has class variables and not instance variables.

*You are somehow mixing string and integers.

*You are not actually using recursion in your code (this is in most cases a good thing though).

A: Did you mean:
exec("Object_%s = Object()" %num)
exec("object_list.append(Object_%s)" %num)

Because otherwise it looks like you are trying to format live lines of code and not strings.
That's the obvious error in your code - but otherwise I must agree with all others - if you don't have a good reason for creating variables - just use a dic.

A: I think you want an object_dict:
object_dict = {}

class Object(object):
    size = ""
    price = ""

def create_object_list(object_dict):
    for num in range(5):
        object_dict["Object_{}".format(num)] = Object()
    return object_dict

If you need order for some reason use a collections.OrderedDict:
from collections import OrderedDict
object_dict = OrderedDict()

which will keep the order the object are created:
OrderedDict([('Object_0', <__main__.Object object at 0x7f05d4044390>), ('Object_1', <__main__.Object object at 0x7f05d3fd3710>), ('Object_2', <__main__.Object object at 0x7f05d3fd36d8>), ('Object_3', <__main__.Object object at 0x7f05d3fd3a90>), ('Object_4', <__main__.Object object at 0x7f05d273a278>)])

You can access each object by key:
print(object_dict["Object_0"])
<__main__.Object object at 0x7f05d4044390>

A: You are trying to dynamically create variable names which is not possible. The % operator only works for strings not identifiers. You probably want to use a list here of strings.
If you really want to create new variables dynamically you can use the locals() built-in function which contains a dictionary of local variables. You can for example use locals()['object_%d' % num] = Object(). The globals() function can be used if you want to create global variables.
Notice that even if you do this, you won't get a list of variable names when you print the list; you'll get a list of values.

A: Yet another way to do this:
class Object(object):
    def __init__(self, inst_id):
        self.name = "Object_%d" % inst_id
        self.size = ""
        self.price = ""

def create_object_list(object_list):
    for num in range(6):
        object_list.append(Object(num))
    return object_list

for x in create_object_list(object_list):
    print x.name

Object_0
Object_1
Object_2
Object_3
Object_4
Object_5

A: Say you have these five variables:
a = (1,2,3)
e = "a string"
i = 1.56
o = {'size':'small', 'price':'low'}
u = None

and a list grouping them:
them = [a,e,i,o,u]

You could have created this list dinamically this way:
same = [eval(_) for _ in 'aeiou']
print(same)
# [(1, 2, 3), 'a string', 1.56, {'price': 'low', 'size': 'small'}, None]

So, the list of variables you need to create can be done the same way:
object_list = [eval('Object_'+str(n)) for n in range(5)]

If the objects already exsist, you can use the variables inside your list, but to create the variables themselves dinamically, you could do:
for _ in ('Object_'+str(n)+'=None' for n in range(5)): # or '=...' any appropriate value
    exec(_)                                            # it could be a call to your Object()

print(objcet_list)
# [None, None, None, None, None]


text:
Q: selectizeInput in R shiny I do R shiny project and in ui.R I have this code:
ui.R
    tabPanel("Ctree",  fluidPage(
  sidebarLayout(
    selectizeInput("ctreeinput","Zvolte atributy k cielovemu atributu LoanAmount",choices=colnames(stats_people),multiple=TRUE),
    mainPanel(tableOutput("ctree1"))
    )
 ))

server.R
output$ctree1<- renderTable({
set.seed(123)
library(party)

myFormula = LoanAmount_1 ~ input$ctreeinput

ctree = ctree(myFormula, data=train.ctree)
table(predict(ctree), train.ctree$LoanAmount_1)

ctreePred = predict(ctree, newdata = test.ctree)
table(ctreePred, test.ctree$LoanAmount_1)
})

In server.R I have myFormula, where I want to create something like this:
myFormula = LoanAmount ~ ApplicantIncome+CoapplicantIncome+Dependents+Gender+Married

... but it must be create by user. I want to use selectizeInput. This solution, what I paste here, it doesn´t work, RStudio says, that ERROR: object 'input' not found. What should I do to work my code? Thanks!

A: In server.R, before defining myFormula, you need to define an object (for instance, dataframe) named input, along with a sub-object (e.g., column) named ctreeinput.


text:
Q: query to fetch the all table name where there is a certain column name How to fetch all tables that have for example a column called CreatedByin SQL Server 2008.

A: In Sql Server you can get this by looking at the sys.columns table
  use DB_MAST_AERRE
  select
         OBJECT_SCHEMA_NAME(object_id) AS SchemaName,
         object_name(object_id) AS TableName
         from
            sys.columns
            where name = 'CreatedBy'

A: use [AdventureWorks2014]
go

declare @columnname varchar(50)
set @columnname='CreatedBy'

select a.name as columnname ,b.name as tablename
from sys.columns a
inner join sys.tables b
on a.object_id=b.object_id
where a.name like '%'+@columnname+'%'


text:
Q: Load full Website WinRT i want to load the Kepler reference Page with HttpClient like this:
string resourceAddress = _url;
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, resourceAddress);
            HttpClient httpClient = new HttpClient();
            // Do not buffer the response:
            HttpResponseMessage response = new HttpResponseMessage();
            response = await httpClient.SendAsync(request,
                 HttpCompletionOption.ResponseContentRead);

            using (Stream responseStream = await response.Content.ReadAsStreamAsync())
            {
                int read = 0;
                byte[] responseBytes = new byte[(Int32)responseStream.Length];
                do
                {
                    read = await responseStream.ReadAsync(responseBytes, 0, responseBytes.Length);
                } while (read != 0);
            }

But i think, the Page won´t be loaded complete, like without all images and iframes etc...

A: Downloading just the first piece of html is rarely going to be enough to give you all the elements of the page, even if you parse it and include all the linked images etc. There is also css and javascript that will bring new content into view when you open a page in a browser and getting all this yourself is going to be an effort similar to implementing your own browser. Your best bet would be to either just load the page once in a WebView control and let it cache its content or use a WebView and scan the DOM to try to get all the elements. You could also write a web service that would download the page for you and just deliver you the whole package... assuming that the page doesn't require authentication.


text:
Q: New line for input in Python I am very new to Python programming (15 minutes) I wanted to make a simple program that would take an input and then print it back out. This is how my code looks.
Number = raw_input("Enter a number")
print Number

How can I make it so a new line follows. I read about using \n but when I tried:
Number = raw_input("Enter a number")\n
print Number

It didn't work.

A: Put it inside of the quotes:
Number = raw_input("Enter a number\n")

\n is a control character, sort of like a key on the keyboard that you cannot press.

You could also use triple quotes and make a multi-line string:
Number = raw_input("""Enter a number
""")

A: If you want the input to be on its own line then you could also just
print "Enter a number"
Number = raw_input()

A: I do this:
    print("What is your name?")
    name = input("")
    print("Hello" , name + "!")

So when I run it and type Bob the whole thing would look like:
What is your name?
Bob
Hello Bob!

A: # use the print function to ask the question:
print("What is your name?")
# assign the variable name to the input function. It will show in a new line.
your_name = input("")
# repeat for any other variables as needed

It will also work with: your_name = input("What is your name?\n")

A: In the python3 this is the following way to take input from user:
For the string:
s=input()

For the integer:
x=int(input())

Taking more than one integer value in the same line (like array):
a=list(map(int,input().split()))

A: in python 3:
#!/usr/bin/python3.7
'''
Read list of numbers and print it
'''
def enter_num():
    i = input("Enter the numbers \n")
    for a in range(len(i)):
        print i[a]

if __name__ == "__main__":
    enter_num()


text:
Q: Change HTML using backstretch Currently I display a slider on my website using Backstretch.
Above the slider I have a text block.
It is possible to change the (html) text every time the image changes?
<script>
                    jQuery(".header-slider-container").backstretch([
                      <?php
                           foreach ($background_slider as $slide) :
                           $image = $slide['afbeelding'];
                           $text_slider = $slide['tekst_slider'];

                      ?>

                            "<?= $image['url'] ?>",
                     <?php
                           endforeach;
                     ?>

                        ], {
                        duration: 4000,
                        transition: 'fade',
                        transitionDuration: 600

                    });

I have already created an extra field in wordpress and can retrieve the value ($text_slider = $slide['tekst_slider'];) , but how do I change this?

A: I have never used that plugin before, but by reading their documentation, it looks like you can listen to an event that is triggered either before or after a new image shows. This is a sample code from their doc that is triggered after an image loads:
$(window).on("backstretch.after", function (e, instance, index) {
  // Do something
});

Where it says Do something is where you would place your code to change the HTML as needed.


text:
Q: Compute the hyperbolic angle subtended to the origin by the unit hyperbola through (ct, x) = (0, 1) I'm trying to find the angle subtended by the unit hyperbola through the point $(ct,x)=(1,0)$. I think that I should be integrating something, but I'm not sure how to set it up. I've been trying to think of this as it would be related to a unit circle, where we would have $R=1$ and then the following
$$
\int_0^{\theta_{0}} R^2(\sin^2\theta+\cos^2\theta)d\theta=R^2\int_0^{2\pi}d\theta=(1)(2\pi)=2\pi
$$
So the angle subtended would just be $2\pi$. I know that $1=\cosh^2 x-\sinh^2 x,$ but as I'm only interested in the right hyperbola, I'm not sure I can use the same trick. I do believe this is related to the total proper time along the hyperbola. Beyond this, I'm stuck, and I feel I'm going about this the wrong way. Any ideas? Thank you!

A:
How, exactly, do I use the parametrization?

If you let $(x,y) = (r\cosh\eta,r\sinh\eta)$ and consider the Jacobian determinant, you can show that the area element transforms as
$$\mathrm{d}A = \mathrm{d}x\,\mathrm{d}y =  r\,\mathrm{d}r\,\mathrm{d}\eta\text{.}$$
Alternatively, you can transform the metric $\mathrm{d}s^2 = \mathrm{d}x^2 + \mathrm{d}y^2$ directly and get its determinant for $\mathrm{d}A^2$, but that's slightly more work.
Integrating $\mathrm{d}A$ between the asymptotes involves $\eta\in(-\infty,+\infty)$, and so obviously gives infinite area.

A: This is what I've come up with:
We begin by first parametrizing our coordinate system with the following transformations. Let
$$
x=\cosh\alpha,\\
ct=\sinh\alpha.
$$
Then, from the unit hyperbola, we want the right-hand hyperbola. The area swept out between the hyperbola and its asymptote is given by
$$
\int_0^{\alpha_0}\left(\cosh^2\alpha-\sinh^2\alpha\right)\text{d}\alpha=\left.\alpha\right|_{\alpha=0}^{\alpha_0}=\alpha_0.
$$
Hence, as $\alpha_0\in(-\infty,\infty)$, the angle subtended to the origin is $\alpha=\infty$.


text:
Q: How do I turn OFF colors for ls output in Terminal on OSX my ls output colors all directories differently from files, regardless whether I type ls or /bin/ls. I don't have any LS_COLOR stuff set in .bashrc or related files that I can find.
How do I turn off these colors? (I am quite happy with just ls -F)
Thanks!

A: As noted in comment, OSX ls pays attention to CLICOLOR.  The ls manual page is the place to look.  It appears to be the same program as in FreeBSD, which uses the terminal database (in contrast to GNU ls).  Likewise, note that the variable is LSCOLORS, rather than LS_COLORS:

CLICOLOR
Use ANSI color sequences to distinguish file types.  See LSCOLORS below.  In addition
  to the file types mentioned in the -F option some extra attributes (setuid bit set,
  etc.) are also displayed.  The colorization is dependent on a terminal type with the
  proper termcap(5) capabilities.  The default "cons25" console has the proper capabilities,
  but to display the colors in an xterm(1), for example, the TERM variable must be
  set to "xterm-color".  Other terminal types may require similar adjustments.  Colorization
  is silently disabled if the output isn't directed to a terminal unless the CLICOLOR_FORCE variable is defined.
CLICOLOR_FORCE
Color sequences are normally disabled if the output isn't directed to a terminal.  This
  can be overridden by setting this flag.  The TERM variable still needs to reference a
  color capable terminal however otherwise it is not possible to determine which color
  sequences to use.
TERM
The CLICOLOR functionality depends on a terminal type with color capabilities.

The wording about "termcap(5)" is outdated; both FreeBSD and OSX have used terminfo databases for more than ten years.
The GNU ls manual page does say LS_COLORS (the two are not the same).  The dircolors manual page makes an oblique reference to a "precompiled database" (this is unrelated to terminfo/termcap, and its use of TERM to get similar results is a source of confusion).


text:
Q: Dealing with heavy profiling of execution times in C++ I'm currently working on a scientific computing project involving huge data and complex algorithms, so I need to do a lot of code profiling. I'm currently relying on <ctime> and clock_t to time the execution of my code.  I'm perfectly happy with this solution... except that I'm basically timing everything and thus for every line of real code I have to call start_time_function123 = clock(),  end_time_function123 = clock() and cout << "function123 execution time: " << (end_time_function123-start_time_function123) / CLOCKS_PER_SEC << endl. This leads to heavy code bloating and quickly makes my code unreadable. How would you deal with that?
The only solution I can think of would be to find an IDE allowing me to mark portions of my code (at different locations, even in different files) and to toggle hide/show all marked code with one button. This would allow me to hide the part of my code related to profiling most of the time and display it only whenever I want to.

A: Have a RAII type that marks code as timed.
struct timed {
  char const* name;
  clock_t start;
  timed( char const* name_to_record):
    name(name_to_record),
    start(clock())
  {}
  ~timed(){
    auto end=clock();
    std::cout << name << " execution time: " << (end-start) / CLOCKS_PER_SEC << std::endl;
  }
};

The use it:
void foo(){
  timed timer(__func__);
  // code
}

Far less noise.
You can augment with non-scope based finish operations.  When doing heavy profiling sometimes I like to include unique ids.  Using cout esoecially with endl could result in it dominating timing; fast recording to a large buffer that is dumped out in an async manner may be optimal.  If you need to time ms level time, even allocation, locks and string manipulation should be avoided.

A: You don't say so explicitly, but I assume you are looking for possible speedups - ways to reduce the time it takes.
You think you need to do this by measuring how much time different parts of it take. If you're interested, there's an orthogonal way to approach it.
Just get it running under a debugger (using a non-optimized debug build).
Manually interrupt it at random, by Ctrl-C, Ctrl-Break, or the IDE's "pause" button.
Display the call stack and carefully examine what the program is doing, at all levels.
Do this with a suspicion that whatever it's doing could be something wasteful that you could find a better way to do.
Then if you start it up again, and halt it again, and see it doing the same thing or something similar, you know you will get a substantial speedup if you fix it.
The fewer samples you took to see that thing twice, the more speedup you will get.
That's the random pausing technique, and the statistical rationale is here.
The reason you do it on a debug build is here.
After you've cut out the fat using this method, you can switch to an optimized build and get the extra margin it gives you.


text:
Q: Store complex data structure (JSON Array) in Redis I have a chat app and I'd like to store recent conversations in Redis. My idea is to have something like this:
{
      "userB" : {
      "userAvatar" : "someURL",
      "lastMessage" : "Hi"
    },

      "userC" : {
      "userAvatar" : "someURL",
      "lastMessage" : "Hi"
    },

      "userD" : {
      "userAvatar" : "someURL",
      "lastMessage" : "Hi"
    }

}

So lets say that userA had chat with userB, userC, and userD.
Can I somehow store this in hash with the key as userA... (HSET userA) But how can I store array type of values inside it? And is it possible to update the content inside this array? For example if userA and userB have further conversation. How can I keep the lastMessage always updated?


text:
Q: Using Case Statement in Where Clause ___ Using date ranges with BETWEEN I am trying to filter a date to a specific range depending on whether or not we have passed the first weekday of the current month.
Oracle seems to not like that I am using BETWEEN.
WHEN
TO_DATE(myDate,'YYYYMMDD')=CASE WHEN TO_DATE(SYSDATE-1) - TO_DATE(last_day(add_months(sysdate, -1))+6)>0
THEN
TO_DATE(last_day(add_months(sysdate, -1))+1, 'YYYYMMDD') --AND to_date(TRUNC(SYSDATE) - 1, 'YYYYMMDD')
Else
TO_DATE(last_day(add_months(sysdate, -2))+1, 'YYYYMMDD') --AND to_date(TRUNC(SYSDATE) - 1, 'YYYYMMDD')
END

Please let me know how to correct this.

A: If you want dates that are equal to or after the first monday of the current month, you can do:
to_date(my_date, 'YYYYMMDD') >= next_day(trunc(sysdate, 'MM') - 1, 'MONDAY')

trunc(sysdate, 'MM') - 1 gives you the last day of the previous month. Then next_day(..., 'MONDAY') gives you the following Monday.
You can change the day name according to what your definition of a week day is. Also, it is worth noting that the day name (the second argument to next_day() must be provided in the language of your session.


text:
Q: What is the derivative of $f(x)$ with respect to $g(x,y)$ 2 Suppose that we have a function $f(x)$ of one variable, like $f(x)=x$.
And I want to derive this function with respect to another multivariate function $g(x,y)=x-y$.
My hypothesis is that the derivative is equal to $0$:
$$\frac{{\partial f(x)}}{{\partial g(x,y)}}=0$$
My reason to think that is that $f(x)$ can never be expressed in terms of $g(x,y)$, so $g(x,y)$ does not impact directly $f(x)$ in any way. Also $x$ and $y$ are independent, meaning they are not related, there is no function between them.
Or maybe is undetermined?
But if that is true, I would need to prove it. I would appreciate if you could help me.

A: Basically it's a normal derivative, but the fact that it does operate on the variable $(x-y)$.
For example:
$$\frac{\partial (x-y)^2}{\partial (x-y)}$$
By calling $(x-y) = z$,  you can find the usual derivative:
$$\frac{\text{d} z^2}{\text{d}z} = 2z \longrightarrow 2(x-y)$$
as it shall be.
In your case your function is simply $x$.
By a change of variable like $x-y = z$ you find that $x = z-y$ hence your derivative is like
$$\frac{\text{d} (z-y)}{\text{d}z} = \frac{\text{d}}{\text{d}z}(z-y) = 1$$
In any case, let me tell you that that is a very ill notation.


text:
Q: How to scrape Local Storage KEY/VALUES with R or Python (RVEST, HTTR, XHR, or something like that) I've been trying to scrape this page's Data https://data.anbima.com.br/debentures?page=1&size=2000&.
I easily could get that table usin rvest bs4 etc.
However i found that the JSON file that sources the table's data have others useful complementary information.
Then i found the XHR link in the browser inspection panel provides the access to the JSON file.
I've been using this link for several month, however in the last few weeks that link (https://data.anbima.com.br/debentures-bff/debentures?page=0&size=2000&field=&order=&) started to request for a authorization code (TOKEN). The issue is that this token changes every period of time or another criteria.
I explore i little more and figure-out that TOKEN is generated by a JS and is stored in a Local Storage inside somewhere in the page. I need this token to include as headers in the code...
My simple question is: How can I scrape that value with r or python?
PLEASE CHECK THE IMAGE BELOW
LOCAL STORAGE VALUES
My simple question is: How can I scrape that value with r or python?
library(httr)
library(rlist)
library(jsonlite)
library(dplyr)
library(tidyverse)
library(V8)

resp<-GET("https://data.anbima.com.br/debentures?page=1&size=1499")
http_type(resp)
http_error(resp)

query <- list(
  page="0",
  size="1470",
  field="",
  order=""
)
URL <- "https://data.anbima.com.br/debentures-bff/debentures"

resp<-GET(URL,
          c(
            # add_headers(Referer = "https://data.anbima.com.br/debentures?page=1&size=1470&"),
            add_headers(Authorization = "03AGdBq25HDdu4v2AzEjXJ_twI97EMrFlaNIcs3IuDHWzTFIp2mCXBqPaQPikuK7VRS3D7IC2v5briUdxPK3LpMPqrb1NoBqcXuI8gUkFdgVyNlObIdNzwQpVjcYASaW9N_gDx-M0SclFK54dDXHyRI7UVPAEQryV-1YSF6ebdJbY4BDr_eXRgMYe6UcK_Uh0YdfU1pMlcuU8O5dXKoRA-9GcX_AeaUxAUo5Mo_hQEGb0IPkPxojvEfgHvFdK0SQ4wgnmnJ0pcieO3h2exnJY1QxQd9sqqkfzdbGLaaCC7eNeWzXRAO3Yd9HtUciMclK612LfEm_ut89rtw8hSzlX3ZY6Vmo6zTvPT0WlMUrGLZ7syDEoDJKCi5xv6CSNgdAxqqqudEltDPUB7
")
            ),
            query=query)

js <- fromJSON(content(resp,as="text"))[[1]]

enter image description here


text:
Q: How to bisect an isosceles trapezoid into two equal area parts Given an isosceles trapezoid:

I want to draw a line parallel to the bases (that is, parallel to and in between AD and BC) such that the top half and the bottom half both have equal area.
Specifically, if we define the height of the trapezoid as 1, I want to know how far from the longer base this bisector will fall. Let's call this value m.
For an isosceles trapezoid where the shorter base is some factor k shorter than the other, I suspect that m will be a function only of k.
Here's a more detailed diagram:

Here are some (possibly incorrect) equations describing this:

*

*Area of ABCD = ((a + ka) / 2) * 1

*Area of EBCF = ((a + ja) / 2) * m

*Area of AEFD = ((ja + ka) / 2) * (1 - m)

*Area of EBCF = Area of AEFD

*Area of EBCF + Area of AEFD = Area of ABCD

Intuitively, I would expect j and a to cancel out of these equations, and to be able to get m solely in terms of k. But I'm having trouble figuring out how to get there.

A: The important thing is to note that $(a-ka)=\frac {ja-ka}{1-m}$.  You can prove that by dropping perpendiculars from $A$ and $D$ to $BC$ and observing the triangles on each end are similar.  You can take $a$ out of this to get $1-k=(1-m)(j-k)$  Couple this with $(1+j)m=(j+k)(1-m)$ from the equal areas and you have two equations in three unknowns, which will get you the one parameter solution set you are looking for. $$1-k=\frac{j-k}{1-m}\\(1+j)m=(j+k)(1-m)\\
1-m-k+km=j-k\\m+jm=j+k-jm-km\\1-m+km=j\\2jm-j=k-km-m\\(2m-1)(1-m+km)=k-km-m$$which gives you a quadratic in $m$

A: Hint: Try breaking the trapezoid up into a rectangle and an isosceles triangle. I think that you will find that as the height increases, the rectangle's area will increase linearly, and that the triangle's area will increase quadraticly.

A: This builds on Ross Milkman's answer and makes it more explicit. I suggested it as an edit to his, but the edit was rejected.

The important thing is to note that $(a-ka)=\frac {ja-ka}{1-m}$.  You can prove that by dropping perpendiculars from $A$ and $D$ to $BC$ and observing the triangles on each end are similar.  You can take $a$ out of this to get $1-k=\frac {j-k}{1-m}$:
$$1-k=\frac{j-k}{1-m}\\
1-m-k+km=j-k\\1-m+km=j$$

Couple this with $(1+j)m=(j+k)(1-m)$ from the equal areas and you have two equations in three unknowns, which will get you the one parameter solution set you are looking for.
$$\\(1+j)m=(j+k)(1-m)\\m+jm=j+k-jm-km\\2jm-j=k-km-m\\j(2m - 1)=k-km-m$$

And then, substitute the first into the second to get a quadratic in $m$:
$$\\(2m-1)(1-m+km)=k-km-m\\2m-1-2m^2+m+2km^2-km=k-km-m\\(2k-2)m^2+4m-(1+k)=0$$

Then, use the quadratic equation to get $m$ in terms of $k$:
$$\\m=\frac{-4±\sqrt{16-4(2k-2)(-1-k)}}{2(2k - 2)}$$
So then, for $k=0.1$: $m=.321518311$ or $m=1.900703911$
Since $m$ can't be a value larger than the height of the trapezoid itself, the first answer is the only one that has meaning in this context.

A: Generalizing to arbitrary trapezoids doesn't make things any more difficult, so we won't assume the trapezoid is isosceles or that it has height $1$.  The key fact is that
$$
(ja)^2=\frac{a^2+(ka)^2}{2}.
$$
This can be seen by extending the lines $BA$ and $CD$ until they meet.  (The case where the sides are parallel is trivial.)  Call the meeting point $O$.  Then triangles $BOC$, $EOF$, and $AOD$ are similar, which implies that their areas are equal to some proportionality constant multiplied by $a^2$, $(ja)^2$, and $(ka)^2$.  The areas of trapezoids $BCFE$ and $EFDA$ are therefore proportional to $a^2-(ja)^2$ and $(ja)^2-(ka)^2$ with the same proportionality constant.  Setting these equal gives the key fact.  As a result,
$$
j=\sqrt{\frac{1+k^2}{2}}.
$$
To find $m$, use that the reduction in horizontal width is proportional to the height to get
$$
\frac{m}{h}=\frac{a-ja}{a-ka}=\frac{1-j}{1-k},
$$
with the result
$$
m=\frac{1-\sqrt{\frac{1+k^2}{2}}}{1-k}h.
$$
Historical aside: The key fact was known in Old Babylonian times (~2000 BCE– ~1600 BCE).  As an example, it was used in the breathtakingly elegant solution to the problem on cuneiform tablet VAT 8512, which is explained in Jens Høyrup's book Algebra in Cuneiform: Introduction to an Old Babylonian Geometrical Technique.  Problems given in Old Babylonian scribal education were generally contrived so as to have exact, finite representations in base-60 notation.  Two whole-number "trapezoidal triples" $(a,ja,ka)$ are $(7,5,1)$ and $(17,13,7)$.  The triple $(51,39,21)$ that appears on VAT 8512 is a multiple of the latter.  If reconstructions of the damaged number at the top of the tablet are to be believed, IM 58045 from the Old Akkadian period (2400 BCE–2250 BCE) may provide an even older example of this triple and is, in fact, one of the oldest known mathematical tablets.  Finally, note that trapezoidal triples are close cousins of Pythagorean triples: if $p^2+q^2=r^2$, then $(q+p)^2+(q-p)^2=2r^2$ so that the Pythagorean triple $(p,q,r)$ corresponds to the trapezoidal triple $(q+p,r,q-p)$.  So $(3,4,5)$ corresponds to $(7,5,1)$ and $(5,12,13)$ corresponds to $(17,13,7)$.


text:
Q: 3D model bad quality in Onirix Targets player app I have created a scene with a 3D model from sketchfab. The model looks great inside the Studio, but when I take a look at the same scene with the player app, the colors other details like reflections look different.
sketchfab model

Onirix Targets player app

Is there any way to solve this problem?
Thanks.
PS: This is the model I am using: https://sketchfab.com/3d-models/back-to-the-future-tribute-for-sketchfab-a95e48f00a8245c997d365f0b46158ea

A: This happens if the designer applies a post-processing filter to their model. More details at:
https://help.sketchfab.com/hc/en-us/articles/115000728943-Post-Processing-Filters
In order to maintain the same effect with Onirix, you need to implement your own application with the Onirix Mobile SDK for Unity:
https://developer.onirix.com/onirix-sdk/targets-sdk
Within the Unity editor, you can modify the visual effects and filters. This way you can make the model look the same. Please also see https://docs.unity3d.com/Manual/comp-Effects.html


text:
Q: Not able to specifically traverse through the syntax tree? I'm trying to implement a Diagnostic Analyzer for Collection initializer and its corresponding Code Fix provider.
Wrong Code:
var sampleList= new List<string>();
sampleList.Add("");
sampleList.Add("");

After CodeFix:
var sampleList= new List<string>(){"", ""};

But I'm stuck at this problem that once I get a node for LocalDeclarationStatement, I'm not aware if there exists a way to get the very next adjacent node from the parent.

In the above Picture I require both the ExpressionStatement after analyzing the LocalDeclarationStatement
REQUIREMENT for analyzer

*

*Identify the LocalDeclarationStatement, a collection that is already initialized but doesnt contain CollectionInitializerExpression

*Find if the very next line has an Expression statement that is using Add method on the same collection

REQUIREMENT for Code fix

*

*Provide Collection initializer syntax for the adjacent Expression statements that are using Add method on the collection

*All other intermitten usage of Add method on the collection has to be avoided.

A: You can do something like:
var declarationStatement = ...;
var block = (BlockSyntax)declarationStatement.Parent;
var index = block.Statements.IndexOf(declarationStatement);
var nextStatement = block.Statements[index + 1];

A: Wouldn't you just need to turn the concrete block into list, and check?
var nodes = yourSyntaxTree.DescentNodes().ToList();

for(var i = 0; i < nodes.Count; i++){
  var localDeclarationStatement = nodes[i] as LocalDeclarationStatement;
  if(localDeclarationStatement==null && i + 1 >= nodes.Length)
      continue;

  var expressionStatement = nodes[i+1] as ExpressionStatement;
  if(expressionStatement==null)
     continue;

  // there you have it.
}


text:
Q: Floyd Algorithm in C++ I'm trying to implement a Floryd Algorithm in C++
I have this already:
a means the node where the edge starts.
b means the node where the edge ends.
t means the time of the edge.
m means the number of edges.
n means the number of nodes.
typedef pair<int,int> nodo;
vector <nodo> g[100000];

void preguntarFloyd()
{
    g->clear();
    int  m;
    int contador = 0;
    cin m;

    for(int k = 0; k < m ; k++)
    {
        int a, b, t;
        cin >> a >> b >> t;
        g[a].push_back(nodo(b,t));
    }

    for (int k = 0; k < n; k++)
    {
        for(int i = 0; i < n; i++)
        {
            for(int j = 0; j <n; j++)
            {
                if(g[i][k].second + g[k][j].second < g[i][j].second )
                {
                    g[i][j].second = g[i][k].second + g[k][j].second;
                }
            }
        }
    }

}

When I try the code, the program crashes saying: "Expression: Vector subscript out of range"
I hope you guys can help me since I haven't been able to work this out!

A: The two most common ways to represent a graph is:

*

*An adjacency-list

*An adjacency-matrix

You have one data structure, in the initialisation phase you handle it like if it was a an adjacency-list then you try to access it as if it were an adjacency-matrix. Obviously this will never work...


text:
Q: dpkg-buildpackage -uc -us -b fails with "dpkg-shlibdeps: error: couldn't find library libmono-2.0.so.1 needed by ...monodis." Trying to build simple .deb packages with this script is failing with this:
   dh_installexamples
   dh_installman
   dh_installcatalogs
   dh_installcron
   dh_installdebconf
   dh_installemacsen
   dh_installifupdown
   dh_installinfo
   dh_pysupport
   dh_installinit
   dh_installmenu
   dh_installmime
   dh_installmodules
   dh_installlogcheck
   dh_installlogrotate
   dh_installpam
   dh_installppp
   dh_installudev
   dh_installwm
   dh_installxfonts
   dh_bugfiles
   dh_lintian
   dh_gconf
   dh_icons
   dh_perl
   # Skipping dh_usrlocal - empty override
   dh_link
   dh_compress
   dh_fixperms
   dh_strip
   dh_makeshlibs
   dh_shlibdeps
dpkg-shlibdeps: error: couldn't find library libmono-2.0.so.1 needed by debian/7digital-mono/usr/usr/bin/monodis (ELF format: 'elf64-x86-64'; RPATH: '').
Note: libraries are not searched in other binary packages that do not have any shlibs or symbols file.
To help dpkg-shlibdeps find private libraries, you might need to set LD_LIBRARY_PATH.
dh_shlibdeps: dpkg-shlibdeps -Tdebian/7digital-mono.substvars debian/7digital-mono/usr/usr/bin/mono debian/7digital-mono/usr/usr/bin/mprof-report debian/7digital-mono/usr/usr/bin/mono-sgen debian/7digital-mono/usr/usr/bin/pedump debian/7digital-mono/usr/usr/bin/monograph debian/7digital-mono/usr/usr/bin/monodis debian/7digital-mono/usr/usr/lib/mono/4.5/mcs.exe.so debian/7digital-mono/usr/usr/lib/mono/4.5/mscorlib.dll.so debian/7digital-mono/usr/usr/lib/mono/2.0/mscorlib.dll.so debian/7digital-mono/usr/usr/lib/libMonoSupportW.so debian/7digital-mono/usr/usr/lib/libikvm-native.so debian/7digital-mono/usr/usr/lib/libmono-2.0.so.1.0.0 debian/7digital-mono/usr/usr/lib/libMonoPosixHelper.so debian/7digital-mono/usr/usr/lib/libmono-profiler-log.so.0.0.0 debian/7digital-mono/usr/usr/lib/libmono-profiler-cov.so.0.0.0 debian/7digital-mono/usr/usr/lib/libmono-profiler-aot.so.0.0.0 debian/7digital-mono/usr/usr/lib/libmonosgen-2.0.so.0.0.0 debian/7digital-mono/usr/usr/lib/libmono-profiler-iomap.so.0.0.0 returned exit code 2
make: *** [binary] Error 9
dpkg-buildpackage: error: fakeroot debian/rules binary gave error exit status 2

Any idea what this means?

A: it means that the binary found (during the build-process) as debian/7digital-mono/usr/usr/bin/monodis (and which will likely end up as /usr/bin/monodis) is linking against libmono-2.0.so.1 but this file cannot be found.
i suspect that the .so-file is part of your package as well (though you haven't given any clue about this), so it's not yet installed on the target system.
what i find most strange is the double occurence of usr in your path, which might well indicate where the problem lies: dpkg-shlibdeps (by means of the linker) probably looks for the .so-file in the standard paths (e.g. usr/lib) and in the package paths (e.g. debian/7digital-mono/usr/lib), but it will not look into debian/7digital-mono/usr/usr/lib

A: Change "debian/rules" file accordingly to indicate the right path to LD_LIBRARY
Search for "dh binary-arch" in rules file and replace with
LD_LIBRARY_PATH=$(LD_LIBRARY_PATH):/usr/lib/i386-linux-gnu:/lib/i386-linux-gnu dh binary-arch

OR
LD_LIBRARY_PATH=$(LD_LIBRARY_PATH):/path-1-to-shared-library:/path-2-to-shared-library dh binary-arch

OR
LD_LIBRARY_PATH=$(LD_LIBRARY_PATH):/path-to-shared-library dh binary-arch


text:
Q: Abbreviate \ref within same section Given sample code
\section{One}
\begin{enumerate}
\item\label{li:one}
\end{enumerate}

\section{Two}
\begin{enumerate}
\item\label{li:two}
\end{enumerate}

I am referencing \ref{li:one} and \ref{li:two}

I would like this to render as
I am referencing (A.1) and (1)
That is, I want to include the section number when referencing labels from another section, but omit it for labels within the same section. How can I do this?
EDIT: I am using enumitem as well as hyperref

A: If you are not using hyperref, you can use the following:
\documentclass{article}
\usepackage{enumitem}% to demonstrate compatability
\usepackage{xstring}

\renewcommand{\thesection}{\Alph{section}}% is this the default?

\makeatletter
\newcommand{\refitem}[1]% #1 = label name
{\@ifundefined{r@#1}{??}{\begingroup%
  \edef\temp{\expandafter\detokenize\ref{#1}}%
  \StrCut{\temp}{.}\tempsection\tempitem%
  \if\thesection\tempsection\relax(\tempitem)%
  \else(\tempsection.\tempitem)%
  \fi
\endgroup}}
\makeatother

\begin{document}
\section{One}
\begin{enumerate}[ref=\thesection.\arabic*]
\item\label{li:one}
\end{enumerate}

\noindent I am referencing  \refitem{li:one} and \refitem{li:two}.

\section{Two}
\begin{enumerate}[ref=\thesection.\arabic*]
\item\label{li:two}
\end{enumerate}

\noindent I am referencing \refitem{li:one} and \refitem{li:two}.
\end{document}

If you are using hyperref, you will need to replace the above \refitem with:
\usepackage{hyperref}
\makeatletter
\def\autoref#1#2#3#4#5\@nil{\edef\anchor{#3}}
\newcommand{\getrefanchor}[1]{\expandafter\expandafter\expandafter\expandafter
    \expandafter\expandafter\expandafter\autoref
    \expandafter\expandafter\expandafter\@gobble
    \csname r@#1\endcsname{}\@nil}

\newcommand{\refitem}[1]% #1 = label name
{\@ifundefined{r@#1}{??}{\begingroup%
  \edef\temp{\expandafter\detokenize\getrefnumber{#1}}%
  \StrCut{\temp}{.}\tempsection\tempitem%
  \getrefanchor{#1}% saves as \anchor
  \if\thesection\tempsection\relax\hyperlink{\anchor}{(\tempitem)}%
  \else\hyperlink{\anchor}{(\tempsection.\tempitem)}%
  \fi
\endgroup}}
\makeatother


text:
Q: Duplicate Identifiers - How to Dynamically Spread Repeating Values in a Column using Tidyverse library(tidyverse)

This question is inspired by Jake Kaupp's answer to the question "tidyr/dplyr - spreading multiple variables for duplicate ids". Using the sample data provided (bottom), I want to have only one Id per row, however there are some instances of repeated id's (148 and 188). Since there are different phone numbers, I would like to spread these out dynamically so that there is a column for each number. In my real dataset I'm not sure how many repeating Id's there will be and this will continually change. I would like to do all this within Tidyverse, but I'm stuck:
First, I used the code below to find the max number of columns needed...
cols <-Df %>%
group_by(Id) %>%
group_size() %>%
max()

Next, I want to do something like the code below but "separate_" is deprecated. I'm not sure what to use here? I've tried various attempts with tidyr::spread, and looked at other options to solve duplicate identifiers, such as adding an index columns (mutate(I=row_numbers()), but couldn't get this to work either.
Df%>%
group_by(Id) %>%
separate_("Ph1", paste0("1:3", 1:cols), sep = ",", fill = "right")

Is there a simple way to accomplish this? The dynamic aspect is important since the dataset will always change and ultimately I would like to make this part of a function.
Sample Data:
Id<-c(199,148,148,145,177,165,144,121,188,188,188,111)
Ph1<-c(6532881717,6572231223,6541132112,6457886543,6548887777,7372222222,6451123425,6783450101,7890986543,6785554444,8764443344,6453348736)
Ph2<-c(NA,NA,NA,NA,NA,7372222222,NA,NA,NA,6785554444,NA,NA)

Df<-data.frame(Id,Ph1,Ph2)

A: You can create a new column to assign a unique id for each phone number for a given Id and then spread using that new column. This avoids the "duplicate id" problem. When spreading, this approach inherently adds as many columns as are needed to accommodate all of the unique phone numbers for each Id. For example, in the code below I've called that new column seq (for "sequence"):
library(tidyverse)

Df %>%
  gather(key, value, -Id) %>%
  filter(!is.na(value)) %>%
  select(-key) %>%
  group_by(Id) %>%
  filter(!duplicated(value)) %>%
  mutate(seq=paste0("Phone_",1:n())) %>%
  spread(seq, value)

     Id    Phone_1    Phone_2    Phone_3
1   111 6453348736         NA         NA
2   121 6783450101         NA         NA
3   144 6451123425         NA         NA
4   145 6457886543         NA         NA
5   148 6572231223 6541132112         NA
6   165 7372222222         NA         NA
7   177 6548887777         NA         NA
8   188 7890986543 6785554444 8764443344
9   199 6532881717         NA         NA


text:
Q: Using a delegate to save values to core data Beginner here, this is my first shot at using a delegate and I'm pretty confused - I'm trying to pass data between two controllers, the first of which is a tableview displaying some products, and the other is a modal view which allows the user to enter a new product to be displayed on that tableview. When the user hits "Save" in the modal view, I want to save the new product into core data and have it be displayed on the tableview.
The user enters information in three text fields in AddProductController (the modal view) and then hits save which calls handleSave:
func handleSave() {

    guard let newProductUrl = self.urlTextField.text else {
        print("error getting text from product url field")
        return
    }
    guard let newProductName = self.nameTextField.text else {
        print("error getting text from product name field")
        return
    }
    guard let newProductImage = self.logoTextField.text else {
        print("error getting text from product logo field")
        return
    }

    DispatchQueue.main.async {
        self.productSaveDelegate?.save(name: newProductName, url: newProductUrl, image: newProductImage)

        let companyController = CompanyController()
        self.navigationController?.pushViewController(companyController, animated: true)
    }

}

Which in turn calls save in ProductController (the tableview):
func save(name: String, url: String, image: String) {

    guard let appDelegate =
        UIApplication.shared.delegate as? AppDelegate else {
            return
    }

    let managedContext =
        appDelegate.persistentContainer.viewContext

    let entity =
        NSEntityDescription.entity(forEntityName: "Product",
                                   in: managedContext)!

    let product = NSManagedObject(entity: entity,
                                  insertInto: managedContext)

    product.setValue(name, forKey: "name")
    product.setValue(url, forKey: "url")
    product.setValue(image, forKey: "image")

    do {
        try managedContext.save()
        products.append(product)
    } catch let error as NSError {
        print("Could not save. \(error), \(error.userInfo)")
    }
    tableView.reloadData()
}

If I'm understanding correctly, I'm using the delegate as a sort of link between the two so that I can pass the user-entered values directly into my save function? Correct me if I'm wrong I'm pretty new. But I create the delegate outside the class scope at the top of ProductController (the tableview controller) like so:
protocol ProductSaveDelegate {
    func save(name: String, url: String, image: String)
}

Then in AddProductController (the modal view where the user enters the new product information) I initialize the delegate near the top of the class:
var productSaveDelegate: ProductSaveDelegate?

And then use it to call the save function in handleSave() as seen above.
When I try to add ProductSaveDelegate to the class definition of AddProductController I get an error saying that AddProductController does not conform to the protocol.
What can I change here to make the user-entered product save to core data properly? Thanks in advance for any help!

A: Delegates are really cool and powerful, but sometimes, yeah, they can be confusing. You need to initialize the delegate inside of the ProductController, not the AddProductController.
This is a great image which shows how a delegate and protocol setup works:

Image from Andrew Bancroft's website
In this instance, your Delegate is your ProductController and your Delegator is your AddProductController

A: MAKE SURE YOU HAVE SUBSCRIBED THE DELEGATE
Do NOT forget -
classObject.delegate = self
I suppose you are already familiar with the delegates,
You're get this error because, either you have not implemented the delegate method from the AddProductController(which in your case is false, as i can see it implemented), or you forgot to subscribe the delegate, to do so you need to make sure -

*

*Subscribing the delegate, i.e. before transitioning to the next controller set the delegate to self like -

  // addProductController is the AddProductController Class's Object

  addProductController.productSaveDelegate = self
  self.navigationController?.present(addProductController, animated: true, completion: nil)

also in the same class you need to implement the method defined in the protocol, i.e func save(name: String, url: String, image: String) in your case(already implemented)
You can also check a small demo, i have impleted here for the protocols.


text:
Q: ACTION_SEND intent not sharing text I have created a share intent for intent chooser.
val shareIntent = Intent(Intent.ACTION_SEND)
shareIntent.type = "video/*"
shareIntent.putExtra(Intent.EXTRA_TEXT, db.getShareMessageDao().getVideoShareMessage() + "\n\n" + shortLink)
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Sharing")
shareIntent.putExtra(Intent.EXTRA_STREAM, uri)
startActivity(Intent.createChooser(shareIntent, getString(R.string.share_video)))

In this intent I have added a video to share which is being shared successfully but the EXTRA_TEXT is not sharing with the intent.
Any idea why is it not working?


text:
Q: HTML5 pointermove/touchmove not working in Microsoft Edge I'm working on something which is more or less a drawing app. I need to support Microsoft Edge and there's the problem. As soon as you want to catch the touchmove or pointermove event, Edge tries to scroll (even if it's not possible). Here's an example. Just try to draw something there (touch/pen), mouse works perfectly even in Edge. In every other browser (except maybe IE) it works very well.
I have no idea why IE is ignoring the preventDefault() function. Has someone an idea?
Sample: https://jsfiddle.net/ryqagkeb/
Actually doesn't work with my Surface Pro & Surface Pen on Chrome and Edge.
canvas = document.getElementsByTagName('canvas')[0];
ctx = canvas.getContext('2d');
start = 0;
canvas.onpointerdown = function(evt) {
    start = 1;
}

canvas.onpointermove = function(evt) {
    if(start) {
        ctx.fillRect(evt.clientX, evt.clientY, 5,5);
    }
}

canvas.onpointerup = function(evt) {
    start = 0;
}

A: So I think I've found the solution myself and posting it now because I think it's pretty helpful. It seems the CSS property "touch-action" can solve the problem.
Setting:
canvas {
    touch-action: none;
}

It seems like it fixes the problem.


text:
Q: What could make a SharePoint Online site not show up in Microsoft Graph API's sites search results? I'm using the Microsoft Graph API to list SharePoint Online sites on a web application. The application uses delegated permissions and runs the following query: https://graph.microsoft.com/v1.0/sites?search=*
On a test tenant, this query returns all the expected sites, but when run on a company tenant, it returns an "item not found" error (below). The company tenant has many sites, so I'm expecting the search query to return results.
{
    "error": {
        "code": "itemNotFound",
        "message": "Item not found",
        "innerError": {
            "date": "2022-08-18T12:51:06",
            "request-id": "zzz",
            "client-request-id": "zzz"
        }
    }
}

*

*The company tenant has sites that were created years ago, so it's unlikely that it's a cache refresh issue.

*Running a query for a specific site on the company tenant (https://graph.microsoft.com/v1.0/sites/{TENANT}.sharepoint.com:/sites/{SiteName}) returns its information successfully.

*Running the search query in Microsoft Graph Explorer still returns the "itemNotFound" error mentioned above. In the Graph Explorer, I tried consenting to application level permissions incrementally (Site.Read.All, Site.ReadWrite.All, Site.Manage.All, and finally Site.FullControl.All) and the search query still returned the same error.

Given this information, what could make a SharePoint Online site not show up in Microsoft Graph API's site search results?
Note: I suspect the issue I'm facing is the same as described on No results for /sites?search= using Microsoft Graph, but that question has no answer, and I have additional information.


text:
Q: Python NameError: name '' is not defined (though it sure seems like it is) New Python guy here, kinda pulling my hair out on this one. Running Python 3.6, Windows... I know "NameError: name '--' is not defined" has plenty of posts, but I honestly haven't been able to resolve this from any of them, so pardon any repetitiousness. ANYway, here's the trouble:
def char_swap():
    swapped_a = [l.replace('a', '@') for l in lines]
    swapped_s = [l.replace('s', '$') for l in lines]
    swapped_i = [l.replace('i', '!') for l in lines]
    swapped_o = [l.replace('o', '0') for l in lines]
    global swapped
    swapped = [swapped_i,swapped_o,swapped_s,swapped_a]
    print(swapped)
    return swapped

def numberAdd():
    added = [n+(str(random.randint(0,9999))) for n in swapped]
    print(added)
    return added

Here, 'lines' is a previous list within the full code. The error is "NameError: name 'swapped' is not defined"
What's almost more boggling to me is that the 'char_swap' function is working just fine, and it's referencing 'lines', which was setup and defined pretty much verbatim how I've defined 'swapped' here. Global, gave it a list value, and off we go. In fact, if I swap out 'swapped' in the numberAdd() function for 'lines', it does its job just fine.
Any help is much appreciated!

A: In the first function char_swap, you have defined the global variable swapped. In the second function number_add, you are using the global variable swapped. The problem is, the global variable swapped is only created when you run char_swap, not when you just define it.
The problem, and the cure, can be illustrated by this simple example:

    def f():
        global z
        z = 17
    def g():
        return z
    > g()
    NameError: name 'z' is not defined
    > f()
    > g()
    17

The first time we execute g, before executing f, python doesn't know about z. After executing f, then python knows about z so g executes properly.