问:
How to get a SharePoint-UserField with JavaScript?
Hallo,

i need to write some javascript that gets the contents of a userfield in a sharepoint-website. I can get most fields with the javascript-function 'getTagFromIdentifierAndTitle' of Using Javascript to Manipulate a List Form Field, but not UserFields.

So how can i get UserFields?

Thanks!

答:
Here is the custom code that I put together. It relies on the exact HTML that SharePoint uses for the PeoplePicker. It does work on both IE and Firefox. For the columnName parameter, pass the "public" name of the column, not the internal name.</p>

```<code>function getParentElementByTagName(baseNode, tagName)
{
  var currNode;

  if(baseNode !== null)
  {
    currNode = baseNode.parentNode;

    while((currNode !== null) && (currNode.nodeName != tagName))
    {
      currNode = currNode.parentNode;
    }

    return currNode;
  }
  else
  {
    return null;
  }
}

function getPeoplePickerCell(columnName)
{
  var search = 'FieldName="' + columnName + '"';

  var nodes = document.getElementsByTagName("TEXTAREA");

  for(var i=0; i < nodes.length; i++)
  {
    if(nodes[i].title == "People Picker")
    {
      var outerCell = getParentElementByTagName(nodes[i], "SPAN").parentNode.parentNode;

      if(outerCell.innerHTML.indexOf(search) > 0)
      {
        return nodes[i].parentNode;
      }
    }
  }

  return null;
}

function getSPPeoplePicker(columnName, value)
{
  var cell = getPeoplePickerCell(columnName);

  if(cell !== null)
  {
    return cell.childNodes[0].innerHTML;
  }
  else
  {
    return null;
  }
}

function setSPPeoplePicker(columnName, value)
{
  var cell = getPeoplePickerCell(columnName);

  if(cell !== null)
  {
    cell.childNodes[0].innerHTML = value;
    cell.childNodes[1].value = value;
  }
}

function disableSPPeoplePicker(columnName)
{
  var cell = getPeoplePickerCell(columnName);

  if(cell !== null)
  {
    disableElement(cell.childNodes[0]);
    disableElement(cell.childNodes[1]);
  }
}

function enableSPPeoplePicker(columnName)
{
  var cell = getPeoplePickerCell(columnName);

  if(cell !== null)
  {
    enableElement(cell.childNodes[0]);
    enableElement(cell.childNodes[1]);
  }
}
</code>```

Body:
Here is the custom code that I put together. It relies on the exact HTML that SharePoint uses for the PeoplePicker. It does work on both IE and Firefox. For the columnName parameter, pass the "public" name of the column, not the internal name.

function getParentElementByTagName(baseNode, tagName)
{
  var currNode;

  if(baseNode !== null)
  {
    currNode = baseNode.parentNode;

    while((currNode !== null) && (currNode.nodeName != tagName))
    {
      currNode = currNode.parentNode;
    }

    return currNode;
  }
  else
  {
    return null;
  }
}

function getPeoplePickerCell(columnName)
{
  var search = 'FieldName="' + columnName + '"';

  var nodes = document.getElementsByTagName("TEXTAREA");

  for(var i=0; i < nodes.length; i++)
  {
    if(nodes[i].title == "People Picker")
    {
      var outerCell = getParentElementByTagName(nodes[i], "SPAN").parentNode.parentNode;

      if(outerCell.innerHTML.indexOf(search) > 0)
      {
        return nodes[i].parentNode;
      }
    }
  }

  return null;
}

function getSPPeoplePicker(columnName, value)
{
  var cell = getPeoplePickerCell(columnName);

  if(cell !== null)
  {
    return cell.childNodes[0].innerHTML;
  }
  else
  {
    return null;
  }
}

function setSPPeoplePicker(columnName, value)
{
  var cell = getPeoplePickerCell(columnName);

  if(cell !== null)
  {
    cell.childNodes[0].innerHTML = value;
    cell.childNodes[1].value = value;
  }
}

function disableSPPeoplePicker(columnName)
{
  var cell = getPeoplePickerCell(columnName);

  if(cell !== null)
  {
    disableElement(cell.childNodes[0]);
    disableElement(cell.childNodes[1]);
  }
}

function enableSPPeoplePicker(columnName)
{
  var cell = getPeoplePickerCell(columnName);

  if(cell !== null)
  {
    enableElement(cell.childNodes[0]);
    enableElement(cell.childNodes[1]);
  }
}

OwnerDisplayName: Tom Winter


来源: stackexchange

问:
Trouble running a VBA macro from VBS
I'm writing a script in VBS to run a macro on many excel files in a directory.  I'm new to VBS and macros.

The root directory has a number of folders in it.  Inside each folder is a number of sub folders.  I'm looking for folders at this level called "inspection".  Inside of those folders I'm looking for files that match the pattern .050. or .120..  If those files are found I want to run an Excel macro on them to modify the footer.

I've managed to set up all of the logic to search for the files and that seems to be working.  I've got a macro recorded in my PERSONAL.XLSB file and I can open files individually and run the macro successfully.

The problem: When I try to call the macro from code I get the following error:

Cannot run the macro

     The macro may not be available in this workbook or all macros may be disabled.

I have macros enabled in Excel.  I've tried a number of methods for running the macro but haven't been able to get any to work.

My VBS script:

```<code>DIM FSO, rootFolder, subFolders, subFolder, inspectionFolders, inspectionFolder, inspectionFiles, inspectionFile, wb

Set FSO = CreateObject("Scripting.FileSystemObject")
Set rootFolder = FSO.GetFolder("N:\ENGINEERING-Test")

Set subFolders = rootFolder.SubFolders

For Each subFolder in subFolders
    WScript.Echo "in " + rootFolder
    WScript.Echo "found folder " + subFolder.Name
    Set inspectionFolders = subFolder.SubFolders
    For Each inspectionFolder in inspectionFolders
        WScript.Echo "found folder " + inspectionFolder.name
        If InStr(1, inspectionFolder.Name, "Inspection", vbTextCompare) Then
            WScript.Echo "In inspection Folder"
            Set inspectionFiles = inspectionFolder.files
            For Each inspectionFile in inspectionFiles
                WScript.Echo "Checking File " + inspectionFile.name
                If InStr(1, inspectionFile.Name, ".050.", vbTextCompare) > 0 Or InStr(1, inspectionFile.Name, ".120.", vbTextCompare) > 0 Then
                    WScript.Echo "Found file " + inspectionFile.name

                    Set xlApp = CreateObject("Excel.application")
                    Set xlBook = xlApp.Workbooks.Open(inspectionFolder & "\" & inspectionFile.name, 0, False)
                    xlApp.Application.Visible = False
                    xlApp.Application.Run "C:\Users\Nick\AppData\Roaming\Microsoft\Excel\XLSTART\PERSONAL.XLSB!Module1.ModifyHeaderFooter"
                    xlApp.ActiveWindow.close
                    xlApp.Quit

                Else
                End If
            Next
        Else
        End If
    Next
Next
</code>```

My macro:

```<code>Sub ModifyHeaderFooter()
'
' ModifyHeaderFooter Macro
'

'
    With ActiveSheet.PageSetup
        .PrintTitleRows = "$1:$3"
        .PrintTitleColumns = ""
    End With
    ActiveSheet.PageSetup.PrintArea = ""
    With ActiveSheet.PageSetup
        .LeftHeader = ""
        .CenterHeader = ""
        .RightHeader = ""
        .LeftFooter = ""
        .CenterFooter = "Company, LLC"
        .RightFooter = "Page &P of  &N&8" & Chr(10) & ""
        .LeftMargin = Application.InchesToPoints(0.45)
        .RightMargin = Application.InchesToPoints(0)
        .TopMargin = Application.InchesToPoints(0)
        .BottomMargin = Application.InchesToPoints(0.58)
        .HeaderMargin = Application.InchesToPoints(0)
        .FooterMargin = Application.InchesToPoints(0)
        .PrintHeadings = False
        .PrintGridlines = False
        .PrintComments = xlPrintNoComments
        .PrintQuality = 300
        .CenterHorizontally = False
        .CenterVertically = False
        .Orientation = xlLandscape
        .Draft = False
        .PaperSize = xlPaperLetter
        .FirstPageNumber = xlAutomatic
        .Order = xlDownThenOver
        .BlackAndWhite = False
        .Zoom = 100
        .PrintErrors = xlPrintErrorsDisplayed
        .OddAndEvenPagesHeaderFooter = False
        .DifferentFirstPageHeaderFooter = False
        .ScaleWithDocHeaderFooter = True
        .AlignMarginsHeaderFooter = False
        .EvenPage.LeftHeader.Text = ""
        .EvenPage.CenterHeader.Text = ""
        .EvenPage.RightHeader.Text = ""
        .EvenPage.LeftFooter.Text = ""
        .EvenPage.CenterFooter.Text = ""
        .EvenPage.RightFooter.Text = ""
        .FirstPage.LeftHeader.Text = ""
        .FirstPage.CenterHeader.Text = ""
        .FirstPage.RightHeader.Text = ""
        .FirstPage.LeftFooter.Text = ""
        .FirstPage.CenterFooter.Text = ""
        .FirstPage.RightFooter.Text = ""
    End With
End Sub
</code>```

At this point I'm able to find the files I'm looking for, and the script attempts to execute the macro, but I get an error.  Can anyone see what I'm doing wrong?

ContentLicense: CC BY-SA 3.0

Title: Trouble running a VBA macro from VBS

Body:
I'm writing a script in VBS to run a macro on many excel files in a directory.  I'm new to VBS and macros.

The root directory has a number of folders in it.  Inside each folder is a number of sub folders.  I'm looking for folders at this level called "inspection".  Inside of those folders I'm looking for files that match the pattern .050. or .120..  If those files are found I want to run an Excel macro on them to modify the footer.

I've managed to set up all of the logic to search for the files and that seems to be working.  I've got a macro recorded in my PERSONAL.XLSB file and I can open files individually and run the macro successfully.

The problem: When I try to call the macro from code I get the following error:

Cannot run the macro

     The macro may not be available in this workbook or all macros may be disabled.

I have macros enabled in Excel.  I've tried a number of methods for running the macro but haven't been able to get any to work.

My VBS script:

DIM FSO, rootFolder, subFolders, subFolder, inspectionFolders, inspectionFolder, inspectionFiles, inspectionFile, wb

Set FSO = CreateObject("Scripting.FileSystemObject")
Set rootFolder = FSO.GetFolder("N:\ENGINEERING-Test")

Set subFolders = rootFolder.SubFolders

For Each subFolder in subFolders
    WScript.Echo "in " + rootFolder
    WScript.Echo "found folder " + subFolder.Name
    Set inspectionFolders = subFolder.SubFolders
    For Each inspectionFolder in inspectionFolders
        WScript.Echo "found folder " + inspectionFolder.name
        If InStr(1, inspectionFolder.Name, "Inspection", vbTextCompare) Then
            WScript.Echo "In inspection Folder"
            Set inspectionFiles = inspectionFolder.files
            For Each inspectionFile in inspectionFiles
                WScript.Echo "Checking File " + inspectionFile.name
                If InStr(1, inspectionFile.Name, ".050.", vbTextCompare) > 0 Or InStr(1, inspectionFile.Name, ".120.", vbTextCompare) > 0 Then
                    WScript.Echo "Found file " + inspectionFile.name

                    Set xlApp = CreateObject("Excel.application")
                    Set xlBook = xlApp.Workbooks.Open(inspectionFolder & "\" & inspectionFile.name, 0, False)
                    xlApp.Application.Visible = False
                    xlApp.Application.Run "C:\Users\Nick\AppData\Roaming\Microsoft\Excel\XLSTART\PERSONAL.XLSB!Module1.ModifyHeaderFooter"
                    xlApp.ActiveWindow.close
                    xlApp.Quit

                Else
                End If
            Next
        Else
        End If
    Next
Next

My macro:

Sub ModifyHeaderFooter()
'
' ModifyHeaderFooter Macro
'

'
    With ActiveSheet.PageSetup
        .PrintTitleRows = "$1:$3"
        .PrintTitleColumns = ""
    End With
    ActiveSheet.PageSetup.PrintArea = ""
    With ActiveSheet.PageSetup
        .LeftHeader = ""
        .CenterHeader = ""
        .RightHeader = ""
        .LeftFooter = ""
        .CenterFooter = "Company, LLC"
        .RightFooter = "Page &P of  &N&8" & Chr(10) & ""
        .LeftMargin = Application.InchesToPoints(0.45)
        .RightMargin = Application.InchesToPoints(0)
        .TopMargin = Application.InchesToPoints(0)
        .BottomMargin = Application.InchesToPoints(0.58)
        .HeaderMargin = Application.InchesToPoints(0)
        .FooterMargin = Application.InchesToPoints(0)
        .PrintHeadings = False
        .PrintGridlines = False
        .PrintComments = xlPrintNoComments
        .PrintQuality = 300
        .CenterHorizontally = False
        .CenterVertically = False
        .Orientation = xlLandscape
        .Draft = False
        .PaperSize = xlPaperLetter
        .FirstPageNumber = xlAutomatic
        .Order = xlDownThenOver
        .BlackAndWhite = False
        .Zoom = 100
        .PrintErrors = xlPrintErrorsDisplayed
        .OddAndEvenPagesHeaderFooter = False
        .DifferentFirstPageHeaderFooter = False
        .ScaleWithDocHeaderFooter = True
        .AlignMarginsHeaderFooter = False
        .EvenPage.LeftHeader.Text = ""
        .EvenPage.CenterHeader.Text = ""
        .EvenPage.RightHeader.Text = ""
        .EvenPage.LeftFooter.Text = ""
        .EvenPage.CenterFooter.Text = ""
        .EvenPage.RightFooter.Text = ""
        .FirstPage.LeftHeader.Text = ""
        .FirstPage.CenterHeader.Text = ""
        .FirstPage.RightHeader.Text = ""
        .FirstPage.LeftFooter.Text = ""
        .FirstPage.CenterFooter.Text = ""
        .FirstPage.RightFooter.Text = ""
    End With
End Sub

At this point I'm able to find the files I'm looking for, and the script attempts to execute the macro, but I get an error.  Can anyone see what I'm doing wrong?

Body: Try just xlApp.Run("PERSONAL.XLSB!ModifyHeaderFooter")


问:
Reverse DNS-style string
In a script running in a Debian environment, what is a good way to reverse a DNS-style string?

For example, if my script has:

```<code>example.org
</code>```

What would be a good way to reverse it, so that the string would read:

```<code>org.example
</code>```

A longer example:

```<code>www.example.org
</code>```

should reverse to:

```<code>org.example.www
</code>```

答:
this might do</p>

```<code>s='www.example.org'
echo $s | tr '.' '\n' | tac | paste -sd.
</code>```

Title: Reverse DNS-style string

Body:
In a script running in a Debian environment, what is a good way to reverse a DNS-style string?

For example, if my script has:

example.org

What would be a good way to reverse it, so that the string would read:

org.example

A longer example:

www.example.org

should reverse to:

org.example.www

Body:
this might do

s='www.example.org'
echo $s | tr '.' '\n' | tac | paste -sd.


问:
Unicode characters (emoji) not displayed when knitting to PDF
I'm working on a Mac and have an R script file. My data frame has the variable "content", a character string that includes emoji

```<code> "This is amazing!  "
</code>```

The following code does not display emoji, but only a combination of numbers and letters:

```<code>head(x$content)
print(x$content[1])

 "This is amazing \U0001f4aa\U0001f4aa "
</code>```

However, once I make use of kable, it displays the emoji in my console

later the emoji is not displayed when I knit the document to PDF:

```<code>kable( x[, "content"])
</code>```

Do I need a special font or a special Latex package that will allow me to knit the document to PDF and display the emojis?

答:
I think the reason is that you are using pdflatex, and your character is a unicode character, which is not supported by pdflatex.

Depending on the encoding of your system you have to use

```<code>enc2utf8(enc2native("This is amazing! "))
</code>```

or simply

```<code>iconv("This is amazing! ","Unicode","UTF-8")
</code>```

In my case the latter does not work as I'm on a system with latin1 encoding

Does that solves your problem ?

Body:
I'm working on a Mac and have an R script file. My data frame has the variable "content", a character string that includes emoji

 "This is amazing!  "

The following code does not display emoji, but only a combination of numbers and letters:

head(x$content)
print(x$content[1])

 "This is amazing \U0001f4aa\U0001f4aa "

However, once I make use of kable, it displays the emoji in my console

later the emoji is not displayed when I knit the document to PDF:

kable( x[, "content"])

Do I need a special font or a special Latex package that will allow me to knit the document to PDF and display the emojis?

Body:
I think the reason is that you are using pdflatex, and your character is a unicode character, which is not supported by pdflatex.

Depending on the encoding of your system you have to use

enc2utf8(enc2native("This is amazing! "))

or simply

iconv("This is amazing! ","Unicode","UTF-8")

In my case the latter does not work as I'm on a system with latin1 encoding

Does that solves your problem ?


问:
Spring Logout not working and redirecting
I have the following JSF Page:

```<code><h:form>
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
    <b:navBar brand="TEST" brandHref="#" inverse="true">

        <p:lightBox styleClass="menucolored">

            <p:commandLink id="logout"
                           type="button"
                           action="/j_spring_security_logout"
                           value="Log Out" ajax="false"
                           styleClass="menucolored"/>
        </p:lightBox>
    </b:navBar>
</h:form>
</code>```

Spring Security xml:

```<code><http use-expressions="true" auto-config="true">
    <form-login login-page="/pages/Login.xhtml"
                login-processing-url="/j_spring_security_check"
                authentication-failure-url="/loginPage?error=1"
                default-target-url="/pages/Home.xhtml"
                always-use-default-target="true"
                username-parameter="j_username"
                password-parameter="j_password"/>

    <!-- On logout success load the login page -->
    <logout logout-success-url="/pages/Login.xhtml" />

    <!-- enable csrf protection -->
    <csrf />
</http>
</code>```

Web.xml

```<code><filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>REQUEST</dispatcher>
</filter-mapping>
</code>```

I have tried replacing the command link with

```<code><h:outputLink value="${request.contextPath}/j_spring_security_logout">logout</h:outputLink>
</code>```

or

```<code><h:outputLink value="${pageContext.request.contextPath}/j_spring_security_logout">logout</h:outputLink>
</code>```

Still no luck. When I click the button nothing happens.

答:
You can use this javascript solution for Spring Security 4 + CSRF + JSF: </p>

```<code><a href="#" onclick="document.getElementById('logout').submit();">Logout</a>
 <form action="logout" id="logout" method="post">
   <input type="hidden" name="${_csrf.parameterName}"
   value="${_csrf.token}" />
</form>
</code>```

Body:
I have the following JSF Page:

<h:form>
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />

</h:form>

Spring Security xml:

<http use-expressions="true" auto-config="true">
    <form-login login-page="/pages/Login.xhtml"
                login-processing-url="/j_spring_security_check"
                authentication-failure-url="/loginPage?error=1"
                default-target-url="/pages/Home.xhtml"
                always-use-default-target="true"
                username-parameter="j_username"
                password-parameter="j_password"/>

    <logout logout-success-url="/pages/Login.xhtml" />

    <csrf />
</http>

Web.xml

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>REQUEST</dispatcher>
</filter-mapping>

I have tried replacing the command link with

<h:outputLink value="${request.contextPath}/j_spring_security_logout">logout</h:outputLink>

or

<h:outputLink value="${pageContext.request.contextPath}/j_spring_security_logout">logout</h:outputLink>

Still no luck. When I click the button nothing happens.

Body:
You can use this javascript solution for Spring Security 4 + CSRF + JSF:

<a href="#" onclick="document.getElementById('logout').submit();">Logout</a>
 <form action="logout" id="logout" method="post">
   <input type="hidden" name="${_csrf.parameterName}"
   value="${_csrf.token}" />
</form>


问:
Returning Actual Data for 'True' Values with Str.Contain
I have a dataframe that's several thousand lines long, structured like below.  I want to identify which rows have the string "John" and then I want to return those rows so that I can see the values (not just a row id and "True"/"False).

How can I accomplish this?  I've been using the str.contains('John') but that just gives me one column with a bunch of boolean responses which is meaningless to me in that form.

FName

JohnDoe

JaneDoe

SallieMae

答:
Let's try to filter data frame to just those names:

```<code>df[df.FName.str.contains('John')]
</code>```

Or this to added a new column to existing dataframe:

```<code>df['Johnames'] = df.FName[df.FName.str.contains('John')]
</code>```

Output:

```<code>       FName Johnames
0    JohnDoe  JohnDoe
1    JaneDoe      NaN
2  SallieMae      NaN
</code>```

Body:
Let's try to filter data frame to just those names:

df[df.FName.str.contains('John')]

Or this to added a new column to existing dataframe:

df['Johnames'] = df.FName[df.FName.str.contains('John')]

Output:

       FName Johnames
0    JohnDoe  JohnDoe
1    JaneDoe      NaN
2  SallieMae      NaN


问:
ImportError: No module named objdem
I have a python package that is intended to be used as a command line script.

The file directory of the package (before dist) is:

```<code>/bin/
    objdem
/objdem/
    __init__.py
    objdem.py
LICENSE
README.md
requirements.txt
setup.py
</code>```

The objdem file contains:

```<code>#!/usr/bin/env python

import objdem
main()
</code>```

And objdem.py is the script that I want to run by typing objdem on the command line.

Where am I going wrong?

On windows instead of an error it opens the objdem file.

EDIT:
You can try it here https://pypi.python.org/pypi/objDEM/1.0.6

EDIT:

setup.py:

```<code>from setuptools import setup

setup(
    name='objDEM',
    version='1.0.3',
    description='Generates an .obj file representing a digital elevation map from coordinate input',
    license="MIT",
    author='Kevin Forrest Connors',
    author_email='kevinforrestconnors.com@gmail.com',
    url="https://github.com/kevinforrestconnors/objdem",
    packages=['objDEM'],
    install_requires=['numpy', 'scipy', 'utm'],
    scripts=['bin/objdem']
)
</code>```

答:
Assuming you package name in setup.py is objdem

```<code>#!/usr/bin/env python

from objDEM import objdem
objDEM.main()
</code>```

your package is named objDEM not objdem

Running your package worked succesfully for me with the above changes.

python setup.py install

./bin/objdem

Title: ImportError: No module named objdem

Body:
I have a python package that is intended to be used as a command line script.

The file directory of the package (before dist) is:

/bin/
    objdem
/objdem/
    __init__.py
    objdem.py
LICENSE
README.md
requirements.txt
setup.py

The objdem file contains:

#!/usr/bin/env python

import objdem
main()

And objdem.py is the script that I want to run by typing objdem on the command line.

Where am I going wrong?

On windows instead of an error it opens the objdem file.

EDIT:
You can try it here https://pypi.python.org/pypi/objDEM/1.0.6

EDIT:

setup.py:

from setuptools import setup

setup(
    name='objDEM',
    version='1.0.3',
    description='Generates an .obj file representing a digital elevation map from coordinate input',
    license="MIT",
    author='Kevin Forrest Connors',
    author_email='kevinforrestconnors.com@gmail.com',
    url="https://github.com/kevinforrestconnors/objdem",
    packages=['objDEM'],
    install_requires=['numpy', 'scipy', 'utm'],
    scripts=['bin/objdem']
)

Body:
Assuming you package name in setup.py is objdem

#!/usr/bin/env python

from objDEM import objdem
objDEM.main()

your package is named objDEM not objdem

Running your package worked succesfully for me with the above changes.

python setup.py install

./bin/objdem


问:
Unable to resovle macro in call symput
I am calling a user defined macro within a data step. The macro contains a do loop and I would like to assign the value of i counter of the do loop to a macro variable for which I am using a call symput. please find my code below. Can you tell me where I am going wrong.</p>

```<code>%let RedressStartYear=2007;
%let RedressEndDate= '31OCT2017'D;

*Yearly Interest Rate;
%let int_rt_2007= '0.0421';
%let int_rt_2008= '0.0421';
%let int_rt_2009= '0.0421';
%let int_rt_2010= '0.0421';
%let int_rt_2011= '0.0421';
%let int_rt_2012= '0.0419';
%let int_rt_2013= '0.0429';
%let int_rt_2014= '0.0430';
%let int_rt_2015= '0.0401';
%let int_rt_2016= '0.0378';
%let int_rt_2017= '0.0358';

Data Redress_Data;
format BilledMonth date9.;
BilledMonth='01MAR2013'D;
BilledYear=Year(BilledMonth);
Customer='ABC Ltd.';
OverChargeAmt=34.6656;
run;

%macro Calculate_CI(billmon, Amt,Payday);

CI_AMT=0;

do i=&RedressStartYear. to year(&payday.) by 1;

*The value of i not getting resolved and getting assigned to the macro variable yr;
Call symput ('yr',i);

    if i<year(&billmon.) then CI_AMT= CI_AMT+0;

    if i=Year(&billmon.) then do;

        No_days_Int_&yr.=intck('day',&billmon.,MDY(12,31,i))+1;
        Days_in_Year_&yr.=intck('day',MDY(01,01,i),MDY(12,31,i))+1;
        CI_AMT= CI_AMT+ (&&int_rt_&yr.* No_days_Int_&yr. * &Amt.)/Days_in_Year_&yr.; end;

    if i>Year(&billmon.) and Year(&billmon.)< Year(&Payday.) then CI_AMT=CI_AMT + (&&int_rt_&yr. * &Amt.);

    if i=Year(&Payday.) then do;
        No_days_Int_&yr.=intck('day',MDY(01,01,i),&Payday.)+1;
        Days_in_Year_&yr.=intck('day',MDY(01,01,i),MDY(12,31,i))+1;
        CI_AMT=CI_AMT+ (&&int_rt_&yr. * No_days_Int_&yr. * &Amt.)/Days_in_Year_&yr. ; end;

end;

%mend Calculate_CI;

Data Redress_Data_CI;
set Redress_Data;
    %Calculate_CI(BilledMonth, OverChargeAmt,&RedressEndDate.);
run;
</code>```

答:
If you truly want the output data set to have 23 new variables, as in

No_days_Int_2007

Days_in_Year_2007

...

No_days_Int_2017

Days_in_Year_2017

CI_AMT

And you don't want to use arrays, change your macro code to loop in macro, not in DATA Step. So

```<code>do i=
</code>```

would become

```<code>%do i=
</code>```

And change the original matching end to %end.

After this change the macro will generate some 'wallpaper' DATA Step source code that does your formulas.

The code construct is on that fine line where inexperienced coders might attempt to deal with the year in the macro variable i as if it were a DATA Step variable.

Advice is always to be able to code a solution in plain DATA Step first, then you can macroize the concept by abstracting and parameterizing salient features and patterns in the plain code.

Title: Unable to resovle macro in call symput

Body:
I am calling a user defined macro within a data step. The macro contains a do loop and I would like to assign the value of i counter of the do loop to a macro variable for which I am using a call symput. please find my code below. Can you tell me where I am going wrong.

%let RedressStartYear=2007;
%let RedressEndDate= '31OCT2017'D;

*Yearly Interest Rate;
%let int_rt_2007= '0.0421';
%let int_rt_2008= '0.0421';
%let int_rt_2009= '0.0421';
%let int_rt_2010= '0.0421';
%let int_rt_2011= '0.0421';
%let int_rt_2012= '0.0419';
%let int_rt_2013= '0.0429';
%let int_rt_2014= '0.0430';
%let int_rt_2015= '0.0401';
%let int_rt_2016= '0.0378';
%let int_rt_2017= '0.0358';

Data Redress_Data;
format BilledMonth date9.;
BilledMonth='01MAR2013'D;
BilledYear=Year(BilledMonth);
Customer='ABC Ltd.';
OverChargeAmt=34.6656;
run;

%macro Calculate_CI(billmon, Amt,Payday);

CI_AMT=0;

do i=&RedressStartYear. to year(&payday.) by 1;

*The value of i not getting resolved and getting assigned to the macro variable yr;
Call symput ('yr',i);

    if i<year(&billmon.) then CI_AMT= CI_AMT+0;

    if i=Year(&billmon.) then do;

        No_days_Int_&yr.=intck('day',&billmon.,MDY(12,31,i))+1;
        Days_in_Year_&yr.=intck('day',MDY(01,01,i),MDY(12,31,i))+1;
        CI_AMT= CI_AMT+ (&&int_rt_&yr.* No_days_Int_&yr. * &Amt.)/Days_in_Year_&yr.; end;

    if i>Year(&billmon.) and Year(&billmon.)< Year(&Payday.) then CI_AMT=CI_AMT + (&&int_rt_&yr. * &Amt.);

    if i=Year(&Payday.) then do;
        No_days_Int_&yr.=intck('day',MDY(01,01,i),&Payday.)+1;
        Days_in_Year_&yr.=intck('day',MDY(01,01,i),MDY(12,31,i))+1;
        CI_AMT=CI_AMT+ (&&int_rt_&yr. * No_days_Int_&yr. * &Amt.)/Days_in_Year_&yr. ; end;

end;

%mend Calculate_CI;

Data Redress_Data_CI;
set Redress_Data;
    %Calculate_CI(BilledMonth, OverChargeAmt,&RedressEndDate.);
run;

Body:
If you truly want the output data set to have 23 new variables, as in

No_days_Int_2007

Days_in_Year_2007

...

No_days_Int_2017

Days_in_Year_2017

CI_AMT

And you don't want to use arrays, change your macro code to loop in macro, not in DATA Step. So

do i=

would become

%do i=

And change the original matching end to %end.

After this change the macro will generate some 'wallpaper' DATA Step source code that does your formulas.

The code construct is on that fine line where inexperienced coders might attempt to deal with the year in the macro variable i as if it were a DATA Step variable.

Advice is always to be able to code a solution in plain DATA Step first, then you can macroize the concept by abstracting and parameterizing salient features and patterns in the plain code.


问:
How to specify which version of perl to use on CentOS
I am running CentOS 5.4 which only has version 5.8 of perl available by default, and I have a program which requires perl 5.10, so I compiled perl 5.10 on CentOS.  How do I specify which perl I want to run the program with because the perl command uses 5.8 by default.</p>

答:
The first line of the program file should reference the perl binary you wish to use:
e.g.

```<code>#!/usr/bin/perl
</code>```

You may also want to change your PATH variable so that the directory your perl 5.10 binary is in is listed prior to the 5.8 binary directory.
e.g.

```<code>export PATH=/path/to/perl/5.10:$PATH
</code>```

ContentLicense: CC BY-SA 2.5

Body:
The first line of the program file should reference the perl binary you wish to use:
e.g.

#!/usr/bin/perl

You may also want to change your PATH variable so that the directory your perl 5.10 binary is in is listed prior to the 5.8 binary directory.
e.g.

export PATH=/path/to/perl/5.10:$PATH


问:
SQL string before and after certain characters
```<code>SELECT NAME
FROM SERVERS
</code>```

returns:

```<code>SDACR.hello.com
SDACR
SDACR\AIR
SDACR.hello.com\WATER
</code>```

I need the SELECT query for below result:

```<code>SDACR
SDACR
SDACR\AIR
SDACR\WATER
</code>```

Kindly help ! I tried using LEFT and RIGHT functions as below, but not able to get combined output correctly:

```<code> SELECT
     LEFT(Name, CHARINDEX('.', Name) - 1)
 FROM
     SERVERS

SELECT
    RIGHT(Name, LEN(Name) - CHARINDEX('\', Name))
FROM
    SERVERS
</code>```

答:
It looks like you're just trying to REPLACE a substring of characters in your column. You should try this:

```<code>SELECT REPLACE(Name,'.hello.com','') AS ReplacementName
FROM SERVERS
</code>```

Body:
SELECT NAME
FROM SERVERS

returns:

SDACR.hello.com
SDACR
SDACR\AIR
SDACR.hello.com\WATER

I need the SELECT query for below result:

SDACR
SDACR
SDACR\AIR
SDACR\WATER

Kindly help ! I tried using LEFT and RIGHT functions as below, but not able to get combined output correctly:

 SELECT
     LEFT(Name, CHARINDEX('.', Name) - 1)
 FROM
     SERVERS

SELECT
    RIGHT(Name, LEN(Name) - CHARINDEX('\', Name))
FROM
    SERVERS

Body:
It looks like you're just trying to REPLACE a substring of characters in your column. You should try this:

SELECT REPLACE(Name,'.hello.com','') AS ReplacementName
FROM SERVERS


问:
How to PHP debug a single website in VS Code
The setup;

Windows OS (well, I have to)

WAMP as server

VS Code for IDE

browser Google Chrome

Everything works fine except... If I am in the middle of debugging my website, and I flip tabs (in Chrome) to my phpMyAdmin to check a db value, VS Code/Xdebug will start debugging phpMyAdmin (same deal with other "localhost" sites)

At this point, everything appears to just lockup and quit working.  I understand it's because xdebug is catching warnings/errors etc. on the "other" websites. Clicking through the "call Stack" and clicking the "continue" button does not always (rarely) keep things moving along.

How do I set vs code/xdebug to monitor only a single website?

my main web application is served [locally] at http://reqapp.dev

my phpMyAdmin is at http://wamp/phpmyadmin/

and other sites are at http://localhost/path/to/website/

I never had an issue in Aptana Studio doing the same thing (same dev environment actually) but it would "launch" the website for debugging, and I think it used a special port. I don't know how to replicate this with VS Code.

EDIT:

most sites are defined as virtual hosts

httpd-vhosts.conf

```<code><VirtualHost *:80>
    ServerName localhost
    DocumentRoot c:/Users/chadmeyers/Sites
    <Directory  "c:/Users/chadmeyers/Sites">
        Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>
</VirtualHost>

<VirtualHost *:80>
    ServerName wamp
    DocumentRoot "c:/wamp64/www"
    <Directory  "c:/wamp64/www/">
        Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>
</VirtualHost>

<VirtualHost *:80>
    ServerName reqApp.dev
    DocumentRoot "c:/users/chadmeyers/sites/aaappdev/public_html"
    <Directory  "c:/users/chadmeyers/sites/aaappdev/public_html/">
        Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>
</VirtualHost>
</code>```

And php.ini

```<code>[xdebug]
zend_extension ="c:\wamp64\bin\php\php7.0.10\ext\php_xdebug-2.5.5-7.0-vc14-x86_64.dll"

xdebug.remote_enable = On
xdebug.remote_autostart = On
xdebug.profiler_enable = On
xdebug.profiler_enable_trigger = On
xdebug.profiler_output_name = cachegrind.out.%t.%p
xdebug.profiler_output_dir ="c:/wamp64/tmp"
xdebug.show_local_vars=0
xdebug.var_display_max_depth = 5
xdebug.var_display_max_children = 256
xdebug.var_display_max_data = 1024
</code>```

Within VS Code PHP Debug I have these settings, but it makes no difference which "profile" I use

```<code>  "version": "0.2.0",
  "configurations": [
    {
      "name": "Listen for XDebug",
      "type": "php",
      "request": "launch",
      "port": 9000
    },
    {
      "name": "Launch currently open script",
      "type": "php",
      "request": "launch",
      "program": "${file}",
      "cwd": "${fileDirname}",
      "port": 9000
    },
    {
      "name": "debug FRAaap",
      "type": "php",
      "request": "launch",
      "program": "${file}",
      "cwd": "C:\\Users\\chadmeyers\\Sites\\aaAppDev\\public_html\\",
      "port": 9000
    }
  ]
}
</code>```

答:
based on some tips about xdebug.remote_autostart I did some more searching and came across this article which gave me a better understanding.  I turned off xdebug.remote_autostart As suggested, the Chrome Xdebug helper is also a big help, automagically starting the debug session.

Now if I want to start Xdebug I just append XDEBUG_SESSION_START and a random string to my url and it works, or use the extension.

I still have lots to figure out to really make this work great, but this will do just fine for now.

Body:
The setup;

Windows OS (well, I have to)

WAMP as server

VS Code for IDE

browser Google Chrome

Everything works fine except... If I am in the middle of debugging my website, and I flip tabs (in Chrome) to my phpMyAdmin to check a db value, VS Code/Xdebug will start debugging phpMyAdmin (same deal with other "localhost" sites)

At this point, everything appears to just lockup and quit working.  I understand it's because xdebug is catching warnings/errors etc. on the "other" websites. Clicking through the "call Stack" and clicking the "continue" button does not always (rarely) keep things moving along.

How do I set vs code/xdebug to monitor only a single website?

my main web application is served [locally] at http://reqapp.dev

my phpMyAdmin is at http://wamp/phpmyadmin/

and other sites are at http://localhost/path/to/website/

I never had an issue in Aptana Studio doing the same thing (same dev environment actually) but it would "launch" the website for debugging, and I think it used a special port. I don't know how to replicate this with VS Code.

EDIT:

most sites are defined as virtual hosts

httpd-vhosts.conf

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot c:/Users/chadmeyers/Sites
    <Directory  "c:/Users/chadmeyers/Sites">
        Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>
</VirtualHost>

<VirtualHost *:80>
    ServerName wamp
    DocumentRoot "c:/wamp64/www"
    <Directory  "c:/wamp64/www/">
        Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>
</VirtualHost>

<VirtualHost *:80>
    ServerName reqApp.dev
    DocumentRoot "c:/users/chadmeyers/sites/aaappdev/public_html"
    <Directory  "c:/users/chadmeyers/sites/aaappdev/public_html/">
        Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>
</VirtualHost>

And php.ini

[xdebug]
zend_extension ="c:\wamp64\bin\php\php7.0.10\ext\php_xdebug-2.5.5-7.0-vc14-x86_64.dll"

xdebug.remote_enable = On
xdebug.remote_autostart = On
xdebug.profiler_enable = On
xdebug.profiler_enable_trigger = On
xdebug.profiler_output_name = cachegrind.out.%t.%p
xdebug.profiler_output_dir ="c:/wamp64/tmp"
xdebug.show_local_vars=0
xdebug.var_display_max_depth = 5
xdebug.var_display_max_children = 256
xdebug.var_display_max_data = 1024

Within VS Code PHP Debug I have these settings, but it makes no difference which "profile" I use

  "version": "0.2.0",
  "configurations": [
    {
      "name": "Listen for XDebug",
      "type": "php",
      "request": "launch",
      "port": 9000
    },
    {
      "name": "Launch currently open script",
      "type": "php",
      "request": "launch",
      "program": "${file}",
      "cwd": "${fileDirname}",
      "port": 9000
    },
    {
      "name": "debug FRAaap",
      "type": "php",
      "request": "launch",
      "program": "${file}",
      "cwd": "C:\\Users\\chadmeyers\\Sites\\aaAppDev\\public_html\\",
      "port": 9000
    }
  ]
}


问:
Disabled input still focusable in Firefox
Minimal example

let input = document.createElement("input");
input.id = "input";
input.type = "number";
input.className = "number-input";
input.disabled = true;
document.body.appendChild(input);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.number-input:focus {
  background: yellow;
}
.number-input {
  -moz-appearance: textfield;
} </code>```

<button onClick="document.getElementById('input').disabled = false">
Enable
</button>

<button onClick="document.getElementById('input').disabled = true">
Disable
</button>```

The created input is semi-disabled on start, i. e. you can click on it and it turns yellow (gets focus), but you can't write a number into it. However after clicking Enable followed by Disable button, it is as disabled as expected. It seems to be a bug that involves the input.type = "number" and the browser specific -moz-appearance: textfield, that I use to hide the up and down buttons.

Any ideas how to really disable the input field, when the page is loaded?

答:
Adding input[disabled] {pointer-events:none} to the CSS seems to fix this. Not sure why Firefox still allows initial focus like that.

However, this CSS fix will only work in browsers that support pointer-events property. There is poor IE support (only 11). There's also a user-select property that may work (haven't tested it) but that still allows the input's data to be submitted in a form, and again may be restricted based on browser support.

A third (likely non-recommended) option would be to (when disabled) have an element in-front of the input to catch the clicks, but that's a pretty messy way to solve it.

Another possibility: when disabling, you could have your JS also apply different property/value for .number-input:focus

let input = document.createElement("input");
input.id = "input";
input.type = "number";
input.className = "number-input";
document.body.appendChild(input);
input.disabled = true;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.number-input:focus {
  background: yellow;
}
.number-input {
  -moz-appearance: textfield;
}

input[disabled] {pointer-events:none}</code>```

<button onClick="document.getElementById('input').disabled = false">
Enable
</button>

<button onClick="document.getElementById('input').disabled = true">
Disable
</button>```

Body:
Minimal example

let input = document.createElement("input");
input.id = "input";
input.type = "number";
input.className = "number-input";
input.disabled = true;
document.body.appendChild(input);

.number-input:focus {
  background: yellow;
}
.number-input {
  -moz-appearance: textfield;
}

<button onClick="document.getElementById('input').disabled = false">
Enable
</button>

<button onClick="document.getElementById('input').disabled = true">
Disable
</button>

The created input is semi-disabled on start, i. e. you can click on it and it turns yellow (gets focus), but you can't write a number into it. However after clicking Enable followed by Disable button, it is as disabled as expected. It seems to be a bug that involves the input.type = "number" and the browser specific -moz-appearance: textfield, that I use to hide the up and down buttons.

Any ideas how to really disable the input field, when the page is loaded?

Body:
Adding input[disabled] {pointer-events:none} to the CSS seems to fix this. Not sure why Firefox still allows initial focus like that.

However, this CSS fix will only work in browsers that support pointer-events property. There is poor IE support (only 11). There's also a user-select property that may work (haven't tested it) but that still allows the input's data to be submitted in a form, and again may be restricted based on browser support.

A third (likely non-recommended) option would be to (when disabled) have an element in-front of the input to catch the clicks, but that's a pretty messy way to solve it.

Another possibility: when disabling, you could have your JS also apply different property/value for .number-input:focus

let input = document.createElement("input");
input.id = "input";
input.type = "number";
input.className = "number-input";
document.body.appendChild(input);
input.disabled = true;

.number-input:focus {
  background: yellow;
}
.number-input {
  -moz-appearance: textfield;
}

input[disabled] {pointer-events:none}

<button onClick="document.getElementById('input').disabled = false">
Enable
</button>

<button onClick="document.getElementById('input').disabled = true">
Disable
</button>


问:
Phusion Passenger - Sticky session - How to add options to set-cookie header?
Enabling sticky sessions in Phusion Passenger adds set-cooke header in next form:

```<code>Set-Cookie: _passenger_route=598708409; Path=/
</code>```

Questions:

How to alter Path?

How to set httpOnly option?

How to set secure option?

How to set other options?

答:
This is the relevant code that sets the cookie.

Path is controlled by the baseURI

httpOnly is not set for this reason:

// Note that we do NOT set HttpOnly. If we set that flag then Chrome
// doesn't send cookies over WebSocket handshakes. Confirmed on Chrome 25.

& 4. The current code offers no way to inject other values.

Body:
Enabling sticky sessions in Phusion Passenger adds set-cooke header in next form:

Set-Cookie: _passenger_route=598708409; Path=/

Questions:

How to alter Path?

How to set httpOnly option?

How to set secure option?

How to set other options?


问:
JSON do not add the last comma
I have the script:

```<code><script type="application/ld+json">
            {
              "@context": "http://schema.org",
              "@type": "Product",
              "aggregateRating": {
                "@type": "AggregateRating",

                "ratingValue": "<?php echo $rating;?>",

              "reviewCount": "<?php echo $review_total; ?>"
              },

              "description": "<?php echo $description; ?>",

              "name": "<?php echo $heading_title; ?>",

              "image": "<?php echo $thumb; ?>",
              "review": [
                <?php foreach($reviewss as $review) {  ?>
                {
                  "@type": "Review",
                  "author": "<?php echo $review['author'];?>",
                  "datePublished": "<?php echo $review['date_added'];?>",
                  "description": "<?php echo $review['text'];?>",
                  "name": "<?php echo $review['author'];?>",
                  "reviewRating": {
                    "@type": "Rating",
                    "bestRating": "5",
                    "ratingValue": "<?php echo $review['rating'];?>",
                    "worstRating": "1"
                    }

                    }
                <?php } ?>
                ]

            }
        </script>
</code>```

It working fine if I have only one review.
If I have several reviews I need add the commas after each piece of this:

```<code>{
                  "@type": "Review",
                  "author": "<?php echo $review['author'];?>",
                  "datePublished": "<?php echo $review['date_added'];?>",
                  "description": "<?php echo $review['text'];?>",
                  "name": "<?php echo $review['author'];?>",
                  "reviewRating": {
                    "@type": "Rating",
                    "bestRating": "5",
                    "ratingValue": "<?php echo $review['rating'];?>",
                    "worstRating": "1"
                    }

                    },
</code>```

But after the last value, comma should be removed.
Can anybody help? How to remove the last comma?

答:
```<code><?php $i=0; foreach($reviewss as $review) {  ?>
                {
                  "@type": "Review",
                  "author": "<?php echo $review['author'];?>",
                  "datePublished": "<?php echo $review['date_added'];?>",
                  "description": "<?php echo $review['text'];?>",
                  "name": "<?php echo $review['author'];?>",
                  "reviewRating": {
                    "@type": "Rating",
                    "bestRating": "5",
                    "ratingValue": "<?php echo $review['rating'];?>",
                    "worstRating": "1"
                    }

                    }
                    <?php
                    if($i<count($reviewss)) echo ',';
                    ?>
                <?php $i++; } ?>
</code>```

I think it should work

Title: JSON do not add the last comma

Body:
I have the script:

It working fine if I have only one review.
If I have several reviews I need add the commas after each piece of this:

{
                  "@type": "Review",
                  "author": "<?php echo $review['author'];?>",
                  "datePublished": "<?php echo $review['date_added'];?>",
                  "description": "<?php echo $review['text'];?>",
                  "name": "<?php echo $review['author'];?>",
                  "reviewRating": {
                    "@type": "Rating",
                    "bestRating": "5",
                    "ratingValue": "<?php echo $review['rating'];?>",
                    "worstRating": "1"
                    }

                    },

But after the last value, comma should be removed.
Can anybody help? How to remove the last comma?

Body:
<?php $i=0; foreach($reviewss as $review) {  ?>
                {
                  "@type": "Review",
                  "author": "<?php echo $review['author'];?>",
                  "datePublished": "<?php echo $review['date_added'];?>",
                  "description": "<?php echo $review['text'];?>",
                  "name": "<?php echo $review['author'];?>",
                  "reviewRating": {
                    "@type": "Rating",
                    "bestRating": "5",
                    "ratingValue": "<?php echo $review['rating'];?>",
                    "worstRating": "1"
                    }

                    }
                    <?php
                    if($i<count($reviewss)) echo ',';
                    ?>
                <?php $i++; } ?>

I think it should work


问:
Pull generated HTML programmatically vs. a HttpWebRequest
For our newsletter, I generate the final body of the email in a web page and then want to pull that into the body of the email. I found a way to do that with HttpWebRequest.

```<code>    private string GetHtmlBody(Guid id)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Format("http://news.domain.com/News/View/{0}", id.ToString()));
        HttpWebResponse responce = (HttpWebResponse)request.GetResponse();
        System.IO.StreamReader sr = new System.IO.StreamReader(responce.GetResponseStream());

        return sr.ReadToEnd();
    }
</code>```

However, I feel there has to be a better way. Can I somehow pull the generated view without making a web call?

答:
Assuming the the email code is in the same project as the website, then you should be able to call the action method, get the ActionResult back, then call the ExecuteResult method.  The downside is that in order to do it this way, you will need to set it up such that the ExecuteResult will write to a stream that you can take advantage of.  In order to do all of this, you will need to mock up some of the classes used by the ControllerContext.

What would probably be a better way (though will likely take more work), is to have the markup you want be generated by an XSLT transform.  XSLT is a type of XML document template that can be merged with an XML document that holds data to produce a desired result.  If you do this, then you can have your process that sends out emails run the transform as well as have your website run the transform.  The advantage of this, is that if you want the markup to be different (i.e. you are redesigning thew newsletter), you will simply need to update the XSLT file and deploy it.

HTH

Body:
For our newsletter, I generate the final body of the email in a web page and then want to pull that into the body of the email. I found a way to do that with HttpWebRequest.

    private string GetHtmlBody(Guid id)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Format("http://news.domain.com/News/View/{0}", id.ToString()));
        HttpWebResponse responce = (HttpWebResponse)request.GetResponse();
        System.IO.StreamReader sr = new System.IO.StreamReader(responce.GetResponseStream());

        return sr.ReadToEnd();
    }

However, I feel there has to be a better way. Can I somehow pull the generated view without making a web call?


问:
AutoHotKey - how to send control and same key multiple times
Specifically I want to hold down the control key, and press the m key, let go of m but keep control held down, and then press m again, which will trigger the function. More generically I'd like to know the syntax for telling autohotkey to read the same key multiple times

How do I do that?

I can do it with a single m like this

```<code>^m::
  Send, The text i want to send
Return
</code>```

So far I have tried

```<code>^m m::
  Send, The text i want to send
Return

^m&m::
  Send, The text i want to send
Return

^mm::
  Send, The text i want to send
Return
</code>```

All of which are illegal

答:
What about this:</p>

```<code>; Depending on how many times a key combination was pressed,
; execute different commands:

^m::
    ctrl_m_count++          ; start counter
    SetTimer ctrl_m_action, -50
return

ctrl_m_action:
    KeyWait, Ctrl
    If (ctrl_m_count = 1)
        MsgBox, ctrl_m_action 1
    If (ctrl_m_count = 2)
        MsgBox, ctrl_m_action 2
    ; ...
    ctrl_m_count := 0       ; reset  counter
return
</code>```

Body:
Specifically I want to hold down the control key, and press the m key, let go of m but keep control held down, and then press m again, which will trigger the function. More generically I'd like to know the syntax for telling autohotkey to read the same key multiple times

How do I do that?

I can do it with a single m like this

^m::
  Send, The text i want to send
Return

So far I have tried

^m m::
  Send, The text i want to send
Return

^m&m::
  Send, The text i want to send
Return

^mm::
  Send, The text i want to send
Return

All of which are illegal

Body:
What about this:

; Depending on how many times a key combination was pressed,
; execute different commands:

^m::
    ctrl_m_count++          ; start counter
    SetTimer ctrl_m_action, -50
return

ctrl_m_action:
    KeyWait, Ctrl
    If (ctrl_m_count = 1)
        MsgBox, ctrl_m_action 1
    If (ctrl_m_count = 2)
        MsgBox, ctrl_m_action 2
    ; ...
    ctrl_m_count := 0       ; reset  counter
return


问:
Delete all words starting with the same letter in a binary tree
I have a function that deletes all words starting with the same first letter in a avl binary tree(letter is given by user).

```<code>node_t* delete_from_tree(node_t* root, char search, int *deleted)
{
    int cmp;
    node_t* new_node = NULL;
    if (root == NULL)
        return root;
    else
    {
        cmp = root->data[0] - search;
        if (cmp == 0)
        {
            *deleted += 1;
            new_node = delete_node(root, root->data);
            return delete_from_tree(root, search, deleted);
        }
        else if (cmp > 0)
        {
            new_node = delete_from_tree(root->left, search, deleted);
        }
        else
        {
            new_node =  delete_from_tree(root->right, search, deleted);
        }
    }
    return root;
}
</code>```

It deletes the words from tree but i cannot understand why unnecessary characters are printing when i call tree traversal.

```<code>void print_inorder(node_t* node)
{
    if (node == NULL)
        return;
    print_in(node->left);
    printf("%s ", node->data);
    print_in(node->right);
}
</code>```

Example: words in a tree: life, value, administation, advantage, add, son.

Expected output:
life, son, value.

Real output:
{t  life, son, value.

答:
Note: This is not a definite answer, but it's too long for a comment space.

You didn't show what new_node = delete_node(root, root->data); does to the tree structure, but most probably it deletes the node pointed at by the root variable.

If so, the root pointer becomes invalid on the return from delete_node(), hence the recursive call in the return statement

```<code>return delete_from_tree(root, search, deleted);
</code>```

makes the called function to operate on a non-NULL, anyway invalid root pointer.

Body:
I have a function that deletes all words starting with the same first letter in a avl binary tree(letter is given by user).

node_t* delete_from_tree(node_t* root, char search, int *deleted)
{
    int cmp;
    node_t* new_node = NULL;
    if (root == NULL)
        return root;
    else
    {
        cmp = root->data[0] - search;
        if (cmp == 0)
        {
            *deleted += 1;
            new_node = delete_node(root, root->data);
            return delete_from_tree(root, search, deleted);
        }
        else if (cmp > 0)
        {
            new_node = delete_from_tree(root->left, search, deleted);
        }
        else
        {
            new_node =  delete_from_tree(root->right, search, deleted);
        }
    }
    return root;
}

It deletes the words from tree but i cannot understand why unnecessary characters are printing when i call tree traversal.

void print_inorder(node_t* node)
{
    if (node == NULL)
        return;
    print_in(node->left);
    printf("%s ", node->data);
    print_in(node->right);
}

Example: words in a tree: life, value, administation, advantage, add, son.

Expected output:
life, son, value.

Real output:
{t  life, son, value.

Body:
Note: This is not a definite answer, but it's too long for a comment space.

You didn't show what new_node = delete_node(root, root->data); does to the tree structure, but most probably it deletes the node pointed at by the root variable.

If so, the root pointer becomes invalid on the return from delete_node(), hence the recursive call in the return statement

return delete_from_tree(root, search, deleted);

makes the called function to operate on a non-NULL, anyway invalid root pointer.


问:
Simple recovery or full recovery?
Today we had an issue with the log file; in three days it grew to 1.3TB (99.5% of the drive) and shrinking it became very difficult.

Anyways, I changed the recovery mode to simple, worked on the issue, prayed, and was able to shrink the log file.

Before changing back to full, I started reading up on it to see if it's actually necessary.

We back up the DB every day, and if anything happens, we can just restore to last night's copy. With that said, and considering the implications of the log file and the amount of processes that run per hour, I don't think it's necessary to set it back to full.

From what I've read, the only reason I would need full recovery is if I want to restore the DB past the last backup I have.

For example, let's say I have a backup from last night. If the database breaks now and it's set as 'simple', then I can only restore to what I have last night.

With 'full', I can use the log file to recover stuff that's not in last night's backup.

Does this make sense? If this is the case, then I think I can leave it as 'simple'.

Thanks.

答:
Yes, this is the case.

I'm betting your log file grew because you weren't backing them up. When you backup transaction logs, the log is automatically truncated. It's also truncated when a checkpoint occurs while in Simple Recovery Model. If you want to keep a full recovery model, then backup your transaction logs hourly, or every 30 minutes, or what ever your business requirements are OK with losing. That is, the question you should ask is "How much data can I afford to lose". What ever this time is, that is how frequent your transaction logs should be backed up. If you are ok with losing an entire's day worth of data (potentially) then using a Simple Recovery Model would suffice.

Title: Simple recovery or full recovery?


问:
eval an input string on button press in react
I want to create a web-app coding game with react that involves evaluating some user (javascript) input.

```<code>  constructor(props) {
    super(props);
    this.state = {
      code: ''
    };
  }

  handleChange(key) {
    return event => this.setState({ [key]: event.target.value });
  }

  funScript() {
    eval(this.state.code);
  }

  anotherScript() {
    console.log("Will this work?");
  }

  render() {
    return (
      <div>
        <input
          type={"text"}
          value={this.state.code}
          onChange={this.handleChange('code')}
         />
        <button onClick={this.funScript()} >run</button>
      </div>
    );
  }
</code>```

I was hoping that the text input would be able to evaluate javascript on button press by the user (the user types in this.anotherScript(); and the console logs "Will this work?". Unfortunately, it doesn't work and I suspect its an issue specific to React. As soon as the input box is typed in, it tries to evaluate the string (without the button even being pressed!). See here for an example: https://codesandbox.io/s/54rkp584ll

Anyone have a proper React solution that doesn't break javascript on the first character input (and evaluates the function)?

答:
When you type

```<code><button onClick={this.funScript()} >run</button>
</code>```

You are calling this.funScript. Remove the parens and you'll just pass the function like you want. Also, funScript needs to be bound to this for it to work.

Body:
I want to create a web-app coding game with react that involves evaluating some user (javascript) input.

  constructor(props) {
    super(props);
    this.state = {
      code: ''
    };
  }

  handleChange(key) {
    return event => this.setState({ [key]: event.target.value });
  }

  funScript() {
    eval(this.state.code);
  }

  anotherScript() {
    console.log("Will this work?");
  }

  render() {
    return (

        <input
          type={"text"}
          value={this.state.code}
          onChange={this.handleChange('code')}
         />
        <button onClick={this.funScript()} >run</button>

    );
  }

I was hoping that the text input would be able to evaluate javascript on button press by the user (the user types in this.anotherScript(); and the console logs "Will this work?". Unfortunately, it doesn't work and I suspect its an issue specific to React. As soon as the input box is typed in, it tries to evaluate the string (without the button even being pressed!). See here for an example: https://codesandbox.io/s/54rkp584ll

Anyone have a proper React solution that doesn't break javascript on the first character input (and evaluates the function)?

Body:
When you type

<button onClick={this.funScript()} >run</button>

You are calling this.funScript. Remove the parens and you'll just pass the function like you want. Also, funScript needs to be bound to this for it to work.


问:
Why is zoom level interpreted different in mapbox-gl-js?
Comparing maps from openlayers, leaflet and mapbox-gl-js, I can see that mapbox-gl-js has a different map image for the same center and zoom combination, and the same div size. It seems to zoom in one level extra compared to the openlayers and leaflet maps. Why is this?</p>

答:
yep that's correct. this one level difference is because the vector tiles used by mapbox-gl-js are 512px and in openlayers/leaflet/mapbox.js the raster tiles used are 256px. in other words, the appearance of a 512 tile at zoom level 0 is the same as the appearance of a 256 tile at zoom level 1. hope this helps!

512px tile 0/0/0

256px tile 1/0/0


问:
Stopping a Clip in Netbeans
So I have a GUI with one button, when clicked once, it plays the song I've got, when clicked a second time, it stops the song, but I guess I don't know how to actually stop it</p>

```<code>private void playButtonActionPerformed(java.awt.event.ActionEvent evt) {
    int i = 0;
    playMusic(Brown);
    i++;

    if (i == 1) {
    plsStop(Brown);
        i--;
    }
    //when the button is clicked, it plays song, when clicked another time, it SHOULD stop it, but like wtf it don't?
}

static public void playMusic(File Sound){
    try{
        Clip clip = AudioSystem.getClip();
        clip.open(AudioSystem.getAudioInputStream(Sound));
        clip.start();
    }catch(Exception e)
    {

    }
}

static public void plsStop(File Sound){
    try{
        Clip clip = AudioSystem.getClip();
        clip.open(AudioSystem.getAudioInputStream(Sound));
        clip.stop();
    }catch(Exception e)
    {

    }
}
</code>```

答: You are re-opening the clip in the plsStop() method. Now you have two copies, and you are trying to stop the copy that is NOT currently playing.  The two methods need to refer to the same clip, which should be a member of the class, not a local variable in the methods.

Title: Stopping a Clip in Netbeans

Body:
So I have a GUI with one button, when clicked once, it plays the song I've got, when clicked a second time, it stops the song, but I guess I don't know how to actually stop it

private void playButtonActionPerformed(java.awt.event.ActionEvent evt) {
    int i = 0;
    playMusic(Brown);
    i++;

    if (i == 1) {
    plsStop(Brown);
        i--;
    }
    //when the button is clicked, it plays song, when clicked another time, it SHOULD stop it, but like wtf it don't?
}

static public void playMusic(File Sound){
    try{
        Clip clip = AudioSystem.getClip();
        clip.open(AudioSystem.getAudioInputStream(Sound));
        clip.start();
    }catch(Exception e)
    {

    }
}

static public void plsStop(File Sound){
    try{
        Clip clip = AudioSystem.getClip();
        clip.open(AudioSystem.getAudioInputStream(Sound));
        clip.stop();
    }catch(Exception e)
    {

    }
}


问:
jQuery click event fires the first time, but not the second
This is the HTML I'm working with:

```<code><ul id="categories">
  <li><a href="#cargo">Cargo Trailers</a></li>
  <div class="dropdown">
    <ul>
      <li><a href="#utility">Utility Trailers</a></li>
    </ul>
  </div>
</ul>
</code>```

I have written a jQuery script to hide the dropdown div. The dropdown div appears the first time the click event is fired. Once the li in the dropdown div is selected and switches places with the first li in the #categories ul, clicking on the li will not bring up the dropdown div.

Here is the jQuery:

```<code>jQuery(document).ready(function($) {

// hide the dropdown div
$('#categories > div').hide();

/*
    Click the drop down arrow function
*/
var $listHeader = $('#categories > li');

$listHeader.click(function() {

    if ( $('#categories > div:hidden') ) {
        //show the drop down
        $('#categories > div').show();
    } else {
        //hide the drop down
        $('#categories > div').hide();
    }
});

/*
    Click a list-item in the drop down function
*/
$('#categories > div a').click(function() {

    /* actions to change the title to the newly selected item */
    // hide the ul
    $('#categories > div').hide();

    // move the clicked item to the header
    $(this).prependTo('#categories > li');

    // move the previous title to the dropdown and sort
    $('#categories > li > a:eq(1)').prependTo('#categories > div > ul > li:empty');

    // Reset the listHeader variable
    $listHeader = $('#categories > li');

    // cancel default browser action
    return false;

});
});
</code>```

答: Maybe prependTo removes the click event handler. Execute the initialization again. If that indeed works, you can choose to use the jQuery.live() function instead of jQuery.click() to bind the click events.

Body:
This is the HTML I'm working with:

Cargo Trailers

Utility Trailers

I have written a jQuery script to hide the dropdown div. The dropdown div appears the first time the click event is fired. Once the li in the dropdown div is selected and switches places with the first li in the #categories ul, clicking on the li will not bring up the dropdown div.

Here is the jQuery:

jQuery(document).ready(function($) {

// hide the dropdown div
$('#categories > div').hide();

/*
    Click the drop down arrow function
*/
var $listHeader = $('#categories > li');

$listHeader.click(function() {

    if ( $('#categories > div:hidden') ) {
        //show the drop down
        $('#categories > div').show();
    } else {
        //hide the drop down
        $('#categories > div').hide();
    }
});

/*
    Click a list-item in the drop down function
*/
$('#categories > div a').click(function() {

    /* actions to change the title to the newly selected item */
    // hide the ul
    $('#categories > div').hide();

    // move the clicked item to the header
    $(this).prependTo('#categories > li');

    // move the previous title to the dropdown and sort
    $('#categories > li > a:eq(1)').prependTo('#categories > div > ul > li:empty');

    // Reset the listHeader variable
    $listHeader = $('#categories > li');

    // cancel default browser action
    return false;

});
});


问:
Doing multiple MySQL database activities at once in PHP
I'm creating a Reddit clone for web development class. Sorting posts by hotness is the final required thing for me to do.

What I'm struggling with, is binding hotness rating to database entry of given post on website. Because I'm already using a mysqli_query in the while loop, I can't start another query for adding hotness rating.

I read posts suggesting to use arrays but that would consume a lot of server resource since hotness would be calculated again on page refresh.

```<code><?php
$link = mysqli_connect("localhost", "username", "password", "database");
if ($link === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
// this is just reddit's hotness algorithm
function hot($ups, $downs, $date) {
    $s = $ups - $downs;
    $order = log10(max(abs($s), 1));
    if ($s > 0) {
        $sign = 1;
    } else if ($s < 0) {
        $sign = -1;
    } else {
        $sign = 0;
    }
    $seconds = $date - 1134028003;
    return round($sign * $order + $seconds / 45000, 2);
}

$query = "SELECT * from posts";
$result = mysqli_query($link, $query);
if($result) {
    // goes through all posts for upvote/downvote values to calculate hotness
    while ($row = mysqli_fetch_array($result)) {
        $post_id = $row['post_id'];
        $time_in_seconds = strtotime($row['timestamp']);
        $hotness_rating = hot($row['upvotes'], $row['downvotes'], $time_in_seconds);
        $hotness_query = 'UPDATE posts SET hotness=$hotness_rating WHERE post_id=$post_id';
        // ideally this would add hotness to post's row in database
        mysqli_query($link, $hotness_query);
    }
} else {
    echo mysqli_error($link);
}
?>
</code>```

答:
You should calculate "hotness" of topic on its update, such as up-vote, down-vote or new message and store it in database at that moment.

This will give you a "hotness" value in database without pointless* recalculations on every refresh and you could simply sort by "hotness".

These recalculations on every refresh is pointless, because if data isn't changed - you will get same result on every refresh and make useless updates to update to same value.

Body:
I'm creating a Reddit clone for web development class. Sorting posts by hotness is the final required thing for me to do.

What I'm struggling with, is binding hotness rating to database entry of given post on website. Because I'm already using a mysqli_query in the while loop, I can't start another query for adding hotness rating.

I read posts suggesting to use arrays but that would consume a lot of server resource since hotness would be calculated again on page refresh.

<?php
$link = mysqli_connect("localhost", "username", "password", "database");
if ($link === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
// this is just reddit's hotness algorithm
function hot($ups, $downs, $date) {
    $s = $ups - $downs;
    $order = log10(max(abs($s), 1));
    if ($s > 0) {
        $sign = 1;
    } else if ($s < 0) {
        $sign = -1;
    } else {
        $sign = 0;
    }
    $seconds = $date - 1134028003;
    return round($sign * $order + $seconds / 45000, 2);
}

$query = "SELECT * from posts";
$result = mysqli_query($link, $query);
if($result) {
    // goes through all posts for upvote/downvote values to calculate hotness
    while ($row = mysqli_fetch_array($result)) {
        $post_id = $row['post_id'];
        $time_in_seconds = strtotime($row['timestamp']);
        $hotness_rating = hot($row['upvotes'], $row['downvotes'], $time_in_seconds);
        $hotness_query = 'UPDATE posts SET hotness=$hotness_rating WHERE post_id=$post_id';
        // ideally this would add hotness to post's row in database
        mysqli_query($link, $hotness_query);
    }
} else {
    echo mysqli_error($link);
}
?>


问:
Expo react-native fetching data from Google API
I want to obtain data from someone who logged in using his Google account. I am able to login and I receive a token, but I can't fetch the data. It seems that it simply doesn't respond. No error thrown, it just seems to waits</p>

```<code>async  logIn() {
  try {
    const result = await Expo.Google.logInAsync({
      androidClientId: '645999128246-gv9drk3gtad84ikeifg37p4k5phdu705.apps.googleusercontent.com',
     // iosClientId: '116235701426-lsptd400ahlctrlveoe4vlg96hcjne51.apps.googleusercontent.com',
      scopes: ['profile', 'email'],
    });

    if (result.type === 'success') {
      console.log(result.accessToken);
      getUserInfo(result.accessToken);
      return result.accessToken;
    } else {
      return {cancelled: true};
    }
  } catch(e) {
    return {error: true};
  }
}
 getUserInfo(accessToken) {
    fetch('https://www.googleapis.com/userinfo/v2/me', {
    headers: { Authorization: `Bearer ${accessToken}`},
  }).then(res => {console.log(res)});
}
  render() {
  this.logIn();
  (...)
</code>```

答:
You are missing an await for the call to this.logIn(); Recommend you read up on Async functions and Promises in JavaScript

You are doing heavy network things in a render call, recommend you read up on React performance coding and general organization of react code

Body:
I want to obtain data from someone who logged in using his Google account. I am able to login and I receive a token, but I can't fetch the data. It seems that it simply doesn't respond. No error thrown, it just seems to waits

async  logIn() {
  try {
    const result = await Expo.Google.logInAsync({
      androidClientId: '645999128246-gv9drk3gtad84ikeifg37p4k5phdu705.apps.googleusercontent.com',
     // iosClientId: '116235701426-lsptd400ahlctrlveoe4vlg96hcjne51.apps.googleusercontent.com',
      scopes: ['profile', 'email'],
    });

    if (result.type === 'success') {
      console.log(result.accessToken);
      getUserInfo(result.accessToken);
      return result.accessToken;
    } else {
      return {cancelled: true};
    }
  } catch(e) {
    return {error: true};
  }
}
 getUserInfo(accessToken) {
    fetch('https://www.googleapis.com/userinfo/v2/me', {
    headers: { Authorization: `Bearer ${accessToken}`},
  }).then(res => {console.log(res)});
}
  render() {
  this.logIn();
  (...)


问:
brute force solution for celebrity algorithm in java
In a party of N people, only one person is known to everyone. Such a person may be present in the party, if yes, (s)he doesn’t know anyone in the party. We can only ask questions like “does A know B? “. Find the stranger (celebrity) in minimum number of questions.

I'm aware that this can be solved using a queue or a stack but I'd like to first solve it using brute force to practice working my way up. My attempt loops through a matrix to see which row has all 0s. Now how do I double check if that row contains one 0 and the rest 1s? Here is my code:

```<code>public static int[][] matrix = {{0, 0, 1, 0},
                                {0, 0, 1, 0},
                                {0, 0, 0, 0},
                                {0, 0, 1, 0}};

public static void main(String[] args) {
    if(knowsCeleb() > 0){
        System.out.println(knowsCeleb() + " is the celebrity.");
    }else{
        System.out.println("There is no celebrity.");
    }
}

public static int knowsCeleb(){
    int count = 0;

    for(int i = 0; i < matrix.length; i++){
        for(int j = 0; j < matrix[i].length; j++){

            if(matrix[i][j] == 0){
                count++;
            }else{
                count = 0;
                break;
            }
        }

        if(count == matrix[i].length){
            return (i+1);
        }
    }
    return 0;
}
</code>```

In this case, the third row is the celebrity because it knows no one (0s in the row) but every one knows it (1s in the column). How do I fix my code so it double checks that the correct column contains 1s and one zero. For example, this input:

```<code> public static int[][] matrix = {{0, 0, 1, 0},
                                {0, 0, 1, 0},
                                {0, 0, 1, 0},
                                {0, 0, 0, 0}};
</code>```

prints that the 4 is a celebrity even though no one knows 4 (no 1s in the last column). How do I execute the second check to verify it is in fact a celebrity? Please help!

答:
If I understand the goal correctly, it seems you have already described the condition that must be met to confirm the matrix entry: "double check that the correct column contains 1s and one zero." So we could make a method that does just that, explicitly check the the column contains ones and one zero:

```<code>public static boolean confirm(int column){
    int zeros = 0;
    int ones = 0;
    column = column - 1; // java indexes from zero, so we decrement column

    boolean confirmed = false; // set the result initially unconfirmed

    // for each row
    for(int i = 0; i < matrix[column].length; i++){
        // if the value in the specified column is zero
        if (matrix[i][column] == 0)
            // add to zeros
            zeros++;
        // otherwise if the value in the specified column is one
        else if (matrix[i][column] == 1)
            // add to ones
            ones++;
    }

    // the condition we want to double check
    // "correct column contains 1s and one zero"
    if (zeros == 1 && ones == 3){
        confirmed = true;  // confirm
    }
    return confirmed;
}
</code>```

Now that we've got the method available, call it from main:

```<code>System.out.println("Confirm " + knowsCeleb() + ": " + confirm(knowsCeleb()));
</code>```

Gives output something like:

```<code>3 is the celebrity.
Confirm 3: true
</code>```

Body:
In a party of N people, only one person is known to everyone. Such a person may be present in the party, if yes, (s)he doesn’t know anyone in the party. We can only ask questions like “does A know B? “. Find the stranger (celebrity) in minimum number of questions.

I'm aware that this can be solved using a queue or a stack but I'd like to first solve it using brute force to practice working my way up. My attempt loops through a matrix to see which row has all 0s. Now how do I double check if that row contains one 0 and the rest 1s? Here is my code:

public static int[][] matrix = {{0, 0, 1, 0},
                                {0, 0, 1, 0},
                                {0, 0, 0, 0},
                                {0, 0, 1, 0}};

public static void main(String[] args) {
    if(knowsCeleb() > 0){
        System.out.println(knowsCeleb() + " is the celebrity.");
    }else{
        System.out.println("There is no celebrity.");
    }
}

public static int knowsCeleb(){
    int count = 0;

    for(int i = 0; i < matrix.length; i++){
        for(int j = 0; j < matrix[i].length; j++){

            if(matrix[i][j] == 0){
                count++;
            }else{
                count = 0;
                break;
            }
        }

        if(count == matrix[i].length){
            return (i+1);
        }
    }
    return 0;
}

In this case, the third row is the celebrity because it knows no one (0s in the row) but every one knows it (1s in the column). How do I fix my code so it double checks that the correct column contains 1s and one zero. For example, this input:

 public static int[][] matrix = {{0, 0, 1, 0},
                                {0, 0, 1, 0},
                                {0, 0, 1, 0},
                                {0, 0, 0, 0}};

prints that the 4 is a celebrity even though no one knows 4 (no 1s in the last column). How do I execute the second check to verify it is in fact a celebrity? Please help!

Body:
If I understand the goal correctly, it seems you have already described the condition that must be met to confirm the matrix entry: "double check that the correct column contains 1s and one zero." So we could make a method that does just that, explicitly check the the column contains ones and one zero:

public static boolean confirm(int column){
    int zeros = 0;
    int ones = 0;
    column = column - 1; // java indexes from zero, so we decrement column

    boolean confirmed = false; // set the result initially unconfirmed

    // for each row
    for(int i = 0; i < matrix[column].length; i++){
        // if the value in the specified column is zero
        if (matrix[i][column] == 0)
            // add to zeros
            zeros++;
        // otherwise if the value in the specified column is one
        else if (matrix[i][column] == 1)
            // add to ones
            ones++;
    }

    // the condition we want to double check
    // "correct column contains 1s and one zero"
    if (zeros == 1 && ones == 3){
        confirmed = true;  // confirm
    }
    return confirmed;
}

Now that we've got the method available, call it from main:

System.out.println("Confirm " + knowsCeleb() + ": " + confirm(knowsCeleb()));

Gives output something like:

3 is the celebrity.
Confirm 3: true


问:
How to use cookies on angular 4+ to make get and post
Can you provide an example or reference of how to use cookies on angular4+ performing GET and POST? On angularJS is documented but not on Angular.io.
Any Equivalent to this: "//code.angularjs.org/X.Y.Z/angular-cookies.js" on Angular4+
Thanks in advance </p>

答:
If you're using the new Angular 5 they introduced something called the HttpInterceptor (https://angular.io/guide/http#intercepting-all-requests-or-responses)

What you can do is create an interceptor that gets your cookie and handles it accordingly.

```<code>import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';

    function getCookie(name) {
     const splitCookie = cookie.split(';');
     for (let i = 0; i < splitCookie.length; i++) {
      const splitValue = val.split('=');
       if (splitValue[0] === name) {
         return splitValue[1];
       }
     }
     return '';
    }

    @Injectable()
    export class AuthInterceptor implements HttpInterceptor {
      constructor(private auth: AuthService) {}

      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // Get the auth header from the service.
        const authHeader = getCookie('auth');
        // Clone the request to add the new header.
        const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
        // Pass on the cloned request instead of the original request.
        return next.handle(authReq);
      }
    }
</code>```

You can also use a library like this to handle cookies:
https://github.com/salemdar/ngx-cookie

Body:
If you're using the new Angular 5 they introduced something called the HttpInterceptor (https://angular.io/guide/http#intercepting-all-requests-or-responses)

What you can do is create an interceptor that gets your cookie and handles it accordingly.

import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';

    function getCookie(name) {
     const splitCookie = cookie.split(';');
     for (let i = 0; i < splitCookie.length; i++) {
      const splitValue = val.split('=');
       if (splitValue[0] === name) {
         return splitValue[1];
       }
     }
     return '';
    }

    @Injectable()
    export class AuthInterceptor implements HttpInterceptor {
      constructor(private auth: AuthService) {}

      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // Get the auth header from the service.
        const authHeader = getCookie('auth');
        // Clone the request to add the new header.
        const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
        // Pass on the cloned request instead of the original request.
        return next.handle(authReq);
      }
    }

You can also use a library like this to handle cookies:
https://github.com/salemdar/ngx-cookie


问:
csv file loop results
I'm trying to extract csv files by the cities with `re.findall(), but when I try to do that and write to results to another csv file, it loops over and over many times!

```<code>import io
import csv
import re

lines=0
outfile1 =codecs.open('/mesh/وسطى.csv','w','utf_8')
outfile6 =codecs.open('/mesh/أخرى.csv','w','utf_8')

with io.open('/mishal.csv','r',encoding="utf-8",newline='') as f:
    reader = csv.reader(f)
    for row in f :
        for rows in row:
            lines += 1

            #الوسطى
            m = re.findall('\u0634\u0642\u0631\u0627\u0621',row)
            if m:
                outfile1.write(row)
            else:
                outfile6.write(row)

print("saved In to mishal !")
f.close()
</code>```

I want the re.finall() cities to not loop, just execute once for each match—not loooooooping so many times whenever there's a match.

Here's a screenshot of the output showing the excessive looping:

答:
csv readers return a list for each line of the file - your outer loop is iterating over the lines/rows and your inner loop is iterating over items in each row.  It isn't clear what you want. but your conditional writes happen for each item in each row.  If your intent is to check and see if there is a match in the row instead of items in the row,

```<code>for row in f :
    match = False
    for item in row:
        lines += 1    #??
        #الوسطى
        match = re.search('\u0634\u0642\u0631\u0627\u0621',item)
    if match:
        outfile1.write(row)
    else:
        outfile6.write(row)
</code>```

You could accomplish the same thing just iterating over the lines in the file without using a csv reader

```<code>with io.open('/mishal.csv','r',encoding="utf-8",newline='') as f:
    for line in f:
        #الوسطى
        if re.search('\u0634\u0642\u0631\u0627\u0621',line):
            outfile1.write(line)
        else:
            outfile6.write(line)
</code>```

Title: csv file loop results

Body:
I'm trying to extract csv files by the cities with `re.findall(), but when I try to do that and write to results to another csv file, it loops over and over many times!

import io
import csv
import re

lines=0
outfile1 =codecs.open('/mesh/وسطى.csv','w','utf_8')
outfile6 =codecs.open('/mesh/أخرى.csv','w','utf_8')

with io.open('/mishal.csv','r',encoding="utf-8",newline='') as f:
    reader = csv.reader(f)
    for row in f :
        for rows in row:
            lines += 1

            #الوسطى
            m = re.findall('\u0634\u0642\u0631\u0627\u0621',row)
            if m:
                outfile1.write(row)
            else:
                outfile6.write(row)

print("saved In to mishal !")
f.close()

I want the re.finall() cities to not loop, just execute once for each match—not loooooooping so many times whenever there's a match.

Here's a screenshot of the output showing the excessive looping:

Body:
csv readers return a list for each line of the file - your outer loop is iterating over the lines/rows and your inner loop is iterating over items in each row.  It isn't clear what you want. but your conditional writes happen for each item in each row.  If your intent is to check and see if there is a match in the row instead of items in the row,

for row in f :
    match = False
    for item in row:
        lines += 1    #??
        #الوسطى
        match = re.search('\u0634\u0642\u0631\u0627\u0621',item)
    if match:
        outfile1.write(row)
    else:
        outfile6.write(row)

You could accomplish the same thing just iterating over the lines in the file without using a csv reader

with io.open('/mishal.csv','r',encoding="utf-8",newline='') as f:
    for line in f:
        #الوسطى
        if re.search('\u0634\u0642\u0631\u0627\u0621',line):
            outfile1.write(line)
        else:
            outfile6.write(line)


问:
How do i slideToggle() text under images without them moving?
I have 3 images in a table and 3 images in another table. I want to add a button under each image and when you click the button it will show some text ("info about img"). I have done that but the problem is, when i target one button all the other images moves down and the image above the button stays fixed. If i target all the buttons by giving them the same class name all the images stays fixed like i want but it shows the text for all images when i click the button, doesnt matter which one i click ofcourse.

/* THIS IS HTML */

```<code><div class="span">
<table>
    <tr>
        <td>
            <div class="imgContainer">
                <div>
                    <img src="images/pinkknitwear.jpg" alt="Pink knitwear"
                title="Pink Knitwear">
                </div>
                <div class="imgButton">
                    <button value="button">ADD TO CART</button>
                </div>
                <div class="btn-cont">
                    <button class="info-btn">DETAILS</button>
                    <ul class="info1">Super nice!</ul>
                </div>
            </div>
        </td>
        <td>

            <div class="imgContainer">
                <div>
                    <img src="images/greenknitwear.jpg" alt="Green Knitwear"
                title="Green Knitwear">
                </div>
                <div class="imgButton">
                    <button value="button">ADD TO CART</button>
                </div>
                <div class="btn-cont">
                    <button class="info-btn">DETAILS</button>
                    <ul class="info1">Super nice!</ul>
                </div>
            </div>
        </td>
        <td>
            <div class="imgContainer">
                <div>
                    <img src="images/redknitwear.jpg" alt="Red Knitwear"
                title="Red Knitwear">

                </div>
                <div class="imgButton">
                    <button value="button">ADD TO CART</button>
                </div>
                <div class="btn-cont">
                    <button class="info-btn">DETAILS</button>
                    <ul class="info1">Super nice!</ul>
                </div>
            </div>
        </td>
    </tr>
 </table>
</code>```

/THIS IS jQUERY/

```<code>$(document).ready(function() {
$(".span").on('click', 'button', function() {
    $(this).closest('.span').find('.info1').slideToggle();

});
});
</code>```

/THIS IS CSS/

```<code>.info1 {display: none;}

.btn-cont button{

 background-color: white;
 border: 1px solid dimgrey;
 color: black;
 padding: 7px 10px;
 text-align: center;
 text-decoration: none;
 display: inline-block;
 flex-direction: row;

}

 .btn-cont button:hover {
 background: gainsboro;
 text-decoration: none;
 cursor: pointer;
 }

 .btn-cont {margin-top: 10px;}
</code>```

Example
Example

答:
Edit js code to this one:</p>

```<code>$(document).ready(function() {
    $(".span").on('click', 'button', function() {
        $(this).parents('.imgContainer').find('.info1').slideToggle();
    });
});
</code>```

Body:
I have 3 images in a table and 3 images in another table. I want to add a button under each image and when you click the button it will show some text ("info about img"). I have done that but the problem is, when i target one button all the other images moves down and the image above the button stays fixed. If i target all the buttons by giving them the same class name all the images stays fixed like i want but it shows the text for all images when i click the button, doesnt matter which one i click ofcourse.

/* THIS IS HTML */

                    <button value="button">ADD TO CART</button>

                    <button class="info-btn">DETAILS</button>

Super nice!

                    <button value="button">ADD TO CART</button>

                    <button class="info-btn">DETAILS</button>

Super nice!

                    <button value="button">ADD TO CART</button>

                    <button class="info-btn">DETAILS</button>

Super nice!

/THIS IS jQUERY/

$(document).ready(function() {
$(".span").on('click', 'button', function() {
    $(this).closest('.span').find('.info1').slideToggle();

});
});

/THIS IS CSS/

.info1 {display: none;}

.btn-cont button{

 background-color: white;
 border: 1px solid dimgrey;
 color: black;
 padding: 7px 10px;
 text-align: center;
 text-decoration: none;
 display: inline-block;
 flex-direction: row;

}

 .btn-cont button:hover {
 background: gainsboro;
 text-decoration: none;
 cursor: pointer;
 }

 .btn-cont {margin-top: 10px;}

Example
Example

Body:
Edit js code to this one:

$(document).ready(function() {
    $(".span").on('click', 'button', function() {
        $(this).parents('.imgContainer').find('.info1').slideToggle();
    });
});


问:
How can I convert a list into string format in python list?
I was wondering how I could change a list written as a string, such as ‘[1,[2,[]],[3,[]]]’ into an actual python list like [1,[2,[]],[3,[]]]. Is there any algorithm for this?</p>

答:
This topic have a lot of examples of solutions for your problem :)

Python - convert string to list

Regards,


问:
Is it possible to get the RSSI values of reflected WiFi Signals?
Suppose I have a single WiFi AP. I want to obtain the RSSI values of all the signals being received from that access point (the signal that comes straight, the one that is reflected off the walls, the one that propagates through a wall etc.)

I am able to get only one RSSI value for one AP at the application layer but ideally, the WiFi NIC card should ideally receive all the signals and choose the signal with the highest RSSI value right?

Please correct me if my question is conceptually wrong. I intend to use this to get the location of an Android device in an indoor environment using WiFi.

答:
There is no way for an AP to tell you that because there is no physical way for it to know what path the waves took, unfortunately.

Longer version: The signal sent from one device to another takes multiple paths, as your question correctly suggests, some portion of the signal passes in a straight line between the sender and the receiver, some portion reflects off objects, some through walls or other materials, etc. When those signals reach the antenna they merge back together in to one.

If the signals arrive "In phase" (meaning the peaks of the waves line up with each other) they add together and the signal appears stronger, if they arrive "out of phase" (with the peak of one wave arriving the same time as the valley of another) then they will cancel each other and the signal will appear weaker. This happens because each path is a different length, so the waves arrive at slightly different times.

I mention that because it is possible, for example, for a direct wave and a reflected wave to both be very strong, but then cancel almost completely at the receiving antenna. So signal strength at the receiver doesn't tell you much about the strength or position of the transmitter, all it really tells you is how the signals combine in space at that exact position.

This video shows a simulation of how the waves interact. You can see that even in the same room as the transmitter, there is a diagonal band where the signal is weak. https://www.youtube.com/watch?time_continue=9&v=6hcK9B4HHY8 All the receiver knows is the strength of the combined waves at the point where it is located.

A beam-forming AP might be able to give you signal strength as a function of direction, which would help, but I don't know if they make that information available.


答:
You can use this selector to toggle only the one element you're interested in:

```<code>$(this).next().slideToggle();
</code>```

Then also set the vertical-align property of your table cells to top to prevent the others from moving.

jsFiddle example

Title: How do i slideToggle() text under images without them moving?

Body:
You can use this selector to toggle only the one element you're interested in:

$(this).next().slideToggle();

Then also set the vertical-align property of your table cells to top to prevent the others from moving.

jsFiddle example


问:
output readonly, input editable with wx.textctrl?
HI, guys,

I am using wxpython to develop a GUI for software configuration, launching and interaction. I want something like a CLI shell window (like pycrust) embedded inside the GUI to interact with a long-term running background process. I could give the input via this shell window and print the output on this window. My current code works very well. But there is problem of editing style, because wx.TextCtrl is simply an editable text window. e.g., I could overwrite or remove any previous text characters or type new input at any location. This is not desirable.

How can I make the wx.TextCtrl like a shell window, i.e. make the output readonly, while keep input editable? e.g.,

1) when input new command, the position only starts after prompt.

2) The user cannot change or replace any previous output text.
I want to force certain restriction, for interaction purpose.

Is there a way to fix the curse prompt? If so, then my problem will be solved, because the user will have no chance to move the curse.

Or is there a way to set certain part of the text (the output and the prompt) readonly?

Or another solution, thanks to 9000's answer, is that I make a grid of windows (a StaticTextCtrl or readonly TextCtrl for output in the upper window; prompt ">>>" on the bottom left area; invisible-border editable window or entry dialog on the bottom right area for input).

any suggestions? Is there any better choice?
Thanks a lot!

答: Just keep track of the location of the prompt each time you display it. Intercept all keypresses and releases, and if anything causes text before the prompt to change, veto that event. It's not that hard, it just takes a little attention to detail and some diligence to capture all text-modification events.</p>