问:
Can't pass info of ListView to next Activity Android
Im trying to pass the info of the selected row of the ListView to a new activity where i can edit or delete the info, but i cant get into the next activity

this is the ListView
LISTADO

public class Listado extends AppCompatActivity {

```<code>ListView listView;
ArrayList<String> listado;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_listado);
    listView = (ListView) findViewById(R.id.listaView);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            int id = Integer.parseInt(listado.get(i).split(" ")[0]);
            String nombre=listado.get(i).split(" ")[1];
            String usuario=listado.get(i).split(" ")[2];
            String password=listado.get(i).split(" ")[3];
            String correo=listado.get(i).split(" ")[4];
            Intent intent=new Intent(Listado.this,Modificar.class);
            intent.putExtra("ID",id);
            intent.putExtra("NOMBRE",nombre);
            intent.putExtra("USUARIO",usuario);
            intent.putExtra("PASSWORD",password);
            intent.putExtra("CORREO",correo);

            startActivity(intent);
        }
    });
}

@Override
protected void onPostResume () {
    super.onPostResume();
    setContentView(R.layout.activity_listado);
    listView = (ListView) findViewById(R.id.listado);
    cargarlistado();
}

private void cargarlistado() {
    listado = ListaPersonas();
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listado);
    listView.setAdapter(adapter);
}

private ArrayList<String> ListaPersonas() {
    ArrayList<String> datos = new ArrayList<String>();
    BaseHelper helper = new BaseHelper(this, "DEMO", null, 1);
    SQLiteDatabase db = helper.getWritableDatabase();
    String sql = "Select * from PERSONAS";
    Cursor c = db.rawQuery(sql, null);
    if (c.moveToFirst()) {
        do {
            String linea = " " + c.getInt(0) + " " + c.getString(1) + " " + c.getString(2) + " " + c.getString(3) + " " + c.getString(4);
            datos.add(linea);
        } while (c.moveToNext());
    }
    db.close();
    return datos;
}
</code>```

}

and this is the place that i want to get the info
MODIFICAR

public class Modificar extends AppCompatActivity {

```<code>EditText ed_nombre,ed_usuario, ed_password, ed_correo;
Button btn_modificar,btn_eliminar;
int id_recibe;
String nombre_recibe,usuario_recibe, password_recibe, correo_recibe;

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

ed_nombre=(EditText) findViewById(R.id.ed_nombre);
ed_usuario=(EditText) findViewById(R.id.ed_usuario);
ed_password=(EditText) findViewById(R.id.ed_password);
ed_correo=(EditText) findViewById(R.id.ed_correo);
btn_modificar=(Button) findViewById(R.id.btn_modificar);
btn_eliminar=(Button) findViewById(R.id.btn_eliminar);

Bundle b=getIntent().getExtras();

if(b!=null)
{
    id_recibe=b.getInt("ID");
    nombre_recibe=b.getString("NOMBRE");
    usuario_recibe=b.getString("USUARIO");
    password_recibe=b.getString("PASSWORD");
    correo_recibe=b.getString("CORREO");
}
ed_nombre.setText(nombre_recibe);
ed_usuario.setText(usuario_recibe);
ed_password.setText(password_recibe);
ed_correo.setText(correo_recibe);

btn_modificar.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        modificar(id_recibe,ed_nombre.getText().toString(),ed_usuario.getText().toString(),ed_password.getText().toString(),ed_correo.getText().toString());
        onBackPressed();
    }
});

btn_eliminar.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        eliminar(id_recibe);
        onBackPressed();
    }
});
</code>```

}

```<code>private void modificar(int id, String nombre, String usuario, String password, String correo)
{
    BaseHelper helper=new BaseHelper(this,"DEMO",null,1);
    SQLiteDatabase db=helper.getWritableDatabase();
    String sql="UPDATE PERSONAS SET NOMBRE='"+nombre+"', USUARIO='"+usuario+"', PASSWORD='"+password+"', CORREO='"+correo+"' WHERE ID="+id;
    db.execSQL(sql);
}

private void eliminar(int id)
{
    BaseHelper helper=new BaseHelper(this,"DEMO",null,1);
    SQLiteDatabase db=helper.getWritableDatabase();
    String sql="DELETE FROM PERSONAS WHERE ID="+id;
    db.execSQL(sql);
}
</code>```

}

here's the activity.xml

```<code>  <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context="com.example.adminclases.appsensor.Listado"
   android:weightSum="1">

<ListView
    android:id="@+id/listaView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</code>```

and Android Manifest

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

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".ActivityIngreso" />
    <activity android:name=".Listado" />
    <activity android:name=".Modificar" />
</application>
</code>```

答:
Change this method :

```<code>@Override
protected void onPostResume () {
    super.onPostResume();
    setContentView(R.layout.activity_listado);
    listView = (ListView) findViewById(R.id.listado);
    cargarlistado();
}
</code>```

To this:

```<code>@Override
protected void onPostResume () {
    super.onPostResume();
    cargarlistado();
}
</code>```

Body:
Im trying to pass the info of the selected row of the ListView to a new activity where i can edit or delete the info, but i cant get into the next activity

this is the ListView
LISTADO

public class Listado extends AppCompatActivity {

ListView listView;
ArrayList<String> listado;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_listado);
    listView = (ListView) findViewById(R.id.listaView);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            int id = Integer.parseInt(listado.get(i).split(" ")[0]);
            String nombre=listado.get(i).split(" ")[1];
            String usuario=listado.get(i).split(" ")[2];
            String password=listado.get(i).split(" ")[3];
            String correo=listado.get(i).split(" ")[4];
            Intent intent=new Intent(Listado.this,Modificar.class);
            intent.putExtra("ID",id);
            intent.putExtra("NOMBRE",nombre);
            intent.putExtra("USUARIO",usuario);
            intent.putExtra("PASSWORD",password);
            intent.putExtra("CORREO",correo);

            startActivity(intent);
        }
    });
}

@Override
protected void onPostResume () {
    super.onPostResume();
    setContentView(R.layout.activity_listado);
    listView = (ListView) findViewById(R.id.listado);
    cargarlistado();
}

private void cargarlistado() {
    listado = ListaPersonas();
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listado);
    listView.setAdapter(adapter);
}

private ArrayList<String> ListaPersonas() {
    ArrayList<String> datos = new ArrayList<String>();
    BaseHelper helper = new BaseHelper(this, "DEMO", null, 1);
    SQLiteDatabase db = helper.getWritableDatabase();
    String sql = "Select * from PERSONAS";
    Cursor c = db.rawQuery(sql, null);
    if (c.moveToFirst()) {
        do {
            String linea = " " + c.getInt(0) + " " + c.getString(1) + " " + c.getString(2) + " " + c.getString(3) + " " + c.getString(4);
            datos.add(linea);
        } while (c.moveToNext());
    }
    db.close();
    return datos;
}

}

and this is the place that i want to get the info
MODIFICAR

public class Modificar extends AppCompatActivity {

EditText ed_nombre,ed_usuario, ed_password, ed_correo;
Button btn_modificar,btn_eliminar;
int id_recibe;
String nombre_recibe,usuario_recibe, password_recibe, correo_recibe;

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

ed_nombre=(EditText) findViewById(R.id.ed_nombre);
ed_usuario=(EditText) findViewById(R.id.ed_usuario);
ed_password=(EditText) findViewById(R.id.ed_password);
ed_correo=(EditText) findViewById(R.id.ed_correo);
btn_modificar=(Button) findViewById(R.id.btn_modificar);
btn_eliminar=(Button) findViewById(R.id.btn_eliminar);

Bundle b=getIntent().getExtras();

if(b!=null)
{
    id_recibe=b.getInt("ID");
    nombre_recibe=b.getString("NOMBRE");
    usuario_recibe=b.getString("USUARIO");
    password_recibe=b.getString("PASSWORD");
    correo_recibe=b.getString("CORREO");
}
ed_nombre.setText(nombre_recibe);
ed_usuario.setText(usuario_recibe);
ed_password.setText(password_recibe);
ed_correo.setText(correo_recibe);

btn_modificar.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        modificar(id_recibe,ed_nombre.getText().toString(),ed_usuario.getText().toString(),ed_password.getText().toString(),ed_correo.getText().toString());
        onBackPressed();
    }
});

btn_eliminar.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        eliminar(id_recibe);
        onBackPressed();
    }
});

}

private void modificar(int id, String nombre, String usuario, String password, String correo)
{
    BaseHelper helper=new BaseHelper(this,"DEMO",null,1);
    SQLiteDatabase db=helper.getWritableDatabase();
    String sql="UPDATE PERSONAS SET NOMBRE='"+nombre+"', USUARIO='"+usuario+"', PASSWORD='"+password+"', CORREO='"+correo+"' WHERE ID="+id;
    db.execSQL(sql);
}

private void eliminar(int id)
{
    BaseHelper helper=new BaseHelper(this,"DEMO",null,1);
    SQLiteDatabase db=helper.getWritableDatabase();
    String sql="DELETE FROM PERSONAS WHERE ID="+id;
    db.execSQL(sql);
}

}

here's the activity.xml

  <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context="com.example.adminclases.appsensor.Listado"
   android:weightSum="1">

<ListView
    android:id="@+id/listaView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

and Android Manifest

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".ActivityIngreso" />
    <activity android:name=".Listado" />
    <activity android:name=".Modificar" />
</application>

Body:
Change this method :

@Override
protected void onPostResume () {
    super.onPostResume();
    setContentView(R.layout.activity_listado);
    listView = (ListView) findViewById(R.id.listado);
    cargarlistado();
}

To this:

@Override
protected void onPostResume () {
    super.onPostResume();
    cargarlistado();
}


来源: stackexchange

问:
UrlMapping to Index is not working
I am trying to get my Index which in my case is just localhost:8080 to go to a different page. This code is not working and I'm just going to the index page instead of rendering "this worked"

My UrlMappings file looks like this:

```<code>package appworld

class UrlMappings {

    static mappings = {

        "/$controller/$action?/$id?(.$format)?"{
            constraints {
                // apply constraints here
            }
        }

        "/" {
            controller = "Home"
            action = "isUserLoggedIn"
        }

        "500"(view:'/error')
        "404"(view:'/notFound')
    }
}
</code>```

The method in HomeController.groovy looks like:

```<code>def isUserLoggedIn() {
   println("We made it from index")
   render "this worked"
}
</code>```

答:
It looks like your syntax is off.  Try:</p>

```<code>"/"(controller:"home", action:"isUserLoggedIn")
</code>```

ContentLicense: CC BY-SA 3.0

Title: UrlMapping to Index is not working

Body:
I am trying to get my Index which in my case is just localhost:8080 to go to a different page. This code is not working and I'm just going to the index page instead of rendering "this worked"

My UrlMappings file looks like this:

package appworld

class UrlMappings {

    static mappings = {

        "/$controller/$action?/$id?(.$format)?"{
            constraints {
                // apply constraints here
            }
        }

        "/" {
            controller = "Home"
            action = "isUserLoggedIn"
        }

        "500"(view:'/error')
        "404"(view:'/notFound')
    }
}

The method in HomeController.groovy looks like:

def isUserLoggedIn() {
   println("We made it from index")
   render "this worked"
}

Body:
It looks like your syntax is off.  Try:

"/"(controller:"home", action:"isUserLoggedIn")


问:
My VBA Excel 2013 Code isn't compiling
When I run this code:

```<code>Private Sub Workbook_Open()
Dim i As Integer
Dim j As Integer
Dim range1 As Integer
Dim range2 As Integer
range1 = 53
range2 = 102

For i = range1 To range2
    For j = (range1 - 50) To (range2 - 50)

        If Cells(2, i) = Cells(2, j) Then
            If Cells(7, i) > Cells(7, j) Then
            Cells(2, i).Interior.ColorIndex = 37 'Went up; Green
            ElseIf Cells(7, i) = Cells(7, j) Then
            Cells(2, i).Interior.ColorIndex = 37 'No change; Grey
            Else
            Cells(2, i).Interior.ColorIndex = 37 'Went down; Red
        End If

    Next j
    If Cells(2, i).Interior.ColorIndex = 0 Then 'Hasn't Changed; No Fill
    Cells(2, i).Interior.ColorIndex = 37 'New Song; Blue
    End If

Next i
End Sub
</code>```

An error appears saying:

Compile error: Next without For

However there definitely is a For for each Next.

So where did I go wrong?

Note: The '37's are just filler numbers, I know it appears as light blue.

答:
Indenting your code in a consistent manner gives the following:

```<code>Private Sub Workbook_Open()
    Dim i As Integer
    Dim j As Integer
    Dim range1 As Integer
    Dim range2 As Integer
    range1 = 53
    range2 = 102

    For i = range1 To range2
        For j = (range1 - 50) To (range2 - 50)

            If Cells(2, i) = Cells(2, j) Then
                If Cells(7, i) > Cells(7, j) Then
                    Cells(2, i).Interior.ColorIndex = 37 'Went up; Green
                ElseIf Cells(7, i) = Cells(7, j) Then
                    Cells(2, i).Interior.ColorIndex = 37 'No change; Grey
                Else
                    Cells(2, i).Interior.ColorIndex = 37 'Went down; Red
                End If

                Next j ' <--- This Next has no For associated with it

                If Cells(2, i).Interior.ColorIndex = 0 Then 'Hasn't Changed; No Fill
                    Cells(2, i).Interior.ColorIndex = 37 'New Song; Blue
                End If
            Next i
        End Sub
</code>```

You can very quickly tell by the indentation levels that the Next j has no For statement associated with it within the current If block.  This is why you get your error.

I suspect that you intended to have an End If just before that Next j and therefore your code would look like:

```<code>Private Sub Workbook_Open()
    Dim i As Integer
    Dim j As Integer
    Dim range1 As Integer
    Dim range2 As Integer
    range1 = 53
    range2 = 102

    For i = range1 To range2
        For j = (range1 - 50) To (range2 - 50)

            If Cells(2, i) = Cells(2, j) Then
                If Cells(7, i) > Cells(7, j) Then
                    Cells(2, i).Interior.ColorIndex = 37 'Went up; Green
                ElseIf Cells(7, i) = Cells(7, j) Then
                    Cells(2, i).Interior.ColorIndex = 37 'No change; Grey
                Else
                    Cells(2, i).Interior.ColorIndex = 37 'Went down; Red
                End If
            End If

        Next j

        If Cells(2, i).Interior.ColorIndex = 0 Then 'Hasn't Changed; No Fill
            Cells(2, i).Interior.ColorIndex = 37 'New Song; Blue
        End If
    Next i
End Sub
</code>```

Title: My VBA Excel 2013 Code isn't compiling

Body:
When I run this code:

Private Sub Workbook_Open()
Dim i As Integer
Dim j As Integer
Dim range1 As Integer
Dim range2 As Integer
range1 = 53
range2 = 102

For i = range1 To range2
    For j = (range1 - 50) To (range2 - 50)

        If Cells(2, i) = Cells(2, j) Then
            If Cells(7, i) > Cells(7, j) Then
            Cells(2, i).Interior.ColorIndex = 37 'Went up; Green
            ElseIf Cells(7, i) = Cells(7, j) Then
            Cells(2, i).Interior.ColorIndex = 37 'No change; Grey
            Else
            Cells(2, i).Interior.ColorIndex = 37 'Went down; Red
        End If

    Next j
    If Cells(2, i).Interior.ColorIndex = 0 Then 'Hasn't Changed; No Fill
    Cells(2, i).Interior.ColorIndex = 37 'New Song; Blue
    End If

Next i
End Sub

An error appears saying:

Compile error: Next without For

However there definitely is a For for each Next.

So where did I go wrong?

Note: The '37's are just filler numbers, I know it appears as light blue.

Body:
Indenting your code in a consistent manner gives the following:

Private Sub Workbook_Open()
    Dim i As Integer
    Dim j As Integer
    Dim range1 As Integer
    Dim range2 As Integer
    range1 = 53
    range2 = 102

    For i = range1 To range2
        For j = (range1 - 50) To (range2 - 50)

            If Cells(2, i) = Cells(2, j) Then
                If Cells(7, i) > Cells(7, j) Then
                    Cells(2, i).Interior.ColorIndex = 37 'Went up; Green
                ElseIf Cells(7, i) = Cells(7, j) Then
                    Cells(2, i).Interior.ColorIndex = 37 'No change; Grey
                Else
                    Cells(2, i).Interior.ColorIndex = 37 'Went down; Red
                End If

                Next j ' <--- This Next has no For associated with it

                If Cells(2, i).Interior.ColorIndex = 0 Then 'Hasn't Changed; No Fill
                    Cells(2, i).Interior.ColorIndex = 37 'New Song; Blue
                End If
            Next i
        End Sub

You can very quickly tell by the indentation levels that the Next j has no For statement associated with it within the current If block.  This is why you get your error.

I suspect that you intended to have an End If just before that Next j and therefore your code would look like:

Private Sub Workbook_Open()
    Dim i As Integer
    Dim j As Integer
    Dim range1 As Integer
    Dim range2 As Integer
    range1 = 53
    range2 = 102

    For i = range1 To range2
        For j = (range1 - 50) To (range2 - 50)

            If Cells(2, i) = Cells(2, j) Then
                If Cells(7, i) > Cells(7, j) Then
                    Cells(2, i).Interior.ColorIndex = 37 'Went up; Green
                ElseIf Cells(7, i) = Cells(7, j) Then
                    Cells(2, i).Interior.ColorIndex = 37 'No change; Grey
                Else
                    Cells(2, i).Interior.ColorIndex = 37 'Went down; Red
                End If
            End If

        Next j

        If Cells(2, i).Interior.ColorIndex = 0 Then 'Hasn't Changed; No Fill
            Cells(2, i).Interior.ColorIndex = 37 'New Song; Blue
        End If
    Next i
End Sub


问:
Robolectric unable to find resource ID when running test
I am new to Robolectric testing in Android Studio and when I try to run tests, the same error appears which states android.content.res.Resources$NotFoundException: Unable to find resource ID #0x0 in packages. I made sure that the JUnit Working Directory was $MODULE_DIR$, but it still didn't work. Adding testOptions.unitTests.includeAndroidResources to my build.gradle file doesn't do anything either. Here is what the test file looks like:

```<code>@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP)
public class StartActivityTests {

    StartActivity activity;

    @Before
    public void setUp() throws Exception {
        activity = Robolectric.buildActivity(StartActivity.class)
            .create()
            .resume()
            .get();
    }

    @Test
    public void shouldNotBeNull() throws Exception
    {
        assertNotNull(activity);
    }

    @Test
    public void clickingNewGame_shouldStartAvatarRoomActivity() {
        StartActivity activity = Robolectric.setupActivity(StartActivity.class);
        activity.findViewById(R.id.newUserButtonFirstPage).performClick();

        Intent expectedIntent = new Intent(activity, AvatarRoomActivity.class);
        Intent actual = ShadowApplication.getInstance().getNextStartedActivity();
        assertEquals(expectedIntent.getComponent(), actual.getComponent());
    }
}
</code>```

Please help! It would be greatly appreciated!

答:
If you are using Android Gradle Plugin 3.0 or above, you need to add the following snippet with the android block of build.gradle

```<code>testOptions {
    unitTests {
        includeAndroidResources = true
    }
}
</code>```

or no Android resource can be found in unit tests.

Body:
I am new to Robolectric testing in Android Studio and when I try to run tests, the same error appears which states android.content.res.Resources$NotFoundException: Unable to find resource ID #0x0 in packages. I made sure that the JUnit Working Directory was $MODULE_DIR$, but it still didn't work. Adding testOptions.unitTests.includeAndroidResources to my build.gradle file doesn't do anything either. Here is what the test file looks like:

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP)
public class StartActivityTests {

    StartActivity activity;

    @Before
    public void setUp() throws Exception {
        activity = Robolectric.buildActivity(StartActivity.class)
            .create()
            .resume()
            .get();
    }

    @Test
    public void shouldNotBeNull() throws Exception
    {
        assertNotNull(activity);
    }

    @Test
    public void clickingNewGame_shouldStartAvatarRoomActivity() {
        StartActivity activity = Robolectric.setupActivity(StartActivity.class);
        activity.findViewById(R.id.newUserButtonFirstPage).performClick();

        Intent expectedIntent = new Intent(activity, AvatarRoomActivity.class);
        Intent actual = ShadowApplication.getInstance().getNextStartedActivity();
        assertEquals(expectedIntent.getComponent(), actual.getComponent());
    }
}

Please help! It would be greatly appreciated!

Body:
If you are using Android Gradle Plugin 3.0 or above, you need to add the following snippet with the android block of build.gradle

testOptions {
    unitTests {
        includeAndroidResources = true
    }
}

or no Android resource can be found in unit tests.


问:
VMWare Image Modification
If I already have an image that exists, can I create an image based on the existing one, except I want to make changes to the exisiting one (mainly configurations).  </p>

答:
As others have said, this is exactly how you implement full backups for your VMs.

When the VM is not running, merely copy the virtual disks into a different location, then restart the VM.

OwnerDisplayName: Oliver S

Title: VMWare Image Modification

LastEditorDisplayName: sascha

OwnerDisplayName: warren

ContentLicense: CC BY-SA 2.5


问:
Ionic 3 - how use cordova plugin Network interface with ionic?
My problem:
I need my app to search the local WiFi network to find a server computer with a application on a specific port. I don't want to hard code the server IP address into the app as it could be possibly used in many locations.

Update: So I need to be able to find the IP address of all devices on the network.

What iv done so far:

Iv followed other guides on stack overflow and online by doing the following steps:

1. install cordova plugin:

```<code> "cordova plugin add cordova-plugin-networkinterface"
</code>```

2. Declare the variable in global scope to access the object

```<code>declare var NetworkInterface: any;
export class TestClass{}
</code>```

3. Call the object using the global variable inside a component

```<code>NetworkInterface.getWiFiIPAddress((ip) => {
   console.log("network ip address = " + ip);
});
</code>```

However this causes an error on run time when running from the mobile:

ERROR Error: Uncaught (in promise):  ReferenceError: NetworkInterface
  is not defined

I've also tried declaring a variable globally and then trying to apply a string value in a component, only to get the same problem. It appears to be more of a problem with the variable not working globally? Any help would be great!

答:
If you want to access the Network plugin you just need to add it to your app.module.ts providers collection. This registers it as a singleton.

```<code>@NgModule({
  declarations: [
    MyApp,
    ...
  ],
  imports: [
    ...
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    ...
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    Network
  ]
})
export class AppModule { }
</code>```

Then you can simply import and and use it on a page as per the plugin docs.

Body:
My problem:
I need my app to search the local WiFi network to find a server computer with a application on a specific port. I don't want to hard code the server IP address into the app as it could be possibly used in many locations.

Update: So I need to be able to find the IP address of all devices on the network.

What iv done so far:

Iv followed other guides on stack overflow and online by doing the following steps:

1. install cordova plugin:

 "cordova plugin add cordova-plugin-networkinterface"

2. Declare the variable in global scope to access the object

declare var NetworkInterface: any;
export class TestClass{}

3. Call the object using the global variable inside a component

NetworkInterface.getWiFiIPAddress((ip) => {
   console.log("network ip address = " + ip);
});

However this causes an error on run time when running from the mobile:

ERROR Error: Uncaught (in promise):  ReferenceError: NetworkInterface
  is not defined

I've also tried declaring a variable globally and then trying to apply a string value in a component, only to get the same problem. It appears to be more of a problem with the variable not working globally? Any help would be great!

Body:
If you want to access the Network plugin you just need to add it to your app.module.ts providers collection. This registers it as a singleton.

@NgModule({
  declarations: [
    MyApp,
    ...
  ],
  imports: [
    ...
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    ...
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    Network
  ]
})
export class AppModule { }

Then you can simply import and and use it on a page as per the plugin docs.


问:
How to read DataInputStream until the end without needing to catch an EOFException?
Suppose we have some binary data byte[] data that only contains Integers. If I wanted to read this data utilizing a DataInputStream, the only approach I can come up with is the following:

```<code>DataInputStream in = new DataInputStream(new ByteArrayInputStream(data));
try {
    while (true){
        int i = in.readInt();
    }
} catch (EOFException e) {
    // we're done!
} catch (IOException e){
    throw new RuntimeException(e);
}
</code>```

What bugs me about this is that reaching the end of the stream is expected and it would exceptional only if no exception was thrown, what IMO defeats the purpose of exceptions in the first place.

When using Java NIO's IntBuffer, there's no such problem.

```<code>IntBuffer in = ByteBuffer.wrap(data).asIntBuffer();
while (in.hasRemaining()){
    int i = in.get();
}
</code>```

Coming from C# and being in the process of learning Java I refuse to believe that this is the intended way of doing this.

Moreover, I just came across Java NIO which seems to be "quite new". Using IntBuffer here instead would be my way of procrastinating the matter. Regardless, I wanna know how this is properly done in Java.

答:
Since you are coming from .NET, Java's DataInputStream is roughly equivalent to BinaryReader of .NET.

Just like its .NET equivalent, DataInputStream class and its main interface, DataInput, have no provision for determining if a primitive of any given type is available for retrieval at the current position of the stream.

You can gain valuable insight of how the designers of the API expect you to use it by looking at designer's own usage of the API.

For example, look at ObjectInputStream.java source, which is used for object deserialization. The code that reads arrays of various types calls type-specific readXYZ methods of DataInput in a loop. In order to figure out where the primitives end, the code retrieves the number of items (line 1642):

```<code>private Object readArray(boolean unshared) throws IOException {
    if (bin.readByte() != TC_ARRAY) {
        throw new InternalError();
    }
    ObjectStreamClass desc = readClassDesc(false);
    int len = bin.readInt();
    ...
    if (ccl == Integer.TYPE) {
        bin.readInts((int[]) array, 0, len);
        ...
    }
    ...
}
</code>```

Above, bin is a BlockDataInputStream, which is another implementation of DataInput interface. Note how len, the number of items in the array stored by array serialization counterpart, is passed to readInts, which calls readInt in a loop len times (line 2918).

Body:
Suppose we have some binary data byte[] data that only contains Integers. If I wanted to read this data utilizing a DataInputStream, the only approach I can come up with is the following:

DataInputStream in = new DataInputStream(new ByteArrayInputStream(data));
try {
    while (true){
        int i = in.readInt();
    }
} catch (EOFException e) {
    // we're done!
} catch (IOException e){
    throw new RuntimeException(e);
}

What bugs me about this is that reaching the end of the stream is expected and it would exceptional only if no exception was thrown, what IMO defeats the purpose of exceptions in the first place.

When using Java NIO's IntBuffer, there's no such problem.

IntBuffer in = ByteBuffer.wrap(data).asIntBuffer();
while (in.hasRemaining()){
    int i = in.get();
}

Coming from C# and being in the process of learning Java I refuse to believe that this is the intended way of doing this.

Moreover, I just came across Java NIO which seems to be "quite new". Using IntBuffer here instead would be my way of procrastinating the matter. Regardless, I wanna know how this is properly done in Java.

Body:
Since you are coming from .NET, Java's DataInputStream is roughly equivalent to BinaryReader of .NET.

Just like its .NET equivalent, DataInputStream class and its main interface, DataInput, have no provision for determining if a primitive of any given type is available for retrieval at the current position of the stream.

You can gain valuable insight of how the designers of the API expect you to use it by looking at designer's own usage of the API.

For example, look at ObjectInputStream.java source, which is used for object deserialization. The code that reads arrays of various types calls type-specific readXYZ methods of DataInput in a loop. In order to figure out where the primitives end, the code retrieves the number of items (line 1642):

private Object readArray(boolean unshared) throws IOException {
    if (bin.readByte() != TC_ARRAY) {
        throw new InternalError();
    }
    ObjectStreamClass desc = readClassDesc(false);
    int len = bin.readInt();
    ...
    if (ccl == Integer.TYPE) {
        bin.readInts((int[]) array, 0, len);
        ...
    }
    ...
}

Above, bin is a BlockDataInputStream, which is another implementation of DataInput interface. Note how len, the number of items in the array stored by array serialization counterpart, is passed to readInts, which calls readInt in a loop len times (line 2918).


问:
Does Azure Cosmos db Emulator require internet connection
Azure Cosmos db Emulator will not launch when my external internet connection is offline.  Is this normal with the current emulator?</p>

答:
Azure Cosmos DB Emulator simulates a service locally and it is supposed that the external network offline does not affect the emulator 's operation.

You could check the points as below to troubleshoot your issue.

Point 1: Try to ping your localhost.

Point 2: Try to telnet the cosmos db local server port.

Point 3: Check to see if the local 8081 port is occupied causing a port conflict. The emulator didn't start at all.

Point 4: Check the hosts configuration file to see if the local IP port is pointing to another domain.

Point 5 : Check the firewall for any restrictions.


问:
JavaScript Glossary: Value vs Expression?
What is the difference between the two terms.
What I understand till now, an expression is any piece of code that produces a value.
But in the program, what should I call this:

```<code>5;
</code>```

A value or an expression? Or can I use the two terms interchangeably?

答:
A value is essentially anything assigned to a variable.

According to EloquentJavaScript:

There are six basic types of values in JavaScript: numbers, strings, Booleans, objects, functions, and undefined values.

According to 2ality:

An expression produces a value and can be written wherever a value is expected, for example as an argument in a function call. Each of the following lines contains an expression:

```<code>myvar
3 + x
myfunc("a", "b")
</code>```

So in short, an expression is anything that can be evaluated; the result of that evaluation is a value.

Hope this helps :)

Body:
What is the difference between the two terms.
What I understand till now, an expression is any piece of code that produces a value.
But in the program, what should I call this:

5;

A value or an expression? Or can I use the two terms interchangeably?

Body:
A value is essentially anything assigned to a variable.

According to EloquentJavaScript:

There are six basic types of values in JavaScript: numbers, strings, Booleans, objects, functions, and undefined values.

According to 2ality:

An expression produces a value and can be written wherever a value is expected, for example as an argument in a function call. Each of the following lines contains an expression:

myvar
3 + x
myfunc("a", "b")

So in short, an expression is anything that can be evaluated; the result of that evaluation is a value.

Hope this helps :)


问:
Parse PFQuery - Check if arrays are identical - Swift
I'm attempting to construct a parse query in xcode that takes an array of objects that was passed to the view controller via a previous segue, creates an array of objectId's from those objects, and queries for an exact match in array objectId values within the key "participants" in the class "MessageThread"

I've been reading through the parse documentation, and the best query I can come up with is containsAllObjectsIn:

Obviously, containsAllObjectsIn will work in some conditions. However, that query only checks that all the objectIds are present in the key "participants". It does not check if the arrays are identical. As such, the query will return objects that, while they do contain all objectIds, may contain extra objectIds.

To counter act this negative effect, I run a check on each returned object to see if the objectIds in the returned object are an identical match to the original array. I've included the view controller code below.

While the code I've currently settled with below seems to be working as intended after testing, I can't help but know there has to be a much more efficient way of checking if the arrays are identical via a PFQuery.

Any ideas or help on how I can make this code better? Thanks.

```<code>import UIKit
import Parse

class MessageThreadViewController: UIViewController {

@IBOutlet weak var sendNewMessageButton: UIButton!

var participantsList:[PFObject] = []
var participantsListIds:[String] = []
var currentMessageThreadObject:PFObject?
var threadMessages:[PFObject] = []

override func viewDidLoad() {
    super.viewDidLoad()
    initialViewSetup()
    checkForExistingMessageThread()
}

func initialViewSetup() {
    sendNewMessageButton.isEnabled = false
    for participant in participantsList {
        participantsListIds.append(participant.objectId!)
    }
}

func checkForExistingMessageThread () {
    print("-------------------")
    print(participantsListIds)
    let query = PFQuery(className: "MessageThread")
    query.whereKey("participants", containsAllObjectsIn: participantsList)
    query.includeKey("messages")
    query.findObjectsInBackground(block: { (threads, error) in
        if error != nil {
            if let error = error {
                print(error)
            }
        } else {
            if let threads = threads {
                if threads.isEmpty {
                    print("no thread found. creating thread....")
                    self.createMessageThread()
                } else {
                    print("existing thread match(es) found")
                    var activeThreadFound = false
                    for thread in threads {
                        let returnedThreadParticipants = thread["participants"] as! [PFObject]
                        var returnedThreadParticipantsIds:[String] = []
                        for participant in returnedThreadParticipants {
                            returnedThreadParticipantsIds.append(participant.objectId!)
                        }
                        if returnedThreadParticipantsIds.containsSameElements(as: self.participantsListIds) {
                            activeThreadFound = true
                            print("thread identical match found")
                            self.currentMessageThreadObject = thread
                            self.sendNewMessageButton.isEnabled = true
                            if let queriedThreadMessages = thread["messages"] {
                                let queriedThreadMessagesAsObjects = queriedThreadMessages as! [PFObject]
                                self.threadMessages = queriedThreadMessagesAsObjects
                                self.messagesTableView.reloadData()
                                self.sendNewMessageButton.isEnabled = true
                            }
                            break
                        } else {

                            print("non-identical thread found")
                        }
                    }
                    if activeThreadFound == false {
                        print("matches were found, but no identical thread. Creating thread....")
                        self.createMessageThread()
                    }
                }
            }
        }
    })
}

func createMessageThread() {
    let newMessageThread = PFObject(className:"MessageThread")
    newMessageThread["participants"] = participantsList
    newMessageThread.saveInBackground(block: { (success, error) in
        if error != nil {
            if let error = error {
                print(error)
            }
        } else {
            self.checkForExistingMessageThread()
        }
    })

}

}

extension Array where Element: Comparable {
func containsSameElements(as other: [Element]) -> Bool {
    return self.count == other.count && self.sorted() == other.sorted()

}
</code>```

答:
My other suggestion is try to combine containedIn and containsAllObjectsInArray in the same query. Please, try something like this:</p>

```<code>let query = PFQuery(className: "MessageThread")
query.whereKey("participants", containsAllObjectsInArray: participantsList)
query.whereKey("participants", containedIn: participantsList)
</code>```

Body:
I'm attempting to construct a parse query in xcode that takes an array of objects that was passed to the view controller via a previous segue, creates an array of objectId's from those objects, and queries for an exact match in array objectId values within the key "participants" in the class "MessageThread"

I've been reading through the parse documentation, and the best query I can come up with is containsAllObjectsIn:

Obviously, containsAllObjectsIn will work in some conditions. However, that query only checks that all the objectIds are present in the key "participants". It does not check if the arrays are identical. As such, the query will return objects that, while they do contain all objectIds, may contain extra objectIds.

To counter act this negative effect, I run a check on each returned object to see if the objectIds in the returned object are an identical match to the original array. I've included the view controller code below.

While the code I've currently settled with below seems to be working as intended after testing, I can't help but know there has to be a much more efficient way of checking if the arrays are identical via a PFQuery.

Any ideas or help on how I can make this code better? Thanks.

import UIKit
import Parse

class MessageThreadViewController: UIViewController {

@IBOutlet weak var sendNewMessageButton: UIButton!

var participantsList:[PFObject] = []
var participantsListIds:[String] = []
var currentMessageThreadObject:PFObject?
var threadMessages:[PFObject] = []

override func viewDidLoad() {
    super.viewDidLoad()
    initialViewSetup()
    checkForExistingMessageThread()
}

func initialViewSetup() {
    sendNewMessageButton.isEnabled = false
    for participant in participantsList {
        participantsListIds.append(participant.objectId!)
    }
}

func checkForExistingMessageThread () {
    print("-------------------")
    print(participantsListIds)
    let query = PFQuery(className: "MessageThread")
    query.whereKey("participants", containsAllObjectsIn: participantsList)
    query.includeKey("messages")
    query.findObjectsInBackground(block: { (threads, error) in
        if error != nil {
            if let error = error {
                print(error)
            }
        } else {
            if let threads = threads {
                if threads.isEmpty {
                    print("no thread found. creating thread....")
                    self.createMessageThread()
                } else {
                    print("existing thread match(es) found")
                    var activeThreadFound = false
                    for thread in threads {
                        let returnedThreadParticipants = thread["participants"] as! [PFObject]
                        var returnedThreadParticipantsIds:[String] = []
                        for participant in returnedThreadParticipants {
                            returnedThreadParticipantsIds.append(participant.objectId!)
                        }
                        if returnedThreadParticipantsIds.containsSameElements(as: self.participantsListIds) {
                            activeThreadFound = true
                            print("thread identical match found")
                            self.currentMessageThreadObject = thread
                            self.sendNewMessageButton.isEnabled = true
                            if let queriedThreadMessages = thread["messages"] {
                                let queriedThreadMessagesAsObjects = queriedThreadMessages as! [PFObject]
                                self.threadMessages = queriedThreadMessagesAsObjects
                                self.messagesTableView.reloadData()
                                self.sendNewMessageButton.isEnabled = true
                            }
                            break
                        } else {

                            print("non-identical thread found")
                        }
                    }
                    if activeThreadFound == false {
                        print("matches were found, but no identical thread. Creating thread....")
                        self.createMessageThread()
                    }
                }
            }
        }
    })
}

func createMessageThread() {
    let newMessageThread = PFObject(className:"MessageThread")
    newMessageThread["participants"] = participantsList
    newMessageThread.saveInBackground(block: { (success, error) in
        if error != nil {
            if let error = error {
                print(error)
            }
        } else {
            self.checkForExistingMessageThread()
        }
    })

}

}

extension Array where Element: Comparable {
func containsSameElements(as other: [Element]) -> Bool {
    return self.count == other.count && self.sorted() == other.sorted()

}

Body:
My other suggestion is try to combine containedIn and containsAllObjectsInArray in the same query. Please, try something like this:

let query = PFQuery(className: "MessageThread")
query.whereKey("participants", containsAllObjectsInArray: participantsList)
query.whereKey("participants", containedIn: participantsList)


问:
Multiple column search with MySQL Stored Procedure
I'm a newbie on MySQL Stored Procedures and need to make a MySQL stored procedure to search a list of products with multiple column filters. The code posted below won't return any values if I don't send all parameters with values. It should display all products if all parameters are empty and filter results when sending other parameters.

```<code>DELIMITER $$

USE `537174_alsuper`$$

DROP PROCEDURE IF EXISTS `ListarProductos`$$

CREATE DEFINER=`537174_alsuper`@`%` PROCEDURE `ListarProductos`(
            IN Token VARCHAR(50),
            IN cID INT(11),
            IN pID INT(11),
            IN os INT(1),
            IN productName VARCHAR(255)
            )
BEGIN

    DECLARE BaseToken VARCHAR(50);
    SELECT TOKEN_VALUE INTO BaseToken FROM web_service_tokens WHERE 1 ORDER BY TOKEN_ID DESC LIMIT 1;

    IF (Token = BaseToken) THEN

    SELECT DISTINCT d.thumbnail, a.productID, a.name_en, a.categoryID, a.Price, a.description_en
    FROM SC_products a, SC_product_pictures d
    WHERE a.ordering_available='1' AND d.productID=a.productID AND

    CASE
        WHEN cID IS NOT NULL
        THEN a.categoryID = cID
        WHEN cID IS NULL
        THEN 1 = 1
    END

    AND

    CASE
        WHEN pID IS NOT NULL
        THEN a.productID = pID
        WHEN pID IS NULL
        THEN 1 = 1
    END

    AND

    CASE

        WHEN os IS NOT NULL
        THEN a.on_special = os
        WHEN os IS NULL
        THEN 1 = 1
    END

    AND

    CASE
        WHEN productName IS NOT NULL
        THEN a.name_en LIKE CONCAT('%',productName,'%')
        WHEN productName IS NULL
        THEN 1 = 1
    END

    ORDER BY a.name_en ASC;

    END IF;

    END$$

DELIMITER ;
</code>```

Can anyone point to the right way on doing a stored procedure search with multiple column filters?

答:
How about this:</p>

```<code>SELECT DISTINCT d.thumbnail, a.productID, a.name_en, a.categoryID, a.Price, a.description_en
FROM SC_products a
INNER JOIN SC_product_pictures d ON d.productID = a.productID
WHERE a.ordering_available='1' AND
(cID IS NULL OR a.categoryID = cID) AND
(pID IS NULL OR a.productID = pID) AND
(os IS NULL OR a.on_special = os) AND
(productName IS NULL OR a.name_en LIKE CONCAT('%', productName, '%'))
</code>```

Body:
I'm a newbie on MySQL Stored Procedures and need to make a MySQL stored procedure to search a list of products with multiple column filters. The code posted below won't return any values if I don't send all parameters with values. It should display all products if all parameters are empty and filter results when sending other parameters.

DELIMITER $$

USE `537174_alsuper`$$

DROP PROCEDURE IF EXISTS `ListarProductos`$$

CREATE DEFINER=`537174_alsuper`@`%` PROCEDURE `ListarProductos`(
            IN Token VARCHAR(50),
            IN cID INT(11),
            IN pID INT(11),
            IN os INT(1),
            IN productName VARCHAR(255)
            )
BEGIN

    DECLARE BaseToken VARCHAR(50);
    SELECT TOKEN_VALUE INTO BaseToken FROM web_service_tokens WHERE 1 ORDER BY TOKEN_ID DESC LIMIT 1;

    IF (Token = BaseToken) THEN

    SELECT DISTINCT d.thumbnail, a.productID, a.name_en, a.categoryID, a.Price, a.description_en
    FROM SC_products a, SC_product_pictures d
    WHERE a.ordering_available='1' AND d.productID=a.productID AND

    CASE
        WHEN cID IS NOT NULL
        THEN a.categoryID = cID
        WHEN cID IS NULL
        THEN 1 = 1
    END

    AND

    CASE
        WHEN pID IS NOT NULL
        THEN a.productID = pID
        WHEN pID IS NULL
        THEN 1 = 1
    END

    AND

    CASE

        WHEN os IS NOT NULL
        THEN a.on_special = os
        WHEN os IS NULL
        THEN 1 = 1
    END

    AND

    CASE
        WHEN productName IS NOT NULL
        THEN a.name_en LIKE CONCAT('%',productName,'%')
        WHEN productName IS NULL
        THEN 1 = 1
    END

    ORDER BY a.name_en ASC;

    END IF;

    END$$

DELIMITER ;

Can anyone point to the right way on doing a stored procedure search with multiple column filters?

Body:
How about this:

SELECT DISTINCT d.thumbnail, a.productID, a.name_en, a.categoryID, a.Price, a.description_en
FROM SC_products a
INNER JOIN SC_product_pictures d ON d.productID = a.productID
WHERE a.ordering_available='1' AND
(cID IS NULL OR a.categoryID = cID) AND
(pID IS NULL OR a.productID = pID) AND
(os IS NULL OR a.on_special = os) AND
(productName IS NULL OR a.name_en LIKE CONCAT('%', productName, '%'))


问:
Updating values of dynamically created nested UI elements C#
I am new to UWP and C# but I have been tasked with creating a UI that is created dynamically based on an XML file that is read in.

I am having trouble updating values that are nested inside an ObservableCollection.

The current structure uses StackPanels as a container to add UI elements to. The heirarchy looks like this when the elements are created.

```<code>StackPanel = Outermost container panel
-StackPanel = Section Stack panel :implements ObservableCollection
--StackPanel = Entry container panel :implements INotifyPropertyChanged
---StackPanel = Entry inner Wrapper panel :implements INotifyPropertyChanged
---- This is where the UI elements like textboxes live
---- TextBox
---- TextBox
</code>```

I need extract the values of the TextBoxes but they don't ever update from their original value.
I am having trouble finding documentation that points to a good way of doing this kind of thing (usually means it shouldn't really be done haaa) any input would be much appreciated.

答:
I ended up using this link to solve my problem.
http://www.teixeira-soft.com/bluescreen/2016/03/23/c-how-to-dinamicaly-select-a-datatemplate-for-each-item-in-a-list/</p>

Body:
I am new to UWP and C# but I have been tasked with creating a UI that is created dynamically based on an XML file that is read in.

I am having trouble updating values that are nested inside an ObservableCollection.

The current structure uses StackPanels as a container to add UI elements to. The heirarchy looks like this when the elements are created.

StackPanel = Outermost container panel
-StackPanel = Section Stack panel :implements ObservableCollection
--StackPanel = Entry container panel :implements INotifyPropertyChanged
---StackPanel = Entry inner Wrapper panel :implements INotifyPropertyChanged
---- This is where the UI elements like textboxes live
---- TextBox
---- TextBox

I need extract the values of the TextBoxes but they don't ever update from their original value.
I am having trouble finding documentation that points to a good way of doing this kind of thing (usually means it shouldn't really be done haaa) any input would be much appreciated.


问:
How to run test on specific browser by selenium grid
I have register two platform with chrome browser on windows 7 and windows 10 into selenium grid server.

I want to run a test at Chrome browser on Windows 10 but when i run the test, the test randomly run on Windows 7 and randomly run on Windows 10 on chrome.

Do you have an idea how to do the configuration to run the test on specific browser and platform when we have registered multiple platform?

hub:

```<code>java -jar selenium-server-standalone-3.7.1.jar -role hub
</code>```

register node on windows 7:

```<code>java -Dwebdriver.chrome.driver=chromedriver_2.33.exe -jar selenium-server-standalone-3.7.1.jar -role node -hub http://localhost:4444
</code>```

register node on windows 10:

```<code>java -Dwebdriver.chrome.driver=chromedriver_2.33.exe -jar selenium-server-standalone-3.7.1.jar -role node -hub http://localhost:4444
</code>```

protractor.conf.js

```<code>exports.config = {

    specs: [
        '**/*.mytest.e2e-spec.ts'
    ],
    multiCapabilities: [
        {
            browserName: 'chrome',
            platform: 'WIN10',
        }
    ],
    seleniumAddress: 'http://localhost:4444/wd/hub',
    baseUrl: 'http://localhost:4200/',
    framework: 'jasmine',
    jasmineNodeOpts: {
        print: function () {
        }
    },
    onPrepare: function () {
        require('ts-node').register({
            project: 'e2e/tsconfig.e2e.json'
        });
    }
};
</code>```

答:
I would suggest that you do the following

Create a node configuration file as seen here, wherein for the WINDOWS7 node, you specify the appropriate platform (make sure you pick a value from here)

Now you start off the node by specifying this newly created nodeConfig json using the command line parameter -nodeConfig node.json ( For more details refer to my blog post here )

Now based on the PLATFORM capabilities specified by your test, it would be routed to the appropriate node.

Body:
I have register two platform with chrome browser on windows 7 and windows 10 into selenium grid server.

I want to run a test at Chrome browser on Windows 10 but when i run the test, the test randomly run on Windows 7 and randomly run on Windows 10 on chrome.

Do you have an idea how to do the configuration to run the test on specific browser and platform when we have registered multiple platform?

hub:

java -jar selenium-server-standalone-3.7.1.jar -role hub

register node on windows 7:

java -Dwebdriver.chrome.driver=chromedriver_2.33.exe -jar selenium-server-standalone-3.7.1.jar -role node -hub http://localhost:4444

register node on windows 10:

java -Dwebdriver.chrome.driver=chromedriver_2.33.exe -jar selenium-server-standalone-3.7.1.jar -role node -hub http://localhost:4444

protractor.conf.js

exports.config = {

    specs: [
        '**/*.mytest.e2e-spec.ts'
    ],
    multiCapabilities: [
        {
            browserName: 'chrome',
            platform: 'WIN10',
        }
    ],
    seleniumAddress: 'http://localhost:4444/wd/hub',
    baseUrl: 'http://localhost:4200/',
    framework: 'jasmine',
    jasmineNodeOpts: {
        print: function () {
        }
    },
    onPrepare: function () {
        require('ts-node').register({
            project: 'e2e/tsconfig.e2e.json'
        });
    }
};


问:
CSS/JS files not showing from server to reverse-proxy OctoPrint server via Nginx
I've got a Nginx server running on website https://example.com. I'm trying to serve a page (from an OctoPi) via reverse proxy, on another remote server that I own/admin, served at http://1.2.3.4:1988.

I can serve up the main page at https://example.com/foo/, but the css and js files are not loading. The console shows that files such as https://example.com/foo/static/webassets/packed_libs.css are giving a 404 error. If I access https://1.2.3.4:1988/foo/static/webassets/packed_libs.css I can read the css file.

I'm sure my nginx config file in /etc/nginx/sites-available/default is probably fubar-ed, but I can't seem to figure out where, since the error nor access logs expose anything wrong, nor do the haproxy logs on the OctoPi.

Nginx config file:

```<code>server {
    listen 80;
    server_name www.example.com;
    listen [::]:80 default_server;
    return  301 https://example.com$request_uri;
}

server {
    listen 443 ssl;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;

    # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}

server{
    listen 80;
    server_name example.com;
    root /var/www/example.com/public;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
        include /etc/nginx/mime.types;
        default_type application/octet-stream;
    }

    location ^~ /foo {
        # Redirecting via reverse proxy to OctoPi server
        proxy_pass http://1.2.3.4:1988/;
        proxy_redirect default;
        proxy_set_header Host $host;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        include mime.types;
        sub_filter '/i18n/' '/foo/i18n/';
        sub_filter '/static/'  '/foo/static/';
        sub_filter_once off;
    }

    location /foo/sockjs {
        proxy_pass http://1.2.3.4:1988/;
        proxy_http_version 1.1;
        proxy_redirect off;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;

    location = /50x.html {
        root /var/www/example.com/public;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;

        # With php7.0-cgi alone:
        # fastcgi_pass 127.0.0.1:9000;
        # With php7.0-fpm:
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
    if ($scheme != "https") {
        return 301 https://$host$request_uri;
    } # managed by Certbot

}
</code>```

答:
I found the documentation to my question here: https://github.com/foosel/OctoPrint/wiki/Reverse-proxy-configuration-examples

I will include the relevant portion for posterity:

```<code>server {
            listen       80;
            server_name  localhost;

            location /foo {
                proxy_pass http://1.2.3.4:1988; # NO trailing slash here!
                proxy_set_header Host $http_host;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Scheme $scheme;

                client_max_body_size 0;
            }
            ...
</code>```

However, I've since moved to back to Apache, since I'm more familiar with its setup and usage.

Body:
I've got a Nginx server running on website https://example.com. I'm trying to serve a page (from an OctoPi) via reverse proxy, on another remote server that I own/admin, served at http://1.2.3.4:1988.

I can serve up the main page at https://example.com/foo/, but the css and js files are not loading. The console shows that files such as https://example.com/foo/static/webassets/packed_libs.css are giving a 404 error. If I access https://1.2.3.4:1988/foo/static/webassets/packed_libs.css I can read the css file.

I'm sure my nginx config file in /etc/nginx/sites-available/default is probably fubar-ed, but I can't seem to figure out where, since the error nor access logs expose anything wrong, nor do the haproxy logs on the OctoPi.

Nginx config file:

server {
    listen 80;
    server_name www.example.com;
    listen [::]:80 default_server;
    return  301 https://example.com$request_uri;
}

server {
    listen 443 ssl;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;

    # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}

server{
    listen 80;
    server_name example.com;
    root /var/www/example.com/public;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
        include /etc/nginx/mime.types;
        default_type application/octet-stream;
    }

    location ^~ /foo {
        # Redirecting via reverse proxy to OctoPi server
        proxy_pass http://1.2.3.4:1988/;
        proxy_redirect default;
        proxy_set_header Host $host;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        include mime.types;
        sub_filter '/i18n/' '/foo/i18n/';
        sub_filter '/static/'  '/foo/static/';
        sub_filter_once off;
    }

    location /foo/sockjs {
        proxy_pass http://1.2.3.4:1988/;
        proxy_http_version 1.1;
        proxy_redirect off;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;

    location = /50x.html {
        root /var/www/example.com/public;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;

        # With php7.0-cgi alone:
        # fastcgi_pass 127.0.0.1:9000;
        # With php7.0-fpm:
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
    if ($scheme != "https") {
        return 301 https://$host$request_uri;
    } # managed by Certbot

}

Body:
I found the documentation to my question here: https://github.com/foosel/OctoPrint/wiki/Reverse-proxy-configuration-examples

I will include the relevant portion for posterity:

server {
            listen       80;
            server_name  localhost;

            location /foo {
                proxy_pass http://1.2.3.4:1988; # NO trailing slash here!
                proxy_set_header Host $http_host;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Scheme $scheme;

                client_max_body_size 0;
            }
            ...

However, I've since moved to back to Apache, since I'm more familiar with its setup and usage.


问:
Div reading as null still
The second part of this is reading null for some reason. It's working for the first part.

```<code>window.onload = function() {
var div = document.createElement("div");
div.innerHTML = '<img alt="pickle" src="images/pickle">';
div.style.visibility = "visible";
div.style.position = "absolute";
div.style.zIndex = "3";
div.className = "jack";
document.body.appendChild(div);
</code>```

second part

```<code>document.onmousemove=function(e){
  var x, y;
  if (e) {x=e.clientX; y=e.clientY;}
  else {x=event.clientX;y=event.clientY;}
  var jack = document.getElementById('jack');
  jack.style.top=y+'px';
  jack.style.left=x+50+'px';
}};
</code>```

window.onload = function() {
var div = document.createElement("div");
div.innerHTML = '';
div.style.visibility = "visible";
div.style.position = "absolute";
div.style.zIndex = "3";
div.className = "jack";
document.body.appendChild(div);

document.onmousemove=function(e){
  var x, y;
  if (e) {x=e.clientX; y=e.clientY;}
  else {x=event.clientX;y=event.clientY;}
  var jack = document.getElementByClassName('jack');
  jack.style.top=y+'px';
  jack.style.left=x+50+'px';
  }};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
</head>
<body>
</body>
</html></code>```

答:
same story:
getElementsByClassName() returns HTMLCollection (array of HTMLElements), getElementsByClassName("css-class")[0] is the first HTMLElement found.

the only exception is getElementById() method. it returns single HTMLElement (because id attribute is unique - one document cannot contain two elements with same id values)

Title: Div reading as null still

Body:
The second part of this is reading null for some reason. It's working for the first part.

window.onload = function() {
var div = document.createElement("div");
div.innerHTML = '';
div.style.visibility = "visible";
div.style.position = "absolute";
div.style.zIndex = "3";
div.className = "jack";
document.body.appendChild(div);

second part

document.onmousemove=function(e){
  var x, y;
  if (e) {x=e.clientX; y=e.clientY;}
  else {x=event.clientX;y=event.clientY;}
  var jack = document.getElementById('jack');
  jack.style.top=y+'px';
  jack.style.left=x+50+'px';
}};

window.onload = function() {
var div = document.createElement("div");
div.innerHTML = '';
div.style.visibility = "visible";
div.style.position = "absolute";
div.style.zIndex = "3";
div.className = "jack";
document.body.appendChild(div);

document.onmousemove=function(e){
  var x, y;
  if (e) {x=e.clientX; y=e.clientY;}
  else {x=event.clientX;y=event.clientY;}
  var jack = document.getElementByClassName('jack');
  jack.style.top=y+'px';
  jack.style.left=x+50+'px';
  }};


问:
How to use UIDocumentPickerViewController to pick a custom type?
I'm having a problem importing a file from the cloud. I'm dealing with a custom filetype that I didn't actually create. So I don't know what the actual extension type is (for example com.example.pdf). The file ends in .toc, so is there a way I can only accept files that end in .toc?

For example something like this:

```<code>UIDocumentPickerViewController(documentTypes: [String("*.toc")], in: .import)
</code>```

If this is not possible, is there a way to allow ANY file to be selected? From there I could just check the last 4 digits and let the user know that the file must end in .toc?

To try and get more information on what type of file this is, I have also ran the following command in terminal:

```<code>file -I filename.toc
</code>```

Which returned:

```<code>filename.toc: text/html; charset=us-ascii
</code>```

Because this says it's a "text/html" file I tried using:

```<code>UIDocumentPickerViewController(documentTypes: [String(kUTTypeText)], in: .import)
</code>```

However, this didn't allow me to select the file... Does anyone have any ideas?

答:
kUTTypeText is for text/plain. You want kUTTypeHTML for text/html.

iOS may not agree that "toc" files are text/html. You should probably add an appropriate "Exported UTI" to your Info.plist that defines an appropriate mime-type for the "toc" extension. Then use that mime-type with your UIDocumentPickerViewController.

See Uniform Type Identifiers Overview for details on setting up an exported UTI in your app.

If you want to allow any file, use kUTTypeItem.

Body:
I'm having a problem importing a file from the cloud. I'm dealing with a custom filetype that I didn't actually create. So I don't know what the actual extension type is (for example com.example.pdf). The file ends in .toc, so is there a way I can only accept files that end in .toc?

For example something like this:

UIDocumentPickerViewController(documentTypes: [String("*.toc")], in: .import)

If this is not possible, is there a way to allow ANY file to be selected? From there I could just check the last 4 digits and let the user know that the file must end in .toc?

To try and get more information on what type of file this is, I have also ran the following command in terminal:

file -I filename.toc

Which returned:

filename.toc: text/html; charset=us-ascii

Because this says it's a "text/html" file I tried using:

UIDocumentPickerViewController(documentTypes: [String(kUTTypeText)], in: .import)

However, this didn't allow me to select the file... Does anyone have any ideas?


问:
document.getElementById("images").children[0] to a string
The toString() method will output [object HTMLImageElement]. I want a string representation of the the image element ''. outerHTML returns undefined in firefox.

How can I accomplish this?

答:
outerHTML is not cross-browser.

The easiest way is to clone the element and add it to a parent element, then get the innerHTML of that:

```<code>var outer = document.createElement('outer'),
    child = document.getElementById(“images”).children[0].cloneNode(true);

outer.appendChild(child);

var imgHtml = outer.innerHTML;
</code>```

Body:
outerHTML is not cross-browser.

The easiest way is to clone the element and add it to a parent element, then get the innerHTML of that:

var outer = document.createElement('outer'),
    child = document.getElementById(“images”).children[0].cloneNode(true);

outer.appendChild(child);

var imgHtml = outer.innerHTML;


问:
How can I swap the dimensions of a netCDF file?
I have a

```<code>dimensions:
    time = 1000 ;
    xr = 100 ;
variables:
    int time(time) ;
        time:long_name = "time since time reference (instant)" ;
        time:units = "hours since 2010-05-01" ;
    double v1(xr, time) ;
        v1:long_name = "V1" ;
        averageInstantRunoff:units = "m s-1" ;
    double v1(time, xr) ;
        v1:long_name = "V1" ;
        averageInstantRunoff:units = "m s-1" ;
    int xr(xr) ;
        xr:long_name = "xr index" ;
        xr:units = "-" ;
</code>```

Here, I want to make variable v1 to have dimensions of (time, xr) instead of (xr,time).

I do this using:

```<code>ncpdq -v v1 -a time,xr test.nc test2.nc
</code>```

But ofcourse, it doesn't copy v2. I do it over large files with large number of variables and I only want to do it for a single variable.

How can I do this?

答:
You can also the use ncap2 permute() method:

```<code>ncap2 -s 'v1_prm=v1.permute($time,$xr)' in.nc out.nc
</code>```

but then your output will have a v1 and a v1_prm. Either way it's a two line process with NCO because you need a second step to append (ncpdq method) or remove the extra variable (ncap2 method).

Body:
I have a

dimensions:
    time = 1000 ;
    xr = 100 ;
variables:
    int time(time) ;
        time:long_name = "time since time reference (instant)" ;
        time:units = "hours since 2010-05-01" ;
    double v1(xr, time) ;
        v1:long_name = "V1" ;
        averageInstantRunoff:units = "m s-1" ;
    double v1(time, xr) ;
        v1:long_name = "V1" ;
        averageInstantRunoff:units = "m s-1" ;
    int xr(xr) ;
        xr:long_name = "xr index" ;
        xr:units = "-" ;

Here, I want to make variable v1 to have dimensions of (time, xr) instead of (xr,time).

I do this using:

ncpdq -v v1 -a time,xr test.nc test2.nc

But ofcourse, it doesn't copy v2. I do it over large files with large number of variables and I only want to do it for a single variable.

How can I do this?

Body:
You can also the use ncap2 permute() method:

ncap2 -s 'v1_prm=v1.permute($time,$xr)' in.nc out.nc

but then your output will have a v1 and a v1_prm. Either way it's a two line process with NCO because you need a second step to append (ncpdq method) or remove the extra variable (ncap2 method).


问:
How to get input value from templates and store to database [Django]
I'm trying to get {{ id }} when user clicks on movie and save it to models. I can't use modelForm because id parameter comes from html template. Any suggestions?

Maybe, there is a different way to get an id of that movie user clicks?

Btw, I'm using tmdb api.

```<code>{% for id, poster in poster_id_zip %}
    <div style="display: inline-block; margin: 10px;" class="">
      <a href="{{ movie_details }}"><img src="{{ poster }}" alt=""></a>
      <form class="add-movie-form" method="POST">
        {% csrf_token %}
        <input type="hidden" name="movie-id" value="{{ id }}">
        <button style="display: block; margin: 5px auto 0 auto;" type="submit" name="add">Add</button>
      </form>
    </div>
{% endfor %}
</code>```

views.py

```<code>def index(request):
    api_key = "api_key"
    image_base_url = "https://image.tmdb.org/t/p/"
    if request.method == "POST":
        user_query = request.POST.get('search-box', ' ')
        if user_query == '':
            user_query = ' '

        search_movies_url = "https://api.themoviedb.org/3/search/movie?api_key={}&query={}".format(api_key, user_query)

        search_results_data = requests.get(search_movies_url)

        total_results = search_results_data.json().get("total_results") # for handling no search results

        movie_ids, poster_path, poster_full_url = [], [], []

        for movie in search_results_data.json().get("results"):
            movie_ids.append(movie.get("id"))
            poster_path.append(movie.get("poster_path"))

        for poster in poster_path:
            poster_full_url.append(image_base_url+"{}{}".format("w185", poster))

        movie_details = "https://api.themoviedb.org/3/movie/{}?api_key={}".format(movie_ids, api_key)

        poster_id_zip = zip(movie_ids, poster_full_url) # grouping ids with poster images

        context = {"movie_ids": movie_ids, "poster_url": poster_full_url, "movie_details": movie_details, "poster_id_zip": poster_id_zip, "total_results": total_results,}

        return render(request, 'homepage/movies.html', context)
    return render(request, 'homepage/index.html')
</code>```

models.py

```<code>from django.db import models

# Create your models here.

class MovieId(models.Model):
    movie_id = models.IntegerField()
    def __str__(self):
        return self.movie_id
</code>```

答:
You don't need a ModelForm here. In the view that you post the form to just save the model in the database.</p>

```<code>if request.method == "POST":
    MovieId.objects.update_or_create(movie_id=request.POST['movie-id'])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to get {{ id }} when user clicks on movie and save it to models. I can't use modelForm because id parameter comes from html template. Any suggestions?

Maybe, there is a different way to get an id of that movie user clicks?

Btw, I'm using tmdb api.

{% for id, poster in poster_id_zip %}

      <form class="add-movie-form" method="POST">
        {% csrf_token %}
        <input type="hidden" name="movie-id" value="{{ id }}">
        <button style="display: block; margin: 5px auto 0 auto;" type="submit" name="add">Add</button>
      </form>

{% endfor %}

views.py

def index(request):
    api_key = "api_key"
    image_base_url = "https://image.tmdb.org/t/p/"
    if request.method == "POST":
        user_query = request.POST.get('search-box', ' ')
        if user_query == '':
            user_query = ' '

        search_movies_url = "https://api.themoviedb.org/3/search/movie?api_key={}&query={}".format(api_key, user_query)

        search_results_data = requests.get(search_movies_url)

        total_results = search_results_data.json().get("total_results") # for handling no search results

        movie_ids, poster_path, poster_full_url = [], [], []

        for movie in search_results_data.json().get("results"):
            movie_ids.append(movie.get("id"))
            poster_path.append(movie.get("poster_path"))

        for poster in poster_path:
            poster_full_url.append(image_base_url+"{}{}".format("w185", poster))

        movie_details = "https://api.themoviedb.org/3/movie/{}?api_key={}".format(movie_ids, api_key)

        poster_id_zip = zip(movie_ids, poster_full_url) # grouping ids with poster images

        context = {"movie_ids": movie_ids, "poster_url": poster_full_url, "movie_details": movie_details, "poster_id_zip": poster_id_zip, "total_results": total_results,}

        return render(request, 'homepage/movies.html', context)
    return render(request, 'homepage/index.html')

models.py

from django.db import models

# Create your models here.

class MovieId(models.Model):
    movie_id = models.IntegerField()
    def __str__(self):
        return self.movie_id

Body:
You don't need a ModelForm here. In the view that you post the form to just save the model in the database.

if request.method == "POST":
    MovieId.objects.update_or_create(movie_id=request.POST['movie-id'])


问:
Visual Studio Error: Master edit already in progress
In source view when I am trying to edit something a dialogue box is coming saying "Master edit already in progress" as shown in the below image

What could be the reason ?
Just closing the form and re-opening it resolves the issue, but I want know, what is happening behind the scene ?

答:
I just got the same error as well.  duplicates each line of code twice, temporarily though.  Then if you attempt to edit any line of code after the duplication of the code goes away, I get the error:

Attempted TextBuffer edit operation while another edit is in progress

Have to restart VS 2015 to resolve the issue.


问:
Enable all GPIO pins on BeagleBone, including the eMMC pins
I'm running Debian Jessie IOT image on a BeagleBone Green.
I like to use the maximum of GPIOs, which is according to the documentation should give me 65 GPIOs.
GPIOs on BeagleBone Green

All work except the pins that are shared with the eMMC:
P8_3-6, P8_20-25

So this works:

config-pin -a P8_7 in+

This does not work:

config-pin -a P8_22 in+

```<code>bash: /sys/devices/platform/ocp/ocp*P8_22_pinmux/state: No such file or directory
Cannot write pinmux file: /sys/devices/platform/ocp/ocp*P8_22_pinmux/state
</code>```

Some information.....

```<code>root@beaglebone:~# cat /sys/devices/platform/bone_capemgr/slots
0: PF----  -1
1: PF----  -1
2: PF----  -1
3: PF----  -1
4: P-O-L-   0 Override Board Name,00A0,Override Manuf,cape-universala
</code>```

cape-universala should export all pins
in dmesg is....

```<code> [    4.002843] pinctrl-single 44e10800.pinmux: pin 44e10814.0 already requested by 481d8000.mmc; cannot claim for ocp:P8_22_pinmux
 [    4.014528] pinctrl-single 44e10800.pinmux: pin-5 (ocp:P8_22_pinmux) status -22
 [    4.021901] pinctrl-single 44e10800.pinmux: could not request pin 5 (44e10814.0) from group pinmux_P8_22_default_pin  on device pinctrl-single
 [    4.034756] bone-pinmux-helper ocp:P8_22_pinmux: Error applying setting, reverse things back
 [    4.089416] pinctrl-single 44e10800.pinmux: pin 44e10814.0 already requested by 481d8000.mmc; cannot claim for ocp:P8_22_pinmux
 [    4.101069] pinctrl-single 44e10800.pinmux: pin-5 (ocp:P8_22_pinmux) status -22
</code>```

I can't seem to disable the eMMC, this is /boot/uEnv.txt

```<code>  cmdline=coherent_pool=1M net.ifnames=0 quiet cape_enable=bone_capemgr.enable_partno=cape-universala cape_disable=bone_capemgr.disable_partno=BB-BONE-EMMC-2G
</code>```

I am booting the BeagleBone from an sd-card, so the eMMC don't have to be used.

what's wrong?

答:
The directory, I am sure you are familiar w/ this procedure, /boot has a file in it called uEnv.txt.

There was an older way to adjust settings and it may still apply. This application of commenting uncommenting the eMMC part to the uEnv.txt file should allow you to use those specific pins for use.

Now...please listen.

I have done this before and have not been able to boot from my eMMC once I have uncommented, remove the # mark, the eMMC. I know that you are using an SD Card. I can test it real quickly and get back to you.

I just wanted to let you know that this exists and that uboot overlays in newer Debian images are what is done now. So, I am pretty sure that we do not use device tree overlays on specific Debian Distros. I guess it all depends on what kernel you have and what image you have booted on your machine.

Um...I have my machine plugged in now and I am about to test the SD Card support after I changed my /boot directory file uEnv.txt to uncomment the eMMC portion to the file. I am using Linux beaglebone 4.4.91-ti-r136 on my machine for compatibility w/ Adafruit_BBIO's PWM.

In that file, the uEnv.txt file in the /boot directory, I had to uncomment this section: disable_uboot_overlay_emmc=1.

I am about to reboot.

Okay...I was able to boot w/ uncommenting the disable_uboot_overlay_emmc=1 portion to the uEnv.txt file.

This should open up the pins. I will test it really quickly.

Seth

P.S. https://github.com/mvduin/bbb-pin-utils is a good utility for showing pins that are available.

This is the photo of my print out using that utility for the pins.

Body:
I'm running Debian Jessie IOT image on a BeagleBone Green.
I like to use the maximum of GPIOs, which is according to the documentation should give me 65 GPIOs.
GPIOs on BeagleBone Green

All work except the pins that are shared with the eMMC:
P8_3-6, P8_20-25

So this works:

config-pin -a P8_7 in+

This does not work:

config-pin -a P8_22 in+

bash: /sys/devices/platform/ocp/ocp*P8_22_pinmux/state: No such file or directory
Cannot write pinmux file: /sys/devices/platform/ocp/ocp*P8_22_pinmux/state

Some information.....

root@beaglebone:~# cat /sys/devices/platform/bone_capemgr/slots
0: PF----  -1
1: PF----  -1
2: PF----  -1
3: PF----  -1
4: P-O-L-   0 Override Board Name,00A0,Override Manuf,cape-universala

cape-universala should export all pins
in dmesg is....

 [    4.002843] pinctrl-single 44e10800.pinmux: pin 44e10814.0 already requested by 481d8000.mmc; cannot claim for ocp:P8_22_pinmux
 [    4.014528] pinctrl-single 44e10800.pinmux: pin-5 (ocp:P8_22_pinmux) status -22
 [    4.021901] pinctrl-single 44e10800.pinmux: could not request pin 5 (44e10814.0) from group pinmux_P8_22_default_pin  on device pinctrl-single
 [    4.034756] bone-pinmux-helper ocp:P8_22_pinmux: Error applying setting, reverse things back
 [    4.089416] pinctrl-single 44e10800.pinmux: pin 44e10814.0 already requested by 481d8000.mmc; cannot claim for ocp:P8_22_pinmux
 [    4.101069] pinctrl-single 44e10800.pinmux: pin-5 (ocp:P8_22_pinmux) status -22

I can't seem to disable the eMMC, this is /boot/uEnv.txt

  cmdline=coherent_pool=1M net.ifnames=0 quiet cape_enable=bone_capemgr.enable_partno=cape-universala cape_disable=bone_capemgr.disable_partno=BB-BONE-EMMC-2G

I am booting the BeagleBone from an sd-card, so the eMMC don't have to be used.

what's wrong?


问:
Where does local variables actually allocated within CLR?
I'm just going inside the CLR and IL and I'm confused by this thing.

I have the following C# code:

```<code>int x = 1;
object obj = x;
int y = (int)obj;
</code>```

And IL disassemble for this

```<code>      // Code size       18 (0x12)
  .maxstack  1
  .locals init ([0] int32 x,
           [1] object obj,
           [2] int32 y)
  IL_0000:  nop
  IL_0001:  ldc.i4.1
  IL_0002:  stloc.0
  IL_0003:  ldloc.0
  IL_0004:  box        [mscorlib]System.Int32
  IL_0009:  stloc.1
  IL_000a:  ldloc.1
  IL_000b:  unbox.any  [mscorlib]System.Int32
  IL_0010:  stloc.2
  IL_0011:  ret
</code>```

So, the ldloc.0 instruction "Loads the local variable at index 0 onto stack.". But where does the locals really stored and where does they loaded from. Because I thought that there are two places where the memory can be allocated: thread stack and heap. And variables should be stored in the stack.

Now, I suppose, that the stack is just an "evaluation stack", while the memory allocation for variables is an implementation detail and depend on platform and JIT compiler. And we actually can split the memory used by our programm on evaluation stack, managed heap, and locals allocated memory.

Is this true? Or there are some other mechanism here?

答:
You are severely conflating many things which are logically different:

Just because a variable is a local variable in C# does not mean that it is on the short term storage pool in IL. Local variables in C# can correspond to short term storage, long term storage, or evaluation stack in the corresponding IL.

Short term storage and evaluation stack in IL can correspond to stack or register storage in the jitted machine code.

When compiling C# to IL, the C# compiler makes locals members of a closure class -- they go on the long term storage pool -- when the lifetime of the local is possibly longer than the activation of the method. (Or when the activation of the method is broken up into little pieces, like it is in an async method.)

If the locals have short lifetimes then the compiler's optimizer chooses whether they go on the short term pool or the evaluation stack; the compiler calls the latter "ephemeral" locals. The algorithm for deciding when to make a local into an ephemeral is interesting; see the compiler source code for details.

The jitter then must decide whether to make short term pool variables and evaluation stack variables into stack locations or registers; it does so again using a complex optimization algorithm that varies depending on register availability and so on.

Finally, of course the C# compiler and the jitter are both free to reify an unread local as nothing at all; storage that is never read from need not actually be allocated.

Body:
I'm just going inside the CLR and IL and I'm confused by this thing.

I have the following C# code:

int x = 1;
object obj = x;
int y = (int)obj;

And IL disassemble for this

      // Code size       18 (0x12)
  .maxstack  1
  .locals init ([0] int32 x,
           [1] object obj,
           [2] int32 y)
  IL_0000:  nop
  IL_0001:  ldc.i4.1
  IL_0002:  stloc.0
  IL_0003:  ldloc.0
  IL_0004:  box        [mscorlib]System.Int32
  IL_0009:  stloc.1
  IL_000a:  ldloc.1
  IL_000b:  unbox.any  [mscorlib]System.Int32
  IL_0010:  stloc.2
  IL_0011:  ret

So, the ldloc.0 instruction "Loads the local variable at index 0 onto stack.". But where does the locals really stored and where does they loaded from. Because I thought that there are two places where the memory can be allocated: thread stack and heap. And variables should be stored in the stack.

Now, I suppose, that the stack is just an "evaluation stack", while the memory allocation for variables is an implementation detail and depend on platform and JIT compiler. And we actually can split the memory used by our programm on evaluation stack, managed heap, and locals allocated memory.

Is this true? Or there are some other mechanism here?


问:
TypeScript: Why let print = console.log.bind(console) only works if there is a import before it?
I'm a bit puzzled that:

```<code>let print = console.log.bind(console)
</code>```

Does not work (gives "Cannot redeclare block-scoped variable 'print'"), but this works perfectly:

```<code>import { readFileSync } from 'fs' //or even import { } from 'anything'
const print = console.log.bind(console)
</code>```

More puzzling, using another name for the variable (like "printIt") works.

What's happening?

答:
The top-level scope in a file is handled differently depending on the presence of top-level import or export statements. This is not a bug:

A file with one top-level import/export (e.g. test.ts in your example) is considered a module. modules have their own scope, and do not merge with global scope declarations.

So as soon as you have top-level import, print variable is now in its own scope and does not conflict with global print defined in dom type declarations (in a browser environment, there is top-level global function named print() that opens print current page dialog).

Body:
I'm a bit puzzled that:

let print = console.log.bind(console)

Does not work (gives "Cannot redeclare block-scoped variable 'print'"), but this works perfectly:

import { readFileSync } from 'fs' //or even import { } from 'anything'
const print = console.log.bind(console)

More puzzling, using another name for the variable (like "printIt") works.

What's happening?


问:
What does the html bindpoint attribute do?
I'm currently making a facebook application and while investigating the (X)HTML source code for a message thread page to see if it was possible to link to specific messages within threads (apparently it's not), I encountered an HTML attribute that I cannot seem to find any information about. Some span elements on the page had a 'bindpoint' attribute that was set to various values (presumably element IDs). Here is an excerpt from the page source (I replaced some private info with Xs)

```<code><div class="GBThreadMessageRow_Info">
  <span class="GBThreadMessageRow_AuthorLink_Wrapper" bindpoint="authorLinkWrapper">
    <a href="http://www.facebook.com/profile.php?id=XXXXXXXXX" class="GBThreadMessageRow_AuthorLink">XXXXXXXX</a>
  </span>
  <span class="GBThreadMessageRow_Date">
    April 8, 2010 at 10:13pm
  </span>
  <span bindpoint="branchLinkWrapper" class="GBThreadMessageRow_BranchLink"><a href="/ajax/messaging/composer.php?thread=XXXXX&msg_id=XXXXX&id=XXXXXX" rel="dialog-post">Reply</a></span>
  <span bindpoint="reportLinkWrapper" class="GBThreadMessageRow_ReportLink"> • <a href="/ajax/report.php?content_type=9&cid=XXXXX&rid=XXXXX&cid2=XXXX&cid3=X&h=XXXXX" rel="dialog" class="action">Report</a></span>
</div>
</code>```

I have never seen this attribute before and any information about it would be useful/helpful/interesting. Thanks!

答:
As was said in the comments, it has to be something they're doing in the javascript code.

Facebook uses an interesting technique to import their javascript files dynamically (basically they seem to write out script tags in the javascript, when necessary), and it's not quite as simple as just pressing ctrl-F through the first file you find.

So, in conclusion, the bindpoint attribute is something internal to the Facebook eco-system, and not standard HTML. From the name, I assume it has something to do with which events (clicks, mouseovers, etc.) should be binded to the element in question, which is signified by a variable name give in the bindpoint attribute. Or maybe it has to do with which element the element in question should be 'binded' to, like the for attribute for a label. Anyway, this is pure speculation.

Body:
I'm currently making a facebook application and while investigating the (X)HTML source code for a message thread page to see if it was possible to link to specific messages within threads (apparently it's not), I encountered an HTML attribute that I cannot seem to find any information about. Some span elements on the page had a 'bindpoint' attribute that was set to various values (presumably element IDs). Here is an excerpt from the page source (I replaced some private info with Xs)

    XXXXXXXX

    April 8, 2010 at 10:13pm

  Reply
   • Report

I have never seen this attribute before and any information about it would be useful/helpful/interesting. Thanks!