问:
nodejs serialport write issues?
I am using the nodejs serialport module (https://npmjs.org/package/serialport) and I am having issues when I write to the serial port.

If I simply write to the port as shown below, the serial device never gets the command.

```<code>var serialport = require("serialport");
var sp = new serialport.SerialPort(serialPortPath);
sp.write("SYST:ADDR?\n");
</code>```

However, if I use a setTimeout as shown below, then it seems to work?

```<code>var serialport = require("serialport");
var sp = new serialport.SerialPort(serialPortPath);
setTimeout(function(){sp.write("SYST:ADDR?\n")},1000);
</code>```

FYI, the "serialPortPath" is set elsewhere in the code.

I am not sure what is going on... any ideas?

答:
Here is another approach which works very well and allows for dynamic addressing of a specific serial device.  In my case I am only interested in connecting to the Numato device connected to our integrated system which is why I have the conditional logic in the list callback.

```<code> exports.testSerial = function(data) {
    serialPort.list(function(err, ports) {

      var port = {};

      for(var i = 0; i < ports.length; i++) {
        try {
          if(typeof ports[i].manufacturer != 'undefined' && ports[i].manufacturer.includes("Numato")) {
            port = ports[i];
          }
        } catch(err) {
          console.dir(err);
        }
      }

      // the port will be opened via the constructor of this call
      var numato = new serial(port.comName, {baudrate : 19200}, function(err) {
        if(err) {
          return console.dir(err);
        }

        // by having the write call within the callback you can access it directly w/o using .on()
        numato.write('relay ' + data.state + ' ' + data.channel + '\r', function(err) {
          if(err) {
            console.dir('error writing');
            console.dir(err);
          }
          console.dir('serial message written');
          numato.close();
        });
      });

      return true;

    });
 }
</code>```

Hope this helps someone in the future!  For reference this is with library version 4.0.7.

Title: nodejs serialport write issues?

Body:
I am using the nodejs serialport module (https://npmjs.org/package/serialport) and I am having issues when I write to the serial port.

If I simply write to the port as shown below, the serial device never gets the command.

var serialport = require("serialport");
var sp = new serialport.SerialPort(serialPortPath);
sp.write("SYST:ADDR?\n");

However, if I use a setTimeout as shown below, then it seems to work?

var serialport = require("serialport");
var sp = new serialport.SerialPort(serialPortPath);
setTimeout(function(){sp.write("SYST:ADDR?\n")},1000);

FYI, the "serialPortPath" is set elsewhere in the code.

I am not sure what is going on... any ideas?

Body:
Here is another approach which works very well and allows for dynamic addressing of a specific serial device.  In my case I am only interested in connecting to the Numato device connected to our integrated system which is why I have the conditional logic in the list callback.

 exports.testSerial = function(data) {
    serialPort.list(function(err, ports) {

      var port = {};

      for(var i = 0; i < ports.length; i++) {
        try {
          if(typeof ports[i].manufacturer != 'undefined' && ports[i].manufacturer.includes("Numato")) {
            port = ports[i];
          }
        } catch(err) {
          console.dir(err);
        }
      }

      // the port will be opened via the constructor of this call
      var numato = new serial(port.comName, {baudrate : 19200}, function(err) {
        if(err) {
          return console.dir(err);
        }

        // by having the write call within the callback you can access it directly w/o using .on()
        numato.write('relay ' + data.state + ' ' + data.channel + '\r', function(err) {
          if(err) {
            console.dir('error writing');
            console.dir(err);
          }
          console.dir('serial message written');
          numato.close();
        });
      });

      return true;

    });
 }

Hope this helps someone in the future!  For reference this is with library version 4.0.7.


来源: stackexchange

问:
Xcode - How to config a project for team working?
I'm working on a team project using Git for versioning. All team members got a personal AppleID and bundle identifier. Every time one of us pushes some changes, others need to adjust their Bundle Identifiers and Team. This is where we need to change settings:

Is there a way to work simultaneously on the same project under it versioning with our personal accounts?

答: You can hold some variables in separate xcconfig files. Adding them to gitignore will prevent from committing them to repository</p>

ContentLicense: CC BY-SA 3.0


问:
Big C# source file with Windows API method signatures, structures, constants: will they all be included in the final .exe?
I want to put all the signatures of Windows API functions I'm using in programs in one class, such as WinAPI, and in a file WinAPI.cs I will include in my projects. The class will be internal static and the methods public static extern. (Something like the huge NativeMethods.cs from the .NET Framework source code).

Let's say WinAPI.cs has one hundred native methods signatures like:

```<code>[DllImport("user32.dll")]
internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
</code>```

If I'm only going to use a few of them in a project (even one or two), if I include the WinAPI.cs file in my project, will the final .exe be filled with the unnecessary method declarations I'm not using (the other 99 or so)?

What about native structure declarations, If I'm not using them in the current project, will they still be included in the final .exe?

```<code>    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int X;
        public int Y;
    }
</code>```

What about constants declarations or readonly members like:

```<code>public const int WH_JOURNALPLAYBACK = 1;
public static readonly int WM_GETTEXT = 0x0D;
</code>```

答:
All elements which you have stated will be included in final assembly.
The only way to get rid of them from final exe file is precompilation directives usage.
For example:

```<code>#if EXCLUDE_METHODS
</code>```

//unused methods here

```<code>#endif
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I want to put all the signatures of Windows API functions I'm using in programs in one class, such as WinAPI, and in a file WinAPI.cs I will include in my projects. The class will be internal static and the methods public static extern. (Something like the huge NativeMethods.cs from the .NET Framework source code).

Let's say WinAPI.cs has one hundred native methods signatures like:

[DllImport("user32.dll")]
internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

If I'm only going to use a few of them in a project (even one or two), if I include the WinAPI.cs file in my project, will the final .exe be filled with the unnecessary method declarations I'm not using (the other 99 or so)?

What about native structure declarations, If I'm not using them in the current project, will they still be included in the final .exe?

    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int X;
        public int Y;
    }

What about constants declarations or readonly members like:

public const int WH_JOURNALPLAYBACK = 1;
public static readonly int WM_GETTEXT = 0x0D;

Body:
All elements which you have stated will be included in final assembly.
The only way to get rid of them from final exe file is precompilation directives usage.
For example:

#if EXCLUDE_METHODS

//unused methods here

#endif


问:
for loop code needs performance improvement
I would need your advice to improve the following code because it takes so much time to execute method1 and method2.  When I execute RemoveFullyContains I am calling method1 and method2. I have placed a time counter around both method and noticed that it takes so much time to execute both methods. May be someone can give me a guidance to improve it.</p>

```<code>public static List<VG> RemoveFullyContains(List<VG> lTree) {
        for (int x = lTree.size()-1; x >= 0; x--) {
            VG vg1 = lTree.get(x);
            for (int y = lTree.size()-1; y >= 0; y--) {
                if (y != x) {
                    VG vg2 = lTree.get(y);
                    if (method1(vg2.getAndVar(), vg1.getAndVar())) {
                        if (method2(vg1.getNotVar(), vg2.getNotVar())) {
                            lTree.remove(x);
                            break;
                        }
                    }
                }
            }
        }
        return lTree;
    }

    private boolean method1(List<String> searchList, List<String> mainList) {
        if (searchList == null || searchList.size() == 0) {
            return true;
        }
        if (mainList == null || mainList.size() == 0) {
            return false;
        }
        if (searchList.size() > mainList.size()) {
            return false;
        }
        for (String item : searchList) {
            if (!mainList.contains(item)) {
                return false;
            }
        }
        return true;
    }

    private boolean method2(List<String> list1, List<String> list2) {
        if ((list1 == null || list1.size() == 0) && (list2 == null || list2.size() == 0)) {
            return true;
        }
        if ((list1 == null || list1.size() == 0) || (list2 == null || list2.size() == 0)) {
            return false;
        }
        if (list1.size() != list2.size()) {
            return false;
        }
        for (String item : list1) {
            if (!list2.contains(item)) {
                return false;
            }
        }
        return true;
    }

VG is a class that has the following methods: hashcode, equal and clone
public class VG {
    private List<String> andVar = new ArrayList();
    private List<String> notVar = new ArrayList();
    private List<VG> orVar = new ArrayList();
    private VG parent;
....
}
</code>```

答:
if the Lists will never be null you could remove the null checks.  Of course most of the time will be spent iterating the Lists.

Since the same Lists are being re-used it would be faster to use a Set to give constant time lookup.  There's a penalty for building the Setbut re-using the same Set for the next iteration would be faster.

```<code>import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

public class Method1 {

    public static void main(String[] args) {
        Method1 methods = new Method1();

        List<VG> vgs = new ArrayList<VG>(1000);
        System.out.print("building VGs...");
        for (int i = 0; i < 1000; i++) {
            vgs.add(methods.buildVg(i));
        }
        System.out.println("complete.");

        System.out.print("testing method1 using List...");
        long current = System.currentTimeMillis();
        for (int i = 0; i < vgs.size() - 2; i++) {
            VG currentVG = vgs.get(i);
            VG nextVG = vgs.get(i + 1);
            methods.method1(currentVG.getAndVar(), currentVG.getAndVar());
            methods.method1(currentVG.getAndVar(), nextVG.getAndVar());
            methods.method1(nextVG.getAndVar(), currentVG.getAndVar());
            methods.method1(nextVG.getAndVar(), nextVG.getAndVar());
        }
        System.out.println("completed in " + (System.currentTimeMillis() - current) + " ms");

        System.out.print("testing method1 using Set...");
        current = System.currentTimeMillis();
        for (int i = 0; i < vgs.size() - 2; i++) {
            VG currentVG = vgs.get(i);
            VG nextVG = vgs.get(i + 1);
            methods.method1(currentVG.getAndVarAsSet(), currentVG.getAndVarAsSet());
            methods.method1(currentVG.getAndVarAsSet(), nextVG.getAndVarAsSet());
            methods.method1(nextVG.getAndVarAsSet(), currentVG.getAndVarAsSet());
            methods.method1(nextVG.getAndVarAsSet(), nextVG.getAndVarAsSet());
        }
        System.out.println("completed in " + (System.currentTimeMillis() - current) + " ms.");
    }

    private VG buildVg(int i) {
        VG vg = new VG();

        List<String> strings = new ArrayList<String>(6000);
        for (int j = 0; j < 6000; j++) {
            String s = UUID.randomUUID().toString();
            strings.add(i + s + j);
        }

        vg.setAndVar(strings);
        return vg;
    }

    private boolean method1(Collection<String> searchList, Collection<String> mainList) {
        if (searchList.size() == 0) {
            return true;
        }
        if (mainList.size() == 0) {
            return false;
        }
        if (searchList.size() > mainList.size()) {
            return false;
        }

        for (String item : searchList) {
            if (!mainList.contains(item)) {
                return false;
            }
        }
        return true;
    }

    private class VG {
        private List<String> andVar = new ArrayList<String>();
        private Set<String> andVarSet;

        public List<String> getAndVar() {
            return andVar;
        }

        public void setAndVar(List<String> andVar) {
            this.andVar = andVar;
        }

        public Set<String> getAndVarAsSet() {
            if (andVarSet != null) {
                return andVarSet;
            }

            andVarSet = new HashSet<String>(andVar.size());
            andVarSet.addAll(andVar);
            return andVarSet;
        }
    }
}
</code>```

Output:

```<code>building VGs...complete.
testing method1 using List...completed in 140966 ms
testing method1 using Set...completed in 1755 ms.
</code>```

If you're using java 8 then streams might be able to make it even faster.

Body:
I would need your advice to improve the following code because it takes so much time to execute method1 and method2.  When I execute RemoveFullyContains I am calling method1 and method2. I have placed a time counter around both method and noticed that it takes so much time to execute both methods. May be someone can give me a guidance to improve it.

public static List<VG> RemoveFullyContains(List<VG> lTree) {
        for (int x = lTree.size()-1; x >= 0; x--) {
            VG vg1 = lTree.get(x);
            for (int y = lTree.size()-1; y >= 0; y--) {
                if (y != x) {
                    VG vg2 = lTree.get(y);
                    if (method1(vg2.getAndVar(), vg1.getAndVar())) {
                        if (method2(vg1.getNotVar(), vg2.getNotVar())) {
                            lTree.remove(x);
                            break;
                        }
                    }
                }
            }
        }
        return lTree;
    }

    private boolean method1(List<String> searchList, List<String> mainList) {
        if (searchList == null || searchList.size() == 0) {
            return true;
        }
        if (mainList == null || mainList.size() == 0) {
            return false;
        }
        if (searchList.size() > mainList.size()) {
            return false;
        }
        for (String item : searchList) {
            if (!mainList.contains(item)) {
                return false;
            }
        }
        return true;
    }

    private boolean method2(List<String> list1, List<String> list2) {
        if ((list1 == null || list1.size() == 0) && (list2 == null || list2.size() == 0)) {
            return true;
        }
        if ((list1 == null || list1.size() == 0) || (list2 == null || list2.size() == 0)) {
            return false;
        }
        if (list1.size() != list2.size()) {
            return false;
        }
        for (String item : list1) {
            if (!list2.contains(item)) {
                return false;
            }
        }
        return true;
    }

VG is a class that has the following methods: hashcode, equal and clone
public class VG {
    private List<String> andVar = new ArrayList();
    private List<String> notVar = new ArrayList();
    private List<VG> orVar = new ArrayList();
    private VG parent;
....
}

Body:
if the Lists will never be null you could remove the null checks.  Of course most of the time will be spent iterating the Lists.

Since the same Lists are being re-used it would be faster to use a Set to give constant time lookup.  There's a penalty for building the Setbut re-using the same Set for the next iteration would be faster.

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

public class Method1 {

    public static void main(String[] args) {
        Method1 methods = new Method1();

        List<VG> vgs = new ArrayList<VG>(1000);
        System.out.print("building VGs...");
        for (int i = 0; i < 1000; i++) {
            vgs.add(methods.buildVg(i));
        }
        System.out.println("complete.");

        System.out.print("testing method1 using List...");
        long current = System.currentTimeMillis();
        for (int i = 0; i < vgs.size() - 2; i++) {
            VG currentVG = vgs.get(i);
            VG nextVG = vgs.get(i + 1);
            methods.method1(currentVG.getAndVar(), currentVG.getAndVar());
            methods.method1(currentVG.getAndVar(), nextVG.getAndVar());
            methods.method1(nextVG.getAndVar(), currentVG.getAndVar());
            methods.method1(nextVG.getAndVar(), nextVG.getAndVar());
        }
        System.out.println("completed in " + (System.currentTimeMillis() - current) + " ms");

        System.out.print("testing method1 using Set...");
        current = System.currentTimeMillis();
        for (int i = 0; i < vgs.size() - 2; i++) {
            VG currentVG = vgs.get(i);
            VG nextVG = vgs.get(i + 1);
            methods.method1(currentVG.getAndVarAsSet(), currentVG.getAndVarAsSet());
            methods.method1(currentVG.getAndVarAsSet(), nextVG.getAndVarAsSet());
            methods.method1(nextVG.getAndVarAsSet(), currentVG.getAndVarAsSet());
            methods.method1(nextVG.getAndVarAsSet(), nextVG.getAndVarAsSet());
        }
        System.out.println("completed in " + (System.currentTimeMillis() - current) + " ms.");
    }

    private VG buildVg(int i) {
        VG vg = new VG();

        List<String> strings = new ArrayList<String>(6000);
        for (int j = 0; j < 6000; j++) {
            String s = UUID.randomUUID().toString();
            strings.add(i + s + j);
        }

        vg.setAndVar(strings);
        return vg;
    }

    private boolean method1(Collection<String> searchList, Collection<String> mainList) {
        if (searchList.size() == 0) {
            return true;
        }
        if (mainList.size() == 0) {
            return false;
        }
        if (searchList.size() > mainList.size()) {
            return false;
        }

        for (String item : searchList) {
            if (!mainList.contains(item)) {
                return false;
            }
        }
        return true;
    }

    private class VG {
        private List<String> andVar = new ArrayList<String>();
        private Set<String> andVarSet;

        public List<String> getAndVar() {
            return andVar;
        }

        public void setAndVar(List<String> andVar) {
            this.andVar = andVar;
        }

        public Set<String> getAndVarAsSet() {
            if (andVarSet != null) {
                return andVarSet;
            }

            andVarSet = new HashSet<String>(andVar.size());
            andVarSet.addAll(andVar);
            return andVarSet;
        }
    }
}

Output:

building VGs...complete.
testing method1 using List...completed in 140966 ms
testing method1 using Set...completed in 1755 ms.

If you're using java 8 then streams might be able to make it even faster.


问:
Could not find method for Android onClick event
I've started to learn to code this week. I've been following tutorials about adding events to Google calendar how I've encountered a problem of not being able to find the method. The error is:

Could not find method onAddEventClicked(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'addEventButton'

This is my code:

```<code>package com.example.user.plannerv2;

import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.provider.CalendarContract;
import android.os.Bundle;
import java.util.Calendar;
import android.provider.CalendarContract.Events;
import android.view.View;

public class sub_page01 extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_sub_page01);
    }

    public void onAddEventClicked(View view) {
        Intent intent = new Intent(Intent.ACTION_INSERT);
        intent.setType("vnd.android.cursor.item/event");

        Calendar cal = Calendar.getInstance();
        long startTime = cal.getTimeInMillis();
        long endTime = cal.getTimeInMillis()  + 60 * 60 * 1000;

        intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startTime);
        intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME,endTime);
        intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true);

        intent.putExtra(Events.TITLE, "Customer Cabin");
        intent.putExtra(Events.DESCRIPTION,  "Cabin is leased out");
        intent.putExtra(Events.EVENT_LOCATION, "Cabin");

        startActivity(intent);
    }
}
</code>```

Here is my XML;

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/addEventButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onAddEventClicked"
        android:text="Add Event" />
</RelativeLayout>
</code>```

This is the error I'm getting:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.user.plannerv2, PID: 16127
                  java.lang.IllegalStateException: Could not find method onAddEventClicked(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'addEventButton'
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
                      at android.view.View.performClick(View.java:6207)
                      at android.widget.TextView.performClick(TextView.java:11094)
                      at android.view.View$PerformClick.run(View.java:23639)
                      at android.os.Handler.handleCallback(Handler.java:751)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6688)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
</code>```

As I've said, I'm not 100% sure as I feel the method is being called. Any help would be great.

答:
Do it like this

```<code>findViewById(R.id.addEventButton).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //Perform your action here
    }
});
</code>```

You are done :)

Body:
I've started to learn to code this week. I've been following tutorials about adding events to Google calendar how I've encountered a problem of not being able to find the method. The error is:

Could not find method onAddEventClicked(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'addEventButton'

This is my code:

package com.example.user.plannerv2;

import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.provider.CalendarContract;
import android.os.Bundle;
import java.util.Calendar;
import android.provider.CalendarContract.Events;
import android.view.View;

public class sub_page01 extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_sub_page01);
    }

    public void onAddEventClicked(View view) {
        Intent intent = new Intent(Intent.ACTION_INSERT);
        intent.setType("vnd.android.cursor.item/event");

        Calendar cal = Calendar.getInstance();
        long startTime = cal.getTimeInMillis();
        long endTime = cal.getTimeInMillis()  + 60 * 60 * 1000;

        intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startTime);
        intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME,endTime);
        intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true);

        intent.putExtra(Events.TITLE, "Customer Cabin");
        intent.putExtra(Events.DESCRIPTION,  "Cabin is leased out");
        intent.putExtra(Events.EVENT_LOCATION, "Cabin");

        startActivity(intent);
    }
}

Here is my XML;

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/addEventButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onAddEventClicked"
        android:text="Add Event" />
</RelativeLayout>

This is the error I'm getting:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.user.plannerv2, PID: 16127
                  java.lang.IllegalStateException: Could not find method onAddEventClicked(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'addEventButton'
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
                      at android.view.View.performClick(View.java:6207)
                      at android.widget.TextView.performClick(TextView.java:11094)
                      at android.view.View$PerformClick.run(View.java:23639)
                      at android.os.Handler.handleCallback(Handler.java:751)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6688)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)

As I've said, I'm not 100% sure as I feel the method is being called. Any help would be great.

Body:
Do it like this

findViewById(R.id.addEventButton).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //Perform your action here
    }
});

You are done :)


问:
Which files updated after composer update
I have added a new package to my project via composer.
Now the project is on a shared hosting.
After uploading only the package from Vendor folder,
The project not working.

What are the other files should I upload to my hosting ?

答:
If you're using the composer autoloader then you should also update the vendor/composer folder and the vendor/autoload.php file.

The composer.lock file will also have changed but this shouldn't affect your application unless you're using composer on the server.


答:
The convolution operation are much more complex than dense layer.
Convolution is the process of adding each element of the image to its local neighbors, weighted by the kernel.
Every convolution is essentially a multiple nested loop. This means that dense layer needs a fraction of the time respect to convolutional layers.
Wikipedia has an enlightening example of the convolution operation.</p>

Title: Why is a CNN slower to train than a fully connected MLP in Keras?

Body:
I looked to the following examples from Keras:

MLP in MNIST: https://github.com/fchollet/keras/blob/master/examples/mnist_mlp.py

CNN in MNIST: https://github.com/fchollet/keras/blob/master/examples/mnist_cnn.py

I run both in Theano on CPU. In the MLP I have a mean time of approximately 16s per epoch with a total of 669,706 parameters:

Layer (type)                 Output Shape              Param #
=================================================================
dense_33 (Dense)             (None, 512)               401920
_________________________________________________________________
dropout_16 (Dropout)         (None, 512)               0
_________________________________________________________________
dense_34 (Dense)             (None, 512)               262656
_________________________________________________________________
dropout_17 (Dropout)         (None, 512)               0
_________________________________________________________________
dense_35 (Dense)             (None, 10)                5130
=================================================================
Total params: 669,706.0
Trainable params: 669,706.0
Non-trainable params: 0.0

In the CNN, I eliminated the last hidden layer from the original code. I also changed the optimizer to rmsprop to make both cases comparable, leaving the following architecture:

Layer (type)                 Output Shape              Param #
=================================================================
conv2d_36 (Conv2D)           (None, 26, 26, 32)        320
_________________________________________________________________
conv2d_37 (Conv2D)           (None, 24, 24, 64)        18496
_________________________________________________________________
max_pooling2d_17 (MaxPooling (None, 12, 12, 64)        0
_________________________________________________________________
dropout_22 (Dropout)         (None, 12, 12, 64)        0
_________________________________________________________________
flatten_17 (Flatten)         (None, 9216)              0
_________________________________________________________________
dense_40 (Dense)             (None, 10)                92170
=================================================================
Total params: 110,986.0
Trainable params: 110,986.0
Non-trainable params: 0.0

However, the average time here is of approximately 340 s per epoch! Even though there are six times less parameters!

To check more on this, I reduced the number of filters per layer to 4, leaving the following architecture:

Layer (type)                 Output Shape              Param #
=================================================================
conv2d_38 (Conv2D)           (None, 26, 26, 4)         40
_________________________________________________________________
conv2d_39 (Conv2D)           (None, 24, 24, 4)         148
_________________________________________________________________
max_pooling2d_18 (MaxPooling (None, 12, 12, 4)         0
_________________________________________________________________
dropout_23 (Dropout)         (None, 12, 12, 4)         0
_________________________________________________________________
flatten_18 (Flatten)         (None, 576)               0
_________________________________________________________________
dense_41 (Dense)             (None, 10)                5770
=================================================================
Total params: 5,958.0
Trainable params: 5,958.0
Non-trainable params: 0.0

Now the time is of 28 s per epoch even though there are roughly 6000 parameters!!

Why is this? Intuitively, the optimization should only depend on the number of variables and the calculation of the gradient (which due to same batch size should be similar).

Some light on this?
Thank you


问:
Change title in extracted legend
I have a data frame:

```<code>df1 = data.frame(Time = rep(0.5:9.5, each = 10), RoiID = rep(1:10, 10), Diameter = runif(100, 5.0, 7.5),Time.hours=rep(c(1,2)))
</code>```

I want to extract the legend from the plot and put to another plot by "grid.arrange".

```<code>p1=ggplot(data=subset(df1,df1$Time.hours==1), aes(x=factor(RoiID), y=Time, fill = Diameter)) +
theme_minimal()  + coord_fixed(ratio=1/2) +
geom_tile(colour = NA, width =1.5 , height = 1)+
scale_fill_gradient(low="black",high="white",limits=c(min(df1$Diameter),max(df1$Diameter)))+
theme(legend.direction="horizontal")

g_legend<-function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)}

grobs <- ggplotGrob(p1 + theme(legend.position="right"))$grobs
mylegend <- grobs[[which(sapply(grobs, function(x) x$name) == "guide-box")]]
mylegend<-g_legend(p1)
</code>```

My question is: How to change the title of legend from "Diameter" to " F49 Diameter" (please see image enclosed) before adding the legend to another plot?

答:
If I've understood you correctly, than you just need to add the  "F49 Diameter" into scale_fill_gradient

So your code looks like this

```<code>p1=ggplot(data=subset(df1,df1$Time.hours==1), aes(x=factor(RoiID), y=Time, fill = Diameter)) +
  theme_minimal()  + coord_fixed(ratio=1/2) +
  geom_tile(colour = NA, width =1.5 , height = 1)+
  scale_fill_gradient("F49 Diameter",low="black",high="white",limits=c(min(df1$Diameter),max(df1$Diameter)))+
  theme(legend.direction="horizontal")
</code>```

And than also your extracted legend

```<code>library(gridExtra)
grid.arrange(g_legend(p1))
</code>```

will be named "F49 Diameter"

Title: Change title in extracted legend

Body:
I have a data frame:

df1 = data.frame(Time = rep(0.5:9.5, each = 10), RoiID = rep(1:10, 10), Diameter = runif(100, 5.0, 7.5),Time.hours=rep(c(1,2)))

I want to extract the legend from the plot and put to another plot by "grid.arrange".

p1=ggplot(data=subset(df1,df1$Time.hours==1), aes(x=factor(RoiID), y=Time, fill = Diameter)) +
theme_minimal()  + coord_fixed(ratio=1/2) +
geom_tile(colour = NA, width =1.5 , height = 1)+
scale_fill_gradient(low="black",high="white",limits=c(min(df1$Diameter),max(df1$Diameter)))+
theme(legend.direction="horizontal")

g_legend<-function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)}

grobs <- ggplotGrob(p1 + theme(legend.position="right"))$grobs
mylegend <- grobs[[which(sapply(grobs, function(x) x$name) == "guide-box")]]
mylegend<-g_legend(p1)

My question is: How to change the title of legend from "Diameter" to " F49 Diameter" (please see image enclosed) before adding the legend to another plot?

Body:
If I've understood you correctly, than you just need to add the  "F49 Diameter" into scale_fill_gradient

So your code looks like this

p1=ggplot(data=subset(df1,df1$Time.hours==1), aes(x=factor(RoiID), y=Time, fill = Diameter)) +
  theme_minimal()  + coord_fixed(ratio=1/2) +
  geom_tile(colour = NA, width =1.5 , height = 1)+
  scale_fill_gradient("F49 Diameter",low="black",high="white",limits=c(min(df1$Diameter),max(df1$Diameter)))+
  theme(legend.direction="horizontal")

And than also your extracted legend

library(gridExtra)
grid.arrange(g_legend(p1))

will be named "F49 Diameter"


问:
Put multiple rows of a gridview into edit mode
I have the need to allow a user to "tab through" making edits on a gridview.  There will be one editable column in the row data. The user should be able to hit tab and go to the next row to edit said column.

I have not found any easy method to accomplish this task.  I found a way to programmatically put a gridview into edit mode, but in testing the code below it works for only 1 row at a time.

```<code>        reviewTransferGV.EditIndex = 0;
        reviewTransferGV.Rows[0].RowState = DataControlRowState.Edit;
        reviewTransferGV.EditIndex = 1;
        reviewTransferGV.Rows[1].RowState = DataControlRowState.Edit;
        reviewTransferGV.DataBind();
</code>```

答:
I did a workaround by creating a property in the page:

```<code>protected bool IsEditMode
{
  get { return this.EditMode; }
  set { this.EditMode = value; }
}
</code>```

Then in the GridView I have the controls for view and edit mode inside an item template. Setting the visibility based on the property value:

```<code><asp:TemplateField SortExpression="Status" HeaderText="Status">
<ItemTemplate>
    <asp:Label Id="lblStatus" Text='<%# Eval("Status") %>' Visible='<%# !IsEditMode %>' runat="server" />
    <asp:TextBox ID="txtStatus" Text='<%# Eval("Status") %>' Visible='<%# IsEditMode %>' runat="server" />
</ItemTemplate>
</code>```

This works for editing the whole gridview. You'll probably need to make a few modifications to make it work for individual rows.

Body:
I have the need to allow a user to "tab through" making edits on a gridview.  There will be one editable column in the row data. The user should be able to hit tab and go to the next row to edit said column.

I have not found any easy method to accomplish this task.  I found a way to programmatically put a gridview into edit mode, but in testing the code below it works for only 1 row at a time.

        reviewTransferGV.EditIndex = 0;
        reviewTransferGV.Rows[0].RowState = DataControlRowState.Edit;
        reviewTransferGV.EditIndex = 1;
        reviewTransferGV.Rows[1].RowState = DataControlRowState.Edit;
        reviewTransferGV.DataBind();

Body:
I did a workaround by creating a property in the page:

protected bool IsEditMode
{
  get { return this.EditMode; }
  set { this.EditMode = value; }
}

Then in the GridView I have the controls for view and edit mode inside an item template. Setting the visibility based on the property value:

<asp:TemplateField SortExpression="Status" HeaderText="Status">
<ItemTemplate>
    <asp:Label Id="lblStatus" Text='<%# Eval("Status") %>' Visible='<%# !IsEditMode %>' runat="server" />
    <asp:TextBox ID="txtStatus" Text='<%# Eval("Status") %>' Visible='<%# IsEditMode %>' runat="server" />
</ItemTemplate>

This works for editing the whole gridview. You'll probably need to make a few modifications to make it work for individual rows.


问:
Android ndk build can't build 32bit executable file
Depending on my first question, I tried to include the fanotify.h header in my application. The application is based on fsmon (a small application to use the fanotify syscall), I changed some code lines for my purpose and created an Android.mk makefile:

```<code>APP_PLATFORM := android-23
TARGET_PLATFORM := android-23
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)

# Enable PIE manually. Will get reset on $(CLEAR_VARS). This
# is what enabling PIE translates to behind the scenes.
LOCAL_CFLAGS += -fPIE -DHAVE_FANOTIFY=1 -DHAVE_SYS_FANOTIFY=0
LOCAL_LDFLAGS += -fPIE -pie

# give module name
LOCAL_MODULE := fsmon

# include fanotify by api 23:
LOCAL_C_INCLUDES := /home/fabian/Android/Sdk/ndk-bundle/platforms/android-23/arch-arm/usr/include

# include fanotify by sysroot ->
# LOCAL_C_INCLUDES := /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/

# list your C files to compile
LOCAL_SRC_FILES := inotify.c fanotify.c util.c main.c

# this option will build executables instead of building library for android application.
include $(BUILD_EXECUTABLE)
</code>```

I need to include the linux/inotify.h and the linux/fanotify.h headers.

On executing ndk-build, only the arm64-v8a, mips64 and x86_64 executable files (in libs/xxx) get created cause of following error messages:

```<code>fabian@fabian-ubuntu:~/kernel_android_goldfish/fsmon/fsmon/jni$ ndk-build
[arm64-v8a] Compile        : fsmon <= inotify.c
[arm64-v8a] Compile        : fsmon <= fanotify.c
[arm64-v8a] Compile        : fsmon <= util.c
[arm64-v8a] Compile        : fsmon <= main.c
[arm64-v8a] Executable     : fsmon
[arm64-v8a] Install        : fsmon => libs/arm64-v8a/fsmon
[x86_64] Compile        : fsmon <= inotify.c
[x86_64] Compile        : fsmon <= fanotify.c
[x86_64] Compile        : fsmon <= util.c
[x86_64] Compile        : fsmon <= main.c
[x86_64] Executable     : fsmon
[x86_64] Install        : fsmon => libs/x86_64/fsmon
[mips64] Compile        : fsmon <= inotify.c
[mips64] Compile        : fsmon <= fanotify.c
[mips64] Compile        : fsmon <= util.c
[mips64] Compile        : fsmon <= main.c
[mips64] Executable     : fsmon
[mips64] Install        : fsmon => libs/mips64/fsmon
[armeabi-v7a] Compile thumb  : fsmon <= inotify.c
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:49:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/linux/signal.h:21:
In file included from /home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:82:
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:92:21: error: use of undeclared identifier
      '__BITS_PER_LONG'
  unsigned long sig[_NSIG_WORDS];
                    ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:25:38: note: expanded from macro '_NSIG_WORDS'
#define _NSIG_WORDS (_KERNEL__NSIG / _NSIG_BPW)
                                     ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:24:19: note: expanded from macro '_NSIG_BPW'
#define _NSIG_BPW __BITS_PER_LONG
                  ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:94:3: error: typedef redefinition with different
      types ('struct (anonymous struct at /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:91:9)' vs
      'unsigned long')
} sigset_t;
  ^
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:20:23: note: previous definition is here
typedef unsigned long sigset_t;
                      ^
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:84:8: error: redefinition of 'sigaction'
struct sigaction {
       ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:101:8: note: previous definition is here
struct sigaction {
       ^
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:49:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/linux/signal.h:21:
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:97:16: error: redefinition of
      'sigaltstack'
typedef struct sigaltstack {
               ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:111:16: note: previous definition is here
typedef struct sigaltstack {
               ^
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:49:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/linux/signal.h:21:
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:101:3: error: typedef redefinition with
      different types ('struct (anonymous struct at
      /home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:97:16)' vs 'struct sigaltstack')
} stack_t;
  ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:116:3: note: previous definition is here
} stack_t;
  ^
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:71:9: warning: 'NSIG' macro redefined [-Wmacro-redefined]
#define NSIG _NSIG
        ^
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:19:9: note: previous definition is here
#define NSIG 32
        ^
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:79:9: warning: 'SIGRTMIN' macro redefined [-Wmacro-redefined]
#define SIGRTMIN (__libc_current_sigrtmin())
        ^
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:58:9: note: previous definition is here
#define SIGRTMIN 32
        ^
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:80:9: warning: 'SIGRTMAX' macro redefined [-Wmacro-redefined]
#define SIGRTMAX (__libc_current_sigrtmax())
        ^
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:59:9: note: previous definition is here
#define SIGRTMAX _NSIG
        ^
5 errors generated.
    make: *** [/home/fabian/kernel_android_goldfish/fsmon/fsmon/obj/local/armeabi-v7a/objs/fsmon/inotify.o] Error 1
</code>```

Cause of inotify.c including the signal.h header which re-includes the linux/signal.h and this in turn the platforms/android-9/arch-arm/usr/include/asm/signal.h , where the error appears. (suddenly from android-9).

I can't figure out where the problem is.. I tried to include the include folder from sysroot - but similar errors appear.

Source file:
inotify.c
fanotify.c

答:
In addition to @mstorsjo's answer, you can use Unified Headers in NDK r14 and newer. These are a new form of the headers that will always be up to date rather than having a different set of headers for each API level.

The advantage of this over increasing your APP_PLATFORM is that your APP_PLAFORM cannot be higher than your minSdkVersion (see our common problems doc). Since fanotify was introduced in a fairly old version of the kernel (2.6.36 for fanotify_init), you should still be able to call it with syscall(__NR_fanotify_init) even though the function doesn't exist in libc in the old version. Still, ENOSYS is always a possibility.

By default in r14 you still get the old form of the headers. The new "unified headers" have the headers you're looking for. If you want to try unified headers, set APP_UNIFIED_HEADERS := true in your Application.mk (settings for other build systems can be found in the link above).

In r15 (first beta due out soon), the default has changed to the new headers, and the option for disabling them has changed (see the same doc in r15).

Body:
Depending on my first question, I tried to include the fanotify.h header in my application. The application is based on fsmon (a small application to use the fanotify syscall), I changed some code lines for my purpose and created an Android.mk makefile:

APP_PLATFORM := android-23
TARGET_PLATFORM := android-23
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)

# Enable PIE manually. Will get reset on $(CLEAR_VARS). This
# is what enabling PIE translates to behind the scenes.
LOCAL_CFLAGS += -fPIE -DHAVE_FANOTIFY=1 -DHAVE_SYS_FANOTIFY=0
LOCAL_LDFLAGS += -fPIE -pie

# give module name
LOCAL_MODULE := fsmon

# include fanotify by api 23:
LOCAL_C_INCLUDES := /home/fabian/Android/Sdk/ndk-bundle/platforms/android-23/arch-arm/usr/include

# include fanotify by sysroot ->
# LOCAL_C_INCLUDES := /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/

# list your C files to compile
LOCAL_SRC_FILES := inotify.c fanotify.c util.c main.c

# this option will build executables instead of building library for android application.
include $(BUILD_EXECUTABLE)

I need to include the linux/inotify.h and the linux/fanotify.h headers.

On executing ndk-build, only the arm64-v8a, mips64 and x86_64 executable files (in libs/xxx) get created cause of following error messages:

fabian@fabian-ubuntu:~/kernel_android_goldfish/fsmon/fsmon/jni$ ndk-build
[arm64-v8a] Compile        : fsmon <= inotify.c
[arm64-v8a] Compile        : fsmon <= fanotify.c
[arm64-v8a] Compile        : fsmon <= util.c
[arm64-v8a] Compile        : fsmon <= main.c
[arm64-v8a] Executable     : fsmon
[arm64-v8a] Install        : fsmon => libs/arm64-v8a/fsmon
[x86_64] Compile        : fsmon <= inotify.c
[x86_64] Compile        : fsmon <= fanotify.c
[x86_64] Compile        : fsmon <= util.c
[x86_64] Compile        : fsmon <= main.c
[x86_64] Executable     : fsmon
[x86_64] Install        : fsmon => libs/x86_64/fsmon
[mips64] Compile        : fsmon <= inotify.c
[mips64] Compile        : fsmon <= fanotify.c
[mips64] Compile        : fsmon <= util.c
[mips64] Compile        : fsmon <= main.c
[mips64] Executable     : fsmon
[mips64] Install        : fsmon => libs/mips64/fsmon
[armeabi-v7a] Compile thumb  : fsmon <= inotify.c
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:49:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/linux/signal.h:21:
In file included from /home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:82:
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:92:21: error: use of undeclared identifier
      '__BITS_PER_LONG'
  unsigned long sig[_NSIG_WORDS];
                    ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:25:38: note: expanded from macro '_NSIG_WORDS'
#define _NSIG_WORDS (_KERNEL__NSIG / _NSIG_BPW)
                                     ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:24:19: note: expanded from macro '_NSIG_BPW'
#define _NSIG_BPW __BITS_PER_LONG
                  ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:94:3: error: typedef redefinition with different
      types ('struct (anonymous struct at /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:91:9)' vs
      'unsigned long')
} sigset_t;
  ^
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:20:23: note: previous definition is here
typedef unsigned long sigset_t;
                      ^
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:84:8: error: redefinition of 'sigaction'
struct sigaction {
       ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:101:8: note: previous definition is here
struct sigaction {
       ^
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:49:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/linux/signal.h:21:
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:97:16: error: redefinition of
      'sigaltstack'
typedef struct sigaltstack {
               ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:111:16: note: previous definition is here
typedef struct sigaltstack {
               ^
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:49:
In file included from /home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/linux/signal.h:21:
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:101:3: error: typedef redefinition with
      different types ('struct (anonymous struct at
      /home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:97:16)' vs 'struct sigaltstack')
} stack_t;
  ^
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/asm-generic/signal.h:116:3: note: previous definition is here
} stack_t;
  ^
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:71:9: warning: 'NSIG' macro redefined [-Wmacro-redefined]
#define NSIG _NSIG
        ^
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:19:9: note: previous definition is here
#define NSIG 32
        ^
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:79:9: warning: 'SIGRTMIN' macro redefined [-Wmacro-redefined]
#define SIGRTMIN (__libc_current_sigrtmin())
        ^
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:58:9: note: previous definition is here
#define SIGRTMIN 32
        ^
In file included from /home/fabian/kernel_android_goldfish/fsmon/fsmon/jni/inotify.c:9:
/home/fabian/Android/Sdk/ndk-bundle/sysroot/usr/include/signal.h:80:9: warning: 'SIGRTMAX' macro redefined [-Wmacro-redefined]
#define SIGRTMAX (__libc_current_sigrtmax())
        ^
/home/fabian/Android/Sdk/ndk-bundle/platforms/android-9/arch-arm/usr/include/asm/signal.h:59:9: note: previous definition is here
#define SIGRTMAX _NSIG
        ^
5 errors generated.
    make: *** [/home/fabian/kernel_android_goldfish/fsmon/fsmon/obj/local/armeabi-v7a/objs/fsmon/inotify.o] Error 1

Cause of inotify.c including the signal.h header which re-includes the linux/signal.h and this in turn the platforms/android-9/arch-arm/usr/include/asm/signal.h , where the error appears. (suddenly from android-9).

I can't figure out where the problem is.. I tried to include the include folder from sysroot - but similar errors appear.

Source file:
inotify.c
fanotify.c


问:
WebAPI Delete not working - 405 Method Not Allowed
I appreciate any help on this as the site is supposed to go live tonight!

I have a web api controller with a Delete method. The method executes fine on my local machine running IIS Express (Windows 8) but as soon as I deployed it to the live IIS server (Windows Server 2008 R2) it stopped working and throws the following error message:

HTTP Error 405.0 - Method Not Allowed
The page you are looking for cannot be displayed because an invalid method (HTTP Verb) is being used

I have looked around the web for solutions and I implemented most reasonable ones. My web config has the following settings:

```<code><system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
<handlers>
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
</code>```

I have also tried to change the Handler Mappings and Request Filtering in IIS to no avail. Please note that the WebDAV Authoring Rules in IIS seems to be disabled.

Any ideas will be greatly appreciated
Thanks.

答:
We had to add custom headers to our web.config as our request had multiple headers that confused the API response.</p>

```<code><httpProtocol>
    <customHeaders>
        <remove name="Access-Control-Allow-Methods" />
        <remove name="Access-Control-Allow-Origin" />
        <remove name="Access-Control-Allow-Headers" />
    </customHeaders>
</httpProtocol>
</code>```

Body:
I appreciate any help on this as the site is supposed to go live tonight!

I have a web api controller with a Delete method. The method executes fine on my local machine running IIS Express (Windows 8) but as soon as I deployed it to the live IIS server (Windows Server 2008 R2) it stopped working and throws the following error message:

HTTP Error 405.0 - Method Not Allowed
The page you are looking for cannot be displayed because an invalid method (HTTP Verb) is being used

I have looked around the web for solutions and I implemented most reasonable ones. My web config has the following settings:

<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
<handlers>
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>

I have also tried to change the Handler Mappings and Request Filtering in IIS to no avail. Please note that the WebDAV Authoring Rules in IIS seems to be disabled.

Any ideas will be greatly appreciated
Thanks.

Body:
We had to add custom headers to our web.config as our request had multiple headers that confused the API response.

<httpProtocol>
    <customHeaders>
        <remove name="Access-Control-Allow-Methods" />
        <remove name="Access-Control-Allow-Origin" />
        <remove name="Access-Control-Allow-Headers" />
    </customHeaders>
</httpProtocol>


问:
Change height makes problems
I implemented spectrum color picker. I'm trying to change the alpha sliders height. (The one with the class name: .sp-alpha.)
When I do that, then the color picker containers (class name: sp-top-inner) height changes.

How can I edit the source file so that I can change the alpha sliders height without affecting other elements?

答:
Set .sp-top-inner height to 150px or add bottom:20px (any number you like):

```<code>.sp-top-inner {
    height: 150px;
}
</code>```

Or

```<code>.sp-top-inner {
        bottom: 20px;
    }
</code>```

then change the height of .sp-alpha and add custom margin:

```<code> .sp-alpha-enabled .sp-alpha {
  height: 20px;
  margin: 5px 5px 5px 0;
}
</code>```

Note: Just add above codes if you want to enable alpha mode.

JSFiddle Demo

Title: Change height makes problems

Body:
Set .sp-top-inner height to 150px or add bottom:20px (any number you like):

.sp-top-inner {
    height: 150px;
}

Or

.sp-top-inner {
        bottom: 20px;
    }

then change the height of .sp-alpha and add custom margin:

 .sp-alpha-enabled .sp-alpha {
  height: 20px;
  margin: 5px 5px 5px 0;
}

Note: Just add above codes if you want to enable alpha mode.

JSFiddle Demo


问:
PL/SQL Function_get total balance has errors
I was trying to create a function that given a customer name, get the total balance of that customer's accounts from the account table(A#, CNAME, BAL).

When compiling in command, I got errors:

line "SELECT SUM(bal) INTO total_a_bal FROM account" ignored

and               line "WHERE account.cname = v_acname" SQL cmd not properly ended.

Please help correct the errors. Any help would be greatly appreciated!

My function is :

```<code>CREATE OR REPLACE FUNCTION totbal
    (v_acname IN account.cname%type)
RETURN NUMBER
IS
    total_a_bal NUMBER;
BEGIN
    SELECT SUM(bal) INTO total_a_bal FROM account
    group by account.cname
    WHERE account.cname = v_acname;
    RETURN total_a_bal;
END;
/
</code>```

答:
Oracle not only works with the parameter definition "account.cname%type" that is preferred method. What it does is to bind the parameter definition to the column in the database. If the column definition is changed the procedure automatically gets the changed.

This concept of defining in terms of data base columns can (and perhaps should) be extended into the variables and return types of the procedure/function itself.

This function then becomes:

```<code>CREATE OR REPLACE FUNCTION totbal
    (v_acname IN account.cname%type)
RETURN account.bal%type
IS
    total_a_bal account.bal%type;
BEGIN
    SELECT SUM(bal) INTO total_a_bal FROM account
    group by account.cname
    WHERE account.cname = v_acname;
    RETURN total_a_bal;
END;
</code>```

Body:
I was trying to create a function that given a customer name, get the total balance of that customer's accounts from the account table(A#, CNAME, BAL).

When compiling in command, I got errors:

line "SELECT SUM(bal) INTO total_a_bal FROM account" ignored

and               line "WHERE account.cname = v_acname" SQL cmd not properly ended.

Please help correct the errors. Any help would be greatly appreciated!

My function is :

CREATE OR REPLACE FUNCTION totbal
    (v_acname IN account.cname%type)
RETURN NUMBER
IS
    total_a_bal NUMBER;
BEGIN
    SELECT SUM(bal) INTO total_a_bal FROM account
    group by account.cname
    WHERE account.cname = v_acname;
    RETURN total_a_bal;
END;
/

Body:
Oracle not only works with the parameter definition "account.cname%type" that is preferred method. What it does is to bind the parameter definition to the column in the database. If the column definition is changed the procedure automatically gets the changed.

This concept of defining in terms of data base columns can (and perhaps should) be extended into the variables and return types of the procedure/function itself.

This function then becomes:

CREATE OR REPLACE FUNCTION totbal
    (v_acname IN account.cname%type)
RETURN account.bal%type
IS
    total_a_bal account.bal%type;
BEGIN
    SELECT SUM(bal) INTO total_a_bal FROM account
    group by account.cname
    WHERE account.cname = v_acname;
    RETURN total_a_bal;
END;


问:
Mercurial commit reverts with "abort: edit failed: vi exited with status 1"
I like using vi/vim for may editing but since vim and mercurial don't place nice together.

When attempting to commit a change the command line exits with:

```<code>$ hg commit
abort: edit failed: vi exited with status 1
</code>```

It appears vi always returns 1 on exit:

Example:

```<code>$ vi
$ echo $?
1
</code>```

答:
A quick hack that solved the problem.

Create a shell file

$ sudo vi /usr/local/bin/hgedit

vi $*
exit 0

Update ~/.hgrc

editor=/usr/local/bin/hgedit

Body:
I like using vi/vim for may editing but since vim and mercurial don't place nice together.

When attempting to commit a change the command line exits with:

$ hg commit
abort: edit failed: vi exited with status 1

It appears vi always returns 1 on exit:

Example:

$ vi
$ echo $?
1


问:
QProgressBar and heavy task
I have heavy task. I created QProgressBar for displaying that programm still work and runned heavy task in another thread using c++ std::thread class. But QProgressBar don't work, only window with QProgressBar starts.
Here is the code:

```<code>QProgressBar progress;
progress.setRange(0, 0);
progress.show();
if (keyLength == 1024)
    std::thread(&RSA::generateKeys, &rsa, RSA::RSA_1024).join();
else if (keyLength == 2048)
    std::thread(&RSA::generateKeys, &rsa, RSA::RSA_2048).join();
</code>```

Here is the result:

答:
This is not how things are done. :) Here you can see an example I have made that uses the Worker pattern (a separate thread that processes some heavy task and reports back to the UI). Here is how my application looks:

I use QThread (worker thread that contains an object that handles the processing) and I can only recommend you to do the same. You can also subclass QThread and override the run() method depending on what you really need however this is rarely the case.

PS: As an alternative you can use QRunnable (very useful for tasks that are done every once in a while which doesn't require a separate thread to be managed all the time). The problem with QRunnable is that it doesn't subclass QObject which means that you can't use the slot-signal mechanism to report back to the UI. Of course you can change that but it defeats the purpose of the runnable which is intended to be a very lightweight solution.

Title: QProgressBar and heavy task

Body:
I have heavy task. I created QProgressBar for displaying that programm still work and runned heavy task in another thread using c++ std::thread class. But QProgressBar don't work, only window with QProgressBar starts.
Here is the code:

QProgressBar progress;
progress.setRange(0, 0);
progress.show();
if (keyLength == 1024)
    std::thread(&RSA::generateKeys, &rsa, RSA::RSA_1024).join();
else if (keyLength == 2048)
    std::thread(&RSA::generateKeys, &rsa, RSA::RSA_2048).join();

Here is the result:


问:
Why do Guava classes provide so many factory methods instead of just one that takes varargs?

Possible Duplicate:

  Why does Guava's ImmutableList have so many overloaded of() methods?

Looking at Guava's ImmutableList (and some other classes), you'll find plenty of overloaded of convenience methods ("Returns an immutable list containing the given elements, in order.") that take a different number of parameters:

```<code>...
public static <E> ImmutableList<E> of(E e1, E e2, E e3)
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4)
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5)
...
</code>```

All the way to this one:

```<code>public static <E> ImmutableList<E> of(E e1,
                                      E e2,
                                      E e3,
                                      E e4,
                                      E e5,
                                      E e6,
                                      E e7,
                                      E e8,
                                      E e9,
                                      E e10,
                                      E e11,
                                      E e12,
                                      E... others)
</code>```

Some colleagues of mine consider this silly, wondering why there's isn't just one method: of(E... elements).  They suspect it's an ill-guided performance "optimisation" that falls into the category "do you think you're smarter than compiler", or something like that.

My hunch is that Kevin Bourrillion et al. put these methods in there for a real reason. Can anyone explain (or speculate) what that reason might be?

答: It's to avoid the overhead of creating a varargs array for the most common use cases.  This is modeled after the way EnumSet.of(..) was designed.</p>

Body:
Possible Duplicate:

  Why does Guava's ImmutableList have so many overloaded of() methods?

Looking at Guava's ImmutableList (and some other classes), you'll find plenty of overloaded of convenience methods ("Returns an immutable list containing the given elements, in order.") that take a different number of parameters:

...
public static <E> ImmutableList<E> of(E e1, E e2, E e3)
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4)
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5)
...

All the way to this one:

public static <E> ImmutableList<E> of(E e1,
                                      E e2,
                                      E e3,
                                      E e4,
                                      E e5,
                                      E e6,
                                      E e7,
                                      E e8,
                                      E e9,
                                      E e10,
                                      E e11,
                                      E e12,
                                      E... others)

Some colleagues of mine consider this silly, wondering why there's isn't just one method: of(E... elements).  They suspect it's an ill-guided performance "optimisation" that falls into the category "do you think you're smarter than compiler", or something like that.

My hunch is that Kevin Bourrillion et al. put these methods in there for a real reason. Can anyone explain (or speculate) what that reason might be?


问:
Local HTML File Scraping Urllib and BeautifulSoup
I am very new to python and have been working from scratch on the following code for two weeks to scrape local files.  Probably nearly a hundred hours learning as much as I can about Python, versionality, importing packages such as lxml, bs4, requests, urllib, os, glob and more. </p>

<p>I'm hopelessly stuck on the first part on getting 12,000 HTML files with strange names all in one directory to load and parse with BeautifulSoup.  I want to get all this data into a csv file or just to output so I can copy it to a file using clipboard.  </p>

```<code>import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

#THIS LOCAL FILE WORKS PERFECTLY. I HAVE 12,000 HTML FILES IN THIS DIRECTORY TO PROCESS.  HOW?
#my_url = 'file://127.0.0.1/C:\\My Web Sites\\BioFachURLS\\www.organic-bio.com\\en\\company\\1-SUNRISE-FARMS.html'
my_url = 'http://www.organic-bio.com/en/company/23694-MARTHOMI-ALLERGY-FREE-FOODS-GMBH'

uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

# html parsing
page_soup = soup(page_html, "html.parser")

# grabs each field
contactname = page_soup.findAll("td", {"itemprop": "name"})
contactstreetaddress = page_soup.findAll("td", {"itemprop": "streetAddress"})
contactpostalcode = page_soup.findAll("td", {"itemprop": "postalCode"})
contactaddressregion = page_soup.findAll("td", {"itemprop": "addressRegion"})
contactaddresscountry = page_soup.findAll("td", {"itemprop": "addressCountry"})
contactfax = page_soup.findAll("td", {"itemprop": "faxNumber"})
contactemail = page_soup.findAll("td", {"itemprop": "email"})
contactphone = page_soup.findAll("td", {"itemprop": "telephone"})
contacturl = page_soup.findAll("a", {"itemprop": "url"})

#Outputs as text without tags
Company = contactname[0].text
Address = contactstreetaddress[0].text
Zip = contactpostalcode[0].text
Region = contactaddressregion[0].text
Country = contactaddresscountry[0].text
Fax = contactfax[0].text
Email = contactemail[0].text
Phone = contactphone[0].text
URL = contacturl[0].text

#Prints with comma delimiters

print(Company + ', ' + Address + ', ' + Zip + ', ' + Region + ', ' + Country + ', ' + Fax + ', ' + Email + ', ' + URL)
</code>```

答:
I have worked with running through folders with bunches of file before, so I could suggest a little help.

We will start with for loop to files from folder

import os
from bs4 import BeautifulSoup as page_soup

phone = [] # A list to store all the phone
path = 'yourpath' # This is your folder name which stores all your html
#be careful that you might need to put a full path such as C:\Users\Niche\Desktop\htmlfolder
for filename in os.listdir(path): #Read files from your path

    #Here we are trying to find the full pathname
    for x in filename: #We will have A-H stored as path
        subpath = os.path.join(path, filename)
        for filename in os.listdir(subpath):
        #Getting the full path of a particular html file
            fullpath = os.path.join(subpath, filename)
            #If we have html tag, then read it
            if fullpath.endswith('.html'): continue
            #Then we will run beautifulsoup to extract the contents
            soup = page_soup(open(fullpath), 'html.parser')
            #Then run your code
            # grabs each field
            contactname = page_soup.findAll("td", {"itemprop": "name"})
            contactstreetaddress = page_soup.findAll("td", {"itemprop": "streetAddress"})
            contactpostalcode = page_soup.findAll("td", {"itemprop": "postalCode"})
            contactaddressregion = page_soup.findAll("td", {"itemprop": "addressRegion"})
            contactaddresscountry = page_soup.findAll("td", {"itemprop": "addressCountry"})
            contactfax = page_soup.findAll("td", {"itemprop": "faxNumber"})
            contactemail = page_soup.findAll("td", {"itemprop": "email"})
            contactphone = page_soup.findAll("td", {"itemprop": "telephone"})
            contacturl = page_soup.findAll("a", {"itemprop": "url"})

            #Outputs as text without tags
            Company = contactname[0].text
            Address = contactstreetaddress[0].text
            Zip = contactpostalcode[0].text
            Region = contactaddressregion[0].text
            Country = contactaddresscountry[0].text
            Fax = contactfax[0].text
            Email = contactemail[0].text
            Phone = contactphone[0].text
            URL = contacturl[0].text
            #Here you might want to consider using dictionary or a list
            #For example append Phone to list call phone
            phone.append(Phone)
```

The code is a bit messy but it ran through all the possible folders (Even you have other folders inside your main folder) then try to find html tags, the open it.

I would suggest using dictionary with company as a key in which I presume that the company's name are different. A bunch of lists would also be great because your value will be sorted accordingly. I am not good with dictionary so I can't advise you more than this. I hope I answer your question.

P.S sorry for a messy code.

Edit : Fixing replace lxml with html.parser

Body:
I am very new to python and have been working from scratch on the following code for two weeks to scrape local files.  Probably nearly a hundred hours learning as much as I can about Python, versionality, importing packages such as lxml, bs4, requests, urllib, os, glob and more.

I'm hopelessly stuck on the first part on getting 12,000 HTML files with strange names all in one directory to load and parse with BeautifulSoup.  I want to get all this data into a csv file or just to output so I can copy it to a file using clipboard.

import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

#THIS LOCAL FILE WORKS PERFECTLY. I HAVE 12,000 HTML FILES IN THIS DIRECTORY TO PROCESS.  HOW?
#my_url = 'file://127.0.0.1/C:\\My Web Sites\\BioFachURLS\\www.organic-bio.com\\en\\company\\1-SUNRISE-FARMS.html'
my_url = 'http://www.organic-bio.com/en/company/23694-MARTHOMI-ALLERGY-FREE-FOODS-GMBH'

uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

# html parsing
page_soup = soup(page_html, "html.parser")

# grabs each field
contactname = page_soup.findAll("td", {"itemprop": "name"})
contactstreetaddress = page_soup.findAll("td", {"itemprop": "streetAddress"})
contactpostalcode = page_soup.findAll("td", {"itemprop": "postalCode"})
contactaddressregion = page_soup.findAll("td", {"itemprop": "addressRegion"})
contactaddresscountry = page_soup.findAll("td", {"itemprop": "addressCountry"})
contactfax = page_soup.findAll("td", {"itemprop": "faxNumber"})
contactemail = page_soup.findAll("td", {"itemprop": "email"})
contactphone = page_soup.findAll("td", {"itemprop": "telephone"})
contacturl = page_soup.findAll("a", {"itemprop": "url"})

#Outputs as text without tags
Company = contactname[0].text
Address = contactstreetaddress[0].text
Zip = contactpostalcode[0].text
Region = contactaddressregion[0].text
Country = contactaddresscountry[0].text
Fax = contactfax[0].text
Email = contactemail[0].text
Phone = contactphone[0].text
URL = contacturl[0].text

#Prints with comma delimiters

print(Company + ', ' + Address + ', ' + Zip + ', ' + Region + ', ' + Country + ', ' + Fax + ', ' + Email + ', ' + URL)

Body:
I have worked with running through folders with bunches of file before, so I could suggest a little help.

We will start with for loop to files from folder

import os
from bs4 import BeautifulSoup as page_soup

phone = [] # A list to store all the phone
path = 'yourpath' # This is your folder name which stores all your html
#be careful that you might need to put a full path such as C:\Users\Niche\Desktop\htmlfolder
for filename in os.listdir(path): #Read files from your path

    #Here we are trying to find the full pathname
    for x in filename: #We will have A-H stored as path
        subpath = os.path.join(path, filename)
        for filename in os.listdir(subpath):
        #Getting the full path of a particular html file
            fullpath = os.path.join(subpath, filename)
            #If we have html tag, then read it
            if fullpath.endswith('.html'): continue
            #Then we will run beautifulsoup to extract the contents
            soup = page_soup(open(fullpath), 'html.parser')
            #Then run your code
            # grabs each field
            contactname = page_soup.findAll("td", {"itemprop": "name"})
            contactstreetaddress = page_soup.findAll("td", {"itemprop": "streetAddress"})
            contactpostalcode = page_soup.findAll("td", {"itemprop": "postalCode"})
            contactaddressregion = page_soup.findAll("td", {"itemprop": "addressRegion"})
            contactaddresscountry = page_soup.findAll("td", {"itemprop": "addressCountry"})
            contactfax = page_soup.findAll("td", {"itemprop": "faxNumber"})
            contactemail = page_soup.findAll("td", {"itemprop": "email"})
            contactphone = page_soup.findAll("td", {"itemprop": "telephone"})
            contacturl = page_soup.findAll("a", {"itemprop": "url"})

            #Outputs as text without tags
            Company = contactname[0].text
            Address = contactstreetaddress[0].text
            Zip = contactpostalcode[0].text
            Region = contactaddressregion[0].text
            Country = contactaddresscountry[0].text
            Fax = contactfax[0].text
            Email = contactemail[0].text
            Phone = contactphone[0].text
            URL = contacturl[0].text
            #Here you might want to consider using dictionary or a list
            #For example append Phone to list call phone
            phone.append(Phone)

The code is a bit messy but it ran through all the possible folders (Even you have other folders inside your main folder) then try to find html tags, the open it.

I would suggest using dictionary with company as a key in which I presume that the company's name are different. A bunch of lists would also be great because your value will be sorted accordingly. I am not good with dictionary so I can't advise you more than this. I hope I answer your question.

P.S sorry for a messy code.

Edit : Fixing replace lxml with html.parser

ContentLicense: CC BY-SA 4.0


问:
How do I display the Interstitial Ad?
I have a navigation bar with three tabs each tab is a fragment.
Now I want that if I click on the second tab, that the Interstitial Ad pops up.
So where do I have to .loadAd the Ad? And where do I have to .show the Ad?

My MainActivity:

```<code>public class MainActivity extends AppCompatActivity{
    public MediaPlayer mp;
    NavigationView mNavigationView;
    FragmentManager mFragmentManager;
    FragmentTransaction mFragmentTransaction;
    public InterstitialAd mInterstitialAd;

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

        mNavigationView = (NavigationView) findViewById(R.id.shitstuff) ;

        mFragmentManager = getSupportFragmentManager();
        mFragmentTransaction = mFragmentManager.beginTransaction();
        mFragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();

        android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);

        AdRequest adRequest = new AdRequest.Builder().build();

        AdRequest adRequest = new AdRequest.Builder().build();
        mInterstitialAd = new InterstitialAd(getContext());
        mInterstitialAd.setAdUnitId("ca-app-pub-9756227769488050/2954649723");
        mInterstitialAd.loadAd(adRequest);

    }
</code>```

My secondFragment:

```<code>public class SecondFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView=inflater.inflate(R.layout.second_layout,container,false);

        return rootView;
    }
</code>```

And (I dont know if that matters) my TabFragment:

```<code>public class TabFragment extends Fragment {
    public static TabLayout tabLayout;
    public static ViewPager viewPager;
    public static int int_items = 3 ;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        /**
         *Inflate tab_layout and setup Views.
         */
            View x =  inflater.inflate(R.layout.tab_layout,null);
            tabLayout = (TabLayout) x.findViewById(R.id.tabs);
            viewPager = (ViewPager) x.findViewById(R.id.viewpager);

        /**
         *Set an Apater for the View Pager
         */
        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));

        /**
         * Now , this is a workaround ,
         * The setupWithViewPager dose't works without the runnable .
         * Maybe a Support Library Bug .
         */

        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                    tabLayout.setupWithViewPager(viewPager);
                   }
        });

        return x;

    }

    class MyAdapter extends FragmentPagerAdapter {

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        /**
         * Return fragment with respect to Position .
         */

        @Override
        public Fragment getItem(int position)
        {

            if(position == 0){
                return new FirstFragment();
            }
            if(position == 1){
                return new SecondFragment();
            }
            if(position == 2){
                return new ThirdFragment();
            }

        return null;
        }

        @Override
        public int getCount() {

            return int_items;

        }

        /**
         * This method returns the title of the tab according to the position.
         */

        @Override
        public CharSequence getPageTitle(int position) {

            switch (position){
                case 0 :
                    return "first";
                case 1 :
                    return "second";
                case 2 :
                    return "third";
            }
                return null;
        }
    }

        });
    }

}
</code>```

So where do I have to say showInterstitial() ?

```<code>final public void showInterstitial(){
    mInterstitialAd.setAdListener(new AdListener() {
        @Override
        public void onAdLoaded() {
            super.onAdLoaded();
            if(mInterstitialAd.isLoaded()){
                mInterstitialAd.show();
            }

        }

        @Override
        public void onAdClosed() {
        }
</code>```

Im hanging on that problem for over a month now, so please give me a explanation in detail. Thanks

答: You should leave the load() in the main activity like you did so it will start caching the ad. Then you will call the showInterstitial() function where you handle the adapter click event, i.e. where you do handle the fragments.</p>

Title: How do I display the Interstitial Ad?

Body:
I have a navigation bar with three tabs each tab is a fragment.
Now I want that if I click on the second tab, that the Interstitial Ad pops up.
So where do I have to .loadAd the Ad? And where do I have to .show the Ad?

My MainActivity:

public class MainActivity extends AppCompatActivity{
    public MediaPlayer mp;
    NavigationView mNavigationView;
    FragmentManager mFragmentManager;
    FragmentTransaction mFragmentTransaction;
    public InterstitialAd mInterstitialAd;

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

        mNavigationView = (NavigationView) findViewById(R.id.shitstuff) ;

        mFragmentManager = getSupportFragmentManager();
        mFragmentTransaction = mFragmentManager.beginTransaction();
        mFragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();

        android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);

        AdRequest adRequest = new AdRequest.Builder().build();

        AdRequest adRequest = new AdRequest.Builder().build();
        mInterstitialAd = new InterstitialAd(getContext());
        mInterstitialAd.setAdUnitId("ca-app-pub-9756227769488050/2954649723");
        mInterstitialAd.loadAd(adRequest);

    }

My secondFragment:

public class SecondFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView=inflater.inflate(R.layout.second_layout,container,false);

        return rootView;
    }

And (I dont know if that matters) my TabFragment:

public class TabFragment extends Fragment {
    public static TabLayout tabLayout;
    public static ViewPager viewPager;
    public static int int_items = 3 ;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        /**
         *Inflate tab_layout and setup Views.
         */
            View x =  inflater.inflate(R.layout.tab_layout,null);
            tabLayout = (TabLayout) x.findViewById(R.id.tabs);
            viewPager = (ViewPager) x.findViewById(R.id.viewpager);

        /**
         *Set an Apater for the View Pager
         */
        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));

        /**
         * Now , this is a workaround ,
         * The setupWithViewPager dose't works without the runnable .
         * Maybe a Support Library Bug .
         */

        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                    tabLayout.setupWithViewPager(viewPager);
                   }
        });

        return x;

    }

    class MyAdapter extends FragmentPagerAdapter {

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        /**
         * Return fragment with respect to Position .
         */

        @Override
        public Fragment getItem(int position)
        {

            if(position == 0){
                return new FirstFragment();
            }
            if(position == 1){
                return new SecondFragment();
            }
            if(position == 2){
                return new ThirdFragment();
            }

        return null;
        }

        @Override
        public int getCount() {

            return int_items;

        }

        /**
         * This method returns the title of the tab according to the position.
         */

        @Override
        public CharSequence getPageTitle(int position) {

            switch (position){
                case 0 :
                    return "first";
                case 1 :
                    return "second";
                case 2 :
                    return "third";
            }
                return null;
        }
    }

        });
    }

}

So where do I have to say showInterstitial() ?

final public void showInterstitial(){
    mInterstitialAd.setAdListener(new AdListener() {
        @Override
        public void onAdLoaded() {
            super.onAdLoaded();
            if(mInterstitialAd.isLoaded()){
                mInterstitialAd.show();
            }

        }

        @Override
        public void onAdClosed() {
        }

Im hanging on that problem for over a month now, so please give me a explanation in detail. Thanks


答:
```<code>public class MainActivity extends Activity {
private InterstitialAd interstitial;

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

mNavigationView = (NavigationView) findViewById(R.id.shitstuff) ;

mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();

android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);

    // Prepare the Interstitial Ad
    interstitial = new InterstitialAd(MainActivity.this);
    // Insert the Ad Unit ID
    interstitial.setAdUnitId("ca-app-pub-123456789/123456789");

    //Locate the Banner Ad in activity_main.xml
    AdView adView = (AdView) this.findViewById(R.id.adView);

    // Request for Ads
    AdRequest adRequest = new AdRequest.Builder().build();

    // Load ads into Banner Ads
    adView.loadAd(adRequest);

}
public void displayInterstitial() {
    // If Ads are loaded, show Interstitial else show nothing.
    // Load ads into Interstitial Ads
    interstitial.loadAd(adRequest);

    // Prepare an Interstitial Ad Listener
    interstitial.setAdListener(new AdListener() {
        public void onAdLoaded() {
            if (interstitial.isLoaded()) {
        interstitial.show();
    }
        }
    });
    }
}
</code>```

Title: How do I display the Interstitial Ad?


问:
Is there any phone that doesn't have sms inbox content provider?
Is there any phone that doesn't have typical sms content provider ("content://sms/inbox")?

Or there is any phone that has different fields scheme?

答: Well, there are tablets that don't have telephony services so I guess it's possible that it doesn't work or just doesn't contain anything :-)</p>


问:
Two objects having same hashcode means they are referring to same object ..right?
Being new to Scala, I have created an Object (singleton). and assinged two different variables to that object as shown below. Both of them show me the same hashcode. Because "School" is a singleton. Is that right?</p>

```<code> object Main extends  App{

 //we can import within the method as well .
 import Scala_DemoSingletonPackage._

  //See both the objeccts have same hashcode.
  println("The hasshcode for first object is " + aSchool.hashCode())
  println("The Hashcode from second object is " + bSchool.hashCode())

}

object School {

  def Printwhateveryouwant(input:String) {
     println(s"This is a singleton object  $input")

 }
</code>```

答:
Two objects having the same hashcode does not mean they are equal due to the nature of hashing (unless you have a perfect hash function that is).  However, if two objects are equal, then they will have the same hashcode.

In scala, if you'd like to check if objects are equal you can use the following:

```<code>aSchool eq bSchool
</code>```

Body:
Being new to Scala, I have created an Object (singleton). and assinged two different variables to that object as shown below. Both of them show me the same hashcode. Because "School" is a singleton. Is that right?

 object Main extends  App{

 //we can import within the method as well .
 import Scala_DemoSingletonPackage._

  //See both the objeccts have same hashcode.
  println("The hasshcode for first object is " + aSchool.hashCode())
  println("The Hashcode from second object is " + bSchool.hashCode())

}

object School {

  def Printwhateveryouwant(input:String) {
     println(s"This is a singleton object  $input")

 }

Body:
Two objects having the same hashcode does not mean they are equal due to the nature of hashing (unless you have a perfect hash function that is).  However, if two objects are equal, then they will have the same hashcode.

In scala, if you'd like to check if objects are equal you can use the following:

aSchool eq bSchool