问:
Can someone explain Maven 2 (or 3) dependency resolution to me?
I used Maven before in quite a few projects but they we already configured by someone else. I quickly understood the main concepts (groups, artifacts and versions for jars, local and remote repositories) so I assumed that if I'm asked I'll be able to set up a new project from scratch easily.

That turned out not to be the case when I deal with multiple modules which depend on one another. I poked around maven docs but they are either way too concise or way too technical (sometimes I get a feeling that Maven people wrote it for themselves and not for Maven users). So I'm asking for community help.

Here's a typical scenario:

Three repositories:

My local repo at <User>/.m2

My company repo at http://maven.mycompany.com/repository

Maven Central at http://repo1.maven.org/maven2/

I'm building a normal Java EE project consisting of one EJB jar with a corresponding client jar, a web module and a JPA module (I like keeping my entities and all db-connectivity separated from business logic). That gives me 5 project in my IDE:

myapp-ear

myapp-ejb

myapp-ejb-client

myapp-jpa

myapp-web

myapp-jpa is used by myapp-ejb and myapp-web. myapp-ejb-client contains business interfaces for my EJBs.

How should I set all that up? I suspect that I need some kind of parent project but I'm not sure how should I organize inter-project dependency resolution. For example: currently when I specify

```<code><dependency>
  <groupId>com.mycompany.myapp</groupId>
  <artifactId>myapp-jpa</artifactId>
  <version>0.1-SNAPSHOT</version>
</dependency>
</code>```

in myapp-ejb's pom.xml maven tries to search for it in my repository and tells me that the .jar can't be found. Even if I build and install all app components into my local repository one by one Maven always fails to build the ear file itself :(

I'd love to get it working under Eclipse or NetBeans.

答:
I think you're on the right path. You need a parent project to pull it all together. In the parent project (and here is the important part) you need your dependencies laid out NOT in the dependency section of your parent pom, rather, you need them in your dependencyManagement section. Then, in your child pom's you can declare dependencies that are in the parent.

The only other gotcha (that I can think of) is that when you check the project using a version control system in Eclipse you need to remember to check the parent project out "as Maven project" otherwise the m2Eclipse plugin tends to freak out and not resolve things properly.

I hope this helps.

Body:
I used Maven before in quite a few projects but they we already configured by someone else. I quickly understood the main concepts (groups, artifacts and versions for jars, local and remote repositories) so I assumed that if I'm asked I'll be able to set up a new project from scratch easily.

That turned out not to be the case when I deal with multiple modules which depend on one another. I poked around maven docs but they are either way too concise or way too technical (sometimes I get a feeling that Maven people wrote it for themselves and not for Maven users). So I'm asking for community help.

Here's a typical scenario:

Three repositories:

My local repo at <User>/.m2

My company repo at http://maven.mycompany.com/repository

Maven Central at http://repo1.maven.org/maven2/

I'm building a normal Java EE project consisting of one EJB jar with a corresponding client jar, a web module and a JPA module (I like keeping my entities and all db-connectivity separated from business logic). That gives me 5 project in my IDE:

myapp-ear

myapp-ejb

myapp-ejb-client

myapp-jpa

myapp-web

myapp-jpa is used by myapp-ejb and myapp-web. myapp-ejb-client contains business interfaces for my EJBs.

How should I set all that up? I suspect that I need some kind of parent project but I'm not sure how should I organize inter-project dependency resolution. For example: currently when I specify

<dependency>
  <groupId>com.mycompany.myapp</groupId>
  <artifactId>myapp-jpa</artifactId>
  <version>0.1-SNAPSHOT</version>
</dependency>

in myapp-ejb's pom.xml maven tries to search for it in my repository and tells me that the .jar can't be found. Even if I build and install all app components into my local repository one by one Maven always fails to build the ear file itself :(

I'd love to get it working under Eclipse or NetBeans.


来源: stackexchange

问:
How does Spark prepare executors on Hadoop YARN?
I'm trying to understand the details of how Spark prepares the executors. In order to do this I tried to debug org.apache.spark.executor.CoarseGrainedExecutorBackend and invoked

```<code>Thread.currentThread().getContextClassLoader.getResource("")
</code>```

It points out to the following directory:

```<code>/hadoop/yarn/local/usercache/_MY_USER_NAME_/appcache/application_1507907717252_15771/container_1507907717252_15771_01_000002/
</code>```

Looking at the directory I found the following files:

```<code>default_container_executor_session.sh
default_container_executor.sh
launch_container.sh
__spark_conf__
__spark_libs__
</code>```

The question is who delivers the files to each executor and then just runs  CoarseGrainedExecutorBackend with the appropriate classpath? What are the scripts? Are they all YARN-autogenerated?

I looked at org.apache.spark.deploy.SparkSubmit, but didn't find anything useful inside.

答:
Ouch...you're asking for quite a lot of details on how Spark communicates with cluster managers while requesting resources. Let me give you some information. Keep asking if you want more...

You are using Hadoop YARN as the cluster manager for Spark applications. Let's focus on this particular cluster manager only (as there are others that Spark supports like Apache Mesos, Spark Standalone, DC/OS and soon Kubernetes that have their own ways to deal with Spark deployments).

By default, while submitting a Spark application using spark-submit, the Spark application (i.e. the SparkContext it uses actually) requests three YARN containers. One container is for that Spark application's ApplicationMaster that knows how to talk to YARN and request two other YARN containers for two Spark executors.

You could review the YARN official documentation's Apache Hadoop YARN and Hadoop: Writing YARN Applications to dig deeper into the YARN internals.

While submitting the Spark application, Spark's ApplicationMaster is submitted to YARN using the YARN "protocol" that requires that the request for the very first YARN container (container 0) uses ContainerLaunchContext that holds all the necessary launch details (see Client.createContainerLaunchContext).

who delivers the files to each executor

That's how YARN gets told how to launch the ApplicationMaster for the Spark application. While fulfilling the request for a ApplicationMaster container, YARN downloads necessary files which you found in the container's working space.

That's very internal to how any YARN application works on YARN and has (almost) nothing to do with Spark.

The code that's responsible for the communication is in Spark's Client, esp. Client.submitApplication.

and then just runs CoarseGrainedExecutorBackend with the appropriate classpath.

Quoting Mastering Apache Spark 2 gitbook:

CoarseGrainedExecutorBackend is a standalone application that is started in a resource container when (...) Spark on YARN’s ExecutorRunnable is started.

ExecutorRunnable is started when when Spark on YARN's YarnAllocator schedules it in allocated YARN resource containers.

What are the scripts? Are they all YARN-autogenerated?

Kind of.

Some are prepared by Spark as part of a Spark application submission while others are YARN-specific.

Enable DEBUG logging level in your Spark application and you'll see the file transfer.

You can find more information in the Spark official documentation's Running Spark on YARN and the Mastering Apache Spark 2 gitbook of mine.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to understand the details of how Spark prepares the executors. In order to do this I tried to debug org.apache.spark.executor.CoarseGrainedExecutorBackend and invoked

Thread.currentThread().getContextClassLoader.getResource("")

It points out to the following directory:

/hadoop/yarn/local/usercache/_MY_USER_NAME_/appcache/application_1507907717252_15771/container_1507907717252_15771_01_000002/

Looking at the directory I found the following files:

default_container_executor_session.sh
default_container_executor.sh
launch_container.sh
__spark_conf__
__spark_libs__

The question is who delivers the files to each executor and then just runs  CoarseGrainedExecutorBackend with the appropriate classpath? What are the scripts? Are they all YARN-autogenerated?

I looked at org.apache.spark.deploy.SparkSubmit, but didn't find anything useful inside.


问:
Cloudant full text search "too many boolean "requests"
Can anyone tell me what the limit is for boolean requests in a Cloudant full text search?

I have 206 OR's and it appears to be too much.

This is basically my query:

```<code>( this:"that" AND ping:pong AND (yes:a1 OR yes:b1 OR yes:c1 OR ...x50 ) ) OR
( this:"that" AND ping:pong AND (yes:a2 OR yes:b2 OR yes:c2 OR ...x50 ) ) OR
( this:"that" AND ping:pong AND (yes:a3 OR yes:b3 OR yes:c3 OR ...x50 ) ) OR
( this:"that" AND ping:pong AND (yes:a4 OR yes:b4 OR yes:c4 OR ...x50 ) )
</code>```

答:
Cloudant full text search is a front-end to Apache Lucene which has a default limit of the number of boolean clauses of 1024.

https://lucene.apache.org/core/6_5_0/core/org/apache/lucene/search/BooleanQuery.html#getMaxClauseCount--

Each of your OR clause contains about half a dozen sub-clauses, meaning that you fall foul of this limit.

If you really find yourself writing queries that tickle that limit, it may be worth investigating if you can restructure your documents a bit.

Body:
Can anyone tell me what the limit is for boolean requests in a Cloudant full text search?

I have 206 OR's and it appears to be too much.

This is basically my query:

( this:"that" AND ping:pong AND (yes:a1 OR yes:b1 OR yes:c1 OR ...x50 ) ) OR
( this:"that" AND ping:pong AND (yes:a2 OR yes:b2 OR yes:c2 OR ...x50 ) ) OR
( this:"that" AND ping:pong AND (yes:a3 OR yes:b3 OR yes:c3 OR ...x50 ) ) OR
( this:"that" AND ping:pong AND (yes:a4 OR yes:b4 OR yes:c4 OR ...x50 ) )


问:
Export node variable in windows like on mac
I would like to pass variables to a mocha test, which is not as simple as expected. Passing a variable like this:

```<code>npm run test --scope=28
</code>```

is not possible, because mocha will catch the input. I also tried to use the npm minimist package and using a user prompt failed also.

Anyway my colleagues are using a mac and are able to pass an env variable by using this command

```<code>export testscope="18" && npm run test
</code>```

But unfortunately this will not work in Windows. So my question is, is there a similar export command for Windows?

答:
You can use the CMD.EXE set command for this, acts like export on *NIX.

```<code>set testscope=18 && npm run test
</code>```

You did not say which shell you are using, in PowerShell, you might want to do this:

```<code>$env:testscope= 18; npm run test
</code>```

The OP finally decided on installing the Linux subsystem of Windows, to do this, you issue the following in Powershell ("opened as Administrator"):

```<code>Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
</code>```

Body:
I would like to pass variables to a mocha test, which is not as simple as expected. Passing a variable like this:

npm run test --scope=28

is not possible, because mocha will catch the input. I also tried to use the npm minimist package and using a user prompt failed also.

Anyway my colleagues are using a mac and are able to pass an env variable by using this command

export testscope="18" && npm run test

But unfortunately this will not work in Windows. So my question is, is there a similar export command for Windows?

Body:
You can use the CMD.EXE set command for this, acts like export on *NIX.

set testscope=18 && npm run test

You did not say which shell you are using, in PowerShell, you might want to do this:

$env:testscope= 18; npm run test

The OP finally decided on installing the Linux subsystem of Windows, to do this, you issue the following in Powershell ("opened as Administrator"):

Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux


问:
how to know what are the possible output for the object recognition machine learning model (CoreML)
The Machine Learning Model I download from Apple's website, can be used to recognise lots of different object through image.

I want to know, say I need to detect all different kinds of trees. Some can be recognised by the model whereas some cannot. Then how would I know how many trees are being trained in this model? in another word, How would I know all the possible tree recognition in this model? How would I find out? Can I decode the model? or parse it or something?

答: These models are trained on the ImageNet dataset. Here is a list of classes that these models can detect: https://github.com/HoldenCaulfieldRye/caffe/blob/master/data/ilsvrc12/synset_words.txt</p>


问:
How to retain the dropdown value inside gridview after footer button click
I have a Dropdown1 outside gridview contains three options Select,A,B.

Inside gridview two dropdowns Dropdown2,Dropdown3  in which Dropdown2 contains three options say Select,C,D.

Based on Dropdown1 & Dropdown2, I am populating Dropdown3 using onchange event in javascript in Dropdown2.

everything working fine for First row but when I add new row, Dropdown3 value vanishes to default "Select"

Javascript function

```<code>function DataformatFetch(Selection) {
                var status = Selection.options[Selection.selectedIndex].value;
                var row = Selection.parentNode.parentNode;
                var rowIndex = row.rowIndex - 1;

                if (document.getElementById("<%=DropDown1.ClientID%>").value == "A") {
                    var Dataformatlist = row.cells[7].getElementsByTagName('SELECT')[0];
                    switch (status) {
                        case "Select":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select","Select");
                            break;
                        case "C":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select","Select");
                            Dataformatlist.options[1] = new Option("1","1");
                            Dataformatlist.options[2] = new Option("2","2");
                            Dataformatlist.options[3] = new Option("3","3");
                            break;
                        case "D":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select","Select");
                            Dataformatlist.options[1] = new Option("11","11");
                            Dataformatlist.options[2] = new Option("22","22");
                            Dataformatlist.options[3] = new Option("33","33");
                            break;
                    }
                }

                else if (document.getElementById("<%=DropDown1.ClientID%>").value == "B") {
                    var Dataformatlist = row.cells[7].getElementsByTagName('SELECT')[0];
                    switch (status) {
                        case "Select":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select");
                            break;
                        case "C":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select","Select");
                            Dataformatlist.options[1] = new Option("111","111");
                            Dataformatlist.options[2] = new Option("222","222");
                            Dataformatlist.options[3] = new Option("333","333");
                            break;
                        case "D":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select","Select");
                            Dataformatlist.options[1] = new Option("1111","1111");
                            Dataformatlist.options[2] = new Option("2222","2222");
                            Dataformatlist.options[3] = new Option("3333","3333");
                            break;
                    }
                }
            }
</code>```

ASPX code

```<code><asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Object Type">
                                <ItemTemplate>
                                   <asp:DropDownList ID="Dropdownlist2" runat="server" OnChange="DataformatFetch(this);">
                                        <asp:ListItem Value="Select">Select</asp:ListItem>
                                        <asp:ListItem Value="C">C</asp:ListItem>
                                        <asp:ListItem Value="D">D</asp:ListItem>
                                    </asp:DropDownList>
                                </ItemTemplate>
                            </asp:TemplateField>
</code>```

C# code

```<code> private void AddNewRowToGrid()
        {
            try
            {
                if (ViewState["CurrentTable"] != null)
                {
                    System.Data.DataTable dtCurrentTable = (System.Data.DataTable)ViewState["CurrentTable"];
                    DataRow drCurrentRow = null;

                    if (dtCurrentTable.Rows.Count > 0)
                    {
                        drCurrentRow = dtCurrentTable.NewRow();
                        //drCurrentRow["REQUESTNO"] = dtCurrentTable.Rows.Count + 1;

                        dtCurrentTable.Rows.Add(drCurrentRow);
                        ViewState["CurrentTable"] = dtCurrentTable;

                        for (int i = 0; i < dtCurrentTable.Rows.Count - 1; i++)
                        {
                            TextBox box2 = (TextBox)DataExchangeGridView.Rows[i].Cells[0].FindControl("PTNTextBox");
                            TextBox box3 = (TextBox)DataExchangeGridView.Rows[i].Cells[1].FindControl("PTDTextBox");
                            TextBox box4 = (TextBox)DataExchangeGridView.Rows[i].Cells[2].FindControl("PTRTextBox");
                            DropDownList box5 = (DropDownList)DataExchangeGridView.Rows[i].Cells[3].FindControl("PIPRDropdownlist");
                            DropDownList box6 = (DropDownList)DataExchangeGridView.Rows[i].Cells[4].FindControl("SupplierNameDroplist");
                            DropDownList box7 = (DropDownList)DataExchangeGridView.Rows[i].Cells[5].FindControl("ObjectTypeDropdownlist");
                            DropDownList box8 = (DropDownList)DataExchangeGridView.Rows[i].Cells[6].FindControl("DataformatDropdownlist");

                            dtCurrentTable.Rows[i]["PARTNUMBER"] = box2.Text;
                            dtCurrentTable.Rows[i]["PARTDESCRIPTION"] = box3.Text;
                            dtCurrentTable.Rows[i]["PARTREVISION"] = box4.Text;
                            dtCurrentTable.Rows[i]["PARTIPR"] = box5.Text;
                            dtCurrentTable.Rows[i]["SUPPLIERNAME"] = box6.Text;
                            dtCurrentTable.Rows[i]["OBJECTTYPE"] = box7.Text;
                            dtCurrentTable.Rows[i]["DATAFORMAT"] = box8.Text;
                        }

                        DataExchangeGridView.DataSource = dtCurrentTable;
                        DataExchangeGridView.DataBind();
                    }
                }
                else
                {
                    Response.Write("ViewState is null");
                }
                SetPreviousData();
            }
            catch (Exception rt)
            {
                rt.ToString();
            }
        }

        private void SetPreviousData()
        {
            try
            {
                int rowIndex = 0;
                if (this.DataExTypeDropDownList.SelectedItem.Value == "Import")
                {
                    if (ViewState["CurrentTable"] != null)
                    {
                        System.Data.DataTable dt = (System.Data.DataTable)ViewState["CurrentTable"];
                        if (dt.Rows.Count > 0)
                        {
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                System.Web.UI.WebControls.TextBox box2 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[0].FindControl("PTNTextBox");
                                System.Web.UI.WebControls.TextBox box3 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[1].FindControl("PTDTextBox");
                                System.Web.UI.WebControls.TextBox box4 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[2].FindControl("PTRTextBox");
                                box2.Enabled = box3.Enabled = box4.Enabled = false;
                                box2.Text = string.Empty;
                                box3.Text = string.Empty;
                                box4.Text = string.Empty;
                                System.Web.UI.WebControls.DropDownList box5 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[3].FindControl("PIPRDropdownlist");
                                System.Web.UI.WebControls.DropDownList box6 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[4].FindControl("SupplierNameDroplist");
                                System.Web.UI.WebControls.DropDownList box7 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[5].FindControl("ObjectTypeDropdownlist");
                                System.Web.UI.WebControls.DropDownList box8 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[6].FindControl("DataformatDropdownlist");

                                //FillDropDownList(box8);

                                if (i < dt.Rows.Count - 1)
                                {
                                    box2.Text = dt.Rows[i]["PARTNUMBER"].ToString();
                                    box3.Text = dt.Rows[i]["PARTDESCRIPTION"].ToString();
                                    box4.Text = dt.Rows[i]["PARTREVISION"].ToString();
                                    box5.Text = dt.Rows[i]["PARTIPR"].ToString();
                                    box6.Text = dt.Rows[i]["SUPPLIERNAME"].ToString();
                                    box7.Text = dt.Rows[i]["OBJECTTYPE"].ToString();
                                    //box8.Text = dt.Rows[i]["DATAFORMAT"].ToString();
                                    string XE = box8.Items.FindByText(dt.Rows[i]["DATAFORMAT"].ToString()).Value;
                                    box8.Text = XE;
                                }
                                rowIndex++;
                            }
                        }
                    }
                }
                else if (this.DataExTypeDropDownList.SelectedItem.Value == "Export")
                {
                    if (ViewState["CurrentTable"] != null)
                    {
                        System.Data.DataTable dt = (System.Data.DataTable)ViewState["CurrentTable"];
                        if (dt.Rows.Count > 0)
                        {
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                System.Web.UI.WebControls.TextBox box2 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[0].FindControl("PTNTextBox");
                                System.Web.UI.WebControls.TextBox box3 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[1].FindControl("PTDTextBox");
                                System.Web.UI.WebControls.TextBox box4 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[2].FindControl("PTRTextBox");
                                System.Web.UI.WebControls.DropDownList box5 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[3].FindControl("PIPRDropdownlist");
                                System.Web.UI.WebControls.DropDownList box6 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[4].FindControl("SupplierNameDroplist");
                                System.Web.UI.WebControls.DropDownList box7 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[5].FindControl("ObjectTypeDropdownlist");
                                System.Web.UI.WebControls.DropDownList box8 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[6].FindControl("DataformatDropdownlist");

                                if (i < dt.Rows.Count - 1)
                                {
                                    box2.Text = dt.Rows[i]["PARTNUMBER"].ToString();
                                    box3.Text = dt.Rows[i]["PARTDESCRIPTION"].ToString();
                                    box4.Text = dt.Rows[i]["PARTREVISION"].ToString();
                                    box5.Text = dt.Rows[i]["PARTIPR"].ToString();
                                    box6.Text = dt.Rows[i]["SUPPLIERNAME"].ToString();
                                    box7.Text = dt.Rows[i]["OBJECTTYPE"].ToString();
                                    box8.Text = dt.Rows[i]["DATAFORMAT"].ToString();
                                }

                                rowIndex++;
                            }
                        }
                    }
                }
            }
            catch (Exception er)
            {
                er.ToString();
            }
        }
</code>```

答:
To start with, the data format is not getting passed back due it being generated client side, so we can add a hidden field to save that value.

```<code><asp:HiddenField ID="selectedValue" runat="server" Value='<%# Eval("Dataformat") %>' />
</code>```

How we populate that field is adding OnChange to the data format dropdown.

```<code><asp:DropDownList ID="Dropdownlist7" runat="server" OnChange="DataformatSelect(this);">

function DataformatSelect(Selection) {
    var selectedValue = Selection.options[Selection.selectedIndex].value;
    Selection.parentNode.getElementsByTagName('INPUT')[0].value = selectedValue;
}
</code>```

On the server side, we must return all the data on postback (and on initial load).

```<code>private DataTable GetEmptyTable()
{
    var table = new DataTable();
    table.Columns.Add("ObjectType", typeof(string));
    table.Columns.Add("Dataformat", typeof(string));
    return table;
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        var table = GetEmptyTable();
        table.Rows.Add("Select", "Select");
        GridView1.DataSource = table;
        GridView1.DataBind();
    }
}

protected void btnAddRow_Click(object sender, EventArgs e)
{
    var table = GetEmptyTable();
    DataRow dr;

    foreach (GridViewRow gvr in GridView1.Rows)
    {
        dr = table.NewRow();
        DropDownList ddlObjectType = gvr.FindControl("Dropdownlist2") as DropDownList;
        HiddenField hdnDataFormat = gvr.FindControl("selectedValue") as HiddenField;

        dr[0] = ddlObjectType.SelectedValue;
        dr[1] = hdnDataFormat.Value;

        table.Rows.Add(dr);
    }

    table.Rows.Add("Select", "Select");

    GridView1.DataSource = table;
    GridView1.DataBind();
}
</code>```

Ensure the Object Type is getting populated with the Bind.

```<code><asp:DropDownList ID="Dropdownlist2" runat="server" OnChange="DataformatFetch(this);" SelectedValue='<%# Bind("ObjectType") %>'>
</code>```

Finally, on page load, we need to sync up the client side generated drop down lists.

```<code><body onload="pageLoad();">

function pageLoad() {
    [].forEach.call(document.getElementsByTagName('tr'), function (row, index) {
        if (index == 0) {
            return;
        }

        DataformatFetch(row.cells[0].getElementsByTagName('select')[0]);

        var selectedValue = row.getElementsByTagName('input')[0].value;
        row.cells[1].getElementsByTagName('select')[0].value = selectedValue;
    });
}
</code>```

Hopefully that fills in any missing gaps to what you already have.

Thanks a lot to add new row in gridview after binding C#, ASP.net

Body:
I have a Dropdown1 outside gridview contains three options Select,A,B.

Inside gridview two dropdowns Dropdown2,Dropdown3  in which Dropdown2 contains three options say Select,C,D.

Based on Dropdown1 & Dropdown2, I am populating Dropdown3 using onchange event in javascript in Dropdown2.

everything working fine for First row but when I add new row, Dropdown3 value vanishes to default "Select"

Javascript function

function DataformatFetch(Selection) {
                var status = Selection.options[Selection.selectedIndex].value;
                var row = Selection.parentNode.parentNode;
                var rowIndex = row.rowIndex - 1;

                if (document.getElementById("<%=DropDown1.ClientID%>").value == "A") {
                    var Dataformatlist = row.cells[7].getElementsByTagName('SELECT')[0];
                    switch (status) {
                        case "Select":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select","Select");
                            break;
                        case "C":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select","Select");
                            Dataformatlist.options[1] = new Option("1","1");
                            Dataformatlist.options[2] = new Option("2","2");
                            Dataformatlist.options[3] = new Option("3","3");
                            break;
                        case "D":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select","Select");
                            Dataformatlist.options[1] = new Option("11","11");
                            Dataformatlist.options[2] = new Option("22","22");
                            Dataformatlist.options[3] = new Option("33","33");
                            break;
                    }
                }

                else if (document.getElementById("<%=DropDown1.ClientID%>").value == "B") {
                    var Dataformatlist = row.cells[7].getElementsByTagName('SELECT')[0];
                    switch (status) {
                        case "Select":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select");
                            break;
                        case "C":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select","Select");
                            Dataformatlist.options[1] = new Option("111","111");
                            Dataformatlist.options[2] = new Option("222","222");
                            Dataformatlist.options[3] = new Option("333","333");
                            break;
                        case "D":
                            Dataformatlist.options.length = 0;
                            Dataformatlist.options[0] = new Option("Select","Select");
                            Dataformatlist.options[1] = new Option("1111","1111");
                            Dataformatlist.options[2] = new Option("2222","2222");
                            Dataformatlist.options[3] = new Option("3333","3333");
                            break;
                    }
                }
            }

ASPX code

<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Object Type">
                                <ItemTemplate>
                                   <asp:DropDownList ID="Dropdownlist2" runat="server" OnChange="DataformatFetch(this);">
                                        <asp:ListItem Value="Select">Select</asp:ListItem>
                                        <asp:ListItem Value="C">C</asp:ListItem>
                                        <asp:ListItem Value="D">D</asp:ListItem>
                                    </asp:DropDownList>
                                </ItemTemplate>
                            </asp:TemplateField>

C# code

 private void AddNewRowToGrid()
        {
            try
            {
                if (ViewState["CurrentTable"] != null)
                {
                    System.Data.DataTable dtCurrentTable = (System.Data.DataTable)ViewState["CurrentTable"];
                    DataRow drCurrentRow = null;

                    if (dtCurrentTable.Rows.Count > 0)
                    {
                        drCurrentRow = dtCurrentTable.NewRow();
                        //drCurrentRow["REQUESTNO"] = dtCurrentTable.Rows.Count + 1;

                        dtCurrentTable.Rows.Add(drCurrentRow);
                        ViewState["CurrentTable"] = dtCurrentTable;

                        for (int i = 0; i < dtCurrentTable.Rows.Count - 1; i++)
                        {
                            TextBox box2 = (TextBox)DataExchangeGridView.Rows[i].Cells[0].FindControl("PTNTextBox");
                            TextBox box3 = (TextBox)DataExchangeGridView.Rows[i].Cells[1].FindControl("PTDTextBox");
                            TextBox box4 = (TextBox)DataExchangeGridView.Rows[i].Cells[2].FindControl("PTRTextBox");
                            DropDownList box5 = (DropDownList)DataExchangeGridView.Rows[i].Cells[3].FindControl("PIPRDropdownlist");
                            DropDownList box6 = (DropDownList)DataExchangeGridView.Rows[i].Cells[4].FindControl("SupplierNameDroplist");
                            DropDownList box7 = (DropDownList)DataExchangeGridView.Rows[i].Cells[5].FindControl("ObjectTypeDropdownlist");
                            DropDownList box8 = (DropDownList)DataExchangeGridView.Rows[i].Cells[6].FindControl("DataformatDropdownlist");

                            dtCurrentTable.Rows[i]["PARTNUMBER"] = box2.Text;
                            dtCurrentTable.Rows[i]["PARTDESCRIPTION"] = box3.Text;
                            dtCurrentTable.Rows[i]["PARTREVISION"] = box4.Text;
                            dtCurrentTable.Rows[i]["PARTIPR"] = box5.Text;
                            dtCurrentTable.Rows[i]["SUPPLIERNAME"] = box6.Text;
                            dtCurrentTable.Rows[i]["OBJECTTYPE"] = box7.Text;
                            dtCurrentTable.Rows[i]["DATAFORMAT"] = box8.Text;
                        }

                        DataExchangeGridView.DataSource = dtCurrentTable;
                        DataExchangeGridView.DataBind();
                    }
                }
                else
                {
                    Response.Write("ViewState is null");
                }
                SetPreviousData();
            }
            catch (Exception rt)
            {
                rt.ToString();
            }
        }

        private void SetPreviousData()
        {
            try
            {
                int rowIndex = 0;
                if (this.DataExTypeDropDownList.SelectedItem.Value == "Import")
                {
                    if (ViewState["CurrentTable"] != null)
                    {
                        System.Data.DataTable dt = (System.Data.DataTable)ViewState["CurrentTable"];
                        if (dt.Rows.Count > 0)
                        {
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                System.Web.UI.WebControls.TextBox box2 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[0].FindControl("PTNTextBox");
                                System.Web.UI.WebControls.TextBox box3 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[1].FindControl("PTDTextBox");
                                System.Web.UI.WebControls.TextBox box4 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[2].FindControl("PTRTextBox");
                                box2.Enabled = box3.Enabled = box4.Enabled = false;
                                box2.Text = string.Empty;
                                box3.Text = string.Empty;
                                box4.Text = string.Empty;
                                System.Web.UI.WebControls.DropDownList box5 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[3].FindControl("PIPRDropdownlist");
                                System.Web.UI.WebControls.DropDownList box6 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[4].FindControl("SupplierNameDroplist");
                                System.Web.UI.WebControls.DropDownList box7 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[5].FindControl("ObjectTypeDropdownlist");
                                System.Web.UI.WebControls.DropDownList box8 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[6].FindControl("DataformatDropdownlist");

                                //FillDropDownList(box8);

                                if (i < dt.Rows.Count - 1)
                                {
                                    box2.Text = dt.Rows[i]["PARTNUMBER"].ToString();
                                    box3.Text = dt.Rows[i]["PARTDESCRIPTION"].ToString();
                                    box4.Text = dt.Rows[i]["PARTREVISION"].ToString();
                                    box5.Text = dt.Rows[i]["PARTIPR"].ToString();
                                    box6.Text = dt.Rows[i]["SUPPLIERNAME"].ToString();
                                    box7.Text = dt.Rows[i]["OBJECTTYPE"].ToString();
                                    //box8.Text = dt.Rows[i]["DATAFORMAT"].ToString();
                                    string XE = box8.Items.FindByText(dt.Rows[i]["DATAFORMAT"].ToString()).Value;
                                    box8.Text = XE;
                                }
                                rowIndex++;
                            }
                        }
                    }
                }
                else if (this.DataExTypeDropDownList.SelectedItem.Value == "Export")
                {
                    if (ViewState["CurrentTable"] != null)
                    {
                        System.Data.DataTable dt = (System.Data.DataTable)ViewState["CurrentTable"];
                        if (dt.Rows.Count > 0)
                        {
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                System.Web.UI.WebControls.TextBox box2 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[0].FindControl("PTNTextBox");
                                System.Web.UI.WebControls.TextBox box3 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[1].FindControl("PTDTextBox");
                                System.Web.UI.WebControls.TextBox box4 = (System.Web.UI.WebControls.TextBox)DataExchangeGridView.Rows[rowIndex].Cells[2].FindControl("PTRTextBox");
                                System.Web.UI.WebControls.DropDownList box5 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[3].FindControl("PIPRDropdownlist");
                                System.Web.UI.WebControls.DropDownList box6 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[4].FindControl("SupplierNameDroplist");
                                System.Web.UI.WebControls.DropDownList box7 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[5].FindControl("ObjectTypeDropdownlist");
                                System.Web.UI.WebControls.DropDownList box8 = (System.Web.UI.WebControls.DropDownList)DataExchangeGridView.Rows[rowIndex].Cells[6].FindControl("DataformatDropdownlist");

                                if (i < dt.Rows.Count - 1)
                                {
                                    box2.Text = dt.Rows[i]["PARTNUMBER"].ToString();
                                    box3.Text = dt.Rows[i]["PARTDESCRIPTION"].ToString();
                                    box4.Text = dt.Rows[i]["PARTREVISION"].ToString();
                                    box5.Text = dt.Rows[i]["PARTIPR"].ToString();
                                    box6.Text = dt.Rows[i]["SUPPLIERNAME"].ToString();
                                    box7.Text = dt.Rows[i]["OBJECTTYPE"].ToString();
                                    box8.Text = dt.Rows[i]["DATAFORMAT"].ToString();
                                }

                                rowIndex++;
                            }
                        }
                    }
                }
            }
            catch (Exception er)
            {
                er.ToString();
            }
        }

Body:
To start with, the data format is not getting passed back due it being generated client side, so we can add a hidden field to save that value.

<asp:HiddenField ID="selectedValue" runat="server" Value='<%# Eval("Dataformat") %>' />

How we populate that field is adding OnChange to the data format dropdown.

<asp:DropDownList ID="Dropdownlist7" runat="server" OnChange="DataformatSelect(this);">

function DataformatSelect(Selection) {
    var selectedValue = Selection.options[Selection.selectedIndex].value;
    Selection.parentNode.getElementsByTagName('INPUT')[0].value = selectedValue;
}

On the server side, we must return all the data on postback (and on initial load).

private DataTable GetEmptyTable()
{
    var table = new DataTable();
    table.Columns.Add("ObjectType", typeof(string));
    table.Columns.Add("Dataformat", typeof(string));
    return table;
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        var table = GetEmptyTable();
        table.Rows.Add("Select", "Select");
        GridView1.DataSource = table;
        GridView1.DataBind();
    }
}

protected void btnAddRow_Click(object sender, EventArgs e)
{
    var table = GetEmptyTable();
    DataRow dr;

    foreach (GridViewRow gvr in GridView1.Rows)
    {
        dr = table.NewRow();
        DropDownList ddlObjectType = gvr.FindControl("Dropdownlist2") as DropDownList;
        HiddenField hdnDataFormat = gvr.FindControl("selectedValue") as HiddenField;

        dr[0] = ddlObjectType.SelectedValue;
        dr[1] = hdnDataFormat.Value;

        table.Rows.Add(dr);
    }

    table.Rows.Add("Select", "Select");

    GridView1.DataSource = table;
    GridView1.DataBind();
}

Ensure the Object Type is getting populated with the Bind.

<asp:DropDownList ID="Dropdownlist2" runat="server" OnChange="DataformatFetch(this);" SelectedValue='<%# Bind("ObjectType") %>'>

Finally, on page load, we need to sync up the client side generated drop down lists.

<body onload="pageLoad();">

function pageLoad() {
    [].forEach.call(document.getElementsByTagName('tr'), function (row, index) {
        if (index == 0) {
            return;
        }

        DataformatFetch(row.cells[0].getElementsByTagName('select')[0]);

        var selectedValue = row.getElementsByTagName('input')[0].value;
        row.cells[1].getElementsByTagName('select')[0].value = selectedValue;
    });
}

Hopefully that fills in any missing gaps to what you already have.

Thanks a lot to add new row in gridview after binding C#, ASP.net


问:
Child categories not appearing in wordpress admin menu
I am creating a plugin and adding some categories

some categories are child categories for instance:

Clothes

Hats

Shirts

I add my category like this:

```<code>function addCategory($name, $description, $slug){
  $term = wp_insert_term( $name, 'product_cat', [
  'description'=> $description,
  'slug' => $slug ]
  );
  if ( is_wp_error( $term ) ) {
     $term_id = $term->error_data['term_exists'] || null;
     return false;
  } else {
     $term_id = $term['term_id'];
     add_term_meta ($term_id, "display_style", "products", true);
     return $term_id;
  }
}
</code>```

if in my category object the parent_id is different from 0 then I call this function:

```<code>function updateParentID($localID, $parentLocalID){
  global $wpdb;
  $table_name = $wpdb->prefix.'term_taxonomy';
  $sql ="UPDATE $table_name SET parent = $parentLocalID WHERE  term_id = $localID";
  $rez = $wpdb->query($sql);
  return $rez;
}
</code>```

If I check my term_taxonomy table I do have the right ID for the parent field.

However if on the admin panel I check the categories I can't see the categories but the item count is at 4:

If I click the Name column to filter by alphabetical order then they appear:

From what I can see they are correctly linked in the database:

I noticed in the admin panel if I edit a child category and just save without changing any details then they will appear correctly:

How could get them to show all the time. Am I missing something when adding the parent.

Note:

I noticed in the docs there's a wp_update_term but I couldn't find any wp_update_term_taxonomy

答:
So I managed to make the update work but have to use wp_update_term

In the end I get this code:

```<code>function updateParentID($localID, $parentLocalID){
  global $wpdb;
  $table_name = $wpdb->prefix.'term_taxonomy';
  $value = wp_update_term( $localID, 'product_cat', array( 'parent' => $parentLocalID ) );
  if ( is_wp_error( $value ) ) {
    return $value->get_error_message();;
  }else {
    return true;
  }
}
</code>```

Body:
I am creating a plugin and adding some categories

some categories are child categories for instance:

Clothes

Hats

Shirts

I add my category like this:

function addCategory($name, $description, $slug){
  $term = wp_insert_term( $name, 'product_cat', [
  'description'=> $description,
  'slug' => $slug ]
  );
  if ( is_wp_error( $term ) ) {
     $term_id = $term->error_data['term_exists'] || null;
     return false;
  } else {
     $term_id = $term['term_id'];
     add_term_meta ($term_id, "display_style", "products", true);
     return $term_id;
  }
}

if in my category object the parent_id is different from 0 then I call this function:

function updateParentID($localID, $parentLocalID){
  global $wpdb;
  $table_name = $wpdb->prefix.'term_taxonomy';
  $sql ="UPDATE $table_name SET parent = $parentLocalID WHERE  term_id = $localID";
  $rez = $wpdb->query($sql);
  return $rez;
}

If I check my term_taxonomy table I do have the right ID for the parent field.

However if on the admin panel I check the categories I can't see the categories but the item count is at 4:

If I click the Name column to filter by alphabetical order then they appear:

From what I can see they are correctly linked in the database:

I noticed in the admin panel if I edit a child category and just save without changing any details then they will appear correctly:

How could get them to show all the time. Am I missing something when adding the parent.

Note:

I noticed in the docs there's a wp_update_term but I couldn't find any wp_update_term_taxonomy

Body:
So I managed to make the update work but have to use wp_update_term

In the end I get this code:

function updateParentID($localID, $parentLocalID){
  global $wpdb;
  $table_name = $wpdb->prefix.'term_taxonomy';
  $value = wp_update_term( $localID, 'product_cat', array( 'parent' => $parentLocalID ) );
  if ( is_wp_error( $value ) ) {
    return $value->get_error_message();;
  }else {
    return true;
  }
}


问:
What is the cause of this mysterious Haskell type error involving reflection?
I was playing with the Haskell reflection package, and I ran into a type error I do not fully understand. First, I tried to write the following function, which happily typechecks:

```<code>{-# LANGUAGE TypeApplications #-}

reifyGood :: (forall s. Reifies s a => Proxy a) -> ()
reifyGood p = reify undefined (\(_ :: Proxy t) -> p @t `seq` ())
</code>```

Interestingly, however, this slightly different program does not typecheck:

```<code>reifyBad :: (forall s. Reifies s s => Proxy s) -> ()
reifyBad p = reify undefined (\(_ :: Proxy t) -> p @t `seq` ())
</code>```

```<code>• Could not deduce (Reifies s s) arising from a use of ‘p’
  from the context: Reifies s a0
    bound by a type expected by the context:
               Reifies s a0 => Proxy s -> ()
• In the first argument of ‘seq’, namely ‘p @t’
  In the expression: p @t `seq` ()
  In the second argument of ‘reify’, namely
    ‘(\ (_ :: Proxy t) -> p @t `seq` ())’
</code>```

The expressions are identical, but note the difference between the type signatures:

```<code>reifyGood :: (forall s. Reifies s a => Proxy a) -> ()
reifyBad  :: (forall s. Reifies s s => Proxy s) -> ()
</code>```

I find this curious. At first glance, this is invalid because, in the second example, the skolem s would escape its scope. However, this is not actually true—the error message never mentions skolem escape, in contrast with this slightly different program:

```<code>reifyBad' :: (forall s. Reifies s s => Proxy s) -> ()
reifyBad' p = reify undefined (\(_ :: Proxy t) -> p @t) `seq` ()
</code>```

```<code>• Couldn't match expected type ‘t0’ with actual type ‘Proxy s’
    because type variable ‘s’ would escape its scope
  This (rigid, skolem) type variable is bound by
    a type expected by the context:
      Reifies s a0 => Proxy s -> t0
• In the expression: p @t
  In the second argument of ‘reify’, namely
    ‘(\ (_ :: Proxy t) -> p @t)’
  In the first argument of ‘seq’, namely
    ‘reify undefined (\ (_ :: Proxy t) -> p @t)’
</code>```

So perhaps something else is at play here.

Examining the type of reify, it becomes a little clear that something is amiss:

```<code>reify :: forall a r. a -> (forall s. Reifies s a => Proxy s -> r) -> r
</code>```

The scopes of a and s are clearly different, so it seems to make sense that GHC would not allow them to unify. However, it seems something about the local equality constraint introduced by the functional dependency on Reifies causes some sort of odd behavior. Interestingly, this pair of functions typechecks:

```<code>foo :: forall a r. Proxy a -> (forall s. (s ~ a) => Proxy s -> r) -> r
foo _ f = f Proxy

bar :: (forall a. Proxy a) -> ()
bar p = let p' = p in foo p' (\(_ :: Proxy s) -> (p' :: Proxy s) `seq` ())
</code>```

…but removing the equality constraint in the type signature of foo makes them fail to typecheck, producing a skolem escape error:

```<code>• Couldn't match type ‘a0’ with ‘s’
    because type variable ‘s’ would escape its scope
  This (rigid, skolem) type variable is bound by
    a type expected by the context:
      Proxy s -> ()
  Expected type: Proxy s
    Actual type: Proxy a0
• In the first argument of ‘seq’, namely ‘(p' :: Proxy s)’
  In the expression: (p' :: Proxy s) `seq` ()
  In the second argument of ‘foo’, namely
    ‘(\ (_ :: Proxy s) -> (p' :: Proxy s) `seq` ())’
</code>```

At this point, I’m perplexed. I have a couple (highly related) questions.

Why does reifyBad fail to typecheck in the first place?

More specifically, why does it produce a missing instance error?

Moreover, is this behavior expected and well-defined, or is it merely a strange edge case of the typechecker that happens to produce this particular result?

答:
```<code>reify :: forall a r. a -> (forall s. Reifies s a => Proxy s -> r) -> r
</code>```

The skolem requirement essentially states that r in the type above can not depend on the s which is being quantified in the second argument. Otherwise, indeed it would "escape" its scope since reify returns r.

In

```<code>reifyBad :: (forall s. Reifies s s => Proxy s) -> ()
reifyBad p = reify undefined (\(_ :: Proxy t) -> p @t `seq` ())
</code>```

we see that the second argument of reify is \(_ :: Proxy t) -> p @t `seq` (), so the type r would be return type of that function, which is (). Since r ~ () does not depend on s, there's no escaping problem here.

However, p @t according to the type of p requires Reifies t t.
Since reify will choose t ~ s, the constraint is the same as Reifies s s.
Instead, reify only provides Reifies s a where a is the type of undefined.

The subtle point here is that, while undefined can produce any type a, the type checker can not unify s and a. This is because a function with the same type as reify is entitled to receive only one value of a fixed (rigid) type a, and then choose as many types s as wanted. Unifying all such ss with a single a would be wrong, effectively constraining the choice of s by reify.

Instead, in the variant

```<code>reifyBad' :: (forall s. Reifies s s => Proxy s) -> ()
reifyBad' p = reify undefined (\(_ :: Proxy t) -> p @t) `seq` ()
</code>```

here r is inferred to be the return type of \(_ :: Proxy t) -> p @t, which is Proxy t, where t ~ s. Since r ~ Proxy s does depend on s, we trigger a skolem error.

Body:
I was playing with the Haskell reflection package, and I ran into a type error I do not fully understand. First, I tried to write the following function, which happily typechecks:

{-# LANGUAGE TypeApplications #-}

reifyGood :: (forall s. Reifies s a => Proxy a) -> ()
reifyGood p = reify undefined (\(_ :: Proxy t) -> p @t `seq` ())

Interestingly, however, this slightly different program does not typecheck:

reifyBad :: (forall s. Reifies s s => Proxy s) -> ()
reifyBad p = reify undefined (\(_ :: Proxy t) -> p @t `seq` ())

• Could not deduce (Reifies s s) arising from a use of ‘p’
  from the context: Reifies s a0
    bound by a type expected by the context:
               Reifies s a0 => Proxy s -> ()
• In the first argument of ‘seq’, namely ‘p @t’
  In the expression: p @t `seq` ()
  In the second argument of ‘reify’, namely
    ‘(\ (_ :: Proxy t) -> p @t `seq` ())’

The expressions are identical, but note the difference between the type signatures:

reifyGood :: (forall s. Reifies s a => Proxy a) -> ()
reifyBad  :: (forall s. Reifies s s => Proxy s) -> ()

I find this curious. At first glance, this is invalid because, in the second example, the skolem s would escape its scope. However, this is not actually true—the error message never mentions skolem escape, in contrast with this slightly different program:

reifyBad' :: (forall s. Reifies s s => Proxy s) -> ()
reifyBad' p = reify undefined (\(_ :: Proxy t) -> p @t) `seq` ()

• Couldn't match expected type ‘t0’ with actual type ‘Proxy s’
    because type variable ‘s’ would escape its scope
  This (rigid, skolem) type variable is bound by
    a type expected by the context:
      Reifies s a0 => Proxy s -> t0
• In the expression: p @t
  In the second argument of ‘reify’, namely
    ‘(\ (_ :: Proxy t) -> p @t)’
  In the first argument of ‘seq’, namely
    ‘reify undefined (\ (_ :: Proxy t) -> p @t)’

So perhaps something else is at play here.

Examining the type of reify, it becomes a little clear that something is amiss:

reify :: forall a r. a -> (forall s. Reifies s a => Proxy s -> r) -> r

The scopes of a and s are clearly different, so it seems to make sense that GHC would not allow them to unify. However, it seems something about the local equality constraint introduced by the functional dependency on Reifies causes some sort of odd behavior. Interestingly, this pair of functions typechecks:

foo :: forall a r. Proxy a -> (forall s. (s ~ a) => Proxy s -> r) -> r
foo _ f = f Proxy

bar :: (forall a. Proxy a) -> ()
bar p = let p' = p in foo p' (\(_ :: Proxy s) -> (p' :: Proxy s) `seq` ())

…but removing the equality constraint in the type signature of foo makes them fail to typecheck, producing a skolem escape error:

• Couldn't match type ‘a0’ with ‘s’
    because type variable ‘s’ would escape its scope
  This (rigid, skolem) type variable is bound by
    a type expected by the context:
      Proxy s -> ()
  Expected type: Proxy s
    Actual type: Proxy a0
• In the first argument of ‘seq’, namely ‘(p' :: Proxy s)’
  In the expression: (p' :: Proxy s) `seq` ()
  In the second argument of ‘foo’, namely
    ‘(\ (_ :: Proxy s) -> (p' :: Proxy s) `seq` ())’

At this point, I’m perplexed. I have a couple (highly related) questions.

Why does reifyBad fail to typecheck in the first place?

More specifically, why does it produce a missing instance error?

Moreover, is this behavior expected and well-defined, or is it merely a strange edge case of the typechecker that happens to produce this particular result?

Body:
reify :: forall a r. a -> (forall s. Reifies s a => Proxy s -> r) -> r

The skolem requirement essentially states that r in the type above can not depend on the s which is being quantified in the second argument. Otherwise, indeed it would "escape" its scope since reify returns r.

In

reifyBad :: (forall s. Reifies s s => Proxy s) -> ()
reifyBad p = reify undefined (\(_ :: Proxy t) -> p @t `seq` ())

we see that the second argument of reify is \(_ :: Proxy t) -> p @t `seq` (), so the type r would be return type of that function, which is (). Since r ~ () does not depend on s, there's no escaping problem here.

However, p @t according to the type of p requires Reifies t t.
Since reify will choose t ~ s, the constraint is the same as Reifies s s.
Instead, reify only provides Reifies s a where a is the type of undefined.

The subtle point here is that, while undefined can produce any type a, the type checker can not unify s and a. This is because a function with the same type as reify is entitled to receive only one value of a fixed (rigid) type a, and then choose as many types s as wanted. Unifying all such ss with a single a would be wrong, effectively constraining the choice of s by reify.

Instead, in the variant

reifyBad' :: (forall s. Reifies s s => Proxy s) -> ()
reifyBad' p = reify undefined (\(_ :: Proxy t) -> p @t) `seq` ()

here r is inferred to be the return type of \(_ :: Proxy t) -> p @t, which is Proxy t, where t ~ s. Since r ~ Proxy s does depend on s, we trigger a skolem error.


问:
Encryption/Decryption For solr
I have a solr Cloud cluster, running on different machines, now the data which is indexed needs to be encrypted in such a way that it it stored in the encrypted format on the hard disk and when solr requires the for some queries or to be indexed it should be able to decrypt it do the operation and the data after operation is done should be stored in the encrypted form. I am ok in using amazon s3 if it solves the problem. I have searched and researched a lot but there is no relevant articles,  if someone can give me nudge on some direction or how can i accomplish this it will be really great help.</p>

答:
There is no built-in support for encrypting indexes, but there are a few open issues with possible patches.

The most promising one is probably LUCENE-6966. If you want to implement it yourself, looking at writing a custom codec is probably the way to go.

If you don't want to deal with manual patching or writing code yourself, Hitachi has a ready-to-deploy solution for Solr and Lucene named Credeon.

To prevent the risk of a data breach from the search indices, Credeon SFS delivers searchable encryption technology which allows the search process to be carried out directly on encrypted data. Specifically, Credeon:

Encrypts the search indices

Uses a unique randomization process for encrypting each plaintext index

Searches through encrypted indices in real time

Returns search results without decrypting the indices

Title: Encryption/Decryption For solr


问:
How many cores TensorFlow use by default (not using Coordinator)?
I guess that tensorflow use single core by default (when I don't use 'Coordinator'), because tensorflow is python library.

However, when I see Activity Monitor on Mac with running tensorflow code
 with default setting, the $CPU of python 3.6 is upper than 100% and the number of thread is greater than 10.

Does tensorflow use multi core by default?

答:
Tensorflow is a python library, but it's essentially a wrapper over native C++ implementation. Whenever you define an op, like this:

with tf.device("/cpu:0"):
  a = tf.Variable(3.0)
  b = tf.constant(4.0)
  c = a * b
```

... c is not a multiplication of python variables a and b, but a tf.multiply op, that has not so trivial CPU and GPU implementations.

So it should not confuse you: tensorflow engine is trying to use all available hardware power to perform operations, in particular, as the FAQ states, is multi-core:

The individual ops have parallel implementations, using multiple cores in a CPU, or multiple threads in a GPU.

By the way, it's worth noting that the "/cpu:0" device aggregates all CPUs on a multi-CPU system.
There is currently no way to pin nodes on specific CPUs or to use
just a subset of all CPUs.

Body:
Tensorflow is a python library, but it's essentially a wrapper over native C++ implementation. Whenever you define an op, like this:

with tf.device("/cpu:0"):
  a = tf.Variable(3.0)
  b = tf.constant(4.0)
  c = a * b

... c is not a multiplication of python variables a and b, but a tf.multiply op, that has not so trivial CPU and GPU implementations.

So it should not confuse you: tensorflow engine is trying to use all available hardware power to perform operations, in particular, as the FAQ states, is multi-core:

The individual ops have parallel implementations, using multiple cores in a CPU, or multiple threads in a GPU.

By the way, it's worth noting that the "/cpu:0" device aggregates all CPUs on a multi-CPU system.
There is currently no way to pin nodes on specific CPUs or to use
just a subset of all CPUs.


问:
kubernetes service exposed to host ip
I created a kubernetes service something like this on my 4 node cluster:

```<code>kubectl expose deployment distcc-deploy --name=distccsvc --port=8080
 --target-port=3632 --type=LoadBalancer
</code>```

The problem is how do I expose this service to an external ip. Without an external ip you can not ping or reach this service endpoint from outside network.

I am not sure if i need to change the kubedns or put some kind of changes.
Ideally I would like the service to be exposed on the host ip.
 Like http://localhost:32876

hypothetically let's say
i have a 4 node vm on which i am running let's say nginx service. i expose it as a lodabalancer service. how can i access the nginx using this service from the vm ?

let's say the service name is nginxsvc is there a way i can do http://:8080. how will i get this here for my 4 node vm ?

答:
LoadBalancer does different things depending on where you deployed kubernetes. If you deployed on AWS (using kops or some other tool) it'll create an elastic load balancer to expose the service. If you deployed on GCP it'll do something similar - Google terminology escapes me at the moment. These are separate VMs in the cloud routing traffic to your service. If you're playing around in minikube LoadBalancer doesn't really do anything, it does a node port with the assumption that the user understands minikube isn't capable of providing a true load balancer.

LoadBalancer is supposed to expose your service via a brand new IP address. So this is what happens on the cloud providers, they requisition VMs with a separate public IP address (GCP gives a static address and AWS a DNS). NodePort will expose as a port on kubernetes node running the pod. This isn't a workable solution for a general deployment but works ok while developing.

Title: kubernetes service exposed to host ip

Body:
I created a kubernetes service something like this on my 4 node cluster:

kubectl expose deployment distcc-deploy --name=distccsvc --port=8080
 --target-port=3632 --type=LoadBalancer

The problem is how do I expose this service to an external ip. Without an external ip you can not ping or reach this service endpoint from outside network.

I am not sure if i need to change the kubedns or put some kind of changes.
Ideally I would like the service to be exposed on the host ip.
 Like http://localhost:32876

hypothetically let's say
i have a 4 node vm on which i am running let's say nginx service. i expose it as a lodabalancer service. how can i access the nginx using this service from the vm ?

let's say the service name is nginxsvc is there a way i can do http://:8080. how will i get this here for my 4 node vm ?


问:
Provisioning Service Fabric behind Application Gateway
We are tying to achieve this.
From my understanding, we should place the outside interface of the SF loadbalancer on a private network and then connect to the App Gateway's LB internal interface using Azure Virtual Network Peering.

Is this doable, are there any issues with this?

答:
Yes, it's doable. There are multiple approaches you could go with -

Deploy App Gateway pointing at sf nodes directly, like shown here - Fine Granular Microservices Load Balancing with Azure Service Fabric and Application Gateway

Deploy App Gateway pointing at SF LB

Catches:

There are limitations around
how many Backend Address Pools you could have(up to 20), and how many machines and http settings each pool could run with. So, for instance, if you have SF cluster with the thousands
of services hosted at different ports, think through using SF LB and SF Reverse Proxy.

Azure Application Gateway requires its subnet. When creating a virtual network, ensure that you leave enough address space to have multiple subnets. Once you deploy an application
gateway to a subnet, only additional application gateways can be added to the subnet.

While digging into your question, I've found out that App Gateway might not play nice with websockets under certain circumstances. Check out
Communication through Azure Application Gateway blocked for WebSocket traffic for the details.

P.S.

If SF LB of yours is public you don't need VNET peering. The same works for private SF LB and Application Gateway installed into the same VNET.


问:
How can I create specialized builders for semantic layout in rails?
This is how I'd like to write markup in say index.html.erb

```<code><%= page_for "Super Cool Page" do |p| %>
    <%= p.header do %>
        Ruby is Cool
    <% end %>
    <%= p.body do %>
        Witty discourse on Ruby.
    <% end %>
    <% if page.has_sidebar? %>
        <%= p.sidebar do %>
            <ul><li>Option 1</li></ul>
        <% end %>
    <% end %>
<% end %>
</code>```

Which would output

```<code><div class="page">
    <header><h1>Super Cool Page</h1></header>
    <section>
    Witty discourse on Ruby.
    </section>
</div>
</code>```

and when page.has_sidebar? is true

```<code><div class="page">
    <header><h1>Super Cool Page</h1></header>
    <asside><ul><li>Option 1</li></ul></asside>
    <section>
    Witty discourse on Ruby.
    </section>
</div>
</code>```

I've taken a look at the FormHelper class in rails for guidance, but it seems like I'd have to duplicate a lot of work which I'm trying to avoid. I'm really just trying to figure out where to hang the classes/modules/methods in the framework and whit kind of object |p| should be.

My first inclination was to create a PageBuilder class that implements header, body and sidebar methods. But I got stuck on the rendering pipeline to get everything output just right.

Is there a gem that already provides this type of semantic generation? If not I'd love any insight on how to set this up.

答:
What you are doing can be achieved with content_for.

Haml is supercool, Slim could even be better?

ContentLicense: CC BY-SA 2.5

Body:
This is how I'd like to write markup in say index.html.erb

<%= page_for "Super Cool Page" do |p| %>
    <%= p.header do %>
        Ruby is Cool
    <% end %>
    <%= p.body do %>
        Witty discourse on Ruby.
    <% end %>
    <% if page.has_sidebar? %>
        <%= p.sidebar do %>

Option 1

        <% end %>
    <% end %>
<% end %>

Which would output

Super Cool Page

    Witty discourse on Ruby.

and when page.has_sidebar? is true

Super Cool Page

    <asside>

Option 1

</asside>

    Witty discourse on Ruby.

I've taken a look at the FormHelper class in rails for guidance, but it seems like I'd have to duplicate a lot of work which I'm trying to avoid. I'm really just trying to figure out where to hang the classes/modules/methods in the framework and whit kind of object |p| should be.

My first inclination was to create a PageBuilder class that implements header, body and sidebar methods. But I got stuck on the rendering pipeline to get everything output just right.

Is there a gem that already provides this type of semantic generation? If not I'd love any insight on how to set this up.


问:
Turn off the leading * in C# block comments
In the following thread...

https://softwareengineering.stackexchange.com/questions/232323/asterisks-in-multi-line-comments

...person27 shows how to turn off the extra asterisk that is placed, automatically, by Visual Studio.  Unfortunately, in VS2013, this option doesn't seem to be available any longer.

Does anyone know - is there still some hidden method for doing this?

To clarify further:

答:
That is for readbility purpopse, anyway, if you are worry about it, simply go to

Options > Text Editor > C# > Advanced > Uncheck "Insert * at the start of new lines when writing /**/ comments"

This is working for Microsoft Visual Studio 2017. It can be related to a Professional/Community version.


问:
Python function to find indexes of 1s in binary array and
I have an array which looks like this

```<code>[1, 0, 1 , 0 , 0, 1]
</code>```

And I want to get those indexes that have 1 in it.
So here I would get an array of [0, 2 , 5]
and then based on it I would create a new array that takes these numbers and exponantiate 2 with them
So the end array is

```<code>[2**0, 2**2, 2**5]
</code>```

Is there a way to write it as shortly as possible?

答:
There is  np.where, np.argwhere, np.nonzero and np.flatnonzero. Take your pick.

np.where and np.nonzero are as far as I know equivalent, only there is also a three argument version of where that does something different. np.argwhere is the transpose and np.flatnonzero gives flat indices.

Body:
I have an array which looks like this

[1, 0, 1 , 0 , 0, 1]

And I want to get those indexes that have 1 in it.
So here I would get an array of [0, 2 , 5]
and then based on it I would create a new array that takes these numbers and exponantiate 2 with them
So the end array is

[2**0, 2**2, 2**5]

Is there a way to write it as shortly as possible?


问:
How do draw italic text on Android canvas?
In my app I am drawing text on Android Canvas;

Now to support underline and bold I am taking help of paint object;

```<code> Paint paint = new Paint();

 paint.setUnderlineText(true);
 paint.setFakeBoldText(true);

 paint.setColor(color);
 paint.setTextSize (font_size);
 canvas_obj.drawText(text,x,y,paint);
</code>```

With this code I am getting bold and underlined text;

I also like to make it italic,

I am developing app for android 2.2 onwards.

how to do it?

Edit:

I am setting Typeface object created with an external font file to support external font; For Italic I am using following code

```<code>paint.setTypeface(Typeface.create(external_font_type_face,Typeface.ITALIC));
</code>```

This also not working,
Tested on Samsung Galaxy Ace (android 2.2)

答:
Use this:</p>

```<code>paint.setTextSkewX(-0.25f);
</code>```

Body:
In my app I am drawing text on Android Canvas;

Now to support underline and bold I am taking help of paint object;

 Paint paint = new Paint();

 paint.setUnderlineText(true);
 paint.setFakeBoldText(true);

 paint.setColor(color);
 paint.setTextSize (font_size);
 canvas_obj.drawText(text,x,y,paint);

With this code I am getting bold and underlined text;

I also like to make it italic,

I am developing app for android 2.2 onwards.

how to do it?

Edit:

I am setting Typeface object created with an external font file to support external font; For Italic I am using following code

paint.setTypeface(Typeface.create(external_font_type_face,Typeface.ITALIC));

This also not working,
Tested on Samsung Galaxy Ace (android 2.2)

Body:
Use this:

paint.setTextSkewX(-0.25f);


问:
Change Event is not working on input field
I'm trying to debug and find the error, why Change Event is not working on input field. so i have put breakpoint on change event of jquery while debugging but it skip that .i am not able to find why it is not stopping at breakpoint for debugging.

html part which is generated dynamically only a part is shown here.

```<code>var p = $('<input type="file" ID="flImage" name="flImage" runat="server" />');
                $("#mainTbl").append(p);
</code>```

script

```<code> <script type="text/javascript">
            $(function () {
                var reader = new FileReader();
                var fileName;
                var contentType;
//tried all three trick to envoke change function but not work
                //$('input[name=flImage]').change(function () {
                $("<input type='file' name='flImage' ID='flImage'/>").change(function () {
                //$("input[name=flImage]").on("change", function(){
                    if (typeof (FileReader) != "undefined") {
                        var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
                        $($(this)[0].files).each(function () {
                            var file = $(this);
                            if (regex.test(file[0].name.toLowerCase())) {
                                fileName = file[0].name;
                                contentType = file[0].type;
                                reader.readAsDataURL(file[0]);
                            } else {
                                alert(file[0].name + " is not a valid image file.");
                                return false;
                            }
                        });
                    } else {
                        alert("This browser does not support HTML5 FileReader.");
                    }
                });
</script>
</code>```

After show many advice from comment i'm trying like this to access input element
is it ok :div.main main-raised > div#pdfFormInsideL1 > table#mainTbl > tbody >tr>'input[name=flImage]
image given below

答:
var p = $('<input type="file" ID="flImage" name="flImage" runat="server" />');
                $("#mainTbl").append(p);

$(function () {
        var reader = new FileReader();
        var fileName;
        var contentType;

        $("input[name=flImage]").on("change", function(){
            if (typeof (FileReader) != "undefined") {
                var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
                $($(this)[0].files).each(function () {
                    var file = $(this);
                    if (regex.test(file[0].name.toLowerCase())) {
                        fileName = file[0].name;
                        contentType = file[0].type;
                        reader.readAsDataURL(file[0]);
                    } else {
                        alert(file[0].name + " is not a valid image file.");
                        return false;
                    }
                });
            } else {
                alert("This browser does not support HTML5 FileReader.");
            }
        });
    });                  ```
<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 id="mainTbl"></div></code>```

Body:
I'm trying to debug and find the error, why Change Event is not working on input field. so i have put breakpoint on change event of jquery while debugging but it skip that .i am not able to find why it is not stopping at breakpoint for debugging.

html part which is generated dynamically only a part is shown here.

var p = $('<input type="file" ID="flImage" name="flImage" runat="server" />');
                $("#mainTbl").append(p);

script

After show many advice from comment i'm trying like this to access input element
is it ok :div.main main-raised > div#pdfFormInsideL1 > table#mainTbl > tbody >tr>'input[name=flImage]
image given below

Body:
var p = $('<input type="file" ID="flImage" name="flImage" runat="server" />');
                $("#mainTbl").append(p);

$(function () {
        var reader = new FileReader();
        var fileName;
        var contentType;

        $("input[name=flImage]").on("change", function(){
            if (typeof (FileReader) != "undefined") {
                var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
                $($(this)[0].files).each(function () {
                    var file = $(this);
                    if (regex.test(file[0].name.toLowerCase())) {
                        fileName = file[0].name;
                        contentType = file[0].type;
                        reader.readAsDataURL(file[0]);
                    } else {
                        alert(file[0].name + " is not a valid image file.");
                        return false;
                    }
                });
            } else {
                alert("This browser does not support HTML5 FileReader.");
            }
        });
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="mainTbl"></div>


问:
Can I bind one element of class to another while initializing in one line?
I have a class (struct) like this:

```<code>type Question struct{
    Question string
    answerOne string
    answerTwo string
    answerCorrect string
}
</code>```

And I initialize it like this:

```<code>q1:=Question{
    Question:"What?",
    answerOne:"A",
    answerTwo:"B",
    answerCorrect: ? //I want this have similar value as `answerOne`
}
</code>```

While initilizing I want one of my values have similar value as another one. Is there any way to do that?

答:
You can create a pointer to struct and then assign the value to struct variable answerCorrect. Finally you can print the valueAt struct pointer.

```<code>package main

import "fmt"

// Question struct for content
type Question struct {
    Question      string
    answerOne     string
    answerTwo     string
    answerCorrect string
}

func main() {
    question := &Question{
        Question:  "What?",
        answerOne: "A",
        answerTwo: "B",
    }

    // apply condition to chose from the answer

    question.answerCorrect = question.answerTwo
    fmt.Println(*question)
}
</code>```

Body:
I have a class (struct) like this:

type Question struct{
    Question string
    answerOne string
    answerTwo string
    answerCorrect string
}

And I initialize it like this:

q1:=Question{
    Question:"What?",
    answerOne:"A",
    answerTwo:"B",
    answerCorrect: ? //I want this have similar value as `answerOne`
}

While initilizing I want one of my values have similar value as another one. Is there any way to do that?

Body:
You can create a pointer to struct and then assign the value to struct variable answerCorrect. Finally you can print the valueAt struct pointer.

package main

import "fmt"

// Question struct for content
type Question struct {
    Question      string
    answerOne     string
    answerTwo     string
    answerCorrect string
}

func main() {
    question := &Question{
        Question:  "What?",
        answerOne: "A",
        answerTwo: "B",
    }

    // apply condition to chose from the answer

    question.answerCorrect = question.answerTwo
    fmt.Println(*question)
}


问:
yii2 remove summary/count from ListView
When I use ListView I it always does a count. For example says something like:

```<code>Showing 1-1 of 1 item.
</code>```

My results/items are above. How can I remove this?

Current ListView code

```<code><?=  ListView::widget([
        'dataProvider' => $dataProvider,
        'itemOptions' => ['class' => 'col-xs-6 col-sm-3'],
        'itemView' => '_index',]);
    ?>
</code>```

答:
Use 'summary'=>'' in your List view

Syntax:

```<code><?= ListView::widget([
        'dataProvider' => $dataProvider,
        'itemOptions' => ['class' => 'item'],
        'itemView' => '_step',
    'summary'=>''

    ]) ?>
</code>```

Title: yii2 remove summary/count from ListView

Body:
When I use ListView I it always does a count. For example says something like:

Showing 1-1 of 1 item.

My results/items are above. How can I remove this?

Current ListView code

<?=  ListView::widget([
        'dataProvider' => $dataProvider,
        'itemOptions' => ['class' => 'col-xs-6 col-sm-3'],
        'itemView' => '_index',]);
    ?>

Body:
Use 'summary'=>'' in your List view

Syntax:

<?= ListView::widget([
        'dataProvider' => $dataProvider,
        'itemOptions' => ['class' => 'item'],
        'itemView' => '_step',
    'summary'=>''

    ]) ?>


问:
Issue running Java Agent
I am trying to run a basic java agent.

I followed this:

How to put classes for javaagent in the classpath

But I am getting these errors

```<code>Failed to find Premain-Class manifest attribute in target/demo.jar
Error occurred during initialization of VM
agent library failed to init: instrument
</code>```

Here is my agent

```<code>package com.example.demo;

import java.lang.instrument.Instrumentation;

public class DriftDetector {

    private static Instrumentation instrumentation;

    public static void premain(String agentArgs, Instrumentation inst) {

        System.out.println("Inside premain");
        instrumentation = inst;
    }

    public static long getObjectSize(Object o) {
        return instrumentation.getObjectSize(o);
    }
}
</code>```

My manifest.mf (inside META-INF)

```<code>Manifest-Version: 1.0
Premain-Class: com.example.demo.DriftDetector
</code>```

and my main class

```<code>package com.example.demo;
import static com.example.demo.DriftDetector.getObjectSize;

public class DemoApplication {

    public static void main(String[] args) {
        System.out.println("Size of Long: " + getObjectSize(new Long(1L)));
    }
}
</code>```

Command to create jar

```<code>mvn package
</code>```

command to run

```<code>java -javaagent:target/demo.jar -jar target/demo.jar
</code>```

答:
Most probably error is in your  manifest.mf

Manifest-Version: 1.0
Premain-Class: DriftDetector

Tty like this its works for me

Title: Issue running Java Agent

Body:
I am trying to run a basic java agent.

I followed this:

How to put classes for javaagent in the classpath

But I am getting these errors

Failed to find Premain-Class manifest attribute in target/demo.jar
Error occurred during initialization of VM
agent library failed to init: instrument

Here is my agent

package com.example.demo;

import java.lang.instrument.Instrumentation;

public class DriftDetector {

    private static Instrumentation instrumentation;

    public static void premain(String agentArgs, Instrumentation inst) {

        System.out.println("Inside premain");
        instrumentation = inst;
    }

    public static long getObjectSize(Object o) {
        return instrumentation.getObjectSize(o);
    }
}

My manifest.mf (inside META-INF)

Manifest-Version: 1.0
Premain-Class: com.example.demo.DriftDetector

and my main class

package com.example.demo;
import static com.example.demo.DriftDetector.getObjectSize;

public class DemoApplication {

    public static void main(String[] args) {
        System.out.println("Size of Long: " + getObjectSize(new Long(1L)));
    }
}

Command to create jar

mvn package

command to run

java -javaagent:target/demo.jar -jar target/demo.jar


问:
Angular Response data
I have one server file ../abc.js which contains data like this:

```<code>var abc=[
   {
       "a":"b",
       "c":"d"
   },

   {
       "e":"f",
       "g":"h"
   }
]
</code>```

i.e. a variable holding Array of objects.

Using angular(v4.x) Ajax call i can get the response as the whole file content but i can't make json() out of it because of this syntax.

My intention is to get the result from my service like:

```<code>[{
 "a":"b",
 "c": "d"
},
{
  "e":"f",
  "g":"h"
}]
</code>```

And my service looks like this:

```<code>getFileData():Observable<any>{
    return this._http.get("../abc.js")
                .map((response:Response)=>{
                     return response.json();  //Here its giving error "unexpected token v" which is coming from var keyword
     })
}
</code>```

答:
//Here its giving error "unexpected token v" which is coming from var
  keyword

You can strip of characters before [ by using substring and then convert to json

```<code>return response.substring( response.indexOf("[") ).json();
</code>```

Title: Angular Response data

Body:
I have one server file ../abc.js which contains data like this:

var abc=[
   {
       "a":"b",
       "c":"d"
   },

   {
       "e":"f",
       "g":"h"
   }
]

i.e. a variable holding Array of objects.

Using angular(v4.x) Ajax call i can get the response as the whole file content but i can't make json() out of it because of this syntax.

My intention is to get the result from my service like:

[{
 "a":"b",
 "c": "d"
},
{
  "e":"f",
  "g":"h"
}]

And my service looks like this:

getFileData():Observable<any>{
    return this._http.get("../abc.js")
                .map((response:Response)=>{
                     return response.json();  //Here its giving error "unexpected token v" which is coming from var keyword
     })
}

Body:
//Here its giving error "unexpected token v" which is coming from var
  keyword

You can strip of characters before [ by using substring and then convert to json

return response.substring( response.indexOf("[") ).json();


问:
Replace older get URL with Route in MVC
I'm developing an application that will replace a much older one. The older one has been in use for many years, and utilises querystring paramaters to reference certain things, for

http://example.com/view_object.asp?obj=Banana

I'd like to re-direct this to my ObjectController's Index action, while passing the querystring value "Banana", in order to allow the older URLs to continue functioning with the new system.

So, the new URL would be:

http://example.com/Object/Banana

I thought this would be simple, by using routes.MapRoute, but i run into an issue where i can't use the ? character.

How do i go about doing this?

Here is what was tried:

```<code>routes.MapRoute(
        name: "OldObjectRoute",
        url: "view_object.asp?obj={object}",
        defaults: new { Controller = "Object", action = "Index", object = UrlParameter.Optional }
        );
</code>```

EDIT:
So, based on the suggestion below that this is a duplicate, i did try what was suggested.
I came up with:

```<code>routes.MapRoute(
                name: "OldObjectRoute",
                url: "view_object.asp{OldList}",
                defaults: new { Controller = "Object", action = "Index", OldList = UrlParameter.Optional }
                );
</code>```

In my controller i have an optional string "OldList" now, that is expecting values from this - and adjusts the querystring to remove the query, and return the correct data based on the object that was requested.

However, now it simply does not work - I'm informed by the IIS Web Core "ASPClassic" handler that a 404 occurs when using MapRequestHandler.
Sounds like it's now interpretting this as a request for a Classic ASP page?
Does anyone know how to stop this happening?

答:
The url argument to the MapRoute method specifies a URL pattern. It means you don't specify the query string inside it, but the expected route values names. So your route mapping should look like this:

```<code>    routes.MapRoute(
    name: "OldObjectRoute",
    url: "{controller}/{action}/{object}",
    defaults: new { Controller = "Object", action = "Index", object = UrlParameter.Optional }
    );
</code>```

But this mapping should be in place already so you might want to distinguish the "old" route, so do:

```<code>    routes.MapRoute(
    name: "OldObjectRoute",
    url: "old/{controller}/{action}/{object}",
    defaults: new { Controller = "Object", action = "Index", object = UrlParameter.Optional }
    );
</code>```

Title: Replace older get URL with Route in MVC

Body:
I'm developing an application that will replace a much older one. The older one has been in use for many years, and utilises querystring paramaters to reference certain things, for

http://example.com/view_object.asp?obj=Banana

I'd like to re-direct this to my ObjectController's Index action, while passing the querystring value "Banana", in order to allow the older URLs to continue functioning with the new system.

So, the new URL would be:

http://example.com/Object/Banana

I thought this would be simple, by using routes.MapRoute, but i run into an issue where i can't use the ? character.

How do i go about doing this?

Here is what was tried:

routes.MapRoute(
        name: "OldObjectRoute",
        url: "view_object.asp?obj={object}",
        defaults: new { Controller = "Object", action = "Index", object = UrlParameter.Optional }
        );

EDIT:
So, based on the suggestion below that this is a duplicate, i did try what was suggested.
I came up with:

routes.MapRoute(
                name: "OldObjectRoute",
                url: "view_object.asp{OldList}",
                defaults: new { Controller = "Object", action = "Index", OldList = UrlParameter.Optional }
                );

In my controller i have an optional string "OldList" now, that is expecting values from this - and adjusts the querystring to remove the query, and return the correct data based on the object that was requested.

However, now it simply does not work - I'm informed by the IIS Web Core "ASPClassic" handler that a 404 occurs when using MapRequestHandler.
Sounds like it's now interpretting this as a request for a Classic ASP page?
Does anyone know how to stop this happening?

Body:
The url argument to the MapRoute method specifies a URL pattern. It means you don't specify the query string inside it, but the expected route values names. So your route mapping should look like this:

    routes.MapRoute(
    name: "OldObjectRoute",
    url: "{controller}/{action}/{object}",
    defaults: new { Controller = "Object", action = "Index", object = UrlParameter.Optional }
    );

But this mapping should be in place already so you might want to distinguish the "old" route, so do:

    routes.MapRoute(
    name: "OldObjectRoute",
    url: "old/{controller}/{action}/{object}",
    defaults: new { Controller = "Object", action = "Index", object = UrlParameter.Optional }
    );


问:
Is there are way to get rowIDs of first occurrences of value from codechunks?
Is there a way to get that realized?

example:(distribution is random)

```<code>ID    size
1      x
2      x
3      x
4      x
5      x
0      2
0      x
0      x
0      x
4      x
5      x
0      4
0      x
0      x
0      x
4      x
5      x
0      3
0      x
0      x
0      x
4      x
5      x
</code>```

This is just an example but very hard to code for me.

The x's are random numeric and not relevant. The values I need are the shown integers in the size column, so everytime a ID==0 occurrs, I need the first size value.

答:
library(dplyr)
df %>%
  mutate(row_idx = row_number()) %>%
  filter(ID==0) %>%
  filter(row_idx-lag(row_idx)>1 | row_number()==1) %>%
  select(-row_idx)
```
<p>Output is:</p>
```1  0    2
2  0    4
3  0    3
```
<br>
```#sample data
> dput(df)
structure(list(ID = c(1L, 2L, 3L, 4L, 5L, 0L, 0L, 0L, 0L, 4L,
5L, 0L, 0L, 0L, 0L, 4L, 5L, 0L, 0L, 0L, 0L, 4L, 5L), size = structure(c(4L,
4L, 4L, 4L, 4L, 1L, 4L, 4L, 4L, 4L, 4L, 3L, 4L, 4L, 4L, 4L, 4L,
2L, 4L, 4L, 4L, 4L, 4L), .Label = c("2", "3", "4", "x"), class = "factor")), .Names = c("ID",
"size"), class = "data.frame", row.names = c(NA, -23L))
```

ContentLicense: CC BY-SA 4.0

Body:
Is there a way to get that realized?

example:(distribution is random)

ID    size
1      x
2      x
3      x
4      x
5      x
0      2
0      x
0      x
0      x
4      x
5      x
0      4
0      x
0      x
0      x
4      x
5      x
0      3
0      x
0      x
0      x
4      x
5      x

This is just an example but very hard to code for me.

The x's are random numeric and not relevant. The values I need are the shown integers in the size column, so everytime a ID==0 occurrs, I need the first size value.

Body:
library(dplyr)
df %>%
  mutate(row_idx = row_number()) %>%
  filter(ID==0) %>%
  filter(row_idx-lag(row_idx)>1 | row_number()==1) %>%
  select(-row_idx)

Output is:

1  0    2
2  0    4
3  0    3

#sample data
> dput(df)
structure(list(ID = c(1L, 2L, 3L, 4L, 5L, 0L, 0L, 0L, 0L, 4L,
5L, 0L, 0L, 0L, 0L, 4L, 5L, 0L, 0L, 0L, 0L, 4L, 5L), size = structure(c(4L,
4L, 4L, 4L, 4L, 1L, 4L, 4L, 4L, 4L, 4L, 3L, 4L, 4L, 4L, 4L, 4L,
2L, 4L, 4L, 4L, 4L, 4L), .Label = c("2", "3", "4", "x"), class = "factor")), .Names = c("ID",
"size"), class = "data.frame", row.names = c(NA, -23L))


问:
I cannot run conda command /activate environment on ubuntu?
I have installed anaconda in ubuntu and am facing a problem with anaconda. I was running the following command in a conda environment:

```<code>271  pip install --user -r requirements.txt
  272  cd ..
  273  conda install ipython jupyter
  274  conda install jupyter
  275  python
  276  sudo apt-get install python-vtk python-wxgtk2.6 python-setuptools python-numpy python-configobj
  277  sudo apt-get install python-vtk python-wxgtk2.8 python-setuptools python-numpy python-configobj
  278  conda install -c anaconda mayavi==4.5.0
</code>```

It suddenly stopped working. Once I want to activate an environment or run any command with conda, I am receiving the following error:

```<code>ERROR: The install method you used for conda--probably either `pip install conda`
or `easy_install conda`--is not compatible with using conda as an application.
If your intention is to install conda as a standalone application, currently
supported install methods include the Anaconda installer and the miniconda
installer.  You can download the miniconda installer from
https://conda.io/miniconda.html.
</code>```

I have even added export PATH=/home/user/anaconda2/bin:$PATH to .bashrc. Could someone please help?

答:
pip install conda can corrupt the conda setup. Download miniconda setup from the path in the error and run below

bash Miniconda3-latest-Linux-x86_64.sh -f

To test your installation, enter the command conda --version. If installed correctly, you will see the version of conda installed.

Body:
I have installed anaconda in ubuntu and am facing a problem with anaconda. I was running the following command in a conda environment:

271  pip install --user -r requirements.txt
  272  cd ..
  273  conda install ipython jupyter
  274  conda install jupyter
  275  python
  276  sudo apt-get install python-vtk python-wxgtk2.6 python-setuptools python-numpy python-configobj
  277  sudo apt-get install python-vtk python-wxgtk2.8 python-setuptools python-numpy python-configobj
  278  conda install -c anaconda mayavi==4.5.0

It suddenly stopped working. Once I want to activate an environment or run any command with conda, I am receiving the following error:

ERROR: The install method you used for conda--probably either `pip install conda`
or `easy_install conda`--is not compatible with using conda as an application.
If your intention is to install conda as a standalone application, currently
supported install methods include the Anaconda installer and the miniconda
installer.  You can download the miniconda installer from
https://conda.io/miniconda.html.

I have even added export PATH=/home/user/anaconda2/bin:$PATH to .bashrc. Could someone please help?


问:
checkbox-inline placing checkbox over text instead of beside
I'm trying to add checkboxes to my form but the bootstrap class "checkbox-inline" does not seem to be working for me.

Here is the code:

```<code><strong>Styles:</strong>
<%= f.collection_check_boxes :style_ids, Style.all, :id, :name do |cb| %>
  <% cb.label(class: "checkbox-inline input_checkbox") {cb.check_box(class: "checkbox") + cb.text} %>
<% end %>
<br><br>

<strong>Ingredients:</strong>
<%= f.collection_check_boxes :ingredient_ids, Ingredient.all, :id, :name do |cbi| %>
  <% cbi.label(class: "checkbox-inline input_checkbox") {cbi.check_box(class: "checkbox") + cbi.text} %>
<% end %>
</code>```

And here is the outcome:

Any help on this would be much appriciated, been pulling my hair out over this.

Edit: After going through the bootstrap docs, it appears checkbox-inline and radio-inline have been dropped. I just need to figure out how to get the checkboxes beside each label

Edit 2: Figured it out! in my css I had

```<code>input {
  width: 100%;
}
</code>```

I removed this and my forms broke, but my checkboxes were in the right place! So instead I just did

```<code>.input_checkbox input {
  width: auto !important;
}
</code>```

--and everything is finally fixed.

答:
You can try like below:

```<code><div class="form-group">
  <label>Styles:</label>

      <%= f.collection_check_boxes :style_ids, Style.all, :id, :name do |cb| %>
        <% cb.label(class: "checkbox-inline input_checkbox") {cb.check_box(class: "checkbox") + cb.text } %>
      <% end %>
</div>
</code>```

I think this will help

Body:
I'm trying to add checkboxes to my form but the bootstrap class "checkbox-inline" does not seem to be working for me.

Here is the code:

Styles:
<%= f.collection_check_boxes :style_ids, Style.all, :id, :name do |cb| %>
  <% cb.label(class: "checkbox-inline input_checkbox") {cb.check_box(class: "checkbox") + cb.text} %>
<% end %>

Ingredients:
<%= f.collection_check_boxes :ingredient_ids, Ingredient.all, :id, :name do |cbi| %>
  <% cbi.label(class: "checkbox-inline input_checkbox") {cbi.check_box(class: "checkbox") + cbi.text} %>
<% end %>

And here is the outcome:

Any help on this would be much appriciated, been pulling my hair out over this.

Edit: After going through the bootstrap docs, it appears checkbox-inline and radio-inline have been dropped. I just need to figure out how to get the checkboxes beside each label

Edit 2: Figured it out! in my css I had

input {
  width: 100%;
}

I removed this and my forms broke, but my checkboxes were in the right place! So instead I just did

.input_checkbox input {
  width: auto !important;
}

--and everything is finally fixed.

Body:
You can try like below:

<div class="form-group">
  <label>Styles:</label>

      <%= f.collection_check_boxes :style_ids, Style.all, :id, :name do |cb| %>
        <% cb.label(class: "checkbox-inline input_checkbox") {cb.check_box(class: "checkbox") + cb.text } %>
      <% end %>
</div>

I think this will help