问:
Scipy optimization with SLSQP disregards constraints

I would like to optimize the following formula with scipy adding the constraint of x[0] - x[1] > 0. When printing this expression in the objective function it gives negative values as well, while the optimization terminates successfully. The final goal would be something like minimizing the sqrt(0.1*x[0]*x[1]) which due to math error fails.

```<code>import numpy as np
from scipy.optimize import minimize

def f(x):

    print x[0] - x[1]
    #return sqrt(0.1*x[0]*x[1])
    return 0.1*x[0]*x[1]

def ineq_constraint(x):

    return x[0] - x[1]

con = {'type': 'ineq', 'fun': ineq_constraint}
x0 = [1, 1]
res = minimize(f, x0, method='SLSQP', constraints=con)

print res
</code>```

And the output:

```<code>0.0
0.0
1.49011611938e-08
-1.49011611938e-08
0.0
0.0
1.49011611938e-08
-1.49011611938e-08
0.0
0.0
1.49011611938e-08
-1.49011611938e-08
4.65661176285e-10
4.65661176285e-10
1.53668223701e-08
-1.44355000176e-08
     fun: 1.7509862319755833e-18
     jac: array([  3.95812066e-10,   4.42378184e-10,   0.00000000e+00])
 message: 'Optimization terminated successfully.'
    nfev: 16
     nit: 4
    njev: 4
  status: 0
 success: True
       x: array([  4.42378184e-09,   3.95812066e-09])
</code>```

答:
In the general case, we don't know your whole task, constraints are not enforced at all steps (as observed)! Without changing the optimizer there is not much to do. And even finding an appropriate optimizer is maybe not easy.

For your case, it would work if your variables are nonnegative! If that's something you can use in your other task, we don't know.

Now there are two approaches for nonnegativity:

inequalities

bounds

Using bounds, explicit handling is used (as far is i know) and those will not be violated during optimization.

Example:

```<code>import numpy as np
from scipy.optimize import minimize
from math import sqrt

def f(x):
    print(x)
    return sqrt(0.1*x[0]*x[1])

def ineq_constraint(x):
    return x[0] - x[1]

con = {'type': 'ineq', 'fun': ineq_constraint}

x0 = [1, 1]
res = minimize(f, x0, method='SLSQP', constraints=con, bounds=[(0, None) for i in range(len(x0))])
print(res)
</code>```

Output:

```<code>[1. 1.]
[1. 1.]
[1.00000001 1.        ]
[1.         1.00000001]
[0.84188612 0.84188612]
[0.84188612 0.84188612]
[0.84188613 0.84188612]
[0.84188612 0.84188613]
[0.05131671 0.05131669]
[0.05131671 0.05131669]
[0.05131672 0.05131669]
[0.05131671 0.0513167 ]
[0. 0.]
[0. 0.]
[1.49011612e-08 0.00000000e+00]
[0.00000000e+00 1.49011612e-08]
     fun: 0.0
     jac: array([0., 0.])
 message: 'Optimization terminated successfully.'
    nfev: 16
     nit: 4
    njev: 4
  status: 0
 success: True
       x: array([0., 0.])
</code>```

Body:
I would like to optimize the following formula with scipy adding the constraint of x[0] - x[1] > 0. When printing this expression in the objective function it gives negative values as well, while the optimization terminates successfully. The final goal would be something like minimizing the sqrt(0.1*x[0]*x[1]) which due to math error fails.

import numpy as np
from scipy.optimize import minimize

def f(x):

    print x[0] - x[1]
    #return sqrt(0.1*x[0]*x[1])
    return 0.1*x[0]*x[1]

def ineq_constraint(x):

    return x[0] - x[1]

con = {'type': 'ineq', 'fun': ineq_constraint}
x0 = [1, 1]
res = minimize(f, x0, method='SLSQP', constraints=con)

print res

And the output:

0.0
0.0
1.49011611938e-08
-1.49011611938e-08
0.0
0.0
1.49011611938e-08
-1.49011611938e-08
0.0
0.0
1.49011611938e-08
-1.49011611938e-08
4.65661176285e-10
4.65661176285e-10
1.53668223701e-08
-1.44355000176e-08
     fun: 1.7509862319755833e-18
     jac: array([  3.95812066e-10,   4.42378184e-10,   0.00000000e+00])
 message: 'Optimization terminated successfully.'
    nfev: 16
     nit: 4
    njev: 4
  status: 0
 success: True
       x: array([  4.42378184e-09,   3.95812066e-09])

Body:
In the general case, we don't know your whole task, constraints are not enforced at all steps (as observed)! Without changing the optimizer there is not much to do. And even finding an appropriate optimizer is maybe not easy.

For your case, it would work if your variables are nonnegative! If that's something you can use in your other task, we don't know.

Now there are two approaches for nonnegativity:

inequalities

bounds

Using bounds, explicit handling is used (as far is i know) and those will not be violated during optimization.

Example:

import numpy as np
from scipy.optimize import minimize
from math import sqrt

def f(x):
    print(x)
    return sqrt(0.1*x[0]*x[1])

def ineq_constraint(x):
    return x[0] - x[1]

con = {'type': 'ineq', 'fun': ineq_constraint}

x0 = [1, 1]
res = minimize(f, x0, method='SLSQP', constraints=con, bounds=[(0, None) for i in range(len(x0))])
print(res)

Output:

[1. 1.]
[1. 1.]
[1.00000001 1.        ]
[1.         1.00000001]
[0.84188612 0.84188612]
[0.84188612 0.84188612]
[0.84188613 0.84188612]
[0.84188612 0.84188613]
[0.05131671 0.05131669]
[0.05131671 0.05131669]
[0.05131672 0.05131669]
[0.05131671 0.0513167 ]
[0. 0.]
[0. 0.]
[1.49011612e-08 0.00000000e+00]
[0.00000000e+00 1.49011612e-08]
     fun: 0.0
     jac: array([0., 0.])
 message: 'Optimization terminated successfully.'
    nfev: 16
     nit: 4
    njev: 4
  status: 0
 success: True
       x: array([0., 0.])


来源: stackexchange

问:
How can I modularize this C# code?
I've been working with .NET table adapters and data tables and I've been wrestling with how to modularize this code but I just can't "see" it.
Here's what I have but there's gotta be a way to combine into a one-liner that handles both cases.

```<code>  class What_I_have
  {
    public void TableAdapterFiller(TSNKF30_STRUCT_ELMNTTableAdapter TableAdapter,
      dsGrids.TSNKF30_STRUCT_ELMNTDataTable DataTable)
    {
      try
      {
        TableAdapter.Fill(DataTable);
      }
      catch (SystemException sex)
      {
        GenericExcHandler(sex, DataTable.TableName);
      }
    }
    public void TableAdapterFiller(TSNKF52_CGFM_USERSTableAdapter TableAdapter,
      dsGrids.TSNKF52_CGFM_USERSDataTable DataTable)
    {
      try
      {
        TableAdapter.Fill(DataTable);
      }
      catch (SystemException sex)
      {
        GenericExcHandler(sex, DataTable.TableName);
      }
    }

  }
</code>```

This is an idea of what I'm trying to do (The type 'HowToTypeThis' presents my quandary):

```<code>  class What_Id_like
  {
    public void TableAdapterFiller(TSNKF30_STRUCT_ELMNTTableAdapter TableAdapter,
      dsGrids.TSNKF30_STRUCT_ELMNTDataTable DataTable)
    {
      IsolatedMethod(TableAdapter, DataTable);
    }
    public void TableAdapterFiller(TSNKF52_CGFM_USERSTableAdapter TableAdapter,
      dsGrids.TSNKF52_CGFM_USERSDataTable DataTable)
    {
      IsolatedMethod(TableAdapter, DataTable);
    }

    void IsolatedMethod(HowToTypeThis tabAdapter,
      HowToTypeThis DataTable)
    {
      try
      {
        TableAdapter.Fill(DataTable);
      }
      catch (SystemException sex)
      {
        GenericExcHandler(sex, DataTable.TableName);
      }
    }

  }
</code>```

答:
Add interfaces:

```<code>public interface ITableAdapter
{
  Fill(IdataTable dt);
}
public interface IDataTable { }
</code>```

Update your classes

```<code>public class TSNKF30_STRUCT_ELMNTTableAdapter : ITableAdapter {}
public class TSNKF30_STRUCT_ELMNTDataTable  : IDataTable {}
</code>```

Write an extension method

```<code>public static class TableAdapterExtensions
{
  public static void FillWith(this ITableAdapter adapter, IDataTable dataTable)
  {
    try
    {
      adapter.Fill(dataTable);
    }
    catch(SystemException sex)
    {
      GenericExcHandler(sex, DataTable.TableName);
    }
  }
}
</code>```

Then usage:

```<code>var ta = new TSNKF30_STRUCT_ELMNTTableAdapter();
var dt = new dsGrids.TSNKF30_STRUCT_ELMNTDataTable();
ta.FillWith(dt);
</code>```

ContentLicense: CC BY-SA 3.0

Title: How can I modularize this C# code?

Body:
I've been working with .NET table adapters and data tables and I've been wrestling with how to modularize this code but I just can't "see" it.
Here's what I have but there's gotta be a way to combine into a one-liner that handles both cases.

  class What_I_have
  {
    public void TableAdapterFiller(TSNKF30_STRUCT_ELMNTTableAdapter TableAdapter,
      dsGrids.TSNKF30_STRUCT_ELMNTDataTable DataTable)
    {
      try
      {
        TableAdapter.Fill(DataTable);
      }
      catch (SystemException sex)
      {
        GenericExcHandler(sex, DataTable.TableName);
      }
    }
    public void TableAdapterFiller(TSNKF52_CGFM_USERSTableAdapter TableAdapter,
      dsGrids.TSNKF52_CGFM_USERSDataTable DataTable)
    {
      try
      {
        TableAdapter.Fill(DataTable);
      }
      catch (SystemException sex)
      {
        GenericExcHandler(sex, DataTable.TableName);
      }
    }

  }

This is an idea of what I'm trying to do (The type 'HowToTypeThis' presents my quandary):

  class What_Id_like
  {
    public void TableAdapterFiller(TSNKF30_STRUCT_ELMNTTableAdapter TableAdapter,
      dsGrids.TSNKF30_STRUCT_ELMNTDataTable DataTable)
    {
      IsolatedMethod(TableAdapter, DataTable);
    }
    public void TableAdapterFiller(TSNKF52_CGFM_USERSTableAdapter TableAdapter,
      dsGrids.TSNKF52_CGFM_USERSDataTable DataTable)
    {
      IsolatedMethod(TableAdapter, DataTable);
    }

    void IsolatedMethod(HowToTypeThis tabAdapter,
      HowToTypeThis DataTable)
    {
      try
      {
        TableAdapter.Fill(DataTable);
      }
      catch (SystemException sex)
      {
        GenericExcHandler(sex, DataTable.TableName);
      }
    }

  }

Body:
Add interfaces:

public interface ITableAdapter
{
  Fill(IdataTable dt);
}
public interface IDataTable { }

Update your classes

public class TSNKF30_STRUCT_ELMNTTableAdapter : ITableAdapter {}
public class TSNKF30_STRUCT_ELMNTDataTable  : IDataTable {}

Write an extension method

public static class TableAdapterExtensions
{
  public static void FillWith(this ITableAdapter adapter, IDataTable dataTable)
  {
    try
    {
      adapter.Fill(dataTable);
    }
    catch(SystemException sex)
    {
      GenericExcHandler(sex, DataTable.TableName);
    }
  }
}

Then usage:

var ta = new TSNKF30_STRUCT_ELMNTTableAdapter();
var dt = new dsGrids.TSNKF30_STRUCT_ELMNTDataTable();
ta.FillWith(dt);


问:
macos command line params not working at the end
On linux systems when you type a command in a shell like rm * -rf, the order of the * and the -rf doesn't matter. My shell interpret it the same way. Now, on my Mac when I type rm -rf * everything works fine, but if I do rm * -rf an error shows up rm: -rf: No such file or directory

I tried that on a macOS and a linux both with fish and bash shells. Same problems.

Does anyone have any idea why the command interpreter on macOS thinks that -rf at the end of the command is not interpreted as parameters of the command ?

答:
It's not about the shell, it's about the commands.
The parsing of command line arguments is not a feature and responsibility of the shell, but of the actual commands.
In both systems the shell faithfully passes the command line arguments in whatever order they were specified, and then it's up to the implementation of the commands to parse them as they see fit.

In linux, the core utilities are typically of the GNU implementation,
while on osx, the core utilities are typically of the BSD implementation.

The man page of the commands should tell you which implementation it is.

For example the last line of man rm in Linux is something like this:

```<code>GNU coreutils 8.21                March 2016                             RM(1)
</code>```

On osx:

```<code>BSD                            January 28, 1999                            BSD
</code>```

Body:
It's not about the shell, it's about the commands.
The parsing of command line arguments is not a feature and responsibility of the shell, but of the actual commands.
In both systems the shell faithfully passes the command line arguments in whatever order they were specified, and then it's up to the implementation of the commands to parse them as they see fit.

In linux, the core utilities are typically of the GNU implementation,
while on osx, the core utilities are typically of the BSD implementation.

The man page of the commands should tell you which implementation it is.

For example the last line of man rm in Linux is something like this:

GNU coreutils 8.21                March 2016                             RM(1)

On osx:

BSD                            January 28, 1999                            BSD


问:
Convert lat long to utm NAD83 zone 20
I have 2 similar data sets, where I want to convert my latitude and longitude to UTM (NAD83 Zone 20N). One of my data sets has the raw data Data set 1, and for the other one I have calculated the average position based on a given time interval Data set 2.

The second data set does have a few NAs in the mean lat and long sections, yet I would need to find a way in the code to accept the NAs and convert all the other lat/longs.

I have tried using different codes that I have found on the Internet, but they are giving me errors or won't convert lat/long to UTM.

Code 1

```<code>setwd("~/Documents/UVI/Thesis/Data/Analyses/Practice/MCP_Lsynagris")

tagdata<-read.csv("Data/allcombinedMAforSA.csv", header=T, sep=",", strip.white=T)
tagdata$detection_time_ast<-as.POSIXct(tagdata$detection_time_ast, format="%Y-%m-%d %H:%M:%S",tz="UTC")

tagdata<-tagdata[order(tagdata$detection_time_ast),]

cord.dec = SpatialPoints(cbind(tagdata$long_nad83, -tagdata$lat_nad83), proj4string = CRS("+proj=longlat"))
#Transfoming coordinate to UTM using ESPG 26920 for NAD83 Zone 20N.
cord_UTM<-spTransform(cord.dec, CRS("+init=esp:26290"))
cord_UTM
</code>```

For the first set of codes I received the following error

```<code>> cord_UTM<-spTransform(cord.dec, CRS("+init=esp:26290"))
Error in spTransform(cord.dec, CRS("+init=esp:26290")) :
  error in evaluating the argument 'CRSobj' in selecting a method for function 'spTransform': Error in CRS("+init=esp:26290") : no system list, errno: 2
> cord_UTM
Error: object 'cord_UTM' not found
</code>```

Code 2

```<code>tagdata<-read.csv("Data/allcombinedMAforSA.csv", header=T, sep=",", strip.white=T)

tagdata$detection_time_ast<-as.POSIXct(tagdata$detection_time_ast, format="%Y-%m-%d %H:%M:%S",tz="UTC")

tagdata<-tagdata[order(tagdata$detection_time_ast),]

coordinates(tagdata) <- c("long_nad83", "lat_83")
proj4string(tagdata) <- CRS("+proj=longlat +datum=NAD83")

res <- spTransform(tagdata, CRS("+proj=utm +zone=20 ellps=NAD83"))
res
as(res, "SpatialPoints")
</code>```

Here are the following errors I received in the second code

```<code>Error in `[.data.frame`(object, , value) : undefined columns selected
> proj4string(tagdata) <- CRS("+proj=longlat +datum=NAD83")
Error in (function (classes, fdef, mtable)  :
  unable to find an inherited method for function ‘proj4string<-’ for signature ‘"data.frame", "CRS"’
>
> res <- spTransform(tagdata, CRS("+proj=utm +zone=20 ellps=NAD83"))
Error in (function (classes, fdef, mtable)  :
  unable to find an inherited method for function ‘spTransform’ for signature ‘"data.frame", "CRS"’
> res
Error: object 'res' not found

> as(res, "SpatialPoints")
Error in .class1(object) : object 'res' not found
</code>```

Is there a better way to go about converting my lat/long to UTM NAD83 Zone 20 for either dat set? As well as, for the code to accept that there are NA's in the average lat/long columns for my second data set.

答:
I got this code from an online source (don't have the reference handy):

```<code>LongLatToUTM<-function(x,y,zone){
  require(sp)
  xy <- data.frame(ID = 1:length(x), X = x, Y = y)
  coordinates(xy) <- c("X", "Y")
  proj4string(xy) <- CRS("+proj=longlat +datum=WGS84")  ## for example
  res <- spTransform(xy, CRS(paste("+proj=utm +zone=",zone," ellps=WGS84",sep='')))
  return(as.data.frame(res))
}
</code>```

Note that this is for WGS84.

ContentLicense: CC BY-SA 4.0

Title: Convert lat long to utm NAD83 zone 20

Body:
I have 2 similar data sets, where I want to convert my latitude and longitude to UTM (NAD83 Zone 20N). One of my data sets has the raw data Data set 1, and for the other one I have calculated the average position based on a given time interval Data set 2.

The second data set does have a few NAs in the mean lat and long sections, yet I would need to find a way in the code to accept the NAs and convert all the other lat/longs.

I have tried using different codes that I have found on the Internet, but they are giving me errors or won't convert lat/long to UTM.

Code 1

setwd("~/Documents/UVI/Thesis/Data/Analyses/Practice/MCP_Lsynagris")

tagdata<-read.csv("Data/allcombinedMAforSA.csv", header=T, sep=",", strip.white=T)
tagdata$detection_time_ast<-as.POSIXct(tagdata$detection_time_ast, format="%Y-%m-%d %H:%M:%S",tz="UTC")

tagdata<-tagdata[order(tagdata$detection_time_ast),]

cord.dec = SpatialPoints(cbind(tagdata$long_nad83, -tagdata$lat_nad83), proj4string = CRS("+proj=longlat"))
#Transfoming coordinate to UTM using ESPG 26920 for NAD83 Zone 20N.
cord_UTM<-spTransform(cord.dec, CRS("+init=esp:26290"))
cord_UTM

For the first set of codes I received the following error

> cord_UTM<-spTransform(cord.dec, CRS("+init=esp:26290"))
Error in spTransform(cord.dec, CRS("+init=esp:26290")) :
  error in evaluating the argument 'CRSobj' in selecting a method for function 'spTransform': Error in CRS("+init=esp:26290") : no system list, errno: 2
> cord_UTM
Error: object 'cord_UTM' not found

Code 2

tagdata<-read.csv("Data/allcombinedMAforSA.csv", header=T, sep=",", strip.white=T)

tagdata$detection_time_ast<-as.POSIXct(tagdata$detection_time_ast, format="%Y-%m-%d %H:%M:%S",tz="UTC")

tagdata<-tagdata[order(tagdata$detection_time_ast),]

coordinates(tagdata) <- c("long_nad83", "lat_83")
proj4string(tagdata) <- CRS("+proj=longlat +datum=NAD83")

res <- spTransform(tagdata, CRS("+proj=utm +zone=20 ellps=NAD83"))
res
as(res, "SpatialPoints")

Here are the following errors I received in the second code

Error in `[.data.frame`(object, , value) : undefined columns selected
> proj4string(tagdata) <- CRS("+proj=longlat +datum=NAD83")
Error in (function (classes, fdef, mtable)  :
  unable to find an inherited method for function ‘proj4string<-’ for signature ‘"data.frame", "CRS"’
>
> res <- spTransform(tagdata, CRS("+proj=utm +zone=20 ellps=NAD83"))
Error in (function (classes, fdef, mtable)  :
  unable to find an inherited method for function ‘spTransform’ for signature ‘"data.frame", "CRS"’
> res
Error: object 'res' not found

> as(res, "SpatialPoints")
Error in .class1(object) : object 'res' not found

Is there a better way to go about converting my lat/long to UTM NAD83 Zone 20 for either dat set? As well as, for the code to accept that there are NA's in the average lat/long columns for my second data set.

Body:
I got this code from an online source (don't have the reference handy):

LongLatToUTM<-function(x,y,zone){
  require(sp)
  xy <- data.frame(ID = 1:length(x), X = x, Y = y)
  coordinates(xy) <- c("X", "Y")
  proj4string(xy) <- CRS("+proj=longlat +datum=WGS84")  ## for example
  res <- spTransform(xy, CRS(paste("+proj=utm +zone=",zone," ellps=WGS84",sep='')))
  return(as.data.frame(res))
}

Note that this is for WGS84.


问:
Getting error " Attempted to read or write protected memory"
This is what is in the header file.

```<code>/// Creates a new file geodatabase in the specified location.
/// @param[in]    path The location where the geodatabase should be created.
/// @param[out]   geodatabase A reference to the newly-created geodatabase.
/// @return       A long integer indicating whether the method finished successfully.
EXT_FILEGDB_API long CreateGeodatabase(const std::wstring& path, Geodatabase& geodatabase);
</code>```

This is what my dllimport looks like.

```<code>[DllImport("FileGDBAPI.dll", EntryPoint = "#49", SetLastError=true, CallingConvention=CallingConvention.Winapi)]
        public static extern int CreateGeodatabase([MarshalAs(UnmanagedType.LPStr)]string path, ref IntPtr geodatabase);
</code>```

..and this is the code thats using it.

```<code>IntPtr Geodatabase = IntPtr.Zero;
                FileGDBAPI_wrapper.CreateGeodatabase("c:\temp\testGDB.gdb", ref Geodatabase);
</code>```

What am I doing wrong?

答:
I see two possible problems:

The C++ code is using a wide string, the C# code an ANSI string

The C++ code is using the std::wstring class, and not a c style null terminated string

I don't think you can fix the second problem easily without changing the API on the C++ side

ContentLicense: CC BY-SA 2.5

Body:
This is what is in the header file.

/// Creates a new file geodatabase in the specified location.
/// @param[in]    path The location where the geodatabase should be created.
/// @param[out]   geodatabase A reference to the newly-created geodatabase.
/// @return       A long integer indicating whether the method finished successfully.
EXT_FILEGDB_API long CreateGeodatabase(const std::wstring& path, Geodatabase& geodatabase);

This is what my dllimport looks like.

[DllImport("FileGDBAPI.dll", EntryPoint = "#49", SetLastError=true, CallingConvention=CallingConvention.Winapi)]
        public static extern int CreateGeodatabase([MarshalAs(UnmanagedType.LPStr)]string path, ref IntPtr geodatabase);

..and this is the code thats using it.

IntPtr Geodatabase = IntPtr.Zero;
                FileGDBAPI_wrapper.CreateGeodatabase("c:\temp\testGDB.gdb", ref Geodatabase);

What am I doing wrong?


问:
changeCursor() doesn't refresh ListView
I have a simple app to manage students list.

In MainActivity, we can add a student to the list. clicking on an added ListView item, opens up a new activity, in which we can edit the students grade.

I'm using custom CursorAdapter with my list, and custom SQLiteOpenHelper DB to handle the DB.

On MainActivity:onResume() I check if the db was changed, and call changeCursor() if so.

When debugging, it seems the DB change flag is set, but the call to changeCursor() doesn't refresh the ListView with new data

EXAMPLE

Add Adi,10

Clicked on the list item -> new activity -> grade edited to 20 -> hit back button

Expect to see Adi,20, still sees Adi,10

Here's my relevant code:

Main Activity:

```<code>public class MainActivity extends AppCompatActivity {
    private SqlDbHelper mDB;
    private SQLAdapter mAdapter;

    @Override
    protected void onResume() {
        super.onResume();
        if(mDB.isDbChanged()) {
            mAdapter.changeCursor(mDB.getAllRows());
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /* Init fields & needed views */
        mDB = new SqlDbHelper(getApplicationContext());
        mAdapter = new SQLAdapter(getApplicationContext(), mDB.getAllRows(), false);
        final ListView lvStudents = findViewById(R.id.lv_students);
        final EditText etName = findViewById(R.id.et_name);
        final EditText etGrade = findViewById(R.id.et_grade);

        /* Listen to ADD BUTTON clicks */
        findViewById(R.id.button_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                insertNewRecord(etName.getText().toString(), etGrade.getText().toString());
                etName.setText("");
                etGrade.setText("");
            }
        });

        /* Set adapter to LV, Listen to list item clicks */
        lvStudents.setAdapter(mAdapter);
        lvStudents.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent listItemIntent = new Intent(getApplicationContext(), ListItemActivity.class);

                /* Put needed info in the Intent extra */
                listItemIntent.putExtra(SqlDbHelper.KEY_ID, l);
                listItemIntent.putExtra(SqlDbHelper.KEY_NAME,
                        ((TextView)view.findViewById(R.id.tv_name)).getText().toString());
                listItemIntent.putExtra(SqlDbHelper.KEY_GRADE,
                        Integer.parseInt( ((TextView)view
                                .findViewById(R.id.tv_grade))
                                .getText().toString() ));
                startActivity(listItemIntent);
            }
        });
    }

    private void insertNewRecord(final String name, final String grade) {
        /* Add the new student to the DB */
        mDB.addStudent(name, gradeInt);
        mAdapter.changeCursor(mDB.getAllRows());
    }
}
</code>```

SQLAdapter:

```<code>final class SQLAdapter extends CursorAdapter {
    private LayoutInflater mInflater;

    public SQLAdapter(Context context, Cursor c, boolean autoRequery) {
        super(context, c, autoRequery);
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
        return mInflater.inflate(R.layout.lv_line, viewGroup, false);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        final String name = cursor.getString(cursor.getColumnIndex(SqlDbHelper.KEY_NAME));
        final int grade = cursor.getInt(cursor.getColumnIndex(SqlDbHelper.KEY_GRADE));

        view.findViewById(R.id.ll_line).setBackgroundColor(Color.RED);
        ((TextView)view.findViewById(R.id.tv_name)).setText(name);
        ((TextView)view.findViewById(R.id.tv_grade)).setText(String.valueOf(grade));
    }

}
</code>```

SqlDbHelper:

```<code>final class SqlDbHelper extends SQLiteOpenHelper {
    // some static string variables //

    /* Flag indicating DB was changed (by editStudent) -
      * For indication to MainActivity to refresh its list onResume */
    private static boolean mDbChanged;

    public SqlDbHelper(Context context) {
        super(context, DB_NAME, null, VERSION);
        mDbChanged = false;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        /* Create sql command to create new table */
        StringBuilder sql = new StringBuilder();
        sql.append("CREATE TABLE " + TABLE_NAME + " (")
                .append(KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,")
                .append(KEY_NAME + " TEXT,")
                .append(KEY_GRADE + " INT")
                .append(")");

        Log.d(TAG, "Query to form table: " + sql.toString());
        sqLiteDatabase.execSQL(sql.toString());
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {}

    public void addStudent(final String name, final int grade) {
        ContentValues cv = new ContentValues();
        cv.put(KEY_NAME, name);
        cv.put(KEY_GRADE, grade);
        getWritableDatabase().insert(TABLE_NAME, null, cv);
    }

    public void editStudent(final long id, final int grade) throws IllegalArgumentException {
        StringBuilder updateQuery = new StringBuilder();
        updateQuery.append("UPDATE " + TABLE_NAME)
                .append(" SET " + KEY_GRADE)
                .append(" = " + grade)
                .append(" WHERE " + KEY_ID)
                .append(" = " + id);

        Log.d(TAG, "Query to edit: " + updateQuery.toString());
        getWritableDatabase().execSQL(updateQuery.toString());

        /* Indicate the change */
        mDbChanged = true;
    }

    /**
     * Aid method to get all rows in the DB
     * @return Cursor pointing to the start of all rows
     */
    public Cursor getAllRows() {
        /* Turn change flag off, if method was called in order
        * to refresh the main listview onResume */
        if(mDbChanged) {
            mDbChanged = false;
        }

        return getReadableDatabase().
                rawQuery("SELECT * FROM " + TABLE_NAME, null);
    }

    public boolean isDbChanged() {
        return mDbChanged;
    }
}
</code>```

ListItemActivity:

```<code>public class ListItemActivity extends AppCompatActivity {
    private Intent mIntent;
    private Button mButtonEdit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_item);

        /* Get needed params for the view */
        mIntent = getIntent();
        mButtonEdit = findViewById(R.id.button_item_edit);
        EditText etGrade = findViewById(R.id.et_item_grade);

        /* Set the Student's Name & Grade */
        final int grade = mIntent.getIntExtra(KEY_GRADE, -1);

        ((TextView)findViewById(R.id.tv_item_name)).
                setText(mIntent.getStringExtra(KEY_NAME));
        etGrade.setText(String.valueOf(grade));

        /* Set on click listener for the edit button */
        mButtonEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SqlDbHelper db = new SqlDbHelper(getApplicationContext());
                db.editStudent(mIntent.getLongExtra(KEY_ID, -1), grade);
            }
        });
    }
}
</code>```

答:
Problem was in ListItemActivity in mButton onClick() method.

Instead of updating the db with new grade entered on the EditText box, I've used an old grade variable which holds the old value of the grade, obtained in onCreate().

Took some time to figure it out, this since due to the fact that the grade on screen in this activity, did change to the new grade, although db was updated with old one.

Solution:

In LastItemActivity::onClick, Change

```<code>db.editStudent(mIntent.getLongExtra(KEY_ID, -1), grade);
</code>```

To

```<code>db.editStudent(mIntent.getLongExtra(KEY_ID, -1), Integer.parseInt(etGrade.getText().toString()))
</code>```

Title: changeCursor() doesn't refresh ListView

Body:
I have a simple app to manage students list.

In MainActivity, we can add a student to the list. clicking on an added ListView item, opens up a new activity, in which we can edit the students grade.

I'm using custom CursorAdapter with my list, and custom SQLiteOpenHelper DB to handle the DB.

On MainActivity:onResume() I check if the db was changed, and call changeCursor() if so.

When debugging, it seems the DB change flag is set, but the call to changeCursor() doesn't refresh the ListView with new data

EXAMPLE

Add Adi,10

Clicked on the list item -> new activity -> grade edited to 20 -> hit back button

Expect to see Adi,20, still sees Adi,10

Here's my relevant code:

Main Activity:

public class MainActivity extends AppCompatActivity {
    private SqlDbHelper mDB;
    private SQLAdapter mAdapter;

    @Override
    protected void onResume() {
        super.onResume();
        if(mDB.isDbChanged()) {
            mAdapter.changeCursor(mDB.getAllRows());
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /* Init fields & needed views */
        mDB = new SqlDbHelper(getApplicationContext());
        mAdapter = new SQLAdapter(getApplicationContext(), mDB.getAllRows(), false);
        final ListView lvStudents = findViewById(R.id.lv_students);
        final EditText etName = findViewById(R.id.et_name);
        final EditText etGrade = findViewById(R.id.et_grade);

        /* Listen to ADD BUTTON clicks */
        findViewById(R.id.button_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                insertNewRecord(etName.getText().toString(), etGrade.getText().toString());
                etName.setText("");
                etGrade.setText("");
            }
        });

        /* Set adapter to LV, Listen to list item clicks */
        lvStudents.setAdapter(mAdapter);
        lvStudents.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent listItemIntent = new Intent(getApplicationContext(), ListItemActivity.class);

                /* Put needed info in the Intent extra */
                listItemIntent.putExtra(SqlDbHelper.KEY_ID, l);
                listItemIntent.putExtra(SqlDbHelper.KEY_NAME,
                        ((TextView)view.findViewById(R.id.tv_name)).getText().toString());
                listItemIntent.putExtra(SqlDbHelper.KEY_GRADE,
                        Integer.parseInt( ((TextView)view
                                .findViewById(R.id.tv_grade))
                                .getText().toString() ));
                startActivity(listItemIntent);
            }
        });
    }

    private void insertNewRecord(final String name, final String grade) {
        /* Add the new student to the DB */
        mDB.addStudent(name, gradeInt);
        mAdapter.changeCursor(mDB.getAllRows());
    }
}

SQLAdapter:

final class SQLAdapter extends CursorAdapter {
    private LayoutInflater mInflater;

    public SQLAdapter(Context context, Cursor c, boolean autoRequery) {
        super(context, c, autoRequery);
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
        return mInflater.inflate(R.layout.lv_line, viewGroup, false);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        final String name = cursor.getString(cursor.getColumnIndex(SqlDbHelper.KEY_NAME));
        final int grade = cursor.getInt(cursor.getColumnIndex(SqlDbHelper.KEY_GRADE));

        view.findViewById(R.id.ll_line).setBackgroundColor(Color.RED);
        ((TextView)view.findViewById(R.id.tv_name)).setText(name);
        ((TextView)view.findViewById(R.id.tv_grade)).setText(String.valueOf(grade));
    }

}

SqlDbHelper:

final class SqlDbHelper extends SQLiteOpenHelper {
    // some static string variables //

    /* Flag indicating DB was changed (by editStudent) -
      * For indication to MainActivity to refresh its list onResume */
    private static boolean mDbChanged;

    public SqlDbHelper(Context context) {
        super(context, DB_NAME, null, VERSION);
        mDbChanged = false;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        /* Create sql command to create new table */
        StringBuilder sql = new StringBuilder();
        sql.append("CREATE TABLE " + TABLE_NAME + " (")
                .append(KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,")
                .append(KEY_NAME + " TEXT,")
                .append(KEY_GRADE + " INT")
                .append(")");

        Log.d(TAG, "Query to form table: " + sql.toString());
        sqLiteDatabase.execSQL(sql.toString());
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {}

    public void addStudent(final String name, final int grade) {
        ContentValues cv = new ContentValues();
        cv.put(KEY_NAME, name);
        cv.put(KEY_GRADE, grade);
        getWritableDatabase().insert(TABLE_NAME, null, cv);
    }

    public void editStudent(final long id, final int grade) throws IllegalArgumentException {
        StringBuilder updateQuery = new StringBuilder();
        updateQuery.append("UPDATE " + TABLE_NAME)
                .append(" SET " + KEY_GRADE)
                .append(" = " + grade)
                .append(" WHERE " + KEY_ID)
                .append(" = " + id);

        Log.d(TAG, "Query to edit: " + updateQuery.toString());
        getWritableDatabase().execSQL(updateQuery.toString());

        /* Indicate the change */
        mDbChanged = true;
    }

    /**
     * Aid method to get all rows in the DB
     * @return Cursor pointing to the start of all rows
     */
    public Cursor getAllRows() {
        /* Turn change flag off, if method was called in order
        * to refresh the main listview onResume */
        if(mDbChanged) {
            mDbChanged = false;
        }

        return getReadableDatabase().
                rawQuery("SELECT * FROM " + TABLE_NAME, null);
    }

    public boolean isDbChanged() {
        return mDbChanged;
    }
}

ListItemActivity:

public class ListItemActivity extends AppCompatActivity {
    private Intent mIntent;
    private Button mButtonEdit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_item);

        /* Get needed params for the view */
        mIntent = getIntent();
        mButtonEdit = findViewById(R.id.button_item_edit);
        EditText etGrade = findViewById(R.id.et_item_grade);

        /* Set the Student's Name & Grade */
        final int grade = mIntent.getIntExtra(KEY_GRADE, -1);

        ((TextView)findViewById(R.id.tv_item_name)).
                setText(mIntent.getStringExtra(KEY_NAME));
        etGrade.setText(String.valueOf(grade));

        /* Set on click listener for the edit button */
        mButtonEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SqlDbHelper db = new SqlDbHelper(getApplicationContext());
                db.editStudent(mIntent.getLongExtra(KEY_ID, -1), grade);
            }
        });
    }
}

Body:
Problem was in ListItemActivity in mButton onClick() method.

Instead of updating the db with new grade entered on the EditText box, I've used an old grade variable which holds the old value of the grade, obtained in onCreate().

Took some time to figure it out, this since due to the fact that the grade on screen in this activity, did change to the new grade, although db was updated with old one.

Solution:

In LastItemActivity::onClick, Change

db.editStudent(mIntent.getLongExtra(KEY_ID, -1), grade);

To

db.editStudent(mIntent.getLongExtra(KEY_ID, -1), Integer.parseInt(etGrade.getText().toString()))


问:
How to toggle a form through button?
I would like to show a form through button click in JS vanilla but nothing work. Here is my code

/* ======= Model ======= */

var model = {
    currentCat: null,
    cats: [
        {
            clickCount : 0,
            name : 'Tabby',
            imgSrc : 'img/434164568_fea0ad4013_z.jpg',
            imgAttribution : 'https://www.flickr.com/photos/bigtallguy/434164568'
        },
        {
            clickCount : 0,
            name : 'Tiger',
            imgSrc : 'img/4154543904_6e2428c421_z.jpg',
            imgAttribution : 'https://www.flickr.com/photos/xshamx/4154543904'
        },
        {
            clickCount : 0,
            name : 'Scaredy',
            imgSrc : 'img/22252709_010df3379e_z.jpg',
            imgAttribution : 'https://www.flickr.com/photos/kpjas/22252709'
        },
        {
            clickCount : 0,
            name : 'Shadow',
            imgSrc : 'img/1413379559_412a540d29_z.jpg',
            imgAttribution : 'https://www.flickr.com/photos/malfet/1413379559'
        },
        {
            clickCount : 0,
            name : 'Sleepy',
            imgSrc : 'img/9648464288_2516b35537_z.jpg',
            imgAttribution : 'https://www.flickr.com/photos/onesharp/9648464288'
        }
    ]
};

/* ======= Octopus ======= */

var octopus = {

    init: function() {
        // set our current cat to the first one in the list
        model.currentCat = model.cats[0];

        // tell our views to initialize
        catListView.init();
        catView.init();
        adminView.init();
    },

    getCurrentCat: function() {
        return model.currentCat;
    },

    getCats: function() {
        return model.cats;
    },

    // set the currently-selected cat to the object passed in
    setCurrentCat: function(cat) {
        model.currentCat = cat;
    },

    // increments the counter for the currently-selected cat
    incrementCounter: function() {
        model.currentCat.clickCount++;
        catView.render();
    }
};

/* ======= View ======= */

var catView = {

    init: function() {
        // store pointers to our DOM elements for easy access later
        this.catElem = document.getElementById('cat');
        this.catNameElem = document.getElementById('cat-name');
        this.catImageElem = document.getElementById('cat-img');
        this.countElem = document.getElementById('cat-count');

        // on click, increment the current cat's counter
        this.catImageElem.addEventListener('click', function(){
            octopus.incrementCounter();
        });

        // render this view (update the DOM elements with the right values)
        this.render();
    },

    render: function() {
        // update the DOM elements with values from the current cat
        var currentCat = octopus.getCurrentCat();
        this.countElem.textContent = currentCat.clickCount;
        this.catNameElem.textContent = currentCat.name;
        this.catImageElem.src = currentCat.imgSrc;
    }
};

var catListView = {

    init: function() {
        // store the DOM element for easy access later
        this.catListElem = document.getElementById('cat-list');

        // render this view (update the DOM elements with the right values)
        this.render();
    },

    render: function() {
        var cat, elem, i;
        // get the cats we'll be rendering from the octopus
        var cats = octopus.getCats();

        // empty the cat list
        this.catListElem.innerHTML = '';

        // loop over the cats
        for (i = 0; i < cats.length; i++) {
            // this is the cat we're currently looping over
            cat = cats[i];

            // make a new cat list item and set its text
            elem = document.createElement('li');
            elem.textContent = cat.name;

            // on click, setCurrentCat and render the catView
            // (this uses our closure-in-a-loop trick to connect the value
            //  of the cat variable to the click event function)
            elem.addEventListener('click', (function(catCopy) {
                return function() {
                    octopus.setCurrentCat(catCopy);
                    catView.render();
                };
            })(cat));

            // finally, add the element to the list
            this.catListElem.appendChild(elem);
        }
    }
};

var adminView = {

      init: function() {
        this.formElement = document.getElementById('admin-form');
        this.buttonAdmin = document.getElementById('admin-button');
        console.log(this);
        this.render();
      },

      render: function() {
        this.formElement.style.display = 'none';
        console.log(this);
        this.buttonAdmin.addEventListener('click', (function(form){
         return  form.style.display = 'block';
        })(this.formElement));
        console.log(this);
      }
};

// make it go!
octopus.init();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cat Clicker</title>
</head>
<body>
    <ul id="cat-list"></ul>
    <div id="cat">
        <h2 id="cat-name"></h2>
        <div id="cat-count"></div>
        <img id="cat-img" src="" alt="cute cat">
    </div>
    <div>
      <button type="button" id="admin-button">Admin</button>
    </div>
    <div id="admin-form">
      <p>Name</p>
      <input type="text" name="new-cat-name" value="">
      <p>Img URL</p>
      <input type="text" name="new-img-url" value="">
      <p># Count</p>
      <input type="text" name="new-count-number" value="">
      <br>
      <button type="button" name="save">Save</button>
      <button type="button" name="cancel">Cancel</button>
    </div>
    <script src="js/app.js"></script>
    <script>
  if(!document.getElementById('admin-button').active){
    document.getElementById('admin-form').style.display ='none';
  }
  </script>
</body>
</html></code>```

I don't understand why the form (#admin-form) is shown when the page is loaded, it should be shown only when the button (#admin-button) is clicked.

Update: I added the script to hide the form in HTML file.

答:
Here's your problem:

```<code>    this.buttonAdmin.addEventListener('click', (function(form){
      return  form.style.display = 'block';
    })(this.formElement));
</code>```

You wrap the handler function in parens and call it immediately. Try:

```<code>    this.buttonAdmin.addEventListener('click', function(){
      this.formElement.style.display = 'block';
    }.bind(this));
</code>```

Or, if you don't want to use bind for whatever reason:

```<code>    var form = this.formElement;
    this.buttonAdmin.addEventListener('click', function(){
      form.style.display = 'block';
    });
</code>```

Title: How to toggle a form through button?

Body:
I would like to show a form through button click in JS vanilla but nothing work. Here is my code

/* ======= Model ======= */

var model = {
    currentCat: null,
    cats: [
        {
            clickCount : 0,
            name : 'Tabby',
            imgSrc : 'img/434164568_fea0ad4013_z.jpg',
            imgAttribution : 'https://www.flickr.com/photos/bigtallguy/434164568'
        },
        {
            clickCount : 0,
            name : 'Tiger',
            imgSrc : 'img/4154543904_6e2428c421_z.jpg',
            imgAttribution : 'https://www.flickr.com/photos/xshamx/4154543904'
        },
        {
            clickCount : 0,
            name : 'Scaredy',
            imgSrc : 'img/22252709_010df3379e_z.jpg',
            imgAttribution : 'https://www.flickr.com/photos/kpjas/22252709'
        },
        {
            clickCount : 0,
            name : 'Shadow',
            imgSrc : 'img/1413379559_412a540d29_z.jpg',
            imgAttribution : 'https://www.flickr.com/photos/malfet/1413379559'
        },
        {
            clickCount : 0,
            name : 'Sleepy',
            imgSrc : 'img/9648464288_2516b35537_z.jpg',
            imgAttribution : 'https://www.flickr.com/photos/onesharp/9648464288'
        }
    ]
};

/* ======= Octopus ======= */

var octopus = {

    init: function() {
        // set our current cat to the first one in the list
        model.currentCat = model.cats[0];

        // tell our views to initialize
        catListView.init();
        catView.init();
        adminView.init();
    },

    getCurrentCat: function() {
        return model.currentCat;
    },

    getCats: function() {
        return model.cats;
    },

    // set the currently-selected cat to the object passed in
    setCurrentCat: function(cat) {
        model.currentCat = cat;
    },

    // increments the counter for the currently-selected cat
    incrementCounter: function() {
        model.currentCat.clickCount++;
        catView.render();
    }
};

/* ======= View ======= */

var catView = {

    init: function() {
        // store pointers to our DOM elements for easy access later
        this.catElem = document.getElementById('cat');
        this.catNameElem = document.getElementById('cat-name');
        this.catImageElem = document.getElementById('cat-img');
        this.countElem = document.getElementById('cat-count');

        // on click, increment the current cat's counter
        this.catImageElem.addEventListener('click', function(){
            octopus.incrementCounter();
        });

        // render this view (update the DOM elements with the right values)
        this.render();
    },

    render: function() {
        // update the DOM elements with values from the current cat
        var currentCat = octopus.getCurrentCat();
        this.countElem.textContent = currentCat.clickCount;
        this.catNameElem.textContent = currentCat.name;
        this.catImageElem.src = currentCat.imgSrc;
    }
};

var catListView = {

    init: function() {
        // store the DOM element for easy access later
        this.catListElem = document.getElementById('cat-list');

        // render this view (update the DOM elements with the right values)
        this.render();
    },

    render: function() {
        var cat, elem, i;
        // get the cats we'll be rendering from the octopus
        var cats = octopus.getCats();

        // empty the cat list
        this.catListElem.innerHTML = '';

        // loop over the cats
        for (i = 0; i < cats.length; i++) {
            // this is the cat we're currently looping over
            cat = cats[i];

            // make a new cat list item and set its text
            elem = document.createElement('li');
            elem.textContent = cat.name;

            // on click, setCurrentCat and render the catView
            // (this uses our closure-in-a-loop trick to connect the value
            //  of the cat variable to the click event function)
            elem.addEventListener('click', (function(catCopy) {
                return function() {
                    octopus.setCurrentCat(catCopy);
                    catView.render();
                };
            })(cat));

            // finally, add the element to the list
            this.catListElem.appendChild(elem);
        }
    }
};

var adminView = {

      init: function() {
        this.formElement = document.getElementById('admin-form');
        this.buttonAdmin = document.getElementById('admin-button');
        console.log(this);
        this.render();
      },

      render: function() {
        this.formElement.style.display = 'none';
        console.log(this);
        this.buttonAdmin.addEventListener('click', (function(form){
         return  form.style.display = 'block';
        })(this.formElement));
        console.log(this);
      }
};

// make it go!
octopus.init();

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Cat Clicker</title>

      <button type="button" id="admin-button">Admin</button>

Name

      <input type="text" name="new-cat-name" value="">

Img URL

      <input type="text" name="new-img-url" value="">

# Count

      <input type="text" name="new-count-number" value="">

      <button type="button" name="save">Save</button>
      <button type="button" name="cancel">Cancel</button>

I don't understand why the form (#admin-form) is shown when the page is loaded, it should be shown only when the button (#admin-button) is clicked.

Update: I added the script to hide the form in HTML file.

Body:
Here's your problem:

    this.buttonAdmin.addEventListener('click', (function(form){
      return  form.style.display = 'block';
    })(this.formElement));

You wrap the handler function in parens and call it immediately. Try:

    this.buttonAdmin.addEventListener('click', function(){
      this.formElement.style.display = 'block';
    }.bind(this));

Or, if you don't want to use bind for whatever reason:

    var form = this.formElement;
    this.buttonAdmin.addEventListener('click', function(){
      form.style.display = 'block';
    });


问:
How to create a square dataframe/matrix given 3 columns - Python
I am struggling to figure out how to develop a square matrix given a format like

```<code>a a 0
a b 3
a c 4
a d 12
b a 3
b b 0
b c 2
...
</code>```

To something like:

```<code>  a b c d e
a 0 3 4 12 ...
b 3 0 2 7 ...
c 4 3 0 .. .
d 12 ...
e . ..
</code>```

in pandas. I developed a method which I thinks works but takes forever to run because it has to iterate through each column and row for every value starting from the beginning each time using for loops. I feel like I'm definitely reinventing the wheel here. This also isnt realistic for my dataset given how many columns and rows there are. Is there something similar to R's cast function in python which can do this significantly faster?

答:
You could use df.pivot:

```<code>import pandas as pd

df = pd.DataFrame([['a', 'a', 0],
                   ['a', 'b', 3],
                   ['a', 'c', 4],
                   ['a', 'd', 12],
                   ['b', 'a', 3],
                   ['b', 'b', 0],
                   ['b', 'c', 2]], columns=['X','Y','Z'])

print(df.pivot(index='X', columns='Y', values='Z'))
</code>```

yields

```<code>Y    a    b    c     d
X
a  0.0  3.0  4.0  12.0
b  3.0  0.0  2.0   NaN
</code>```

Here, index='X' tells df.pivot to use the column labeled 'X' as the index, and columns='Y' tells it to use the column labeled 'Y' as the column index.

See the docs for more on pivot and other reshaping methods.

Alternatively, you could use pd.crosstab:

```<code>print(pd.crosstab(index=df.iloc[:,0], columns=df.iloc[:,1],
                  values=df.iloc[:,2], aggfunc='sum'))
</code>```

Unlike df.pivot which expects each (a1, a2) pair to be unique, pd.crosstab
(with agfunc='sum') will aggregate duplicate pairs by summing the associated
values. Although there are no duplicate pairs in your posted example, specifying
how duplicates are supposed to be aggregated is required when the values
parameter is used.

Also, whereas df.pivot is passed column labels, pd.crosstab is passed
array-likes (such as whole columns of df). df.iloc[:, i] is the ith column
of df.

Body:
I am struggling to figure out how to develop a square matrix given a format like

a a 0
a b 3
a c 4
a d 12
b a 3
b b 0
b c 2
...

To something like:

  a b c d e
a 0 3 4 12 ...
b 3 0 2 7 ...
c 4 3 0 .. .
d 12 ...
e . ..

in pandas. I developed a method which I thinks works but takes forever to run because it has to iterate through each column and row for every value starting from the beginning each time using for loops. I feel like I'm definitely reinventing the wheel here. This also isnt realistic for my dataset given how many columns and rows there are. Is there something similar to R's cast function in python which can do this significantly faster?

Body:
You could use df.pivot:

import pandas as pd

df = pd.DataFrame([['a', 'a', 0],
                   ['a', 'b', 3],
                   ['a', 'c', 4],
                   ['a', 'd', 12],
                   ['b', 'a', 3],
                   ['b', 'b', 0],
                   ['b', 'c', 2]], columns=['X','Y','Z'])

print(df.pivot(index='X', columns='Y', values='Z'))

yields

Y    a    b    c     d
X
a  0.0  3.0  4.0  12.0
b  3.0  0.0  2.0   NaN

Here, index='X' tells df.pivot to use the column labeled 'X' as the index, and columns='Y' tells it to use the column labeled 'Y' as the column index.

See the docs for more on pivot and other reshaping methods.

Alternatively, you could use pd.crosstab:

print(pd.crosstab(index=df.iloc[:,0], columns=df.iloc[:,1],
                  values=df.iloc[:,2], aggfunc='sum'))

Unlike df.pivot which expects each (a1, a2) pair to be unique, pd.crosstab
(with agfunc='sum') will aggregate duplicate pairs by summing the associated
values. Although there are no duplicate pairs in your posted example, specifying
how duplicates are supposed to be aggregated is required when the values
parameter is used.

Also, whereas df.pivot is passed column labels, pd.crosstab is passed
array-likes (such as whole columns of df). df.iloc[:, i] is the ith column
of df.


问:
External Play Pause Button Swap SVG & Text on State Change
I have an external button below the playback window used to toggle play and pause, which has a CSS SVG background image with the following code, works great:

```<code><a onclick="jwplayer().play();" class="jwp-btn jwp-btn-icon-pl">Play</a>
</code>```

What I want to do is a state change, so that if the "> Play" is displayed on the button, and the user clicks the button to play, that the SVG, and text swaps to "|| Pause" (using a different SVG and text). And then reverses back if the button is clicked again.

I suspect that this will use JavaScript (which I'm OK with, jQuery is OK too), and jwplayer().on('play') and jwplayer().on('pause') event triggers. The SVG icon does not have to be in CSS.

But I'm at a loss as to how to achieve this.

Here's the player code (using a playlist as well):

```<code><script>
              var playerInstance = jwplayer("containerpreview");
                playerInstance.setup({
                  //file: "//content.jwplatform.com/videos/12345.mp4",
                  //image: "//content.jwplatform.com/thumbs23456.jpg",
                  //playlist: "//content.jwplatform.com/feeds/123.rss",
                  playlist: "//cdn.jwplayer.com/v2/playlists/222?format=mrss",
                  displaytitle: false,
                  width: "100%",
                  aspectratio: "16:9"
                });

                var list = document.getElementById("list");
                var html = list.innerHTML;

                playerInstance.on('ready',function(){
                var playlist = playerInstance.getPlaylist();
                for (var index=0;index<playlist.length;index++){
                var playindex = index +1;
                html += "<li><span class='dropt' title='"+playlist[index].title+"'><a href='javascript:playThis("+index+")'><img height='75' width='120' src='" + playlist[index].image + "'</img></br>"+playlist[index].title+"</a></br><span style='width:500px;'</span></span></li>"
                list.innerHTML = html;
                }

                });

                function playThis(index) {
                playerInstance.playlistItem(index);
                }

              </script>
</code>```

答:
You didn't provide any HTML, Js code about your file (just a single a tag is not enough), but this will give you an idea about how you can do this:

js/jQuery:

```<code> jwplayer("containerpreview").on('play', function(){
      $('.jwp-btn').empty().html("Your (Pause)SVG Element");
 });

 jwplayer("containerpreview").on('pause', function(){
      $('.jwp-btn').empty().html("Your (Play)SVG Element");
 });
</code>```

Body:
I have an external button below the playback window used to toggle play and pause, which has a CSS SVG background image with the following code, works great:

Play

What I want to do is a state change, so that if the "> Play" is displayed on the button, and the user clicks the button to play, that the SVG, and text swaps to "|| Pause" (using a different SVG and text). And then reverses back if the button is clicked again.

I suspect that this will use JavaScript (which I'm OK with, jQuery is OK too), and jwplayer().on('play') and jwplayer().on('pause') event triggers. The SVG icon does not have to be in CSS.

But I'm at a loss as to how to achieve this.

Here's the player code (using a playlist as well):

Body:
You didn't provide any HTML, Js code about your file (just a single a tag is not enough), but this will give you an idea about how you can do this:

js/jQuery:

 jwplayer("containerpreview").on('play', function(){
      $('.jwp-btn').empty().html("Your (Pause)SVG Element");
 });

 jwplayer("containerpreview").on('pause', function(){
      $('.jwp-btn').empty().html("Your (Play)SVG Element");
 });


问:
How to get value from a multi-array?
I want to get a specific value of a variable from multi array, if the condition matches.

When I print my array:

```<code>print_r($myarray);
</code>```

gives array like this:

```<code>Array
(
  [0] => Array
   (
     [id] => 21 //check for this value
     [customer_id] => 12456 //get this value
     [date] => 12-06-2017
   )
  [1] => Array
   (
     [id] => 15
     [customer_id] => 12541
     [date] => 12-06-2017
   )
  [2] => Array
   (
     [id] => 12
     [customer_id] => 25415
     [date] => 12-06-2017
   )
)
</code>```

I am trying to get customer number if the ID matches with 21

```<code>foreach ($myarray as $array){
  if($array[][id] == "21"){ //this is where I'm making mistake
    $cust_id = $myarray[]['customer_id'];
    return $cust_id;
  }
}
</code>```

答:
You can create a custom function and call it, like this

```<code>function arraySearch($theArray, $searchKey, $searchValue, $returnKey){

    foreach($theArray as $value){
            if($value[$searchKey] == $searchValue)  return $value[$returnKey]; //found, return the value of the choosen $returnKey var
    }

     return false; //not found, so return false

}
</code>```

and then use it

```<code>echo arraySearch($myarray, 'id', '21', 'customer_id'); // it returns 12456
</code>```

EXAMPLE

Title: How to get value from a multi-array?

Body:
I want to get a specific value of a variable from multi array, if the condition matches.

When I print my array:

print_r($myarray);

gives array like this:

Array
(
  [0] => Array
   (
     [id] => 21 //check for this value
     [customer_id] => 12456 //get this value
     [date] => 12-06-2017
   )
  [1] => Array
   (
     [id] => 15
     [customer_id] => 12541
     [date] => 12-06-2017
   )
  [2] => Array
   (
     [id] => 12
     [customer_id] => 25415
     [date] => 12-06-2017
   )
)

I am trying to get customer number if the ID matches with 21

foreach ($myarray as $array){
  if($array[][id] == "21"){ //this is where I'm making mistake
    $cust_id = $myarray[]['customer_id'];
    return $cust_id;
  }
}

Body:
You can create a custom function and call it, like this

function arraySearch($theArray, $searchKey, $searchValue, $returnKey){

    foreach($theArray as $value){
            if($value[$searchKey] == $searchValue)  return $value[$returnKey]; //found, return the value of the choosen $returnKey var
    }

     return false; //not found, so return false

}

and then use it

echo arraySearch($myarray, 'id', '21', 'customer_id'); // it returns 12456

EXAMPLE


问:
Add EventListener to dynamic child angular
I want to add an eventListener on my childEvent but i don't know how to do.

I'm dynamically creating components inside SchemaExploitationComponent using the ViewContainerRef.createComponent() method, which returns a ComponentRef object.

I need to dynamically add an event listener to this component so it will call  the ajouterEvenement method defined inside SchemaExploitationComponent.

Parent Class :

```<code>@Component({
  selector: 'app-schema-exploitation',
  template: ` <div #parent (evenement)="ajouterEvenement($event)"></div> `
  styleUrls: ['./schema-exploitation.component.css']
})
export class SchemaExploitationComponent implements OnInit {

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild('parent', { read: ViewContainerRef }) container: ViewContainerRef;

  ajouterEvenement(evenement) {
    console.log(evenement);
  }

  ouvrirModal(evenement: string) {

    if (evenement == "Alarme")
    {
      let comp:ComponentFactory<RegroupementAlarmeComponent> = this._cfr.resolveComponentFactory(RegroupementAlarmeComponent);
      var alarmeComponent = this.container.createComponent(comp);
      alarmeComponent.instance._ref = alarmeComponent;

    }
    if (evenement == "Appel Client")
    {
     // here dynamic component created

     let comp:ComponentFactory<RegroupementAppelClientComponent> = this._cfr.resolveComponentFactory(RegroupementAppelClientComponent);
      let appelClientComponent = this.container.createComponent(comp);
      appelClientComponent.instance._ref = appelClientComponent;
    }
    if (evenement == "TD")
    {

      let comp:ComponentFactory<RegroupementTdComponent> = this._cfr.resolveComponentFactory(RegroupementTdComponent);
      var tdComponent = this.container.createComponent(comp);
      tdComponent.instance._ref = tdComponent;
    }
  }

  constructor(
    protected schema: SchemaExploitationService,
    protected route: ActivatedRoute,
    private _cfr: ComponentFactoryResolver
  ) {}

  ngOnInit() {

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

Dynamic child class :

```<code>@Component({
  selector: 'app-regroupement-alarme',
  template: `
             <buttontype="button" label="Valider" (click)="ajouterAlarme()"></button>
  `,
  styleUrls: ['./regroupement-alarme.component.css']
})
export class RegroupementAlarmeComponent implements OnInit {

  @Output() evenement = new EventEmitter<Alarme>();
  _ref:any;
  alarme:Alarme = new Alarme();

  removeObject()
  {
    this._ref.destroy();
  }
  ajouterAlarme()
  {
    this.evenement.emit(this.alarme);
    this.removeObject();
  }

  constructor() { }

  ngOnInit() {
  }

}
</code>```

I want to pass the object "Alarme" from my child component to my parentComponent using an EventEmmitter but it's like my parent don't listen to my event.

答:
Have you tried this ?

```<code>  alarmeObjectFromChild: any;

  ouvrirModal(evenement: string) {

    if (evenement == "Alarme")
    {
      let comp:ComponentFactory<RegroupementAlarmeComponent> = this._cfr.resolveComponentFactory(RegroupementAlarmeComponent);
      var alarmeComponent = this.container.createComponent(comp);
      alarmeComponent.instance.evenement.subscribe((alarmeObjectYouWant) => {
        this.alarmeObjectFromChild = alarmeObjectYouWant;
        //do whatever you want
      })
      alarmeComponent.instance._ref = alarmeComponent;

    }
  }
</code>```

Here you have github repo for the solution https://github.com/solenski/stackoverflow47683459.git

Body:
I want to add an eventListener on my childEvent but i don't know how to do.

I'm dynamically creating components inside SchemaExploitationComponent using the ViewContainerRef.createComponent() method, which returns a ComponentRef object.

I need to dynamically add an event listener to this component so it will call  the ajouterEvenement method defined inside SchemaExploitationComponent.

Parent Class :

@Component({
  selector: 'app-schema-exploitation',
  template: ` <div #parent (evenement)="ajouterEvenement($event)"></div> `
  styleUrls: ['./schema-exploitation.component.css']
})
export class SchemaExploitationComponent implements OnInit {

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild('parent', { read: ViewContainerRef }) container: ViewContainerRef;

  ajouterEvenement(evenement) {
    console.log(evenement);
  }

  ouvrirModal(evenement: string) {

    if (evenement == "Alarme")
    {
      let comp:ComponentFactory<RegroupementAlarmeComponent> = this._cfr.resolveComponentFactory(RegroupementAlarmeComponent);
      var alarmeComponent = this.container.createComponent(comp);
      alarmeComponent.instance._ref = alarmeComponent;

    }
    if (evenement == "Appel Client")
    {
     // here dynamic component created

     let comp:ComponentFactory<RegroupementAppelClientComponent> = this._cfr.resolveComponentFactory(RegroupementAppelClientComponent);
      let appelClientComponent = this.container.createComponent(comp);
      appelClientComponent.instance._ref = appelClientComponent;
    }
    if (evenement == "TD")
    {

      let comp:ComponentFactory<RegroupementTdComponent> = this._cfr.resolveComponentFactory(RegroupementTdComponent);
      var tdComponent = this.container.createComponent(comp);
      tdComponent.instance._ref = tdComponent;
    }
  }

  constructor(
    protected schema: SchemaExploitationService,
    protected route: ActivatedRoute,
    private _cfr: ComponentFactoryResolver
  ) {}

  ngOnInit() {

    });
  }
}

Dynamic child class :

@Component({
  selector: 'app-regroupement-alarme',
  template: `
             <buttontype="button" label="Valider" (click)="ajouterAlarme()"></button>
  `,
  styleUrls: ['./regroupement-alarme.component.css']
})
export class RegroupementAlarmeComponent implements OnInit {

  @Output() evenement = new EventEmitter<Alarme>();
  _ref:any;
  alarme:Alarme = new Alarme();

  removeObject()
  {
    this._ref.destroy();
  }
  ajouterAlarme()
  {
    this.evenement.emit(this.alarme);
    this.removeObject();
  }

  constructor() { }

  ngOnInit() {
  }

}

I want to pass the object "Alarme" from my child component to my parentComponent using an EventEmmitter but it's like my parent don't listen to my event.

Body:
Have you tried this ?

  alarmeObjectFromChild: any;

  ouvrirModal(evenement: string) {

    if (evenement == "Alarme")
    {
      let comp:ComponentFactory<RegroupementAlarmeComponent> = this._cfr.resolveComponentFactory(RegroupementAlarmeComponent);
      var alarmeComponent = this.container.createComponent(comp);
      alarmeComponent.instance.evenement.subscribe((alarmeObjectYouWant) => {
        this.alarmeObjectFromChild = alarmeObjectYouWant;
        //do whatever you want
      })
      alarmeComponent.instance._ref = alarmeComponent;

    }
  }

Here you have github repo for the solution https://github.com/solenski/stackoverflow47683459.git


问:
Lua : Fetch a webpage
I want to fetch a webpage and get the result in a string, but I don't know how to do it. I search online and didn't find how to do it.</p>

答:
if you don't have socket (like me), but you have the http library/module, then you could try this:

```<code>http.get("https://nodemcu.readthedocs.io/en/master/en/modules/http/", nil, function(code, data)
    if (code ~= 200) then
        print("HTTP request failed")
    else
        print(code, data)
    end
end)
</code>```

it works for me

you can find more info in the docs https://nodemcu.readthedocs.io/en/master/en/modules/http/#httpget

Title: Lua : Fetch a webpage

Body:
if you don't have socket (like me), but you have the http library/module, then you could try this:

http.get("https://nodemcu.readthedocs.io/en/master/en/modules/http/", nil, function(code, data)
    if (code ~= 200) then
        print("HTTP request failed")
    else
        print(code, data)
    end
end)

it works for me

you can find more info in the docs https://nodemcu.readthedocs.io/en/master/en/modules/http/#httpget


问:
How to resize a Windows 10 window and ignore the transparent border?
Our 3d application window needs to cover the whole desktop of the user, including the task bar (not resizable, not maximized, not full screen as seen in video games, just a window with the [X] in the top-right corner, the title bar, and the status bar).

To achieve this, we used the following code:

```<code>void
CTheApp::SetFullScreenMode()
{
  HWND hwnd = getHandle();

  long style = ::GetWindowLong(hwnd, GWL_STYLE);
  style &= ~(WS_MAXIMIZEBOX|WS_MINIMIZEBOX|WS_THICKFRAME);
  ::SetWindowLong(hwnd, GWL_STYLE, style);

  // get screen dimensions
  int width  = ::GetSystemMetrics(SM_CXSCREEN);
  int height = ::GetSystemMetrics(SM_CYSCREEN);

  ::MoveWindow(hwnd, 0, 0, width, height, TRUE);
}
</code>```

It worked for our needs... until Windows 10 arrived.

With Windows 10, there is a small gap on the left, right and bottom that the window does not cover. (More precisely: 9 pixels on the left, 9 pixels on the right, and 9 pixels on the bottom.)

It seems that Windows 10 adds this transparent style to the border of non-maximized windows.

How could I make it so that the window would stretch visually correctly on the whole screen in Windows 10 (leave no apparent gap), while keeping the feature valid for previous versions of Windows (Windows 7 - Windows 8.1)? Is there a clean way to set this "transparency" to zero?

I thought about hacking it and expanding the sizes by 9 pixels on each side, but this could cause issues when the user has another Theme set up (e.g. High contrast), or when the app will be using multiple windows on multiple monitors.

答: This is handled by the Desktop Window Manager and can be overridden. The chief step is WM_NCCALCSIZE (window message, non client) which you override to return 0,0</p>

Body:
Our 3d application window needs to cover the whole desktop of the user, including the task bar (not resizable, not maximized, not full screen as seen in video games, just a window with the [X] in the top-right corner, the title bar, and the status bar).

To achieve this, we used the following code:

void
CTheApp::SetFullScreenMode()
{
  HWND hwnd = getHandle();

  long style = ::GetWindowLong(hwnd, GWL_STYLE);
  style &= ~(WS_MAXIMIZEBOX|WS_MINIMIZEBOX|WS_THICKFRAME);
  ::SetWindowLong(hwnd, GWL_STYLE, style);

  // get screen dimensions
  int width  = ::GetSystemMetrics(SM_CXSCREEN);
  int height = ::GetSystemMetrics(SM_CYSCREEN);

  ::MoveWindow(hwnd, 0, 0, width, height, TRUE);
}

It worked for our needs... until Windows 10 arrived.

With Windows 10, there is a small gap on the left, right and bottom that the window does not cover. (More precisely: 9 pixels on the left, 9 pixels on the right, and 9 pixels on the bottom.)

It seems that Windows 10 adds this transparent style to the border of non-maximized windows.

How could I make it so that the window would stretch visually correctly on the whole screen in Windows 10 (leave no apparent gap), while keeping the feature valid for previous versions of Windows (Windows 7 - Windows 8.1)? Is there a clean way to set this "transparency" to zero?

I thought about hacking it and expanding the sizes by 9 pixels on each side, but this could cause issues when the user has another Theme set up (e.g. High contrast), or when the app will be using multiple windows on multiple monitors.


问:
Select root element of a transclusion in a component with multiple transclusions
I am writing components to help with implementing Semantic-UI elements. My template for the 'card' element contains several <ng-content> elements used for transclusion of specific sections of the card. Due to the specifics of Semantic-UI's CSS, I wish to apply class names to the root elements of some of the transclusions. I have tried using a wrapper element with the class assigned but that causes some bugs in the child elements due to incorrect nesting for the CSS rules.

The component template at this time:

```<code><div class="image" *ngIf="image">
  <img src="{{image}}">
</div>
<div class="content">
  <ng-content select="[card-title]"></ng-content>
  <div class="meta">
    <ng-content select="[card-subtitle]"></ng-content>
  </div>
  <div class="description">
    <ng-content select="[card-content]"></ng-content>
  </div>
</div>
<div class="extra content">
  <ng-content select="[card-extra]"></ng-content>
</div>
<ng-content></ng-content>
</code>```

Ideally, I want something closer to this but understand that you cannot just assign class names to <ng-content>:

```<code><div class="image" *ngIf="image">
  <img src="{{image}}">
</div>
<div class="content">
  <ng-content select="[card-title]"></ng-content>
  <ng-content select="[card-subtitle]" class="meta"></ng-content>
  <ng-content select="[card-content]" class="description"></ng-content>
</div>
<ng-content select="[card-extra]" class="extra content"></ng-content>
<ng-content></ng-content>
</code>```

Is there any way I can select the root element of what replaces [card-subtitle] so that I can then add the class "meta" to it? I've seen a couple of answers but they assume you only have a single <ng-content> element.

答:
You can get a reference of each content child with the @ContentChild decorator and then use something like Renderer2 to add a class to each corresponding nativeElement. Notice however, that you have to pass a component or directive to the @ContentChild decorator, so this will only work if card-title, for example, is a selector for let's say  SemanticUiCardTitleDirective and also you need a reference to the native element, so you have to set the read property to ElementRef.

So, inside your component:

```<code>import { AfterContentInit, Component, ElementRef, Renderer2 } from '@angular/core';
import { SemanticUiCardTitleDirective, //...etc } from 'path/to/directives';

@Component({..})
export class SomeComponent implements AfterContentInit {
  @ContentChild(SemanticUiCardTitleDirective, { read: ElementRef })
  cardTitle: ElementRef;

  constructor(private renderer: Renderer2) {}

  ngAfterContentInit() {
    this.renderer.addClass(this.cardTitle.nativeElement, 'some-class');
  }
}
</code>```

Body:
I am writing components to help with implementing Semantic-UI elements. My template for the 'card' element contains several <ng-content> elements used for transclusion of specific sections of the card. Due to the specifics of Semantic-UI's CSS, I wish to apply class names to the root elements of some of the transclusions. I have tried using a wrapper element with the class assigned but that causes some bugs in the child elements due to incorrect nesting for the CSS rules.

The component template at this time:

  <ng-content select="[card-title]"></ng-content>

    <ng-content select="[card-subtitle]"></ng-content>

    <ng-content select="[card-content]"></ng-content>

  <ng-content select="[card-extra]"></ng-content>

<ng-content></ng-content>

Ideally, I want something closer to this but understand that you cannot just assign class names to <ng-content>:

  <ng-content select="[card-title]"></ng-content>
  <ng-content select="[card-subtitle]" class="meta"></ng-content>
  <ng-content select="[card-content]" class="description"></ng-content>

<ng-content select="[card-extra]" class="extra content"></ng-content>
<ng-content></ng-content>

Is there any way I can select the root element of what replaces [card-subtitle] so that I can then add the class "meta" to it? I've seen a couple of answers but they assume you only have a single <ng-content> element.

Body:
You can get a reference of each content child with the @ContentChild decorator and then use something like Renderer2 to add a class to each corresponding nativeElement. Notice however, that you have to pass a component or directive to the @ContentChild decorator, so this will only work if card-title, for example, is a selector for let's say  SemanticUiCardTitleDirective and also you need a reference to the native element, so you have to set the read property to ElementRef.

So, inside your component:

import { AfterContentInit, Component, ElementRef, Renderer2 } from '@angular/core';
import { SemanticUiCardTitleDirective, //...etc } from 'path/to/directives';

@Component({..})
export class SomeComponent implements AfterContentInit {
  @ContentChild(SemanticUiCardTitleDirective, { read: ElementRef })
  cardTitle: ElementRef;

  constructor(private renderer: Renderer2) {}

  ngAfterContentInit() {
    this.renderer.addClass(this.cardTitle.nativeElement, 'some-class');
  }
}


问:
Is a DOM Text Node guaranteed to not be interpreted as HTML?
Does anyone know whether a DOM Node of type Text is guaranteed not be interpreted as HTML by the browser?

More details follow.

Background

I'm building a simple web comment system for a friend, and I've been thinking about XSS attacks.  I don't think filtering or escaping HTML tags is a very elegant solution--it's too easy to come up with a convolution that will slip past the filter.  The fundamental issue is that I want to guarantee that, for certain pieces of content (i.e. the content that random unauthenticated web users POST), the browser never tries to interpret or run the content.

A plain(text) start

The first thought that came to mind is just to use Content-Type: text/plain, but this has to apply to a whole page.  You can put a plaintext IFRAME in the middle of a page, but it's ugly, and it creates focus problems if the user clicks into the frame.

innerText/textContent/JQuery

It turns out that there are some browser-specific (innerText in IE, textContent in FF, Safari, etc.) attributes that, when set, are required to create a single Text node.

JQuery tries to avoid the difference in browser-specific attributes, by implementing a single function text(val) that skips the browser-specific attributes and goes directly to document.createTextNode(text), which, as you can guess, creates a Text node.

W3 DOM Text Nodes

So I think this is close to what I want, it looks good--Text nodes can't have children, and it appears like they can't be interpreted as HTML.  But I am not 100% sure from the official docs.

Interface Node: http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-1950641247

Interface Text: http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-1312295772

textContent: http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-textContent

The part from textContent is particularly encouraging, because it says "on setting, no parsing is performed either, the input string is taken as pure textual content."  But is this fundamental to all Text nodes, or only nodes on which you set textContent?  This probably seems like a dumb quibble, but it might be important because IE doesn't support textContent (see above).

Back around to the initial question

Can anyone confirm/reject that this will work?  That is, that a w3 DOM compliant browser will never interpret a Text node as HTML, no matter what the content?  I'd be extremely grateful to have this tormenting little uncertainty resolved.

Thank you for your time!

答: Yes, this is confirmed, to the extent that for what ever browser it wasn't, that browser would have a serious defect. A text node that rendered anything but text would be a contradiction. By using document.createTextNode("some string"); and appending that node, the string is guaranteed to be rendered as text.

OwnerDisplayName: Zach


问:
In Laravel 5, how do you dump variables on vue enabled templates?
Prior to vue being part of Laravel, I would often debug by simply using {{ dump($var) }}

Doing so now throws an exception within javascript as Vue doesn't like

答:
You can try {{ var_dump($variable) }}

If you are just looking to see the contents of the variables you are working with you can use the PHP functions var_dump() instead of dump(). It's not styled in the same sleek way that dump() is and you can't collapse or expand sections like you can with dump(). But it will dump the data you need without messing with your Vue code.

{{ dump($variable) }} without Vue:

{{ var_dump($variable) }} with or without Vue:


问:
Distinct sum of values in Tableau
I have a data with columns called Brand, Market and Target. The Brand having members like A, B, C & D repeats across 2 kinds of Market - OPL and CPL. So the Target for each of Brand and Market also repeats in column Target, as in below image:

All I would want is to get sum of Target for each of Brand at OPL (highlighted in orange) and sum of Target for each of Brand at CPL (highlighted in yellow)

So sum for OPL should be 10000 + 7000 + 4000 + 9000 = 30000
and sum for CPL should be 5000 + 2000 + 8000 + 3000 = 18000

I used a logic like

IF [Market] = 'OPL' THEN
{FIXED [Brand]+[Market] : MIN([Target])}
END

Image as below:

which gave me total of target at OPL which is 58000, which is not the one I wanted. Please help me with correct calculation, do let me know for any further details.

答:
Try this:

```<code>SUM( { FIXED [Brand], [Market]: AVG(Target) } )
</code>```

Averaging within each Market and Brand will eliminate the duplicates in your sum.

Title: Distinct sum of values in Tableau

Body:
Try this:

SUM( { FIXED [Brand], [Market]: AVG(Target) } )

Averaging within each Market and Brand will eliminate the duplicates in your sum.


问:
JADE Agent doesn't added to Agents list
i want to run a simple agent in JADE environment(Mac OSX El Capitan, Jade 4.4.0), this is my Agent code:

```<code>public class BookBuyerAgent extends Agent {
    protected void setup() {
        // Printout a welcome message
        System.out.println("Hello World! My name is "+getLocalName());

    }
}
</code>```

i set CLASSPATH in bash_profile like this:

```<code>export CLASSPATH=/Users/John/jade/lib/jade.jar:/Users/John/jade/lib/jadeExamples.jar:/Users/John/jade/lib/commons-codec/commons-codec-1.3.jar:/Users/John/jade/src/jade/:/Users/John/Desktop/
</code>```

Im running my agent like this:

```<code>java  jade.Boot -gui -agents buyer:com.app.jade.BookBuyerAgent
</code>```

but i get this warning:

```<code>WARNING: Automatic main-detection mechanism initialization failed (Error setting up multicast socket - Caused by:  Can't assign requested address). Mechanism disabled!
</code>```

an then this error:

```<code>SEVERE: Cannot create agent buyer: Class com.app.jade.BookBuyerAgent for agent ( agent-identifier :name buyer@192.168.1.4:1099/JADE ) not found - Caused by:  com.app.jade.BookBuyerAgent
</code>```

and after that, Jade GUI appears but my agent does not added to agents list and it doesn't work. i checked everything but i don't know what's the problem.

this is full message i get:

```<code>Feb 27, 2016 4:14:59 PM jade.core.Runtime beginContainer
INFO: ----------------------------------
    This is JADE 4.4.0 - revision 6778 of 21-12-2015 12:24:43
    downloaded in Open Source, under LGPL restrictions,
    at http://jade.tilab.com/
----------------------------------------
Feb 27, 2016 4:14:59 PM jade.imtp.leap.LEAPIMTPManager initialize
INFO: Listening for intra-platform commands on address:
- jicp://192.168.1.4:1099

Feb 27, 2016 4:14:59 PM jade.core.AgentContainerImpl init
WARNING: Automatic main-detection mechanism initialization failed (Error setting up multicast socket - Caused by:  Can't assign requested address). Mechanism disabled!
Feb 27, 2016 4:15:01 PM jade.core.BaseService init
INFO: Service jade.core.management.AgentManagement initialized
Feb 27, 2016 4:15:01 PM jade.core.BaseService init
INFO: Service jade.core.messaging.Messaging initialized
Feb 27, 2016 4:15:01 PM jade.core.BaseService init
INFO: Service jade.core.resource.ResourceManagement initialized
Feb 27, 2016 4:15:01 PM jade.core.BaseService init
INFO: Service jade.core.mobility.AgentMobility initialized
Feb 27, 2016 4:15:01 PM jade.core.BaseService init
INFO: Service jade.core.event.Notification initialized
Feb 27, 2016 4:15:31 PM jade.mtp.http.HTTPServer <init>
INFO: HTTP-MTP Using XML parser com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser
Feb 27, 2016 4:15:31 PM jade.core.messaging.MessagingService boot
INFO: MTP addresses:
http://192.168.1.4:7778/acc
Feb 27, 2016 4:15:31 PM jade.core.AgentContainerImpl startBootstrapAgents
SEVERE: Cannot create agent buyer: Class com.app.jade.BookBuyerAgent for agent ( agent-identifier :name buyer@192.168.1.4:1099/JADE ) not found - Caused by:  com.app.jade.BookBuyerAgent
Feb 27, 2016 4:15:31 PM jade.core.AgentContainerImpl joinPlatform
INFO: --------------------------------------
Agent container Main-Container@192.168.1.4 is ready.
</code>```

答:
I am not sure if I understood the issue, but for the warning, here what I've found:
This warning tells that the automatic main detection mechanism (i.e. the mechanism by means of which a peripheral container is able to automatically discover where the Main Container is running) is disabled since the underlying network stack does not support IP-multicast (this is always the case for instance when you work on a Windows XP PC not connected to the network).
Provided that, when starting a peripheral container you explicitly specify the host and port of the Main Container (when different from the default ones), you can forget about this warning.

For deploying agents (Assuming there is a container deployed)

java  jade.Boot -container -host localhost -agents buyer:com.app.jade.BookBuyerAgent```

Title: JADE Agent doesn't added to Agents list

Body:
i want to run a simple agent in JADE environment(Mac OSX El Capitan, Jade 4.4.0), this is my Agent code:

public class BookBuyerAgent extends Agent {
    protected void setup() {
        // Printout a welcome message
        System.out.println("Hello World! My name is "+getLocalName());

    }
}

i set CLASSPATH in bash_profile like this:

export CLASSPATH=/Users/John/jade/lib/jade.jar:/Users/John/jade/lib/jadeExamples.jar:/Users/John/jade/lib/commons-codec/commons-codec-1.3.jar:/Users/John/jade/src/jade/:/Users/John/Desktop/

Im running my agent like this:

java  jade.Boot -gui -agents buyer:com.app.jade.BookBuyerAgent

but i get this warning:

WARNING: Automatic main-detection mechanism initialization failed (Error setting up multicast socket - Caused by:  Can't assign requested address). Mechanism disabled!

an then this error:

SEVERE: Cannot create agent buyer: Class com.app.jade.BookBuyerAgent for agent ( agent-identifier :name buyer@192.168.1.4:1099/JADE ) not found - Caused by:  com.app.jade.BookBuyerAgent

and after that, Jade GUI appears but my agent does not added to agents list and it doesn't work. i checked everything but i don't know what's the problem.

this is full message i get:

Feb 27, 2016 4:14:59 PM jade.core.Runtime beginContainer
INFO: ----------------------------------
    This is JADE 4.4.0 - revision 6778 of 21-12-2015 12:24:43
    downloaded in Open Source, under LGPL restrictions,
    at http://jade.tilab.com/
----------------------------------------
Feb 27, 2016 4:14:59 PM jade.imtp.leap.LEAPIMTPManager initialize
INFO: Listening for intra-platform commands on address:
- jicp://192.168.1.4:1099

Feb 27, 2016 4:14:59 PM jade.core.AgentContainerImpl init
WARNING: Automatic main-detection mechanism initialization failed (Error setting up multicast socket - Caused by:  Can't assign requested address). Mechanism disabled!
Feb 27, 2016 4:15:01 PM jade.core.BaseService init
INFO: Service jade.core.management.AgentManagement initialized
Feb 27, 2016 4:15:01 PM jade.core.BaseService init
INFO: Service jade.core.messaging.Messaging initialized
Feb 27, 2016 4:15:01 PM jade.core.BaseService init
INFO: Service jade.core.resource.ResourceManagement initialized
Feb 27, 2016 4:15:01 PM jade.core.BaseService init
INFO: Service jade.core.mobility.AgentMobility initialized
Feb 27, 2016 4:15:01 PM jade.core.BaseService init
INFO: Service jade.core.event.Notification initialized
Feb 27, 2016 4:15:31 PM jade.mtp.http.HTTPServer <init>
INFO: HTTP-MTP Using XML parser com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser
Feb 27, 2016 4:15:31 PM jade.core.messaging.MessagingService boot
INFO: MTP addresses:
http://192.168.1.4:7778/acc
Feb 27, 2016 4:15:31 PM jade.core.AgentContainerImpl startBootstrapAgents
SEVERE: Cannot create agent buyer: Class com.app.jade.BookBuyerAgent for agent ( agent-identifier :name buyer@192.168.1.4:1099/JADE ) not found - Caused by:  com.app.jade.BookBuyerAgent
Feb 27, 2016 4:15:31 PM jade.core.AgentContainerImpl joinPlatform
INFO: --------------------------------------
Agent container Main-Container@192.168.1.4 is ready.


问:
How to retrieve a list of subnets for launching a Fargate task?
I'm using the AWS SDK with C# in Visual Studio 2017, and have a prototype working which launches a Fargate service in ECS.  As part of the setup, you instantiate a CreateServiceRequest object which requires a NetworkConfiguration.AwsVpcConfiguration setting with SecurityGroups and Subnets.

```<code>var request = new CreateServiceRequest();

request.ServiceName = "myService";
request.TaskDefinition = "myTask";   // family[:revision] of the task definition to use
request.ClientToken = Guid.NewGuid().ToString().Replace("-", "");  // max 32 characters!
request.Cluster = "default";
request.DesiredCount = 1;
request.LaunchType = LaunchType.FARGATE;

request.DeploymentConfiguration = new DeploymentConfiguration
{
    MaximumPercent = 100,
    MinimumHealthyPercent = 50
};

// configure the network and security groups for the task
List<string> securityGroups = new List<string>();
securityGroups.Add("sg-123456");

List<string> subnets = new List<string>();
subnets.Add("subnet-9b36aa97");

request.NetworkConfiguration = new NetworkConfiguration
{
    AwsvpcConfiguration = new AwsVpcConfiguration
    {
        AssignPublicIp = AssignPublicIp.ENABLED,
        SecurityGroups = securityGroups,
        Subnets = subnets
    }
};
</code>```

When I configure a service manually via the AWS Console, they display a list of subnets from which to choose.  So, I'm wondering how I might programmatically retrieve that list of subnets which are available in our VPC.

I'm searching their SDK documentation for possible solutions, any pointers to their docs or examples is appreciated!

答:
Take a look at EC2Client, you'll find a lot of VPC-related APIs are associated with the EC2 service. Specifically check out AmazonEC2Client.DescribeSubnets(DescribeSubnetsRequest), method documentation here:

Request

Amazon.EC2.Model.DescribeSubnetsRequest

Response

Amazon.EC2.Model.DescribeSubnetsResponse

Response contains a list of Amazon.EC2.Model.Subnet that you will retrieve string property SubnetId from, when deciding which subnet to pass on to your Fargate request.

Example Usage (From the linked documentation):

```<code>var response = client.DescribeSubnets(new DescribeSubnetsRequest
{
    Filters = new List<filter> {
        new Filter {
            Name = "vpc-id",
            Values = new List<string> {
                "vpc-a01106c2"
            }
        }
    }
});

List<subnet> subnets = response.Subnets;
</code>```

Further Reading

AWS Documentation - EC2Client - Search this document for 'DescribeSubnets' to find async variants of this SDK method.

Body:
I'm using the AWS SDK with C# in Visual Studio 2017, and have a prototype working which launches a Fargate service in ECS.  As part of the setup, you instantiate a CreateServiceRequest object which requires a NetworkConfiguration.AwsVpcConfiguration setting with SecurityGroups and Subnets.

var request = new CreateServiceRequest();

request.ServiceName = "myService";
request.TaskDefinition = "myTask";   // family[:revision] of the task definition to use
request.ClientToken = Guid.NewGuid().ToString().Replace("-", "");  // max 32 characters!
request.Cluster = "default";
request.DesiredCount = 1;
request.LaunchType = LaunchType.FARGATE;

request.DeploymentConfiguration = new DeploymentConfiguration
{
    MaximumPercent = 100,
    MinimumHealthyPercent = 50
};

// configure the network and security groups for the task
List<string> securityGroups = new List<string>();
securityGroups.Add("sg-123456");

List<string> subnets = new List<string>();
subnets.Add("subnet-9b36aa97");

request.NetworkConfiguration = new NetworkConfiguration
{
    AwsvpcConfiguration = new AwsVpcConfiguration
    {
        AssignPublicIp = AssignPublicIp.ENABLED,
        SecurityGroups = securityGroups,
        Subnets = subnets
    }
};

When I configure a service manually via the AWS Console, they display a list of subnets from which to choose.  So, I'm wondering how I might programmatically retrieve that list of subnets which are available in our VPC.

I'm searching their SDK documentation for possible solutions, any pointers to their docs or examples is appreciated!

Body:
Take a look at EC2Client, you'll find a lot of VPC-related APIs are associated with the EC2 service. Specifically check out AmazonEC2Client.DescribeSubnets(DescribeSubnetsRequest), method documentation here:

Request

Amazon.EC2.Model.DescribeSubnetsRequest

Response

Amazon.EC2.Model.DescribeSubnetsResponse

Response contains a list of Amazon.EC2.Model.Subnet that you will retrieve string property SubnetId from, when deciding which subnet to pass on to your Fargate request.

Example Usage (From the linked documentation):

var response = client.DescribeSubnets(new DescribeSubnetsRequest
{
    Filters = new List<filter> {
        new Filter {
            Name = "vpc-id",
            Values = new List<string> {
                "vpc-a01106c2"
            }
        }
    }
});

List<subnet> subnets = response.Subnets;

Further Reading

AWS Documentation - EC2Client - Search this document for 'DescribeSubnets' to find async variants of this SDK method.


问:
Query on eloquent relationship
I have Book and Store models which have belongsToMany relationship.

In Book.php

```<code>public function stores(){
        return $this->belongsToMany('App\Store')->withPivot('qty');
    }
</code>```

In Store.php

```<code>public function books(){
        return $this->belongsToMany('App\Book')->withPivot('qty');
    }
</code>```

Now I just want to know the total number of books in store A and B together. How can I do it with eloquent ORM? I can get all books belonging to store A and B using whereHas but cannot go further to aggregate the qty field in the pivot table.

答:
So you want the total qty of books by combination of store id and book id

The way you've described your DB structure, it looks like your pivot table has exactly these columns: book_id, store_id and qty

So all you really need to do is:

DB::table('book_stores')->get()

Title: Query on eloquent relationship

Body:
I have Book and Store models which have belongsToMany relationship.

In Book.php

public function stores(){
        return $this->belongsToMany('App\Store')->withPivot('qty');
    }

In Store.php

public function books(){
        return $this->belongsToMany('App\Book')->withPivot('qty');
    }

Now I just want to know the total number of books in store A and B together. How can I do it with eloquent ORM? I can get all books belonging to store A and B using whereHas but cannot go further to aggregate the qty field in the pivot table.


问:
How to change opacity of a Xul element at runtime?
I've tried

```<code>document.getElementById("myId").style = "opacity: 0.5";
</code>```

but it didn't work:

Error: setting a property that has
  only a getter

Also looks like there's no "opacity" attribute or parameter (in the box or window element).

Any idea?

答:
The opacity is a property of the style property i.e.</p>

```<code>document.getElementById("myId").style.opacity = 0.5;
</code>```

Body:
I've tried

document.getElementById("myId").style = "opacity: 0.5";

but it didn't work:

Error: setting a property that has
  only a getter

Also looks like there's no "opacity" attribute or parameter (in the box or window element).

Any idea?

Body:
The opacity is a property of the style property i.e.

document.getElementById("myId").style.opacity = 0.5;


问:
Error: 9 while fitting sklearn.naive_bayes.MultinomialNB()
While fitting Multinomial Naive Bayes Classifier with TfidfCountvectorizer, I am getting killed: 9 error

```<code>def classify(vector, df):
    clf = MultinomialNB()
    model = clf.fit(vector, df.iloc[0:, 1].values)

if __name__ == "__main__":
    train, test = gen_train_test(pd.read_csv('Data/datalabel.csv'))
    vector = joblib.load('Data/tf.pkl')
    classify(vector, train, name='mnb')
    print('Program executed!')
</code>```

Here, the train is of size 409MB, and the vector is of size 20.3GB.

I am using a MacBook Pro-13 2017, 8GB RAM, 256 GB SSD.

答:
This simple modification in code solved the issue</p>

```<code>vector = joblib.load(open('Data/tf.pkl', 'rb'))
</code>```

Body:
While fitting Multinomial Naive Bayes Classifier with TfidfCountvectorizer, I am getting killed: 9 error

def classify(vector, df):
    clf = MultinomialNB()
    model = clf.fit(vector, df.iloc[0:, 1].values)

if __name__ == "__main__":
    train, test = gen_train_test(pd.read_csv('Data/datalabel.csv'))
    vector = joblib.load('Data/tf.pkl')
    classify(vector, train, name='mnb')
    print('Program executed!')

Here, the train is of size 409MB, and the vector is of size 20.3GB.

I am using a MacBook Pro-13 2017, 8GB RAM, 256 GB SSD.

Body:
This simple modification in code solved the issue

vector = joblib.load(open('Data/tf.pkl', 'rb'))