问:
Can't access DropDownList control from GridView header row
I have a problem with GridView headers. I can't access a DropDown control from a header, even tho there is one.This is how my grid looks like

```<code><asp:GridView runat="server"
               ID="AcceptedRecordsGridview"
               AutoGenerateColumns="false"
               DataKeyNames="idn"
               CssClass="table"
               GridLines="none"
               AllowPaging="true"
               OnPageIndexChanging="OnPaging"
               AllowSorting="true"
               PageSize="4" >
    <Columns>
        <asp:TemplateField HeaderText="ID" SortExpression="idn">
            <ItemTemplate>
                <asp:Label ID="Label2" runat="server" Text='<%# Bind("idn") %>'>
                </asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Eval("idn") %>'>
                </asp:Label>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Message info" SortExpression="ninfo">
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("ninfo") %>'>
                </asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ninfo") %>'>
                </asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Unit ID" SortExpression="idb">
            <ItemTemplate>
                <asp:Label ID="Label2" runat="server" Text='<%# Bind("idb") %>'>
                </asp:Label>
           </ItemTemplate>
           <EditItemTemplate>
               <asp:Label ID="Label1" runat="server" Text='<%# Eval("idb") %>'>
               </asp:Label>
           </EditItemTemplate>
       </asp:TemplateField>
       <asp:TemplateField>
           <HeaderTemplate>
               Status:
               <asp:DropDownList ID="ddlStatus"
                                 runat="server"
                                 OnSelectedIndexChanged = "StatusChanged"
                                 AutoPostBack = "true"
                                 AppendDataBoundItems = "true" >
                   <asp:ListItem Text = "ALL" Value = "ALL">
                   </asp:ListItem>
                   <asp:ListItem Text = "Top 10" Value = "10">
                   </asp:ListItem>
               </asp:DropDownList>
           </HeaderTemplate>
           <ItemTemplate>
               <asp:Label ID="Label2" runat="server" Text='<%# Bind("status") %>'>
               </asp:Label>
           </ItemTemplate>
           <EditItemTemplate>
               <asp:Label ID="Label1" runat="server" Text='<%# Eval("status") %>'>
               </asp:Label>
           </EditItemTemplate>
       </asp:TemplateField>
       <asp:TemplateField HeaderText="Received" SortExpression="time">
           <ItemTemplate>
               <asp:Label ID="Label2" runat="server" Text='<%# Bind("time") %>'>
               </asp:Label>
           </ItemTemplate>
           <EditItemTemplate>
               <asp:Label ID="Label1" runat="server" Text='<%# Eval("time") %>'>
               </asp:Label>
           </EditItemTemplate>
       </asp:TemplateField>
       <asp:TemplateField HeaderText="Solved" SortExpression="timeUpdated">
           <ItemTemplate>
               <asp:Label ID="Label2" runat="server" Text='<%# Bind("timeUpdated") %>'>
               </asp:Label>
           </ItemTemplate>
           <EditItemTemplate>
               <asp:Label ID="Label1" runat="server" Text='<%# Eval("timeUpdated") %>'>
               </asp:Label>
           </EditItemTemplate>
       </asp:TemplateField>
   </Columns>
</asp:GridView>
</code>```

I want to access drop down control from the HeaderTeamplate tag. I tried different solutions, like this one DropDownList ddlStatus =                 (DropDownList)AcceptedRecordsGridview.HeaderRow.FindControl("ddlStatus");
also I tried to get the control using RowDataBound, and also tried with foreach statement to loop through rows but every time I get null reference exception. Can someone please tell what I am doing wrong? Thank you very much in advance.

答:
try this</p>

```<code>foreach (GridViewRow gr in AcceptedRecordsGridview.Rows)
{
  if (gr.RowType == DataControlRowType.Header)
  {
   DropDownList drop = gr.FindControl("DropDownList1") as DropDownList;
  }

}
</code>```

Body:
I have a problem with GridView headers. I can't access a DropDown control from a header, even tho there is one.This is how my grid looks like

<asp:GridView runat="server"
               ID="AcceptedRecordsGridview"
               AutoGenerateColumns="false"
               DataKeyNames="idn"
               CssClass="table"
               GridLines="none"
               AllowPaging="true"
               OnPageIndexChanging="OnPaging"
               AllowSorting="true"
               PageSize="4" >
    <Columns>
        <asp:TemplateField HeaderText="ID" SortExpression="idn">
            <ItemTemplate>
                <asp:Label ID="Label2" runat="server" Text='<%# Bind("idn") %>'>
                </asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Eval("idn") %>'>
                </asp:Label>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Message info" SortExpression="ninfo">
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("ninfo") %>'>
                </asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ninfo") %>'>
                </asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Unit ID" SortExpression="idb">
            <ItemTemplate>
                <asp:Label ID="Label2" runat="server" Text='<%# Bind("idb") %>'>
                </asp:Label>
           </ItemTemplate>
           <EditItemTemplate>
               <asp:Label ID="Label1" runat="server" Text='<%# Eval("idb") %>'>
               </asp:Label>
           </EditItemTemplate>
       </asp:TemplateField>
       <asp:TemplateField>
           <HeaderTemplate>
               Status:
               <asp:DropDownList ID="ddlStatus"
                                 runat="server"
                                 OnSelectedIndexChanged = "StatusChanged"
                                 AutoPostBack = "true"
                                 AppendDataBoundItems = "true" >
                   <asp:ListItem Text = "ALL" Value = "ALL">
                   </asp:ListItem>
                   <asp:ListItem Text = "Top 10" Value = "10">
                   </asp:ListItem>
               </asp:DropDownList>
           </HeaderTemplate>
           <ItemTemplate>
               <asp:Label ID="Label2" runat="server" Text='<%# Bind("status") %>'>
               </asp:Label>
           </ItemTemplate>
           <EditItemTemplate>
               <asp:Label ID="Label1" runat="server" Text='<%# Eval("status") %>'>
               </asp:Label>
           </EditItemTemplate>
       </asp:TemplateField>
       <asp:TemplateField HeaderText="Received" SortExpression="time">
           <ItemTemplate>
               <asp:Label ID="Label2" runat="server" Text='<%# Bind("time") %>'>
               </asp:Label>
           </ItemTemplate>
           <EditItemTemplate>
               <asp:Label ID="Label1" runat="server" Text='<%# Eval("time") %>'>
               </asp:Label>
           </EditItemTemplate>
       </asp:TemplateField>
       <asp:TemplateField HeaderText="Solved" SortExpression="timeUpdated">
           <ItemTemplate>
               <asp:Label ID="Label2" runat="server" Text='<%# Bind("timeUpdated") %>'>
               </asp:Label>
           </ItemTemplate>
           <EditItemTemplate>
               <asp:Label ID="Label1" runat="server" Text='<%# Eval("timeUpdated") %>'>
               </asp:Label>
           </EditItemTemplate>
       </asp:TemplateField>
   </Columns>
</asp:GridView>

I want to access drop down control from the HeaderTeamplate tag. I tried different solutions, like this one DropDownList ddlStatus =                 (DropDownList)AcceptedRecordsGridview.HeaderRow.FindControl("ddlStatus");
also I tried to get the control using RowDataBound, and also tried with foreach statement to loop through rows but every time I get null reference exception. Can someone please tell what I am doing wrong? Thank you very much in advance.

Body:
try this

foreach (GridViewRow gr in AcceptedRecordsGridview.Rows)
{
  if (gr.RowType == DataControlRowType.Header)
  {
   DropDownList drop = gr.FindControl("DropDownList1") as DropDownList;
  }

}


来源: stackexchange

问:
How to login SSH on Azure Databricks cluster
I used the following ubuntu command to access SSH login as,

ssh user@hostname_or_IP

Can able to see Master node hostname

but not able to get the username from Azure Databricks cluster

Refer this doc,
https://docs.azuredatabricks.net/user-guide/clusters/spark-config.html#spark-config

答:
As per my knowledge, you cannot SSH on Azure Databricks.

Note: Azure Databricks integrated with Azure Active Directory – So, Azure Databricks users are only regular AAD users.

Azure Active Directory users can be used directly in Azure Databricks
for al user-based access control (Clusters, jobs, Notebooks etc.).

Azure Databricks has delegated user authentication to AAD enabling
single-sign on (SSO) and unified authentication.

Notebooks and their outputs, are stored in the Databricks account.
However, AAD based access control ensures that only authorized users
can access them.

ContentLicense: CC BY-SA 3.0


问:
Is SQLite a good choice for a large, read only database for research?
I have a large number of records (say around 10 to 100 million), which I want to be able to query.

This is a research project, the database is going to be mostly read only, and I only need one connection at a time. I would like the queries to be reasonably fast.

Is SQLite a reasonable choice for this purpose?

答:
My experience with SQLite is that it may be quite slow on large recordsets, depending on how you structure your queries. If your data is de-normalized and you can get by querying a single table against its primary key then it's acceptably fast, but if your data is fully normalized and your queries involve several joins then it can be much slower than a client-server database.

SQLite's principal advantage is its small size and single file nature that make it easy to distribute embedded in an app. As that doesn't seem to be a requirement for you though, I think you'd be better off going with something else. SQL Server Express is good if you're using Windows, MySQL or Postgres otherwise would be a good choice.

ContentLicense: CC BY-SA 2.5


问:
Hibernate XML mapping or Annotation mapping config better for real time project using spring framework
Please let me know which one is better for real time project Hibernate XML Mapping or Annotation base Mapping ?</p>

答: For new projects better to use annotations, because XML mapping doesn't support all features that annotation mapping does.</p>


答:
The foreach approach doesn't work because GridView.Rows never returns the header or footer but just the rows which RowType is DataRow.

So you have to use RowDataBound which is called after the grid is data-bound for each row including the header and footer. So it's necessary  to check the RowType:

```<code>protected void AcceptedRecordsGridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        DropDownList ddlStatus = (DropDownList) e.Row.FindControl("ddlStatus");
    }
}
</code>```

Title: Can't access DropDownList control from GridView header row

Body:
The foreach approach doesn't work because GridView.Rows never returns the header or footer but just the rows which RowType is DataRow.

So you have to use RowDataBound which is called after the grid is data-bound for each row including the header and footer. So it's necessary  to check the RowType:

protected void AcceptedRecordsGridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        DropDownList ddlStatus = (DropDownList) e.Row.FindControl("ddlStatus");
    }
}


问:
pathlib.Path().glob() and multiple file extension
I need to specify multiple file extensions like pathlib.Path(temp_folder).glob('*.xls', '*.txt'):

How I can do it?

https://docs.python.org/dev/library/pathlib.html#pathlib.Path.glob

答:
If you need to use pathlib.Path.glob()

```<code>from pathlib import Path
def get_files(extensions):
    all_files = []
    for ext in extensions:
        all_files.extend(Path('.').glob(ext))
    return all_files

files = get_files(('*.txt', '*.py', '*.cfg'))
</code>```

Body:
If you need to use pathlib.Path.glob()

from pathlib import Path
def get_files(extensions):
    all_files = []
    for ext in extensions:
        all_files.extend(Path('.').glob(ext))
    return all_files

files = get_files(('*.txt', '*.py', '*.cfg'))

ContentLicense: CC BY-SA 4.0


问:
com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet
I am running my first mobile automation test case using appium in android studio.
I am using latest version of appium and android studio and Java 8.
I have set all the project dependencies.

But I have encountered with the following error.

```<code>java.lang.NoSuchMethodError: com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet(Ljava/util/Comparator;)Ljava/util/stream/Collector;

at org.openqa.selenium.remote.NewSessionPayload.lambda$validate$4(NewSessionPayload.java:199)
at java.util.stream.ReferencePipeline$11$1.accept(ReferencePipeline.java:372)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.stream.ReferencePipeline$11$1.accept(ReferencePipeline.java:373)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.openqa.selenium.remote.NewSessionPayload.validate(NewSessionPayload.java:215)
at org.openqa.selenium.remote.NewSessionPayload.<init>(NewSessionPayload.java:163)
at org.openqa.selenium.remote.NewSessionPayload.create(NewSessionPayload.java:114)
at org.openqa.selenium.remote.NewSessionPayload.create(NewSessionPayload.java:107)
at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:67)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:142)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:601)
at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:180)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:219)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:142)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:155)
at io.appium.java_client.AppiumDriver.<init>(AppiumDriver.java:109)
at io.appium.java_client.android.AndroidDriver.<init>(AndroidDriver.java:39)
at com.example.gourav.myapp.FristTest.setUp(FristTest.java:53)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)
java.lang.NullPointerException
at com.example.gourav.myapp.FristTest.End(FristTest.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:33)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)

Process finished with exit code -1
</code>```

Code for test case:-

```<code>    public class FristTest
    {
      AndroidDriver driver;

     @Before
     public void setUp() throws MalformedURLException
     {
        // Created object of DesiredCapabilities class.
        DesiredCapabilities capabilities = new DesiredCapabilities();

        // Set android deviceName desired capability. Set your device name.
        capabilities.setCapability("deviceName", "ZH33L2CB5H");

        // Set BROWSER_NAME desired capability. It's Android in our case here.
        capabilities.setCapability(CapabilityType.BROWSER_NAME, "Android");

        // Set android VERSION desired capability. Set your mobile device's OS version.
        capabilities.setCapability(CapabilityType.VERSION, "7.1.1");

        // Set android platformName desired capability. It's Android in our case here.
        capabilities.setCapability("platformName", "Android");

        // Set android appPackage desired capability. It is
        // com.android.calculator2 for calculator application.
        // Set your application's appPackage if you are using any other app.
        capabilities.setCapability("appPackage", "com.android.calculator2");

        // Set android appActivity desired capability. It is
        // com.android.calculator2.Calculator for calculator application.
        // Set your application's appPackage if you are using any other app.
        capabilities.setCapability("appActivity", "com.android.calculator2.Calculator");

        // Created object of RemoteWebDriver will all set capabilities.
        // Set appium server address and port number in URL string.
        // It will launch calculator app in android device.
        driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
    }

    @Test
    public void testFirstCalculator()
    {

        // Click on DELETE/CLR button to clear result text box before running test.
        driver.findElements(By.xpath("//android.widget.Button")).get(0).click();

        // Click on number 2 button.
        driver.findElement(By.name("7")).click();
    }

    @After
    public void End()
    {
        driver.close();
    }
}
</code>```

Please help. I have googled this problem but didnot get any solution.

答:
There is a problem in your project setup. Make sure you are using correct dependencies, for gradle it should look like:

dependencies {
    compile fileTree(dir: 'lib', include: ['*.jar'])
    compile 'junit:junit:4.12'
    compile 'io.appium:java-client:5.0.4'
}

Note 1: Since you don't start appium server programatically, server should be already running before you lauch test

Note 2: driver.findElement(By.name("7")) will fail because name locator strategy is deprecated for Appium, use driver.findElement(MobileBy.AccessibilityId(<your_value>)) instead

Body:
I am running my first mobile automation test case using appium in android studio.
I am using latest version of appium and android studio and Java 8.
I have set all the project dependencies.

But I have encountered with the following error.

java.lang.NoSuchMethodError: com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet(Ljava/util/Comparator;)Ljava/util/stream/Collector;

at org.openqa.selenium.remote.NewSessionPayload.lambda$validate$4(NewSessionPayload.java:199)
at java.util.stream.ReferencePipeline$11$1.accept(ReferencePipeline.java:372)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.stream.ReferencePipeline$11$1.accept(ReferencePipeline.java:373)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.openqa.selenium.remote.NewSessionPayload.validate(NewSessionPayload.java:215)
at org.openqa.selenium.remote.NewSessionPayload.<init>(NewSessionPayload.java:163)
at org.openqa.selenium.remote.NewSessionPayload.create(NewSessionPayload.java:114)
at org.openqa.selenium.remote.NewSessionPayload.create(NewSessionPayload.java:107)
at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:67)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:142)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:601)
at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:180)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:219)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:142)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:155)
at io.appium.java_client.AppiumDriver.<init>(AppiumDriver.java:109)
at io.appium.java_client.android.AndroidDriver.<init>(AndroidDriver.java:39)
at com.example.gourav.myapp.FristTest.setUp(FristTest.java:53)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)
java.lang.NullPointerException
at com.example.gourav.myapp.FristTest.End(FristTest.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:33)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)

Process finished with exit code -1

Code for test case:-

    public class FristTest
    {
      AndroidDriver driver;

     @Before
     public void setUp() throws MalformedURLException
     {
        // Created object of DesiredCapabilities class.
        DesiredCapabilities capabilities = new DesiredCapabilities();

        // Set android deviceName desired capability. Set your device name.
        capabilities.setCapability("deviceName", "ZH33L2CB5H");

        // Set BROWSER_NAME desired capability. It's Android in our case here.
        capabilities.setCapability(CapabilityType.BROWSER_NAME, "Android");

        // Set android VERSION desired capability. Set your mobile device's OS version.
        capabilities.setCapability(CapabilityType.VERSION, "7.1.1");

        // Set android platformName desired capability. It's Android in our case here.
        capabilities.setCapability("platformName", "Android");

        // Set android appPackage desired capability. It is
        // com.android.calculator2 for calculator application.
        // Set your application's appPackage if you are using any other app.
        capabilities.setCapability("appPackage", "com.android.calculator2");

        // Set android appActivity desired capability. It is
        // com.android.calculator2.Calculator for calculator application.
        // Set your application's appPackage if you are using any other app.
        capabilities.setCapability("appActivity", "com.android.calculator2.Calculator");

        // Created object of RemoteWebDriver will all set capabilities.
        // Set appium server address and port number in URL string.
        // It will launch calculator app in android device.
        driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
    }

    @Test
    public void testFirstCalculator()
    {

        // Click on DELETE/CLR button to clear result text box before running test.
        driver.findElements(By.xpath("//android.widget.Button")).get(0).click();

        // Click on number 2 button.
        driver.findElement(By.name("7")).click();
    }

    @After
    public void End()
    {
        driver.close();
    }
}

Please help. I have googled this problem but didnot get any solution.


问:
Email sending in aspnetboilerplate not working
This is the settings:

```<code>AddSettingIfNotExists(EmailSettingNames.DefaultFromAddress, "abc@xyz.tech");
AddSettingIfNotExists(EmailSettingNames.DefaultFromDisplayName, "abc.tech Emailservice");
AddSettingIfNotExists(EmailSettingNames.Smtp.UserName, "abc@xyz.tech");
AddSettingIfNotExists(EmailSettingNames.Smtp.Domain, "abc.tech");
AddSettingIfNotExists(EmailSettingNames.Smtp.EnableSsl,"false");
AddSettingIfNotExists(EmailSettingNames.Smtp.Host, "webmail.abc.tech");
AddSettingIfNotExists(EmailSettingNames.Smtp.Port, "25");
AddSettingIfNotExists(EmailSettingNames.Smtp.Password, "gdfdgd");
AddSettingIfNotExists(EmailSettingNames.Smtp.UseDefaultCredentials, "false");
</code>```

This is the email sending code:

```<code>// See "Update"
</code>```

I am getting this exception:

Bad sequence of commands. The server response was: This mail server
  requires authentication when attempting to send to a non-local e-mail
  address. Please check your mail client settings or contact your
  administrator to verify that the domain or address is defined for this
  server

Update

```<code>public class UserAppService // ...
{
    private readonly UserManager _userManager;
    private readonly RoleManager _roleManager;
    IRepository<User, long> _rep;
    private readonly IRepository<Role> _roleRepository;
    private readonly IPasswordHasher<User> _passwordHasher;
    public readonly IEmailSender _emailSender;

    public UserAppService(
        IRepository<User, long> repository,
        UserManager userManager,
        RoleManager roleManager,
        IRepository<Role> roleRepository,
        IPasswordHasher<User> passwordHasher, IEmailSender em)
        : base(repository)
    {
        _rep = repository;
        _userManager = userManager;
        _roleManager = roleManager;
        _roleRepository = roleRepository;
        _passwordHasher = passwordHasher;
        _emailSender = em;
    }

    [AbpAllowAnonymous]
    public override async Task<UserDto> Create(CreateUserDto input)
    {
        // CheckCreatePermission();

        var user = ObjectMapper.Map<User>(input);

        user.TenantId = AbpSession.TenantId;
        user.Password = _passwordHasher.HashPassword(user, input.Password);
        user.IsEmailConfirmed = false;

        CheckErrors(await _userManager.CreateAsync(user));

        if (input.RoleNames != null)
        {
            CheckErrors(await _userManager.SetRoles(user, input.RoleNames));
        }

        CurrentUnitOfWork.SaveChanges();

        try
        {
            await _emailSender.SendAsync("test@gmail.com", "sdfs", "sdfsd", false);
        }
        catch (Exception ex)
        {
        }

        return MapToEntityDto(user);
    }
}
</code>```

答:
This mail server requires authentication when attempting to send to a non-local e-mail address.

Looks like an issue with your SMTP server (related).

Try sending an email to yourself or another user in the same domain.

I can't send mail to other domains same domain it is working what will be the problem.

Contact the system administrator of your SMTP server.

using smtp ordinary .net code it is working fine

You can send a MailMessage using IEmailSender too.

Body:
This is the settings:

AddSettingIfNotExists(EmailSettingNames.DefaultFromAddress, "abc@xyz.tech");
AddSettingIfNotExists(EmailSettingNames.DefaultFromDisplayName, "abc.tech Emailservice");
AddSettingIfNotExists(EmailSettingNames.Smtp.UserName, "abc@xyz.tech");
AddSettingIfNotExists(EmailSettingNames.Smtp.Domain, "abc.tech");
AddSettingIfNotExists(EmailSettingNames.Smtp.EnableSsl,"false");
AddSettingIfNotExists(EmailSettingNames.Smtp.Host, "webmail.abc.tech");
AddSettingIfNotExists(EmailSettingNames.Smtp.Port, "25");
AddSettingIfNotExists(EmailSettingNames.Smtp.Password, "gdfdgd");
AddSettingIfNotExists(EmailSettingNames.Smtp.UseDefaultCredentials, "false");

This is the email sending code:

// See "Update"

I am getting this exception:

Bad sequence of commands. The server response was: This mail server
  requires authentication when attempting to send to a non-local e-mail
  address. Please check your mail client settings or contact your
  administrator to verify that the domain or address is defined for this
  server

Update

public class UserAppService // ...
{
    private readonly UserManager _userManager;
    private readonly RoleManager _roleManager;
    IRepository<User, long> _rep;
    private readonly IRepository<Role> _roleRepository;
    private readonly IPasswordHasher<User> _passwordHasher;
    public readonly IEmailSender _emailSender;

    public UserAppService(
        IRepository<User, long> repository,
        UserManager userManager,
        RoleManager roleManager,
        IRepository<Role> roleRepository,
        IPasswordHasher<User> passwordHasher, IEmailSender em)
        : base(repository)
    {
        _rep = repository;
        _userManager = userManager;
        _roleManager = roleManager;
        _roleRepository = roleRepository;
        _passwordHasher = passwordHasher;
        _emailSender = em;
    }

    [AbpAllowAnonymous]
    public override async Task<UserDto> Create(CreateUserDto input)
    {
        // CheckCreatePermission();

        var user = ObjectMapper.Map<User>(input);

        user.TenantId = AbpSession.TenantId;
        user.Password = _passwordHasher.HashPassword(user, input.Password);
        user.IsEmailConfirmed = false;

        CheckErrors(await _userManager.CreateAsync(user));

        if (input.RoleNames != null)
        {
            CheckErrors(await _userManager.SetRoles(user, input.RoleNames));
        }

        CurrentUnitOfWork.SaveChanges();

        try
        {
            await _emailSender.SendAsync("test@gmail.com", "sdfs", "sdfsd", false);
        }
        catch (Exception ex)
        {
        }

        return MapToEntityDto(user);
    }
}


问:
Escp command to print table border
I am working on Epson dot matrix printer and printing using Esc/p command. But I have problem when i want to print a border of table. The table border will use the extended ASCII :

So I want to use character : 179, 180, 185, 186, etc.... But when I send it to printer, it print strange character. So how to make it work?

I am trying to select character set but it seems still not work. If anyone know about, please let me know.

答:
There are several sets of ASCII tables in the printer.
The printer documentation shows which table is default.

To send extended character to printer, it must be written as hex byte:

```<code>data="\xC9" # example extended byte
</code>```

If you need more precise answer, please let us know which printer you are using, show example of your code.

Title: Escp command to print table border

Body:
There are several sets of ASCII tables in the printer.
The printer documentation shows which table is default.

To send extended character to printer, it must be written as hex byte:

data="\xC9" # example extended byte

If you need more precise answer, please let us know which printer you are using, show example of your code.


问:
VB macros in excel
i am new to working with macros and writing macros in excel. CAn someone point me to some tutorials/examples which will help me understand and write macros for writing and editing excel documents.</p>

答: There are loads of examples on the Chip Pearson site although some may be a bit advanced</p>

Title: VB macros in excel


问:
Plugin Jenkins to Capture html just before an error execution?
Does anybody know how to capture the html/url before an error appear in the test case with Selenium Webdriver??
I need to know the previous URL, and I don't know how...
I use Jenkins to run my tests.

I need some shell command to take a screenshoot and save in some directory.
How could be that shell code?

I've tried with: UI TEST CAPTURE Plugin
But it didn't work...it doesn't let me to configure it. I don't know why. (I show you in a picture)

I've written the following to my test-case java file:

```<code>String actualTest = this.getClass().getName()+"."+testname.getMethodName();
File scrFile = ((TakesScreenshot)FabricaWebDriver.getDriver()).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("target/screenshots/"+actualTest+".png"));
</code>```

But it work only when a test is SUCCESS.
I need it when a test is FAILED,...... and I'm not able to get it.

I've tried with these conditions I show you in an image, but it doesn't work and I don't understand why...

答:
With regard to capturing the URL, I presume your site directs you to a page such as www.yoursite.com/error.htm or something similar?

In which case, the only option you have is to store the URL before each Selenium action, which is a pain

C#:

```<code>var currentURL = Driver.Url;
</code>```

Or, if you're referring to handling an exception, you'd just capture the URL in the catch block.

Body:
Does anybody know how to capture the html/url before an error appear in the test case with Selenium Webdriver??
I need to know the previous URL, and I don't know how...
I use Jenkins to run my tests.

I need some shell command to take a screenshoot and save in some directory.
How could be that shell code?

I've tried with: UI TEST CAPTURE Plugin
But it didn't work...it doesn't let me to configure it. I don't know why. (I show you in a picture)

I've written the following to my test-case java file:

String actualTest = this.getClass().getName()+"."+testname.getMethodName();
File scrFile = ((TakesScreenshot)FabricaWebDriver.getDriver()).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("target/screenshots/"+actualTest+".png"));

But it work only when a test is SUCCESS.
I need it when a test is FAILED,...... and I'm not able to get it.

I've tried with these conditions I show you in an image, but it doesn't work and I don't understand why...

Body:
With regard to capturing the URL, I presume your site directs you to a page such as www.yoursite.com/error.htm or something similar?

In which case, the only option you have is to store the URL before each Selenium action, which is a pain

C#:

var currentURL = Driver.Url;

Or, if you're referring to handling an exception, you'd just capture the URL in the catch block.


问:
How to dynamically append sections and use those to append other sections with JQuery?
Straight to the point. I have a problem with .append() function. I need to append a section, containing datetime-local and a button to another section, which is visible.

This new appended button must append another section, containing the same elements, but WITH DIFFERENT IDs. First part of the code is working, but second doesn’t and I can’t get why. I know my code is elegant like an elephant, but...

Your help is appreciated!

$(document).ready(function() {
  var max_fields = 2;
  var wrapper = $(".input_1");
  var add_button = $(".add_1");

  var x = 1;

  $(add_button).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append('
-.-.-
<input type="datetime-local">Remove
 <button class="add_2">return</button>
');
    }
  });

  $(wrapper).on("click", ".remove_1", function(e) {
    e.preventDefault();
    $(this).parent('section').remove();
    x--;
  })
});

//level 2
$(document).ready(function() {
  var max_fields_2 = 2;
  var wrapper_2 = $(".input_2");
  var add_button_2 = $(".add_2");

  var x = 1;

  $(add_button_2).click(function(e) {
    e.preventDefault();
    if (x < max_fields_2) {
      x++;
      $(wrapper_2).append('
-.-.-
<input type="datetime-local">Remove
 <button class="add_3">return 2</button>
');
    }
  });

  $(wrapper_2).on("click", ".remove_2", function(e) {
    e.preventDefault();
    $(this).parent('section').remove();
    x--;
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="input_1">
  <input type="datetime-local"><br/>
  <button class="add_1">return to icu</button>
</section></code>```

答:
var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID

    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('
<input type="text" name="mytext[]"/>Remove
'); //add input box
        }
    });

    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input_fields_wrap">
    <button class="add_field_button">Add More Fields</button>
    <div><input type="text" name="mytext[]"></div>
</div></code>```

happ coding :)

Body:
Straight to the point. I have a problem with .append() function. I need to append a section, containing datetime-local and a button to another section, which is visible.

This new appended button must append another section, containing the same elements, but WITH DIFFERENT IDs. First part of the code is working, but second doesn’t and I can’t get why. I know my code is elegant like an elephant, but...

Your help is appreciated!

$(document).ready(function() {
  var max_fields = 2;
  var wrapper = $(".input_1");
  var add_button = $(".add_1");

  var x = 1;

  $(add_button).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append('
-.-.-
<input type="datetime-local">Remove
 <button class="add_2">return</button>
');
    }
  });

  $(wrapper).on("click", ".remove_1", function(e) {
    e.preventDefault();
    $(this).parent('section').remove();
    x--;
  })
});

//level 2
$(document).ready(function() {
  var max_fields_2 = 2;
  var wrapper_2 = $(".input_2");
  var add_button_2 = $(".add_2");

  var x = 1;

  $(add_button_2).click(function(e) {
    e.preventDefault();
    if (x < max_fields_2) {
      x++;
      $(wrapper_2).append('
-.-.-
<input type="datetime-local">Remove
 <button class="add_3">return 2</button>
');
    }
  });

  $(wrapper_2).on("click", ".remove_2", function(e) {
    e.preventDefault();
    $(this).parent('section').remove();
    x--;
  })
});

  <input type="datetime-local">

  <button class="add_1">return to icu</button>

Body:
var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID

    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
        }
    });

    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input_fields_wrap">
    <button class="add_field_button">Add More Fields</button>
    <div><input type="text" name="mytext[]"></div>
</div>

happ coding :)


问:
RAML, Request parameter title not defined
I have am having some trouble with my RAML file.

when I call this URL in GET:

```<code>mysite.com/test/nextversion?msn=xxx&ata=xx&title=xxx
</code>```

it tells me that the parameters are not defined:

```<code>"Request parameter msn not defined in RAML\nRequest parameter title not defined in RAML\nRequest parameter ata not defined in RAML"
</code>```

This is my RAML definition:

```<code>/test/nextversion:
  get:
    queryParameters:
      msn:
        description: msn id
        type: string
        required: false
      title:
        description: ata title
        type: string
        required: false
      ata:
        description: ata id
        type: string
        required: false
    responses:
      200:
        description: OK
        body:
          application/json:
            type: string
      550:
        body:
          application/json:
            type: DefaultResponse

/test/{ipid}/nextversion:
  uriParameters:
    ipid:
      type: string
  get:
    responses:
      200:
        description: OK
        body:
          application/json:
            type: string
      550:
        body:
          application/json:
            type: DefaultResponse
</code>```

Now I have noticed that it always goes into the second one cause when I remove the first definition it gives me the same error, even though it shoul tell me that it cant find the right definition.
When I remove the second definition it works fine but I have another endpoint depending on that one.

Can anyone explain to me why this is not working in my RAML file?

答:
It appears it's all about the order of the RAML url definitions.

It should go from most specific to most general case cause the RAML will stop at the first url definition that fits, which is not always the right one.

In my case the request was actually going into a url definition defined before the ones described in my question, cause it fit the url definition minus everything comming after it.

Body:
I have am having some trouble with my RAML file.

when I call this URL in GET:

mysite.com/test/nextversion?msn=xxx&ata=xx&title=xxx

it tells me that the parameters are not defined:

"Request parameter msn not defined in RAML\nRequest parameter title not defined in RAML\nRequest parameter ata not defined in RAML"

This is my RAML definition:

/test/nextversion:
  get:
    queryParameters:
      msn:
        description: msn id
        type: string
        required: false
      title:
        description: ata title
        type: string
        required: false
      ata:
        description: ata id
        type: string
        required: false
    responses:
      200:
        description: OK
        body:
          application/json:
            type: string
      550:
        body:
          application/json:
            type: DefaultResponse

/test/{ipid}/nextversion:
  uriParameters:
    ipid:
      type: string
  get:
    responses:
      200:
        description: OK
        body:
          application/json:
            type: string
      550:
        body:
          application/json:
            type: DefaultResponse

Now I have noticed that it always goes into the second one cause when I remove the first definition it gives me the same error, even though it shoul tell me that it cant find the right definition.
When I remove the second definition it works fine but I have another endpoint depending on that one.

Can anyone explain to me why this is not working in my RAML file?


问:
Java use JNA call dll error:Invalid memory access

I want to call dll to write/read from hardware.However, I get the error below:

dll method:

```<code>int NewKey(char *room,char *gate,char *stime,char *guestname,char *guestid, int  overflag, int Breakfast, long *cardno,char * track1,char * track2);
</code>```

java method:

```<code>int NewKey(String room, String gate,String time,String guestname,String guestid, int overflag, int Breakfast, NativeLongByReference cardno, String track1, String track2);
</code>```

The api document shows cardno as a out parameter  and track1，track2 could be null.

```<code>NativeLongByReference cardNo = new NativeLongByReference ();

int res = CLibrary.INSTANCE.NewKey("010001", "00", "201712021200201712031200", "Guest Name","Account No.", 0, 1, cardNo, null, null);
</code>```

It don t work. So I use a simple method:

```<code>dll method :

int EraseCard (long  cardno,char * track1,char * track2);
</code>```

java method:

```<code>int EraseCard(NativeLong cardno, String  track1, String  track2);

NativeLong a = new NativeLong(0L);

int res = CLibrary.INSTANCE.EraseCard (a, null, null);
</code>```

It gets the same error again:

```<code>Exception in thread "main" java.lang.Error: Invalid memory access
at com.sun.jna.Native.invokeInt(Native Method)
at com.sun.jna.Function.invoke(Function.java:383)
at com.sun.jna.Function.invoke(Function.java:315)
at com.sun.jna.Library$Handler.invoke(Library.java:212)
at A90PmsInterface.main(A90PmsInterface.java:104)
</code>```

It seems like the error only occurs when I try to use the dll methods to read/write from/to hardware.

How can I solve the problem?

details: win7 64 bite, jre1.8 32bite, jna4.1

答:
If you want to access memory from the dll, you will need to setup the proper data type needed to reference the memory location. On pointer objects your jna should use ByteByReference for char* or you can also use PointerByReference instead of declaring the object as a String. Using PointerByReference will help you avoid memory leaks.

JNA Marshalling / Unmarshalling

is a good place to start. Good Luck!

Edit:
Java method declaration - (example of JNA XXByReference usage)

```<code>public int E1K_DI_Reads(int connection, byte channel, byte channelCount, IntByReference value);
</code>```

Java usage -

```<code>public int readDI(int connection, byte channel, byte count){
    IntByReference refValue = new IntByReference();
    lib.E1K_DI_Reads(connection, channel, count, refValue);
    int value = refValue.getValue();
    return value;
}
</code>```

From your example:

```<code>int NewKey(PointerByReference room, PointerByReference gate,PointerByReference time,PointerByReference guestname,PointerByReference guestid, int overflag, int Breakfast, NativeLongByReference cardno, PointerByReference track1, PointerByReference track2);
</code>```

You will have to adjust your methods code to get the actual pointers value.

Body:
I want to call dll to write/read from hardware.However, I get the error below:

dll method:

int NewKey(char *room,char *gate,char *stime,char *guestname,char *guestid, int  overflag, int Breakfast, long *cardno,char * track1,char * track2);

java method:

int NewKey(String room, String gate,String time,String guestname,String guestid, int overflag, int Breakfast, NativeLongByReference cardno, String track1, String track2);

The api document shows cardno as a out parameter  and track1，track2 could be null.

NativeLongByReference cardNo = new NativeLongByReference ();

int res = CLibrary.INSTANCE.NewKey("010001", "00", "201712021200201712031200", "Guest Name","Account No.", 0, 1, cardNo, null, null);

It don t work. So I use a simple method:

dll method :

int EraseCard (long  cardno,char * track1,char * track2);

java method:

int EraseCard(NativeLong cardno, String  track1, String  track2);

NativeLong a = new NativeLong(0L);

int res = CLibrary.INSTANCE.EraseCard (a, null, null);

It gets the same error again:

Exception in thread "main" java.lang.Error: Invalid memory access
at com.sun.jna.Native.invokeInt(Native Method)
at com.sun.jna.Function.invoke(Function.java:383)
at com.sun.jna.Function.invoke(Function.java:315)
at com.sun.jna.Library$Handler.invoke(Library.java:212)
at A90PmsInterface.main(A90PmsInterface.java:104)

It seems like the error only occurs when I try to use the dll methods to read/write from/to hardware.

How can I solve the problem?

details: win7 64 bite, jre1.8 32bite, jna4.1

Body:
If you want to access memory from the dll, you will need to setup the proper data type needed to reference the memory location. On pointer objects your jna should use ByteByReference for char* or you can also use PointerByReference instead of declaring the object as a String. Using PointerByReference will help you avoid memory leaks.

JNA Marshalling / Unmarshalling

is a good place to start. Good Luck!

Edit:
Java method declaration - (example of JNA XXByReference usage)

public int E1K_DI_Reads(int connection, byte channel, byte channelCount, IntByReference value);

Java usage -

public int readDI(int connection, byte channel, byte count){
    IntByReference refValue = new IntByReference();
    lib.E1K_DI_Reads(connection, channel, count, refValue);
    int value = refValue.getValue();
    return value;
}

From your example:

int NewKey(PointerByReference room, PointerByReference gate,PointerByReference time,PointerByReference guestname,PointerByReference guestid, int overflag, int Breakfast, NativeLongByReference cardno, PointerByReference track1, PointerByReference track2);

You will have to adjust your methods code to get the actual pointers value.


问:
Big query SQL Error: Column name user_dim is ambiguous at [3:3]
how can i run a query that goes through both my android and iOS data to return what i need in one table.

currently getting the above error when i run this

```<code>#standardSQL
SELECT
  user_dim.app_info.app_instance_id,
  user_dim.device_info.device_category,
  user_dim.device_info.user_default_language,
  user_dim.device_info.platform_version,
  user_dim.device_info.device_model,
  user_dim.geo_info.country,
  user_dim.geo_info.city,
  user_dim.app_info.app_version,
  user_dim.app_info.app_store,
  user_dim.app_info.app_platform
FROM
</code>```

app.com_aaa_IOS.app_events_20171204,app.com_aaa_ANDROID.app_events_20171204

答:
```<code>SELECT
  user_dim.app_info.app_instance_id,
  user_dim.device_info.device_category,
  user_dim.device_info.user_default_language,
  user_dim.device_info.platform_version,
  user_dim.device_info.device_model,
  user_dim.geo_info.country,
  user_dim.geo_info.city,
  user_dim.app_info.app_version,
  user_dim.app_info.app_store,
  user_dim.app_info.app_platform
FROM
  app.com_aaa_IOS.app_events_20171204

UNION ALL

SELECT
  user_dim.app_info.app_instance_id,
  user_dim.device_info.device_category,
  user_dim.device_info.user_default_language,
  user_dim.device_info.platform_version,
  user_dim.device_info.device_model,
  user_dim.geo_info.country,
  user_dim.geo_info.city,
  user_dim.app_info.app_version,
  user_dim.app_info.app_store,
  user_dim.app_info.app_platform
FROM
  app.com_aaa_ANDROID.app_events_20171204
</code>```

Body:
how can i run a query that goes through both my android and iOS data to return what i need in one table.

currently getting the above error when i run this

#standardSQL
SELECT
  user_dim.app_info.app_instance_id,
  user_dim.device_info.device_category,
  user_dim.device_info.user_default_language,
  user_dim.device_info.platform_version,
  user_dim.device_info.device_model,
  user_dim.geo_info.country,
  user_dim.geo_info.city,
  user_dim.app_info.app_version,
  user_dim.app_info.app_store,
  user_dim.app_info.app_platform
FROM

app.com_aaa_IOS.app_events_20171204,app.com_aaa_ANDROID.app_events_20171204


问:
Why does this line not compile List<Object> l = new ArrayList<String>()?
I want to be able to make a list like so -

```<code>List<Object> l = new ArrayList<String>();
</code>```

The standard library implementation of ArrayList does not allow this. It gives compile time error. So I am writing my own implementation of the ArrayList.

So far I have tried this -

```<code>public class ArrayList<Y extends X> implements List<X> {...}
public class ArrayList<X super Y> implements List<X> {...}
</code>```

which do not compile.

So, how can I write an ArrayList where I would be able to use it like I mentioned above?

```<code>List<Object> l = new ArrayList<String>();
</code>```

People have pointed out this post
 Is List<Dog> a subclass of List<Animal>? Why aren't Java's generics implicitly polymorphic?

But I still don't understand. The reason given was that we want to avoid situations like so -

```<code>List<Object> l = new ArrayList<String>();
l.add(new Dog());
</code>```

While this makes sense, I can do a similar kind of thing with Java Arrays which compiles but throws Exception at runtime.

```<code>Object o[] = new String[10];
o[0] = new Dog();
</code>```

So what is the rationale behind allowing the latter code to compile but not the former?

EDIT - Similar question has already been asked as indicated above.
This question also helps Why is the ArrayStoreException a RuntimeException?

答:
You can just write

```<code>List<Object> l = new ArrayList<Object>();
</code>```

the type parameter exists only at compile time, so this makes no difference.

Body:
I want to be able to make a list like so -

List<Object> l = new ArrayList<String>();

The standard library implementation of ArrayList does not allow this. It gives compile time error. So I am writing my own implementation of the ArrayList.

So far I have tried this -

public class ArrayList<Y extends X> implements List<X> {...}
public class ArrayList<X super Y> implements List<X> {...}

which do not compile.

So, how can I write an ArrayList where I would be able to use it like I mentioned above?

List<Object> l = new ArrayList<String>();

People have pointed out this post
 Is List<Dog> a subclass of List<Animal>? Why aren't Java's generics implicitly polymorphic?

But I still don't understand. The reason given was that we want to avoid situations like so -

List<Object> l = new ArrayList<String>();
l.add(new Dog());

While this makes sense, I can do a similar kind of thing with Java Arrays which compiles but throws Exception at runtime.

Object o[] = new String[10];
o[0] = new Dog();

So what is the rationale behind allowing the latter code to compile but not the former?

EDIT - Similar question has already been asked as indicated above.
This question also helps Why is the ArrayStoreException a RuntimeException?

Body:
You can just write

List<Object> l = new ArrayList<Object>();

the type parameter exists only at compile time, so this makes no difference.


问:
Rails - CanCan - If can? works on page load but not via a AJAX Partial
Hello I have the following in a partial.

```<code><% if can? :update, @permission %>
Yes
<% end %>
</code>```

For the exact same user, when this loads via html this works great. But when I render that partial via ajax, as so:

```<code>$('#current').html('<%=escape_javascript(render :partial =>"permissions/teammembers", :locals => {:teammembers => @teammembers}) %>');
</code>```

Then cancan is return false, why is that? the current_user is the same person making the request?

Thanks

答: Check if @permission is not nil. Throw it and see if it is ok.</p>

Body:
Hello I have the following in a partial.

<% if can? :update, @permission %>
Yes
<% end %>

For the exact same user, when this loads via html this works great. But when I render that partial via ajax, as so:

$('#current').html('<%=escape_javascript(render :partial =>"permissions/teammembers", :locals => {:teammembers => @teammembers}) %>');

Then cancan is return false, why is that? the current_user is the same person making the request?

Thanks


问:
What's the best way to write robots.txt for github pages using multiple repos?
I am using Github pages to build my personal website with Jekyll. I have a head site in the username.github.io repo, project A site in the projectA repo, project B in the projectB repo and so on. I have put a CNAME file under the username.github.io repo so that all of my sites are under the customized domain name (www.mydomain.com). I have noticed that with robots.txt file pointing to the sitemap.txt file under each repo, the sitemap.txt can only contain page links for pages in each separate repo. So, I have a couple of questions:

Since my site is structured as www.mydomain.com, www.mydomain.com/projectA, www.mydomain.com/projectB and so on corresponding to the pages in single repos, will the search engine recognize all of my site pages even though the sitemap.txt under the username.github.io head repo only has the page links generated in the single repo?

What is the best way to write the robots.txt file in my case?

Thanks!
Qi

答:
Standards and disclaimer

Sitemap: in robots.txt is a nonstandard extension according to Wikipedia. Remember that:

Using the Sitemap protocol does not guarantee that web pages are included in search engines, but provides hints for web crawlers to do a better job of crawling your site.

Wikipedia also lists allow: as a nonstandard extension.

Multiple sitemaps in robots.txt

You can specify more than one Sitemap file per robots.txt file. When specifying more than one sitemap in robots.txt this is the format:

```<code>Sitemap: http://www.example.com/sitemap-host1.xml

Sitemap: http://www.example.com/sitemap-host2.xml
</code>```

An index of sitemaps

There is also a type of sitemap file that is an index of sitemap files.

If you have a Sitemap index file, you can include the location of just that file. You don't need to list each individual Sitemap listed in the index file.

```<code><?xml version="1.0" encoding="UTF-8"?>

<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

   <sitemap>

      <loc>http://www.example.com/sitemap1.xml.gz</loc>

      <lastmod>2004-10-01T18:23:17+00:00</lastmod>

   </sitemap>

   <sitemap>

      <loc>http://www.example.com/sitemap2.xml.gz</loc>

      <lastmod>2005-01-01</lastmod>

   </sitemap>

</sitemapindex>
</code>```

<lastmod> is optional.

About excluding content

The Sitemaps protocol enables you to let search engines know what content you would like indexed. To tell search engines the content you don't want indexed, use a robots.txt file or robots meta tag. See robotstxt.org for more information on how to exclude content from search engines.

If you want search engines not to index anything it should be in the robots.txt file (in the User Page repository) as:

```<code>User-agent: *
Disallow: /project_to_disallow/
Disallow: /projectname/page_to_disallow.html
</code>```

Alternatively you can use the robots tag.

Suggestions

```<code>User-agent: *
Disallow: /project_to_disallow/
Disallow: /projectname/page_to_disallow.html

Sitemap: http://www.example.com/sitemap.xml

Sitemap: http://www.example.com/projectA/sitemap.xml

Sitemap: http://www.example.com/projectB/sitemap.xml
</code>```

or, if you are using a sitemap index file

```<code>User-agent: *
Disallow: /project_to_disallow/
Disallow: /projectname/page_to_disallow.html

Sitemap: http://www.example.com/siteindex.xml
</code>```

where http://www.example.com/siteindex.xml looks like

```<code><?xml version="1.0" encoding="UTF-8"?>

<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

   <sitemap>

      <loc>http://www.example.com/sitemap.xml</loc>

   </sitemap>

   <sitemap>

      <loc>http://www.example.com/projectA/sitemap.xml</loc>

   </sitemap>

   <sitemap>

      <loc>http://www.example.com/projectB/sitemap.xml</loc>

   </sitemap>

</sitemapindex>
</code>```

For info on how set up robots.txt with GitHub Pages see my answer here.

Body:
Standards and disclaimer

Sitemap: in robots.txt is a nonstandard extension according to Wikipedia. Remember that:

Using the Sitemap protocol does not guarantee that web pages are included in search engines, but provides hints for web crawlers to do a better job of crawling your site.

Wikipedia also lists allow: as a nonstandard extension.

Multiple sitemaps in robots.txt

You can specify more than one Sitemap file per robots.txt file. When specifying more than one sitemap in robots.txt this is the format:

Sitemap: http://www.example.com/sitemap-host1.xml

Sitemap: http://www.example.com/sitemap-host2.xml

An index of sitemaps

There is also a type of sitemap file that is an index of sitemap files.

If you have a Sitemap index file, you can include the location of just that file. You don't need to list each individual Sitemap listed in the index file.

<?xml version="1.0" encoding="UTF-8"?>

<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

   <sitemap>

      <loc>http://www.example.com/sitemap1.xml.gz</loc>

      <lastmod>2004-10-01T18:23:17+00:00</lastmod>

   </sitemap>

   <sitemap>

      <loc>http://www.example.com/sitemap2.xml.gz</loc>

      <lastmod>2005-01-01</lastmod>

   </sitemap>

</sitemapindex>

<lastmod> is optional.

About excluding content

The Sitemaps protocol enables you to let search engines know what content you would like indexed. To tell search engines the content you don't want indexed, use a robots.txt file or robots meta tag. See robotstxt.org for more information on how to exclude content from search engines.

If you want search engines not to index anything it should be in the robots.txt file (in the User Page repository) as:

User-agent: *
Disallow: /project_to_disallow/
Disallow: /projectname/page_to_disallow.html

Alternatively you can use the robots tag.

Suggestions

User-agent: *
Disallow: /project_to_disallow/
Disallow: /projectname/page_to_disallow.html

Sitemap: http://www.example.com/sitemap.xml

Sitemap: http://www.example.com/projectA/sitemap.xml

Sitemap: http://www.example.com/projectB/sitemap.xml

or, if you are using a sitemap index file

User-agent: *
Disallow: /project_to_disallow/
Disallow: /projectname/page_to_disallow.html

Sitemap: http://www.example.com/siteindex.xml

where http://www.example.com/siteindex.xml looks like

<?xml version="1.0" encoding="UTF-8"?>

<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

   <sitemap>

      <loc>http://www.example.com/sitemap.xml</loc>

   </sitemap>

   <sitemap>

      <loc>http://www.example.com/projectA/sitemap.xml</loc>

   </sitemap>

   <sitemap>

      <loc>http://www.example.com/projectB/sitemap.xml</loc>

   </sitemap>

</sitemapindex>

For info on how set up robots.txt with GitHub Pages see my answer here.


问:
EntityTypeBuilder does not contain a definition for ToTable in EF Core
I have this sample code:

```<code>using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Models;

namespace MySampleNamespace
{
    public class MyDbContext : DbContext
    {
        public MyDbContext(DbContextOptions<MyDbContext> options)
            : base(options)
        {
        }

        public DbSet<User> Users { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            new UserMap(modelBuilder.Entity<User>());
        }

        public class UserMap
        {
            public UserMap(EntityTypeBuilder<User> entityBuilder)
            {
                entityBuilder.ToTable("User");
                entityBuilder.Property(s => s.Username).HasMaxLength(15).IsRequired();
            }
        }
    }
}
</code>```

I was testing out some example from MS website, but I can't find ToTable method. In the example, I checked what are the Usings and the only Using the example had is Microsoft.EntityFrameworkCore aside from the class project for the model he was using. Was this changed? How do I do this now?

答:
Porting from EF6 to EFCore, we had this issue. Our cause was .HasKey now returns a KeyBuilder and the .ToTable doesn't operate on it. So reversing that worked.

Ie. Was:

```<code>mp.HasKey(m => m.Id)
  .ToTable("Table")
</code>```

Became:

```<code>mp.ToTable("Table")
  .HasKey(m => m.Id);
</code>```

Body:
I have this sample code:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Models;

namespace MySampleNamespace
{
    public class MyDbContext : DbContext
    {
        public MyDbContext(DbContextOptions<MyDbContext> options)
            : base(options)
        {
        }

        public DbSet<User> Users { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            new UserMap(modelBuilder.Entity<User>());
        }

        public class UserMap
        {
            public UserMap(EntityTypeBuilder<User> entityBuilder)
            {
                entityBuilder.ToTable("User");
                entityBuilder.Property(s => s.Username).HasMaxLength(15).IsRequired();
            }
        }
    }
}

I was testing out some example from MS website, but I can't find ToTable method. In the example, I checked what are the Usings and the only Using the example had is Microsoft.EntityFrameworkCore aside from the class project for the model he was using. Was this changed? How do I do this now?

Body:
Porting from EF6 to EFCore, we had this issue. Our cause was .HasKey now returns a KeyBuilder and the .ToTable doesn't operate on it. So reversing that worked.

Ie. Was:

mp.HasKey(m => m.Id)
  .ToTable("Table")

Became:

mp.ToTable("Table")
  .HasKey(m => m.Id);


答:
Just as your link says, define your List like so:

```<code>List<? extends Object> l = new ArrayList<String>();
</code>```

EDIT

Yes, the reason that

```<code>List<? extends Object> l = new ArrayList<String>(); l.add("asda");
</code>```

doesn't work is to avoid runtime exceptions, because the Type of the List could be is anything extending Object so the compiler treats it as such (could be anything/unknown). However you can still edit the list if you keep a reference to the original.

```<code>List<String> strList = new ArrayList<>();
List<? extends Object> objList = strList;
strList.add("asdf");
// Will return Strings that only have the Object interface
Object o = objList.get(0);
</code>```

The purpose of List<? extends Object> is just to give your code a type guarantee (some type extending Object in this case) and the compiler, thanks to generics, is able to ensure that condition at compile time but it also needs to ensure that you don't violate the original list. Take for example the following code:

```<code>List<Integer> intList = new ArrayList<>();
List<? extends Object> objList = intList;
// compile error to protect the original list
objList.add("asdf");
</code>```

So because the objList is of type ? you can't add a String to it. Even though String is a subclass of Object it might not be (and isn't in this case) the same type as?.

Also don't forget that generic types are gone at runtime because of Type Erasure. Generics are a compile time guarantee.

Also, now I see your true question.

I need the reason for why is the same thing allowed for Arrays, why not compile time error in that case? Basically what I am asking is why do we have this dual policy, one for Arrays and a different policy for generic ArrayLists?

See this question and its related answers regarding that

Title: Why does this line not compile List<Object> l = new ArrayList<String>()?

Body:
Just as your link says, define your List like so:

List<? extends Object> l = new ArrayList<String>();

EDIT

Yes, the reason that

List<? extends Object> l = new ArrayList<String>(); l.add("asda");

doesn't work is to avoid runtime exceptions, because the Type of the List could be is anything extending Object so the compiler treats it as such (could be anything/unknown). However you can still edit the list if you keep a reference to the original.

List<String> strList = new ArrayList<>();
List<? extends Object> objList = strList;
strList.add("asdf");
// Will return Strings that only have the Object interface
Object o = objList.get(0);

The purpose of List<? extends Object> is just to give your code a type guarantee (some type extending Object in this case) and the compiler, thanks to generics, is able to ensure that condition at compile time but it also needs to ensure that you don't violate the original list. Take for example the following code:

List<Integer> intList = new ArrayList<>();
List<? extends Object> objList = intList;
// compile error to protect the original list
objList.add("asdf");

So because the objList is of type ? you can't add a String to it. Even though String is a subclass of Object it might not be (and isn't in this case) the same type as?.

Also don't forget that generic types are gone at runtime because of Type Erasure. Generics are a compile time guarantee.

Also, now I see your true question.

I need the reason for why is the same thing allowed for Arrays, why not compile time error in that case? Basically what I am asking is why do we have this dual policy, one for Arrays and a different policy for generic ArrayLists?

See this question and its related answers regarding that


问:
Bit Coin API for bit coin rate
I am using following code to get bitcoin price it is working off line but not working on server. </p>

```<code>$api = "http://blockchain.info/ticker";
$json = file_get_contents($api);
$data = json_decode($json, TRUE);
$rate = $data["USD"]["15m"];
$symbol = $data["USD"]["symbol"];

echo $rate.$symbol;
?>
</code>```

答:
Solve when i use curl

```<code>$url = "http://blockchain.info/ticker";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$data = json_decode($result, TRUE);
$rate = $data["USD"]["15m"];
$symbol = $data["USD"]["symbol"];
echo $rate.$symbol;
</code>```

thanks to all for support..

Title: Bit Coin API for bit coin rate

Body:
I am using following code to get bitcoin price it is working off line but not working on server.

$api = "http://blockchain.info/ticker";
$json = file_get_contents($api);
$data = json_decode($json, TRUE);
$rate = $data["USD"]["15m"];
$symbol = $data["USD"]["symbol"];

echo $rate.$symbol;
?>

Body:
Solve when i use curl

$url = "http://blockchain.info/ticker";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$data = json_decode($result, TRUE);
$rate = $data["USD"]["15m"];
$symbol = $data["USD"]["symbol"];
echo $rate.$symbol;

thanks to all for support..


问:
How can I remove the zone from a DateTime value?
I have this DateTime:

```<code>=> Fri, 03 Feb 2012 11:52:42 -0500
</code>```

How can I remove the zone(-0500) in ruby?
I just want something like this:

```<code>=> Fri, 03 Feb 2012 11:52:42
</code>```

答:
In addition to the accepted answer you can also add the same strftime parameters to DATE_FORMATS a Rails hash allowing you to standardise output formats in your application.

In config/initializers/datetime_formats.rb:

```<code>Time::DATE_FORMATS[:nozone] = '%a, %d %b %Y %H:%M:%S'
</code>```

Then in your code you could do:

```<code>Time.zone.now.to_s(:nozone)
</code>```

You could even make it the default:

```<code>Time::DATE_FORMATS[:default] = '%a, %d %b %Y %H:%M:%S'
Time.zone.now.to_s
</code>```

There is also a separate hash for dates:

```<code>Date::DATE_FORMATS[:default] = '%a, %d %b %Y'
</code>```

This feature has been around for years but appears to be little known.

Body:
I have this DateTime:

=> Fri, 03 Feb 2012 11:52:42 -0500

How can I remove the zone(-0500) in ruby?
I just want something like this:

=> Fri, 03 Feb 2012 11:52:42

Body:
In addition to the accepted answer you can also add the same strftime parameters to DATE_FORMATS a Rails hash allowing you to standardise output formats in your application.

In config/initializers/datetime_formats.rb:

Time::DATE_FORMATS[:nozone] = '%a, %d %b %Y %H:%M:%S'

Then in your code you could do:

Time.zone.now.to_s(:nozone)

You could even make it the default:

Time::DATE_FORMATS[:default] = '%a, %d %b %Y %H:%M:%S'
Time.zone.now.to_s

There is also a separate hash for dates:

Date::DATE_FORMATS[:default] = '%a, %d %b %Y'

This feature has been around for years but appears to be little known.


问:
Issues with creating column name for DataFrame in Python3
I do not understand why "u" has NaNvalues. What wrong am I doing here?  </p>

```<code>>>> z=pd.DataFrame([['abcb','asasa'],['sdsd','aeio']])
>>> z
          0      1
    0  abcb  asasa
    1  sdsd   aeio
>>> u=pd.DataFrame(z,columns=['hello','ajsajs'])
>>> u
    hello  ajsajs
 0    NaN     NaN
 1    NaN     NaN
</code>```

答:
Alternate construction calls

You can use the underlying NumPy array:

```<code>u = pd.DataFrame(z.values, columns=['hello','ajsajs'])

  hello ajsajs
0  abcb  asasa
1  sdsd   aeio
</code>```

Alternately, you could use:

```<code>u = z.rename(columns={0: 'hello',1: 'ajsajs'})
</code>```

And lastly as suggested by @Dark:

```<code>u = z.set_axis(['hello','ajsajs'], axis=1, inplace=False)
</code>```

A small note on inplace in set_axis -

WARNING: inplace=None currently falls back to to True, but in a future
  version, will default to False. Use inplace=True explicitly rather
  than relying on the default.

In pandas 0.20.3 the syntax would be just:

```<code>u = z.set_axis(axis=1, labels=['hello','ajsajs'])
</code>```

@Dark's solution appears fastest here.

Why current method doesn't work

I believe the issue here is that there's a .reindex being called when the DataFrame is constructed in this way.  Here's some source code where ellipses denote irrelevant stuff I'm leaving out:

```<code>from pandas.core.internals import BlockManager

# pandas.core.frame.DataFrame
class DataFrame(NDFrame):
    def __init__(self, data=None, index=None, columns=None, dtype=None,
                 copy=False):
        # ...
        if isinstance(data, DataFrame):
            data = data._data
        if isinstance(data, BlockManager):
            mgr = self._init_mgr(data, axes=dict(index=index, columns=columns),
                                 dtype=dtype, copy=copy)
        # ... a bunch of other if statements irrelevant to your case
        NDFrame.__init__(self, mgr, fastpath=True)
        # ...
</code>```

What's happening here:

DataFrame inherits from a more generic base class which in turn has multiple inheritance.  (Pandas is great, but its source can be like trying to backtrack through a spider's web.)

In u = pd.DataFrame(z,columns=['hello','ajsajs']), x is a DataFrame.  Therefore, the first if statement below is True and data = data._data.  What's _data?  It's a BlockManager.*  (To be continued below...)

Because we just converted what you passed to its BlockManager, the next if statement also evaluates True.  Then mgr gets assigned to the result of the _init_mrg method and the parent class's __init__ gets called, passing mgr.

* confirm with isinstance(z._data, BlockManager).

Now on to part 2...

```<code># pandas.core.generic.NDFrame
class NDFrame(PandasObject, SelectionMixin):
    def __init__(self, data, axes=None, copy=False, dtype=None,
             fastpath=False):
    # ...

    def _init_mgr(self, mgr, axes=None, dtype=None, copy=False):
        """ passed a manager and a axes dict """
        for a, axe in axes.items():
            if axe is not None:
                mgr = mgr.reindex_axis(axe,
                                       axis=self._get_block_manager_axis(a),
                                       copy=False)
    # ...
        return mgr
</code>```

Here is where _init_mgr is defined, which gets called above.  Essentially in your case you have:

```<code>columns=['hello','ajsajs']
axes=dict(index=None, columns=columns)
# ...
</code>```

When you go to reindex axis and specify a new axis where none of the new labels are included in the old object, you get all NaNs.  This seems like a deliberate design decision.  Consider this related example to prove the point, where one new column is present and one is not:

```<code>pd.DataFrame(z, columns=[0, 'ajsajs'])

      0  ajsajs
0  abcb     NaN
1  sdsd     NaN
</code>```

Body:
I do not understand why "u" has NaNvalues. What wrong am I doing here?

>>> z=pd.DataFrame([['abcb','asasa'],['sdsd','aeio']])
>>> z
          0      1
    0  abcb  asasa
    1  sdsd   aeio
>>> u=pd.DataFrame(z,columns=['hello','ajsajs'])
>>> u
    hello  ajsajs
 0    NaN     NaN
 1    NaN     NaN

Body:
Alternate construction calls

You can use the underlying NumPy array:

u = pd.DataFrame(z.values, columns=['hello','ajsajs'])

  hello ajsajs
0  abcb  asasa
1  sdsd   aeio

Alternately, you could use:

u = z.rename(columns={0: 'hello',1: 'ajsajs'})

And lastly as suggested by @Dark:

u = z.set_axis(['hello','ajsajs'], axis=1, inplace=False)

A small note on inplace in set_axis -

WARNING: inplace=None currently falls back to to True, but in a future
  version, will default to False. Use inplace=True explicitly rather
  than relying on the default.

In pandas 0.20.3 the syntax would be just:

u = z.set_axis(axis=1, labels=['hello','ajsajs'])

@Dark's solution appears fastest here.

Why current method doesn't work

I believe the issue here is that there's a .reindex being called when the DataFrame is constructed in this way.  Here's some source code where ellipses denote irrelevant stuff I'm leaving out:

from pandas.core.internals import BlockManager

# pandas.core.frame.DataFrame
class DataFrame(NDFrame):
    def __init__(self, data=None, index=None, columns=None, dtype=None,
                 copy=False):
        # ...
        if isinstance(data, DataFrame):
            data = data._data
        if isinstance(data, BlockManager):
            mgr = self._init_mgr(data, axes=dict(index=index, columns=columns),
                                 dtype=dtype, copy=copy)
        # ... a bunch of other if statements irrelevant to your case
        NDFrame.__init__(self, mgr, fastpath=True)
        # ...

What's happening here:

DataFrame inherits from a more generic base class which in turn has multiple inheritance.  (Pandas is great, but its source can be like trying to backtrack through a spider's web.)

In u = pd.DataFrame(z,columns=['hello','ajsajs']), x is a DataFrame.  Therefore, the first if statement below is True and data = data._data.  What's _data?  It's a BlockManager.*  (To be continued below...)

Because we just converted what you passed to its BlockManager, the next if statement also evaluates True.  Then mgr gets assigned to the result of the _init_mrg method and the parent class's __init__ gets called, passing mgr.

* confirm with isinstance(z._data, BlockManager).

Now on to part 2...

# pandas.core.generic.NDFrame
class NDFrame(PandasObject, SelectionMixin):
    def __init__(self, data, axes=None, copy=False, dtype=None,
             fastpath=False):
    # ...

    def _init_mgr(self, mgr, axes=None, dtype=None, copy=False):
        """ passed a manager and a axes dict """
        for a, axe in axes.items():
            if axe is not None:
                mgr = mgr.reindex_axis(axe,
                                       axis=self._get_block_manager_axis(a),
                                       copy=False)
    # ...
        return mgr

Here is where _init_mgr is defined, which gets called above.  Essentially in your case you have:

columns=['hello','ajsajs']
axes=dict(index=None, columns=columns)
# ...

When you go to reindex axis and specify a new axis where none of the new labels are included in the old object, you get all NaNs.  This seems like a deliberate design decision.  Consider this related example to prove the point, where one new column is present and one is not:

pd.DataFrame(z, columns=[0, 'ajsajs'])

      0  ajsajs
0  abcb     NaN
1  sdsd     NaN


问:
creating complex dictionary from string with multiple keys in python
I'm getting output string in format like this:

```<code>w = "name: some name|age: 23|street: some address|favorite meal: meal|name: some other name|age: 15|street: some other address|pet: dog|name: <and so on..>"
</code>```

The issue is that this string is not fully predictable, the info after "name" until another "name" belongs to the given person and the "keys" for that info could be more than one word ( although I think I can estimate/predict all the "key words")

Is there a way to arrange this into python dictionary ? ( I guess this would require dictionary with another dictionary as its value... but how would I extract all the info from the string and keep the relevant data together ( the string is much longer around 10 people in one )

答:
Simply use each 'name' key as a marker:

```<code>w = "name: some name|age: 23|street: some address|favorite meal: meal|name: some other name|age: 15|street: some other address|pet: dog"

output = []
current = {}
for item in w.split('|'):
    key_value = item.split(':')
    key = key_value[0].strip()
    value = key_value[1].strip()
    if key == 'name':
        current = {key:value}
        output.append(current)
    else:
        current[key] = value

print(output)
</code>```

Output:

```<code>[{'name': 'some name', 'age': '23', 'street': 'some address', 'favorite meal': 'meal'}, {'name': 'some other name', 'age': '15', 'street': 'some other address', 'pet': 'dog'}]
</code>```

Body:
I'm getting output string in format like this:

w = "name: some name|age: 23|street: some address|favorite meal: meal|name: some other name|age: 15|street: some other address|pet: dog|name: <and so on..>"

The issue is that this string is not fully predictable, the info after "name" until another "name" belongs to the given person and the "keys" for that info could be more than one word ( although I think I can estimate/predict all the "key words")

Is there a way to arrange this into python dictionary ? ( I guess this would require dictionary with another dictionary as its value... but how would I extract all the info from the string and keep the relevant data together ( the string is much longer around 10 people in one )

Body:
Simply use each 'name' key as a marker:

w = "name: some name|age: 23|street: some address|favorite meal: meal|name: some other name|age: 15|street: some other address|pet: dog"

output = []
current = {}
for item in w.split('|'):
    key_value = item.split(':')
    key = key_value[0].strip()
    value = key_value[1].strip()
    if key == 'name':
        current = {key:value}
        output.append(current)
    else:
        current[key] = value

print(output)

Output:

[{'name': 'some name', 'age': '23', 'street': 'some address', 'favorite meal': 'meal'}, {'name': 'some other name', 'age': '15', 'street': 'some other address', 'pet': 'dog'}]


问:
rollback transaction error rails from google geocoding api
I am trying to create a review form in my rails app but when i click on the submit button,  the form cannot be submitted.When i lookup the error in the terminal and i get this error. i searched the error but couldn't find any solution. did anyone had this issue before?:

```<code>Google API error: over query limit.
   (0.1ms)  rollback transaction
</code>```

Update

I am not only getting the Google API error. sometimes i get this error and other time i only get  rollback transaction only.

This is the Reviews Controller:

```<code>class ReviewsController < ApplicationController

  # check if logged in
  before_action :check_login, except: [:index, :show]

  def index
    # this is our list page for our reviews
    @price = params[:price]
    @cuisine = params[:cuisine]
    @location = params[:location]

    # start with all the reviews
    @reviews = Review.all

    # filtering by price
    if @price.present?
      @reviews = @reviews.where(price: @price)
    end

    # filter by cuisine
    if @cuisine.present?
      @reviews = @reviews.where(cuisine: @cuisine)
    end

    # search near the location
    if @location.present?
      @reviews = @reviews.near(@location)
    end

  end

  def new
    # the form for adding a new review
    @review = Review.new
  end

  def create
    # take info from the form and add it to the model
    @review = Review.new(form_params)

    # and then associate it with a user
    @review.user = @current_user

    # we want to check if the model can be saved
    # if it is, we're go the home page again
    # if it isn't, show the new form
    if @review.save
      flash[:succces] = "Your review was posted!"

      redirect_to root_path
    else
      # show the view for new.html.erb
      render "new"
    end

  end

  def show
    # individual review page
    @review = Review.find(params[:id])
  end

  def destroy
    # find the individual review
    @review = Review.find(params[:id])

    # destroy if they have access
    if @review.user == @current_user
      @review.destroy
    end

    # redirect to the home page
    redirect_to root_path
  end

  def edit
    # find the individual review (to edit)
    @review = Review.find(params[:id])

    if @review.user != @current_user
      redirect_to root_path
    elsif @review.created_at < 4.hours.ago
      redirect_to review_path(@review)
    end
  end

  def update
    # find the individual review
    @review = Review.find(params[:id])

    if @review.user != @current_user
      redirect_to root_path
    else
      # update with the new info from the form
      if @review.update(form_params)

        # redirect somewhere new
        redirect_to review_path(@review)
      else
        render "edit"
      end
    end
  end

  def form_params
    params.require(:review).permit(:title, :restaurant, :body, :score,
      :ambiance, :cuisine, :price, :address)
  end

end
</code>```

This is the  Review form page:

```<code><%= simple_form_for @review do |f| %>
  <%= f.input :title %>
  <%= f.input :restaurant %>
  <%= f.input :address %>
  <%= f.input :body %>
  <%= f.input :cuisine %>
  <%= f.input :price %>
  <%= f.input :score %>
  <%= f.input :ambiance %>

  <%= f.button :submit %>
<% end %>
</code>```

The Review Model

```<code>class Review < ApplicationRecord

  # add an association that has a 1-to-many relationship
  has_many :comments
  has_many :bookmarks

  # add an association to the user
  belongs_to :user

  geocoded_by :address
  after_validation :geocode

  validates :title, presence: true
  validates :body, length: { minimum: 10 }
  validates :score, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 10 }
  validates :restaurant, presence: true
  validates :address, presence: true

  def to_param
    id.to_s + "-" + title.parameterize
  end

end
</code>```

This is My Schema file

```<code>  create_table "reviews", force: :cascade do |t|
    t.string "title"
    t.text "body"
    t.integer "score"
    t.string "restaurant"
    t.integer "price"
    t.string "cuisine"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "phone_number"
    t.string "ambiance"
    t.text "address"
    t.float "latitude"
    t.float "longitude"
    t.integer "user_id"
  end
</code>```

答:
You probably reached your Google API quota.

In model you have geocoded_by ... that is used by gem geocoder so have a look at that.

Google has per second limit as well as per day limit link

Body:
I am trying to create a review form in my rails app but when i click on the submit button,  the form cannot be submitted.When i lookup the error in the terminal and i get this error. i searched the error but couldn't find any solution. did anyone had this issue before?:

Google API error: over query limit.
   (0.1ms)  rollback transaction

Update

I am not only getting the Google API error. sometimes i get this error and other time i only get  rollback transaction only.

This is the Reviews Controller:

class ReviewsController < ApplicationController

  # check if logged in
  before_action :check_login, except: [:index, :show]

  def index
    # this is our list page for our reviews
    @price = params[:price]
    @cuisine = params[:cuisine]
    @location = params[:location]

    # start with all the reviews
    @reviews = Review.all

    # filtering by price
    if @price.present?
      @reviews = @reviews.where(price: @price)
    end

    # filter by cuisine
    if @cuisine.present?
      @reviews = @reviews.where(cuisine: @cuisine)
    end

    # search near the location
    if @location.present?
      @reviews = @reviews.near(@location)
    end

  end

  def new
    # the form for adding a new review
    @review = Review.new
  end

  def create
    # take info from the form and add it to the model
    @review = Review.new(form_params)

    # and then associate it with a user
    @review.user = @current_user

    # we want to check if the model can be saved
    # if it is, we're go the home page again
    # if it isn't, show the new form
    if @review.save
      flash[:succces] = "Your review was posted!"

      redirect_to root_path
    else
      # show the view for new.html.erb
      render "new"
    end

  end

  def show
    # individual review page
    @review = Review.find(params[:id])
  end

  def destroy
    # find the individual review
    @review = Review.find(params[:id])

    # destroy if they have access
    if @review.user == @current_user
      @review.destroy
    end

    # redirect to the home page
    redirect_to root_path
  end

  def edit
    # find the individual review (to edit)
    @review = Review.find(params[:id])

    if @review.user != @current_user
      redirect_to root_path
    elsif @review.created_at < 4.hours.ago
      redirect_to review_path(@review)
    end
  end

  def update
    # find the individual review
    @review = Review.find(params[:id])

    if @review.user != @current_user
      redirect_to root_path
    else
      # update with the new info from the form
      if @review.update(form_params)

        # redirect somewhere new
        redirect_to review_path(@review)
      else
        render "edit"
      end
    end
  end

  def form_params
    params.require(:review).permit(:title, :restaurant, :body, :score,
      :ambiance, :cuisine, :price, :address)
  end

end

This is the  Review form page:

<%= simple_form_for @review do |f| %>
  <%= f.input :title %>
  <%= f.input :restaurant %>
  <%= f.input :address %>
  <%= f.input :body %>
  <%= f.input :cuisine %>
  <%= f.input :price %>
  <%= f.input :score %>
  <%= f.input :ambiance %>

  <%= f.button :submit %>
<% end %>

The Review Model

class Review < ApplicationRecord

  # add an association that has a 1-to-many relationship
  has_many :comments
  has_many :bookmarks

  # add an association to the user
  belongs_to :user

  geocoded_by :address
  after_validation :geocode

  validates :title, presence: true
  validates :body, length: { minimum: 10 }
  validates :score, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 10 }
  validates :restaurant, presence: true
  validates :address, presence: true

  def to_param
    id.to_s + "-" + title.parameterize
  end

end

This is My Schema file

  create_table "reviews", force: :cascade do |t|
    t.string "title"
    t.text "body"
    t.integer "score"
    t.string "restaurant"
    t.integer "price"
    t.string "cuisine"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "phone_number"
    t.string "ambiance"
    t.text "address"
    t.float "latitude"
    t.float "longitude"
    t.integer "user_id"
  end