问:
how to show closest div on hover?
i want to hover over a child element for it to show the NEAREST footer div on tumblr.

```<code><div class="entry">
{block:Posts}
<div class="container">
{block:Text}{/block:Text}
{block:Photo}{/block:Photo}
{block:Text}{/block:Text}
</div>
<div class="footer"></div>
{/block:Posts}
</div>
</code>```

the footer class is to be hidden but i want it so that when i hover over any one of the post type, only the footer of that post shows.

example :

i hover over my text post about something, it'll show the footer of THAT post specifically!

any help would be appreciated!

edit : i think my circumstances weren't properly explained so i updated!

答:
You can have a css rule that conditionally hides the two, so long as the one is not hovered.

.one:not(:hover) + .two {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="one">hi</div>
<div class="two">this</div>

<div class="one">is</div>
<div class="two">an</div>

<div class="one">example</div>
<div class="two">code</div></code>```

Title: how to show closest div on hover?

Body:
i want to hover over a child element for it to show the NEAREST footer div on tumblr.

{block:Posts}

{block:Text}{/block:Text}
{block:Photo}{/block:Photo}
{block:Text}{/block:Text}

{/block:Posts}

the footer class is to be hidden but i want it so that when i hover over any one of the post type, only the footer of that post shows.

example :

i hover over my text post about something, it'll show the footer of THAT post specifically!

any help would be appreciated!

edit : i think my circumstances weren't properly explained so i updated!

Body:
You can have a css rule that conditionally hides the two, so long as the one is not hovered.

.one:not(:hover) + .two {
  display: none;
}

<div class="one">hi</div>
<div class="two">this</div>

<div class="one">is</div>
<div class="two">an</div>

<div class="one">example</div>
<div class="two">code</div>


来源: stackexchange

问:
Can't play a reversed .wav file with MediaPlayer
I've created an app that records audio, saves the sample to the sd card then plays it back, using the record and play buttons. I need to reverse this sample. I can do all this and the the reversed sample is saved on the SD card under a different name. The original sample is test.wav and the same sample reversed is save as revFile.wav. when i try play revFile.wav android says it can't play this format.

I've litterally put the sample in an array then reversed the contents, something is telling me that there could be header info at the start of the sample that needs striping first, any ideas. thanks.

Here's what i have so far.

```<code>public class recorder extends Activity  {
    MediaRecorder myRecorder = null;
    DataInputStream dis = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void onClickPlay(View v){
        Log.v("onClickplay", "play clicked");

        try{
            MediaPlayer mp = new MediaPlayer();
            mp.setDataSource(Environment.getExternalStorageDirectory().getPath() + "/test.wav");
            mp.prepare();
            mp.start();
        } catch(Exception e3) {
            e3.printStackTrace();
        }
        TextView text = (TextView)findViewById(R.id.TextView01);
        text.setText("playing");
    }

    public void onClickRecord(View v){
        Log.v("onClickRecord", "record clicked");

        File path = Environment.getExternalStorageDirectory();
        Log.v("file path", ""+path.getAbsolutePath());

        File file = new File(path, "test.wav");
        if(file.exists()){
            file.delete();
        }
        path.mkdirs();
        Log.v("file path", ""+file.getAbsolutePath());
        myRecorder = new MediaRecorder();
        myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        myRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        myRecorder.setOutputFile(file.getAbsolutePath());
        Log.i("myrecorder", "about to prepare recording");
        try{
            myRecorder.prepare();
        } catch(Exception e) {
            e.printStackTrace();
        }

        Log.i("myrecorder", "prepared");
        myRecorder.start();   // Recording is now started
        Log.i("myrecorder", "recording");
        TextView text = (TextView)findViewById(R.id.TextView01);
        text.setText("recording");
    }

    public void onClickStop(View v){
        Log.v("onClickStop", "stop clicked");

            try{
             myRecorder.stop();
             myRecorder.reset();   // You can reuse the object by going back to setAudioSource() step
             myRecorder.release(); // Now the object cannot be reused
            }catch(Exception e){}

            TextView text = (TextView)findViewById(R.id.TextView01);
             text.setText("recording stopped");

        }

public void onClickReverse(View v){
        Log.v("onClickReverse", "reverse clicked");

        File f = Environment.getExternalStorageDirectory();
        String path = f.getAbsolutePath();
        path = path + "/test.wav";
        Log.v("path = ", ""+path);
        Log.v("dir = ", ""+f.getAbsolutePath());
        Log.v("test file exists? = ", ""+f.getAbsolutePath()+"/test.wav");

        File f2 = new File(path);
        Log.v("f2 = ", ""+f2.getAbsolutePath());

        try {
            InputStream is = new FileInputStream(f2);
            BufferedInputStream bis = new BufferedInputStream(is);
            dis = new DataInputStream(bis);
        } catch (Exception e) {
            e.printStackTrace();
        }

        int fileLength = (int)f2.length();
        byte[] buffer = new byte[fileLength];

        /*File reversedFile = Environment.getExternalStorageDirectory();
          File revFile = new File(reversedFile, "reversedFile.wav");
          Log.v("reversedfile path", ""+ revFile.getAbsolutePath());

          if(revFile.exists()){
              revFile.delete();
          }

          reversedFile.mkdirs();
    */

        byte[] byteArray = new byte[fileLength +1];
        Log.v("bytearray size = ", ""+byteArray.length);

        try {
            while(dis.read(buffer) != -1 ) {
                dis.read(buffer);
                Log.v("about to read buffer", "buffer");

                byteArray = buffer;
            }

            Log.v(" buffer size = ", ""+ buffer.length);
        } catch (IOException e) {
            e.printStackTrace();
        }

          byte[] tempArray = new byte[fileLength];

          int j=0;
          for (int i=byteArray.length-1; i >=0; i--) {
              tempArray[ j++ ] = byteArray[i];
          }

          File revPath = Environment.getExternalStorageDirectory();
          Log.v("revpath path", ""+revPath.getAbsolutePath());

          File revFile = new File(revPath, "revFile.wav");
          Log.v("revfile path ", ""+revFile.getAbsolutePath());
          if(revFile.exists()){
              revFile.delete();
          }

          revPath.mkdirs();

          try {
              OutputStream os = new FileOutputStream(revFile);
              BufferedOutputStream bos = new BufferedOutputStream(os);
              DataOutputStream dos = new DataOutputStream(bos);
              Log.v("temparray size = ", ""+ tempArray.length);
              dos.write(tempArray);
              dos.flush();
              dos.close();
          } catch (Exception e) {
              e.printStackTrace();
          }

          try{
              MediaPlayer mp = new MediaPlayer();
              mp.setDataSource(Environment.getExternalStorageDirectory().getPath()
                                                                    +"/revFile.wav");

              mp.prepare();
              mp.start();
         } catch(Exception e3) {
                e3.printStackTrace();
         }
          TextView text = (TextView)findViewById(R.id.TextView01);
           text.setText("playing reversed file");
      }

}// end of onclickrev
</code>```

答: I'm pretty sure that you're right and that the problem is that you can't just reverse the bytes in the file to reverse the waveform because you're destroying header information.  You should try to see if there's a good library out there to do this, since I have little experience working with .wav files.</p>

ContentLicense: CC BY-SA 2.5

Body:
I've created an app that records audio, saves the sample to the sd card then plays it back, using the record and play buttons. I need to reverse this sample. I can do all this and the the reversed sample is saved on the SD card under a different name. The original sample is test.wav and the same sample reversed is save as revFile.wav. when i try play revFile.wav android says it can't play this format.

I've litterally put the sample in an array then reversed the contents, something is telling me that there could be header info at the start of the sample that needs striping first, any ideas. thanks.

Here's what i have so far.

public class recorder extends Activity  {
    MediaRecorder myRecorder = null;
    DataInputStream dis = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void onClickPlay(View v){
        Log.v("onClickplay", "play clicked");

        try{
            MediaPlayer mp = new MediaPlayer();
            mp.setDataSource(Environment.getExternalStorageDirectory().getPath() + "/test.wav");
            mp.prepare();
            mp.start();
        } catch(Exception e3) {
            e3.printStackTrace();
        }
        TextView text = (TextView)findViewById(R.id.TextView01);
        text.setText("playing");
    }

    public void onClickRecord(View v){
        Log.v("onClickRecord", "record clicked");

        File path = Environment.getExternalStorageDirectory();
        Log.v("file path", ""+path.getAbsolutePath());

        File file = new File(path, "test.wav");
        if(file.exists()){
            file.delete();
        }
        path.mkdirs();
        Log.v("file path", ""+file.getAbsolutePath());
        myRecorder = new MediaRecorder();
        myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        myRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        myRecorder.setOutputFile(file.getAbsolutePath());
        Log.i("myrecorder", "about to prepare recording");
        try{
            myRecorder.prepare();
        } catch(Exception e) {
            e.printStackTrace();
        }

        Log.i("myrecorder", "prepared");
        myRecorder.start();   // Recording is now started
        Log.i("myrecorder", "recording");
        TextView text = (TextView)findViewById(R.id.TextView01);
        text.setText("recording");
    }

    public void onClickStop(View v){
        Log.v("onClickStop", "stop clicked");

            try{
             myRecorder.stop();
             myRecorder.reset();   // You can reuse the object by going back to setAudioSource() step
             myRecorder.release(); // Now the object cannot be reused
            }catch(Exception e){}

            TextView text = (TextView)findViewById(R.id.TextView01);
             text.setText("recording stopped");

        }

public void onClickReverse(View v){
        Log.v("onClickReverse", "reverse clicked");

        File f = Environment.getExternalStorageDirectory();
        String path = f.getAbsolutePath();
        path = path + "/test.wav";
        Log.v("path = ", ""+path);
        Log.v("dir = ", ""+f.getAbsolutePath());
        Log.v("test file exists? = ", ""+f.getAbsolutePath()+"/test.wav");

        File f2 = new File(path);
        Log.v("f2 = ", ""+f2.getAbsolutePath());

        try {
            InputStream is = new FileInputStream(f2);
            BufferedInputStream bis = new BufferedInputStream(is);
            dis = new DataInputStream(bis);
        } catch (Exception e) {
            e.printStackTrace();
        }

        int fileLength = (int)f2.length();
        byte[] buffer = new byte[fileLength];

        /*File reversedFile = Environment.getExternalStorageDirectory();
          File revFile = new File(reversedFile, "reversedFile.wav");
          Log.v("reversedfile path", ""+ revFile.getAbsolutePath());

          if(revFile.exists()){
              revFile.delete();
          }

          reversedFile.mkdirs();
    */

        byte[] byteArray = new byte[fileLength +1];
        Log.v("bytearray size = ", ""+byteArray.length);

        try {
            while(dis.read(buffer) != -1 ) {
                dis.read(buffer);
                Log.v("about to read buffer", "buffer");

                byteArray = buffer;
            }

            Log.v(" buffer size = ", ""+ buffer.length);
        } catch (IOException e) {
            e.printStackTrace();
        }

          byte[] tempArray = new byte[fileLength];

          int j=0;
          for (int i=byteArray.length-1; i >=0; i--) {
              tempArray[ j++ ] = byteArray[i];
          }

          File revPath = Environment.getExternalStorageDirectory();
          Log.v("revpath path", ""+revPath.getAbsolutePath());

          File revFile = new File(revPath, "revFile.wav");
          Log.v("revfile path ", ""+revFile.getAbsolutePath());
          if(revFile.exists()){
              revFile.delete();
          }

          revPath.mkdirs();

          try {
              OutputStream os = new FileOutputStream(revFile);
              BufferedOutputStream bos = new BufferedOutputStream(os);
              DataOutputStream dos = new DataOutputStream(bos);
              Log.v("temparray size = ", ""+ tempArray.length);
              dos.write(tempArray);
              dos.flush();
              dos.close();
          } catch (Exception e) {
              e.printStackTrace();
          }

          try{
              MediaPlayer mp = new MediaPlayer();
              mp.setDataSource(Environment.getExternalStorageDirectory().getPath()
                                                                    +"/revFile.wav");

              mp.prepare();
              mp.start();
         } catch(Exception e3) {
                e3.printStackTrace();
         }
          TextView text = (TextView)findViewById(R.id.TextView01);
           text.setText("playing reversed file");
      }

}// end of onclickrev


问:
Qt/OSX WebSocket opening handshake timed out
I just developed an Application in Qt that uses a WebSocket Server (QWebSocketServer). I did this under Linux and everything worked great, but when I ran the code on Mac OS I was unable to connect to the server from a webpage on Chrome.

The connection took ages, and I got WebSocket opening handshake timed out from Chrome after a few minutes.

In the end I went back to basics and tried Qt's example:

http://doc.qt.io/qt-5/qtwebsockets-sslechoserver-example.html

Exactly the same.

edit:

After removing SSL and using non-secure websockets it works, even on the same port.

Chrome on the Mac can access a secure Qt WebSocket server on a remote (non-Mac) computer, but Chrome on a remote computer times out while connecting to the Mac (securely) - so it would appear to be something wrong with the Qt QWebSocketServer example. It works fine on both Linux and Windows.

There is a connection being made (because the web browser fails instantly if the application isn't running or is closed), but for whatever reason it isn't completing.

Any idea what this might be, or how I can go about trying to track it down?

thanks!

答:
The issue here seems to be some interaction with MacOS's permissions system.

The first time you run the application and connect, the app will pop up a window asking for permissions to access your keychain (I guess to install the certificate).

If you close the dialog at that point, it won't come back, and it seems no QtWebSocketServer based programs will function from then on, until your reboot!

ContentLicense: CC BY-SA 3.0


问:
adding angular component dynamically to new html element
I have read about  ViewContainerRef, ComponentFactoryResolver.

Basically:

put  tag in your html

declare the following in your ts:
@ViewChild('parent', { read: ViewContainerRef })
parent: ViewContainerRef;

instantiate your component using:
const childComponent = this.componentFactoryResolver.resolveComponentFactory(ChildComponent );
this.parent.createComponent(childComponent);

However, it does not work on   already exist in your html on your page load.

The problem is I am using a popup that is generated using google map api (the popup where it appears when you click somewhere on the map).

I need to put div parent tag  after the popup appears

```<code>var infowindow = new google.maps.InfoWindow({
      // content: this.contentString
      content: " <div #parent></div>"
    });
</code>```

Therefore I tried to bind it into onclick event on the popup as the following:

```<code>  marker.addListener('click', () => {
        infowindow.open(this.map, marker);
        const childComponent = this.componentFactoryResolver.resolveComponentFactory(CentreDetailsComponent);
        this.parent.createComponent(childComponent);
      });
</code>```

However, it does not work as per the screenshot. Is it because of the div parent tag is not generated on page load? can someone please assist? Thx

答:
The best Solution is. You just go for AgmCore

```<code>npm install --save @agm/core
</code>```

for that you need to add core module in your ngModule like :

```<code>import { AgmCoreModule } from '@agm/core';
@NgModule({
    imports: [
        AgmCoreModule.forRoot({
            apiKey: 'api_key_googlemap'
          })
    ]})
</code>```

and your html view file will looks like

```<code> <div  style="height: 700px; width: 100%;">
    <agm-map [latitude]="32.02" [longitude]="52.2" [zoom]="17">
        <agm-marker   [latitude]="52.2" [longitude]="32.02"   title="Name" >
           <agm-info-window  [isOpen]="true"  >
              <h6>Name</h6>
           </agm-info-window>
         </agm-marker>
       </agm-map>
</div>
</code>```

if you want click function in marker

```<code><agm-marker (markerClick)="yourClickFunction()"></agm-marker>
</code>```

Hope this will resolve your problem.

Body:
I have read about  ViewContainerRef, ComponentFactoryResolver.

Basically:

put  tag in your html

declare the following in your ts:
@ViewChild('parent', { read: ViewContainerRef })
parent: ViewContainerRef;

instantiate your component using:
const childComponent = this.componentFactoryResolver.resolveComponentFactory(ChildComponent );
this.parent.createComponent(childComponent);

However, it does not work on   already exist in your html on your page load.

The problem is I am using a popup that is generated using google map api (the popup where it appears when you click somewhere on the map).

I need to put div parent tag  after the popup appears

var infowindow = new google.maps.InfoWindow({
      // content: this.contentString
      content: "

"
    });

Therefore I tried to bind it into onclick event on the popup as the following:

  marker.addListener('click', () => {
        infowindow.open(this.map, marker);
        const childComponent = this.componentFactoryResolver.resolveComponentFactory(CentreDetailsComponent);
        this.parent.createComponent(childComponent);
      });

However, it does not work as per the screenshot. Is it because of the div parent tag is not generated on page load? can someone please assist? Thx

Body:
The best Solution is. You just go for AgmCore

npm install --save @agm/core

for that you need to add core module in your ngModule like :

import { AgmCoreModule } from '@agm/core';
@NgModule({
    imports: [
        AgmCoreModule.forRoot({
            apiKey: 'api_key_googlemap'
          })
    ]})

and your html view file will looks like

 <div  style="height: 700px; width: 100%;">
    <agm-map [latitude]="32.02" [longitude]="52.2" [zoom]="17">
        <agm-marker   [latitude]="52.2" [longitude]="32.02"   title="Name" >
           <agm-info-window  [isOpen]="true"  >
              <h6>Name</h6>
           </agm-info-window>
         </agm-marker>
       </agm-map>
</div>

if you want click function in marker

<agm-marker (markerClick)="yourClickFunction()"></agm-marker>

Hope this will resolve your problem.


问:
Selecting the second checkbox also selects the first one
I have a form with two checkboxes that allows the user to select yes or no based on the question asked. Now when I select the second checkbox, the first checkbox is also selected which is what I don't want. When I say the area within the second container is clicked, you have to directly click on the checkbox area (the label or the rest of the container won't select the checkbox like the first checkbox and it's container will). So when you click the second checkbox directly it also checks the first.

My question is, why is it allowing me to check anywhere within the first container, but not the second container? Additionally, why is the first being selected when I only want to select the second one?

HTML (disregard the inline CSS that will be moved over to stylesheet.css):

```<code><div style="background: #FFF; width: 1200px; height: 700px; display: block; margin: 100px auto; overflow: auto;">
    <div style="display: block; margin: 30px auto; height: 400px; width: 1000px">
      <h4 style="font-family: 'Lato', sans-serif; margin-top: 90px; letter-spacing: 1px;"><strong>Blah blah blah?</strong></h4>

      <div class="inline field" style="max-width: 500px;">

        <form role="form" action="" style="margin-top: 60px;">
          <div class="checkbox" style="height: 50px; border: 2px solid #f8f8f8; border-radius: 2px;">
            <label for="checkbox1" style="height: 46px; padding-top: 14px; width: 500px;">
              <input type="checkbox" id="checkbox1" class="checkbox-circle" value="true" style="background: red; margin-right: 20px;" />
              Yes</label>
          </div>

          <div class="checkbox" style="height: 50px; border: 2px solid #f8f8f8; border-radius: 2px;">
            <label for="checkbox1" style="height: 46px; padding-top: 14px; width: 500px;">
              <input type="checkbox" id="checkbox1" class="checkbox-circle" value="true" style="background: red; margin-right: 20px;" />
              No</label>
          </div>
        </form>

      </div>
    </div>
  </div>
</code>```

Image of the form:

答: Both label and input objects reference "checkbox1" and are not unique.  Make sure the second label and input tags are unique.

Body:
I have a form with two checkboxes that allows the user to select yes or no based on the question asked. Now when I select the second checkbox, the first checkbox is also selected which is what I don't want. When I say the area within the second container is clicked, you have to directly click on the checkbox area (the label or the rest of the container won't select the checkbox like the first checkbox and it's container will). So when you click the second checkbox directly it also checks the first.

My question is, why is it allowing me to check anywhere within the first container, but not the second container? Additionally, why is the first being selected when I only want to select the second one?

HTML (disregard the inline CSS that will be moved over to stylesheet.css):

Blah blah blah?

        <form role="form" action="" style="margin-top: 60px;">

              <input type="checkbox" id="checkbox1" class="checkbox-circle" value="true" style="background: red; margin-right: 20px;" />
              Yes

              <input type="checkbox" id="checkbox1" class="checkbox-circle" value="true" style="background: red; margin-right: 20px;" />
              No

        </form>

Image of the form:


问:
Unable to connect to GitHub API
We are getting an error "Unable to connect to GitHub API: org.kohsuke.github.HttpException: Server returned HTTP response code: -1, message: 'null' for URL: https://github.xxx.com/api/v3/user" when trying to use github pull request builder in jenkins</p>

答:
You may need to add your Certificate Authority cert to the java keytool.

If you look in your jenkins log and find something like this:

```<code>org.kohsuke.github.HttpException: Server returned HTTP response code: -1, message: 'null' for URL: https://github.xxx.com/api/v3/user
</code>```

Scroll down and see if there is a line like this:

```<code>Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
</code>```

This error is saying that the SSL handshake failed with something about the PKIX path/certpath.  Try adding your CA Cert to the keytool and restarting Jenkins to see if that helps.

Here's the post  that helped me modify the java certs with the keytool. (the default keytool password is "changeit")

Title: Unable to connect to GitHub API

Body:
You may need to add your Certificate Authority cert to the java keytool.

If you look in your jenkins log and find something like this:

org.kohsuke.github.HttpException: Server returned HTTP response code: -1, message: 'null' for URL: https://github.xxx.com/api/v3/user

Scroll down and see if there is a line like this:

Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

This error is saying that the SSL handshake failed with something about the PKIX path/certpath.  Try adding your CA Cert to the keytool and restarting Jenkins to see if that helps.

Here's the post  that helped me modify the java certs with the keytool. (the default keytool password is "changeit")


问:
Linking of IPP 2018 with mingw
I am trying to use the 2018 version of Intel IPP with mingw, and I have trouble linking the .lib that Intel provides to my program. The program I am compiling is the IPP example at https://software.intel.com/en-us/ipp-dev-guide-building-intel-ipp-applications

Here is the makefile:

```<code>HDIR = "C:\Program Files (x86)\IntelSWTools\compilers_and_libraries_2018.1.156\windows\ipp\include"
LDADD = "C:\Program Files (x86)\IntelSWTools\compilers_and_libraries_2018.1.156\windows\ipp\lib\intel64_win"
SOURCES= test.cpp
OBJECTS1=$(patsubst %.cpp,%.o,$(SOURCES))
OBJECTS=$(patsubst %.c,%.o,$(OBJECTS1))

all debug profile static depend: $(OBJECTS)
    g++ -o test.exe test.o $(CXXFLAGS) -L$(LDADD) -lippcc -lippi -lipps -lippcore -lm

%.o: %.cpp
    g++ -c $< -I $(HDIR) $(CXXFLAGS)

%.o: %.c
    g++ -c $< -I $(HDIR) $(CXXFLAGS)

clean:
    rm -f *.o
</code>```

and here's the gcc output:

```<code>g++ -c test.cpp -I "C:\Program Files (x86)\IntelSWTools\compilers_and_libraries_
2018.1.156\windows\ipp\include"
g++ -o test.exe test.o  -L"C:\Program Files (x86)\IntelSWTools\compilers_and_lib
raries_2018.1.156\windows\ipp\lib\intel64_win" -lippcc -lippi -lipps -lippcore -
lm
test.o:test.cpp:(.text+0x14): undefined reference to `ippInit'
test.o:test.cpp:(.text+0x19): undefined reference to `ippGetLibVersion'
test.o:test.cpp:(.text+0x5f): undefined reference to `ippGetCpuFeatures'
test.o:test.cpp:(.text+0x79): undefined reference to `ippGetEnabledCpuFeatures'
collect2: error: ld returned 1 exit status
Makefile:8: recipe for target 'all' failed
make: *** [all] Error 1
</code>```

The linker is finding the libraries, but I don't understand why I am getting undefined references. Has anybody had any success in compiling recent IPP versions with mingw ?

答:
I solved it by linking to the .dll instead of the .lib, and using the 32-bit version of the dll (stupidly I though my gcc was 64-bits but it was not).

The correct path to give to the linker for the libraries is:

```<code>LDADD = "C:\Program Files (x86)\IntelSWTools\compilers_and_libraries_2018.1.156\windows\redist\ia32_win\ipp"
</code>```

(if you are using 32-bits)

Title: Linking of IPP 2018 with mingw

Body:
I am trying to use the 2018 version of Intel IPP with mingw, and I have trouble linking the .lib that Intel provides to my program. The program I am compiling is the IPP example at https://software.intel.com/en-us/ipp-dev-guide-building-intel-ipp-applications

Here is the makefile:

HDIR = "C:\Program Files (x86)\IntelSWTools\compilers_and_libraries_2018.1.156\windows\ipp\include"
LDADD = "C:\Program Files (x86)\IntelSWTools\compilers_and_libraries_2018.1.156\windows\ipp\lib\intel64_win"
SOURCES= test.cpp
OBJECTS1=$(patsubst %.cpp,%.o,$(SOURCES))
OBJECTS=$(patsubst %.c,%.o,$(OBJECTS1))

all debug profile static depend: $(OBJECTS)
    g++ -o test.exe test.o $(CXXFLAGS) -L$(LDADD) -lippcc -lippi -lipps -lippcore -lm

%.o: %.cpp
    g++ -c $< -I $(HDIR) $(CXXFLAGS)

%.o: %.c
    g++ -c $< -I $(HDIR) $(CXXFLAGS)

clean:
    rm -f *.o

and here's the gcc output:

g++ -c test.cpp -I "C:\Program Files (x86)\IntelSWTools\compilers_and_libraries_
2018.1.156\windows\ipp\include"
g++ -o test.exe test.o  -L"C:\Program Files (x86)\IntelSWTools\compilers_and_lib
raries_2018.1.156\windows\ipp\lib\intel64_win" -lippcc -lippi -lipps -lippcore -
lm
test.o:test.cpp:(.text+0x14): undefined reference to `ippInit'
test.o:test.cpp:(.text+0x19): undefined reference to `ippGetLibVersion'
test.o:test.cpp:(.text+0x5f): undefined reference to `ippGetCpuFeatures'
test.o:test.cpp:(.text+0x79): undefined reference to `ippGetEnabledCpuFeatures'
collect2: error: ld returned 1 exit status
Makefile:8: recipe for target 'all' failed
make: *** [all] Error 1

The linker is finding the libraries, but I don't understand why I am getting undefined references. Has anybody had any success in compiling recent IPP versions with mingw ?

Body:
I solved it by linking to the .dll instead of the .lib, and using the 32-bit version of the dll (stupidly I though my gcc was 64-bits but it was not).

The correct path to give to the linker for the libraries is:

LDADD = "C:\Program Files (x86)\IntelSWTools\compilers_and_libraries_2018.1.156\windows\redist\ia32_win\ipp"

(if you are using 32-bits)


问:
Linux 32 NASM How can i do this task ;( any tips?
I have a problem with my exam and dont know how i can program this maybe someone has an idea.
I have to take random digits and letters from the comando row, overall there are 8 pieces ******** . The First digit or letter i have to multiply with 7 the second with 3 the third with 1 and then again from the beginning, the fourth digit or letter again with 7 this scheme up to the 8 numeral. Then after all i have to add up all digits and the last digit of the Result need to be output it.
i dont have an idea how i can do this maybe some one have an idea i think first of all i have to change the string into a integer and then? push on the stack? or what really dont know thx for your help</p>

答:
try to create linux32 binary, that just cleanly exits (or even displays "hello world"). Verify it is really elf32 (and you are not building elf64, it's often default in modern 64b distros). If you have Win10, and you plan to use the ubuntu inside it, you are out of luck, it doesn't support 32b binaries, you will then need full common linux distro in some virtual machine. Use strace ./<binary> to see what system calls it is doing. Use debugger to single step over each instruction, see what values are in registers and check memory content (for example the instruction opcodes at entry point). I.e. verify your nasm + other tools are in place and works, and you are comfortable with them.

modify it to "hello world" example, if it is not yet. Try to find tutorial which explains it enough, that you actually understand how it works.

From here on, after every following step always single-step over the code in debugger and reason about what the instructions are doing, and if they really do what you intended, without any unwanted side effects.

Try programmatically change "e" to "E" (by a simple mov instruction, not by writing big E in the string definition). (to verify that you understand how string works, and also to put it into read-write memory, if you have original hello-world example with read-only definition).

check some documentation/tutorials how command line arguments can be accessed, try to output it instead of hello world.

At this moment you should be skilled enough to access single letters of the input string.

convert letter/digit from ASCII code to your encoding (I have a suspicion you have defined values for letters for the task, like A is 10, etc., which is not compatible with ASCII, where A is 65).

multiply it by constant value, if you don't know yet how to have array of "weights".

do that in some loop for all values

create support array with multiplication weights (either 8 of them for each input char), or just the distinct ones + handle wrap-around.

sum the results of multiplication into some intermediate result

use div 10 to extract last digit only as remainder of division

convert the remainder into ASCII character, and store it into memory as string, to display it instead of hello world/etc. And display it.

verify it four times in debugger, also for invalid inputs, etc.. fix all bugs.

DONE.

push on the stack?

Why? Does it make it more crisp or salty?

You know what your task is. It's actually quite neat task in terms that it really reads as calculation (with some other tasks it may be more difficult for beginners to see their calculation-nature, but this one is like naturally calculation-like, no subtlety or hiding). Focus on the task. If you need to multiply each letter, then just multiply it. If you need sum of the results, then just add summing. Etc.

Don't throw some code into the source just to try if it does help, assembly doesn't work like that, you have almost no chance to fix anything just by accident, by copy/pasting more and more code from Internet. That sort-of-works in high level languages, but never in assembly. Always focus what calculation you want, and write that in CPU instructions. For ideas what can be written in ASM, keep reading through instruction set reference guide (search for example for the 80386 limited list, which is enough for you task, but doesn't contain another hundreds of floating point/MMX/SSE instructions, which you can check later, after you have decent knowledge of the basic instructions). Check some simple tutorials to see how instructions are used to calculate desired result.

And yes, everything in computer is basically an calculation. You put the input values into, run the calculation over it, and output the results. It's just a bit more tricky, as the result is not numbers per-se, you can count as result of calculation also certain part of code executed, like "run this code calling OS API displaying a string". But nonetheless, think about it as about a deterministic calculation, going instruction by instruction. From one state you will get into next state. Find a formulae which leads from input state to the end state and write it in CPU instructions. Done.


问:
Shadow-dom support for selenium
I am working on an automation project which uses shadow DOMs extensively.
I use the execute_script function to access shadow root elements.

For example:

root = driver.execute_script('return document.querySelector(".flex.vertical.layout").shadowRoot')
```

Then I use the root element to access the elements within.
Since we have shadow root elements at many levels, this is annoying me a lot.
Is there any better solution to access elements within shadow root elements?

I am using Chrome 2.20 driver.

答:
You can write extension methods to operate on IWebElement to expand the root as below.

public static class SeleniumExtension
{
    public static IWebElement ExpandRootElement(this IWebElement element, IWebDriver driver)
    {
        return (IWebElement)((IJavaScriptExecutor)driver)
                .ExecuteScript("return arguments[0].shadowRoot", element);
    }
}
```
<p>You can use the above extension method to traverse through the element's hierarchy to reach the element of interest.</p>
<pre class="lang-java prettyprint-override"><code>By downloads_manager_ShadowDom= By.TagName("downloads-manager");
By downloadToolBarShadowDom = By.CssSelector("downloads-toolbar");
By toolBarElement = By.CssSelector("cr-toolbar");

IWebElement ToolBarElement = driver.FindElement(downloads_manager_ShadowDom).ExpandRootElement(driver).FindElement(downloadToolBarShadowDom).ExpandRootElement(driver).FindElement(toolBarElement);
</code>```

ContentLicense: CC BY-SA 4.0

Title: Shadow-dom support for selenium

Body:
I am working on an automation project which uses shadow DOMs extensively.
I use the execute_script function to access shadow root elements.

For example:

root = driver.execute_script('return document.querySelector(".flex.vertical.layout").shadowRoot')

Then I use the root element to access the elements within.
Since we have shadow root elements at many levels, this is annoying me a lot.
Is there any better solution to access elements within shadow root elements?

I am using Chrome 2.20 driver.

Body:
You can write extension methods to operate on IWebElement to expand the root as below.

public static class SeleniumExtension
{
    public static IWebElement ExpandRootElement(this IWebElement element, IWebDriver driver)
    {
        return (IWebElement)((IJavaScriptExecutor)driver)
                .ExecuteScript("return arguments[0].shadowRoot", element);
    }
}

You can use the above extension method to traverse through the element's hierarchy to reach the element of interest.

By downloads_manager_ShadowDom= By.TagName("downloads-manager");
By downloadToolBarShadowDom = By.CssSelector("downloads-toolbar");
By toolBarElement = By.CssSelector("cr-toolbar");

IWebElement ToolBarElement = driver.FindElement(downloads_manager_ShadowDom).ExpandRootElement(driver).FindElement(downloadToolBarShadowDom).ExpandRootElement(driver).FindElement(toolBarElement);


问:
Angular 4 POST to WCF REST service returns NULL response
I'm trying to issue a POST of a JSON content from an Angular 4 single-page application (runs locally over http://localhost:4200/) to a REST WCF webservice endpoint (runs locally, and the endpoint is the following: http://localhost:3026/ToshlSrvc.svc/Add).

I use standard Http.post() method + RxJs  extensions in order to issue the POST request. The webservice actually receive the POST and relative content and it correctly does what it's designed for (adds the deserialized object to an Entity Framework context, persist to DB and returns the new Id), so there's no error at all client side nor server side.

Unfortunately the "data" args of the subscribe() method used to listen over http.post() is always NULL! I can't get the new Id contained into the POST response! But if i check in network activities of Chrome or if i issue a post with PostMan i see that the response body is the following:

```<code><int xmlns="http://schemas.microsoft.com/2003/10/Serialization/">1250</int>
</code>```

(1250 in this case is the correct new ID)

I can't figure out what's wrong here.
Have you got some suggestions?

Any help is appreciated.

THE CASE

Here's the TypeScript code of how i reach the webService:

```<code>public Add(resource: Entry): void{
    const WEBSERVICE_ADDRESS: string = "http://localhost:3026/ToshlSrvc.svc";
    const headers = new HttpHeaders().set( 'Content-Type', 'application/json; charset=utf-8');
    return this.http.post(this.WEBSERVICE_ADDRESS + '/Add', JSON.stringify(resource), { headers: headers})
                    .catch(this.handleError);
                    .subscribe(data => {
                            console.log(data); //I always get null!
                     });
   }
</code>```

Here's the declaration of the webservice's endpoint:

```<code>[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, UriTemplate = "/Add")]
int Add(EntryDTO entry);
</code>```

The body of my webservice's endpoint:

```<code>int IToshlSrvc.Add(EntryDTO entry)
{

    Entry newEntry = null;

    //Create new entry and add to collection
    if (entry.Type == eTypeDTO.Expense) {
        newEntry = new ExpenseEntry();
        newEntry.Id = this._provider.Expenses.Max(x => x.Id) + 1;
        this._provider.Expenses.Add((ExpenseEntry)newEntry);
    }
    else {
        newEntry = new IncomeEntry();
        newEntry.Id = this._provider.Incomes.Max(x => x.Id) + 1;
        this._provider.Incomes.Add((IncomeEntry)newEntry);
    }

    //Set values
    newEntry.Categories = entry.Categories;
    newEntry.Date = Convert.ToDateTime(entry.Date);
    newEntry.Description = entry.Description;
    newEntry.Value = entry.Value;

    //Returns
    return newEntry.Id;
}
</code>```

The OPTIONS preflight and POST request check:
https://www.dropbox.com/s/900q3oor6dex0hl/issueOPTIONS.png?dl=0
https://www.dropbox.com/s/no8o78oqsolxk21/issuePOST.png?dl=0

In order to allow communication between these different domains i've enabled CORS like exposed here https://enable-cors.org/server_wcf.html + i needed to add an empty GetOptions() endpoint in my webservice like exposed here: Ajax POST to WCF Rest CORS-compliant WebService throws error 405.

I needed to do this because the Enable-Cors.org strategy doesn't work at all without the abovementioned GetOptions() method. I think that this point or a wrong CORS settings can concur in this problem.

答: Your service returns XML. Try to set response type to JSON.</p>

Body:
I'm trying to issue a POST of a JSON content from an Angular 4 single-page application (runs locally over http://localhost:4200/) to a REST WCF webservice endpoint (runs locally, and the endpoint is the following: http://localhost:3026/ToshlSrvc.svc/Add).

I use standard Http.post() method + RxJs  extensions in order to issue the POST request. The webservice actually receive the POST and relative content and it correctly does what it's designed for (adds the deserialized object to an Entity Framework context, persist to DB and returns the new Id), so there's no error at all client side nor server side.

Unfortunately the "data" args of the subscribe() method used to listen over http.post() is always NULL! I can't get the new Id contained into the POST response! But if i check in network activities of Chrome or if i issue a post with PostMan i see that the response body is the following:

<int xmlns="http://schemas.microsoft.com/2003/10/Serialization/">1250</int>

(1250 in this case is the correct new ID)

I can't figure out what's wrong here.
Have you got some suggestions?

Any help is appreciated.

THE CASE

Here's the TypeScript code of how i reach the webService:

public Add(resource: Entry): void{
    const WEBSERVICE_ADDRESS: string = "http://localhost:3026/ToshlSrvc.svc";
    const headers = new HttpHeaders().set( 'Content-Type', 'application/json; charset=utf-8');
    return this.http.post(this.WEBSERVICE_ADDRESS + '/Add', JSON.stringify(resource), { headers: headers})
                    .catch(this.handleError);
                    .subscribe(data => {
                            console.log(data); //I always get null!
                     });
   }

Here's the declaration of the webservice's endpoint:

[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, UriTemplate = "/Add")]
int Add(EntryDTO entry);

The body of my webservice's endpoint:

int IToshlSrvc.Add(EntryDTO entry)
{

    Entry newEntry = null;

    //Create new entry and add to collection
    if (entry.Type == eTypeDTO.Expense) {
        newEntry = new ExpenseEntry();
        newEntry.Id = this._provider.Expenses.Max(x => x.Id) + 1;
        this._provider.Expenses.Add((ExpenseEntry)newEntry);
    }
    else {
        newEntry = new IncomeEntry();
        newEntry.Id = this._provider.Incomes.Max(x => x.Id) + 1;
        this._provider.Incomes.Add((IncomeEntry)newEntry);
    }

    //Set values
    newEntry.Categories = entry.Categories;
    newEntry.Date = Convert.ToDateTime(entry.Date);
    newEntry.Description = entry.Description;
    newEntry.Value = entry.Value;

    //Returns
    return newEntry.Id;
}

The OPTIONS preflight and POST request check:
https://www.dropbox.com/s/900q3oor6dex0hl/issueOPTIONS.png?dl=0
https://www.dropbox.com/s/no8o78oqsolxk21/issuePOST.png?dl=0

In order to allow communication between these different domains i've enabled CORS like exposed here https://enable-cors.org/server_wcf.html + i needed to add an empty GetOptions() endpoint in my webservice like exposed here: Ajax POST to WCF Rest CORS-compliant WebService throws error 405.

I needed to do this because the Enable-Cors.org strategy doesn't work at all without the abovementioned GetOptions() method. I think that this point or a wrong CORS settings can concur in this problem.


问:
How to determine type in disk file before reading to ArrayList?
If I read a file using

```<code>Scanner in = new Scanner(new File(diskFile));
</code>```

How, after that, would I be able to determine which type it is so I can read it into an arraylist of the same type? It's easier to do when you know which type it is such as int

```<code>do {
    nextInt = in.nextInt();
    n.add(nextInt);
}while(in.hasNextInt() == true);
</code>```

but if I don't know if the file type is String, int, double, etc. How would I be able to add them to an ArrayList of the same type? So my solution would be to figure out the type before adding it to an ArrayList, but I have no idea how to do that.

答:
Assuming you have a single unknown value per line in your input file, I'd recommend you read it as a String and then test the string value using the simple parsers available with the common types.  You can test by catching exceptions.  Here is an example for Integer.</p>

```<code>        int newData = 0;
        boolean haveInt = true;
        try {
                 newData = Integer.parseInt(theInputString);
        } catch (NumberFormatException e) {
            haveInt = false;
        }
        if (haveInt) {
           intArrayList.add(newData);
        }
</code>```

Body:
If I read a file using

Scanner in = new Scanner(new File(diskFile));

How, after that, would I be able to determine which type it is so I can read it into an arraylist of the same type? It's easier to do when you know which type it is such as int

do {
    nextInt = in.nextInt();
    n.add(nextInt);
}while(in.hasNextInt() == true);

but if I don't know if the file type is String, int, double, etc. How would I be able to add them to an ArrayList of the same type? So my solution would be to figure out the type before adding it to an ArrayList, but I have no idea how to do that.

Body:
Assuming you have a single unknown value per line in your input file, I'd recommend you read it as a String and then test the string value using the simple parsers available with the common types.  You can test by catching exceptions.  Here is an example for Integer.

        int newData = 0;
        boolean haveInt = true;
        try {
                 newData = Integer.parseInt(theInputString);
        } catch (NumberFormatException e) {
            haveInt = false;
        }
        if (haveInt) {
           intArrayList.add(newData);
        }


问:
Select visible pixels in a layer
I'm writing a Photoshop script using JavaScript where I need to select all visible pixels in a layer to apply an effect on another layer.

The selection I need is the same as when you control+click on a layer thumbnail.

How can I do this?

答:
I think what you are after is this:

```<code>var id1268 = charIDToTypeID( "setd" );
var desc307 = new ActionDescriptor();
var id1269 = charIDToTypeID( "null" );
var ref257 = new ActionReference();
var id1270 = charIDToTypeID( "Chnl" );
var id1271 = charIDToTypeID( "fsel" );
ref257.putProperty( id1270, id1271 );
desc307.putReference( id1269, ref257 );
var id1272 = charIDToTypeID( "T   " );
var ref258 = new ActionReference();
var id1273 = charIDToTypeID( "Chnl" );
var id1274 = charIDToTypeID( "Chnl" );
var id1275 = charIDToTypeID( "Trsp" );
ref258.putEnumerated( id1273, id1274, id1275 );
desc307.putReference( id1272, ref258 );
executeAction( id1268, desc307, DialogModes.NO )
</code>```

Which will make a selection of all current pixels in the current layer (like pressing CTRL)

Title: Select visible pixels in a layer

Body:
I think what you are after is this:

var id1268 = charIDToTypeID( "setd" );
var desc307 = new ActionDescriptor();
var id1269 = charIDToTypeID( "null" );
var ref257 = new ActionReference();
var id1270 = charIDToTypeID( "Chnl" );
var id1271 = charIDToTypeID( "fsel" );
ref257.putProperty( id1270, id1271 );
desc307.putReference( id1269, ref257 );
var id1272 = charIDToTypeID( "T   " );
var ref258 = new ActionReference();
var id1273 = charIDToTypeID( "Chnl" );
var id1274 = charIDToTypeID( "Chnl" );
var id1275 = charIDToTypeID( "Trsp" );
ref258.putEnumerated( id1273, id1274, id1275 );
desc307.putReference( id1272, ref258 );
executeAction( id1268, desc307, DialogModes.NO )

Which will make a selection of all current pixels in the current layer (like pressing CTRL)


问:
Generating and Optimizing Webp via Gulp
I'm using the generator webapp which includes imagemin. I've also added imagemin-webp and gulp-webp to my build.

I am unsure how to implement. I want to keep the original jpg and png images in addition to adding webp, and have all these images optimized when running gulp build task.

I am confused at this stage.

How do I implement it based on my current setup:

```<code>const webp = require('gulp-webp');
const imageminWebp = require('imagemin-webp');

gulp.task('images', () => {
    return gulp.src('app/images/**/*')
    .pipe(webp())
    .pipe($.cache($.imagemin()))
    .pipe(gulp.dest('dist/images'));
});
</code>```

Currently, this just generates unoptimized webp files and doesn't package any of the original jpg and png files.

答:
You have to include gulp-clone to output the original files with their webp counterparts. It would look something like this:</p>

```<code>const webp = require('gulp-webp');
const imageminWebp = require('imagemin-webp');
const clone = require('gulp-clone');
const clonesink = clone.sink();

gulp.task('images', () => {
    return gulp
        .src('app/images/**/*')
        .pipe($.cache($.imagemin())) // optimize images before converting
        .pipe(clonesink) // start stream
        .pipe(webp()) // convert images to webp and save a copy of the original format
        .pipe(clonesink.tap()) // close stream and send both formats to dist
        .pipe(gulp.dest('dist/images'));
});
</code>```

Title: Generating and Optimizing Webp via Gulp

Body:
I'm using the generator webapp which includes imagemin. I've also added imagemin-webp and gulp-webp to my build.

I am unsure how to implement. I want to keep the original jpg and png images in addition to adding webp, and have all these images optimized when running gulp build task.

I am confused at this stage.

How do I implement it based on my current setup:

const webp = require('gulp-webp');
const imageminWebp = require('imagemin-webp');

gulp.task('images', () => {
    return gulp.src('app/images/**/*')
    .pipe(webp())
    .pipe($.cache($.imagemin()))
    .pipe(gulp.dest('dist/images'));
});

Currently, this just generates unoptimized webp files and doesn't package any of the original jpg and png files.

Body:
You have to include gulp-clone to output the original files with their webp counterparts. It would look something like this:

const webp = require('gulp-webp');
const imageminWebp = require('imagemin-webp');
const clone = require('gulp-clone');
const clonesink = clone.sink();

gulp.task('images', () => {
    return gulp
        .src('app/images/**/*')
        .pipe($.cache($.imagemin())) // optimize images before converting
        .pipe(clonesink) // start stream
        .pipe(webp()) // convert images to webp and save a copy of the original format
        .pipe(clonesink.tap()) // close stream and send both formats to dist
        .pipe(gulp.dest('dist/images'));
});


问:
Compiling C++ with -m32 With Cygwin G++ Windows 64bit Error
I am trying to compile my c++ program with -m32 using cygwin g++ but I get an error when I try to do so.

From what I read about the problem, I need to download a package from cygwin package manager that will allow -m32 to work but I am not sure which package it is. Another post I read said I had to install gcc-multilib and g++-multilib from the package manager but those packages are not in the selection of packages available.

```<code>/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0//libgcc_s.dll.a when     searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/libgcc_s.dll.a when     searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0//libgcc_s.dll.a when     searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/libgcc_s.dll.a when     searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     cannot find -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0//libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0//libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0//libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     cannot find -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../libcygwin.a     when searching for -lcygwin
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../libcygwin.a     when searching for -lcygwin
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../libcygwin.a     when searching for -lcygwin
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     cannot find -lcygwin
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     cannot find -ladvapi32
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     cannot find -lshell32
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     cannot find -luser32
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     cannot find -lkernel32
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0//libgcc_s.dll.a when     searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/libgcc_s.dll.a when     searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0//libgcc_s.dll.a when     searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/libgcc_s.dll.a when     searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     cannot find -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0//libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0//libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0//libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     cannot find -lgcc
collect2: error: ld returned 1 exit status
</code>```

Thanks.

答:
As you say, the {gcc|g++}-mulitlib packages are not provided by the cygwin
package manager.

To build 32-bit C++ targets, install package mingw64-i686-gcc-g++, which
is the mingw64 cross compiler for 32-bit targets. Then build with the
compiler /usr/bin/i686-w64-mingw32-g++. There is no need for the -m32
option.

Body:
I am trying to compile my c++ program with -m32 using cygwin g++ but I get an error when I try to do so.

From what I read about the problem, I need to download a package from cygwin package manager that will allow -m32 to work but I am not sure which package it is. Another post I read said I had to install gcc-multilib and g++-multilib from the package manager but those packages are not in the selection of packages available.

/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0//libgcc_s.dll.a when     searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/libgcc_s.dll.a when     searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0//libgcc_s.dll.a when     searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/libgcc_s.dll.a when     searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     cannot find -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0//libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0//libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0//libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     cannot find -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../libcygwin.a     when searching for -lcygwin
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../libcygwin.a     when searching for -lcygwin
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../libcygwin.a     when searching for -lcygwin
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     cannot find -lcygwin
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     cannot find -ladvapi32
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     cannot find -lshell32
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     cannot find -luser32
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     cannot find -lkernel32
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0//libgcc_s.dll.a when     searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/libgcc_s.dll.a when     searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0//libgcc_s.dll.a when     searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/libgcc_s.dll.a when     searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     cannot find -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0//libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0//libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0//libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/6.4.0/libgcc.a when     searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/6.4.0/../../../../x86_64-pc-cygwin/bin/ld:     cannot find -lgcc
collect2: error: ld returned 1 exit status

Thanks.


问:
Return data filtered on ngOnInit
In my component.ts I have a function that returns data from a service, and saves it to myPosts object. The function is called getData();
What I want to do is filter getData initially by date before calling it on ngOnInit().

So initially my table would display all last months' posts.
And then I should be able to change the date on another function and filter for different ranges.

My filtering functions are on the controller.
How do I call the filter Function after I get the data, so that initially that data is filtered on ngOnInit ?

```<code>public getData() {
this.postsService.getAllPosts().subscribe(results => {
  this.myPosts= results['data'];
});
}

filterByDate(){
  const monthAgo= moment().subtract(1, 'month');
   this.myPosts= this.myPosts.filter(item => moment(item.SubmittedDate).isAfter(monthAgo));
}
</code>```

答:
Call the getData() method in the constructor and then use the filter function filterByDate() in ngOnInIt

```<code>export class SomeClass implements OnInIt {
      public getData() {
        this.postsService.getAllPosts().subscribe(results => {
          this.myPosts = this.filterByDate(results['data']);
        });
      }
      public filterByDate(myPosts){
          const monthAgo = moment().subtract(1, 'month');
          return myPosts.filter(item =>
          moment(item.SubmittedDate).isAfter(monthAgo));
        }
      constructor() {
        this.posts = this.getData();
      }
      ngOnInIt() {
        this.filterPosts = this.filterByDate(posts);
      }
    }
</code>```

Title: Return data filtered on ngOnInit

Body:
In my component.ts I have a function that returns data from a service, and saves it to myPosts object. The function is called getData();
What I want to do is filter getData initially by date before calling it on ngOnInit().

So initially my table would display all last months' posts.
And then I should be able to change the date on another function and filter for different ranges.

My filtering functions are on the controller.
How do I call the filter Function after I get the data, so that initially that data is filtered on ngOnInit ?

public getData() {
this.postsService.getAllPosts().subscribe(results => {
  this.myPosts= results['data'];
});
}

filterByDate(){
  const monthAgo= moment().subtract(1, 'month');
   this.myPosts= this.myPosts.filter(item => moment(item.SubmittedDate).isAfter(monthAgo));
}

Body:
Call the getData() method in the constructor and then use the filter function filterByDate() in ngOnInIt

export class SomeClass implements OnInIt {
      public getData() {
        this.postsService.getAllPosts().subscribe(results => {
          this.myPosts = this.filterByDate(results['data']);
        });
      }
      public filterByDate(myPosts){
          const monthAgo = moment().subtract(1, 'month');
          return myPosts.filter(item =>
          moment(item.SubmittedDate).isAfter(monthAgo));
        }
      constructor() {
        this.posts = this.getData();
      }
      ngOnInIt() {
        this.filterPosts = this.filterByDate(posts);
      }
    }


问:
Appveyoyr fails to build ASP.NET Core WebApi Project
I keep on getting this error:

error MSB4041: The default XML namespace of the project must be the
  MSBuild XML namespace. If the project is authored in the MSBuild 2003
  format, please add
  xmlns="http://schemas.microsoft.com/developer/msbuild/2003" to the
   element. If the project has been authored in the old 1.0 or
  1.2 format, please convert it to MSBuild 2003 format.

My project is set up in Rider, it compiles smoothly localy. I guess it might me something with the MSBuild version.

My appveyor.yml looks like this:

```<code>version: 1.0.{build}
image: Visual Studio 2017
configuration: Release
platform: Any CPU
before_build:
- cmd: set ASPNETCORE_ENVIRONMENT=Production
build:
  project: BoatInspectorWebApi.sln
  verbosity: detailed
</code>```

Can't really think of what's going on.

Has anyone experienced similar issues?

UPDATE (detailed log and exported yml)]
I exported the yml to check myself for errors and did a detailed log and the part with the error printed looks like this

Building with tools version "12.0".
C:\projects\boatinspectorwebapi\BoatInspectorWebApi\BoatInspectorWebApi.csproj(1,1): error MSB4041: The default XML namespace of the project must be the MSBuild XML namespace. If the project is authored in the MSBuild 2003 format, please add xmlns="http://schemas.microsoft.com/developer/msbuild/2003" to the  element. If the project has been authored in the old 1.0 or 1.2 format, please convert it to MSBuild 2003 format.
Done Building Project "C:\projects\boatinspectorwebapi\BoatInspectorWebApi\BoatInspectorWebApi.csproj" (default targets) -- FAILED.

Well it looks like Appveyor is using MsBuild 12 and that is causing a problem. I am using 15 or 14 localy and everything builds fine. Not sure whether its 14 or 15 cause they are both installed. Anyway, does anyone know if it is possible to build with 15 in Appveyor?

答: Please add image: Visual Studio 2017 to your appveyor.yml

Body:
I keep on getting this error:

error MSB4041: The default XML namespace of the project must be the
  MSBuild XML namespace. If the project is authored in the MSBuild 2003
  format, please add
  xmlns="http://schemas.microsoft.com/developer/msbuild/2003" to the
   element. If the project has been authored in the old 1.0 or
  1.2 format, please convert it to MSBuild 2003 format.

My project is set up in Rider, it compiles smoothly localy. I guess it might me something with the MSBuild version.

My appveyor.yml looks like this:

version: 1.0.{build}
image: Visual Studio 2017
configuration: Release
platform: Any CPU
before_build:
- cmd: set ASPNETCORE_ENVIRONMENT=Production
build:
  project: BoatInspectorWebApi.sln
  verbosity: detailed

Can't really think of what's going on.

Has anyone experienced similar issues?

UPDATE (detailed log and exported yml)]
I exported the yml to check myself for errors and did a detailed log and the part with the error printed looks like this

Building with tools version "12.0".
C:\projects\boatinspectorwebapi\BoatInspectorWebApi\BoatInspectorWebApi.csproj(1,1): error MSB4041: The default XML namespace of the project must be the MSBuild XML namespace. If the project is authored in the MSBuild 2003 format, please add xmlns="http://schemas.microsoft.com/developer/msbuild/2003" to the  element. If the project has been authored in the old 1.0 or 1.2 format, please convert it to MSBuild 2003 format.
Done Building Project "C:\projects\boatinspectorwebapi\BoatInspectorWebApi\BoatInspectorWebApi.csproj" (default targets) -- FAILED.

Well it looks like Appveyor is using MsBuild 12 and that is causing a problem. I am using 15 or 14 localy and everything builds fine. Not sure whether its 14 or 15 cause they are both installed. Anyway, does anyone know if it is possible to build with 15 in Appveyor?


问:
Suggestions for Python debugging tools?
Yesterday I made a simulation using Python. I had a few difficulties with variables and debugging.

Is there any software for Python, which provides a decent debugger?

Related question: What is the best way to debug my Python code?

答:
I'd recommend pydb and ipython for interactive debugging.

Both have screencasts available at showmedo.com

Introduction to pydb

The showmedo series on IPython

OwnerDisplayName: Masi

Title: Suggestions for Python debugging tools?

LastEditorDisplayName: J.F. Sebastian

OwnerDisplayName: Ryan

LastEditorDisplayName: Ryan


问:
Binary to Integer -> Erlang
I have a binary M such that 34= will always be present and the rest may vary between any number of digits but will always be an integer.

```<code>M = [<<"34=21">>]
</code>```

When I run this command I get an answer like

```<code>hd([X || <<"34=", X/binary >> <- M])

Answer -> <<"21">>
</code>```

How can I get this to be an integer with the most care taken to make it as efficient as possible?

答:
```<code>[<<"34=",X/binary>>] = M,
list_to_integer(binary_to_list(X)).
</code>```

That yields the integer 21

Title: Binary to Integer -> Erlang

Body:
I have a binary M such that 34= will always be present and the rest may vary between any number of digits but will always be an integer.

M = [<<"34=21">>]

When I run this command I get an answer like

hd([X || <<"34=", X/binary >> <- M])

Answer -> <<"21">>

How can I get this to be an integer with the most care taken to make it as efficient as possible?

Body:
[<<"34=",X/binary>>] = M,
list_to_integer(binary_to_list(X)).

That yields the integer 21


问:
Adding a whole number and a decimal in Javascript results in removal of the decimal?
I'm sure this is simple, but in my javascript code, I have two numbers. One contains a decimal, and the other doesn't, and I add them together (ie. 7.5 + 5), I am getting a result with NO decimal value.

Do I need to cast each number variable as a double? I know that all numbers are doubles in javascript - which is why I do not understand this behavior...

For instance, I have var answer = week1 + week2;. Does this make sense?

Thanks in advance!

答:
I am sorry for wasting time - turns out I was using parseInt instead of parseFloat to gather the "week" values I spoke about.

Can someone please close this question or delete it? Before the shame consumes me?


问:
Can std::vector or some other dynamic container which allows iterating reside partially in RAM and swap (Linux)?
I have a text processing application which uses std::vector in its code to store huge arrays, tables, etc. When I do mining of huge texts, the application crashes when meets a rim of RAM, without entering swap.

Unfortunately, crash message is not informative, it's just segfault. There are a lot of possibilities to investigate with debugger of course, but regardless of this situation, I became curious about one thing which caught my attention in the explanation of how std::vector works:

whenever you declare a vector object, it reserves some contiguous
  space in memory.  And if during an insertion, its exceeds that
  capacity, it will create new space with a buffer in memory, copy the
  data from the vector, insert the new data, and destroy older memory.

If your program is going to do lot of insertion and deletion, use
  std::list.

Could it be, that when application (and I am interested in std::vector in particular) requests creating a contiguous object which exceeds RAM size and even though there is a place in the swap, it throws error?

Can I operate a dynamic array which resides in both RAM and swap with std::list or some other container?

Thanks everyone and sorry for the noob question! That's not my program and I was just trying to make it working, and that idea of made me curious. So looks like it's just a coincidence that it crashes when approaches the size of RAM which is equal to mine.

答:
Swap is transparent to program operation. Whenever your program is actually using a particular page of memory it will be brought into main memory  but at any other time the OS is free to move it to swap and your program will simply remain unaware of that fact.

A segfault indicates that you are trying to access an invalid address (either for reading or writing).


问:
Paho mqtt callbacks on multiple subscription
I have subscribed to multiple (around 4) topics using paho.mqtt.

On receiving message from each topic, I want to buffer the message until it reaches some threshold and then later insert bulk messages into MySQL database.I want to gather some 1000 messages and check if the threshold is greater than 1000 and then finally insert into database on certain time interval (for every 1 minute).

For each topic, there is corresponding table in the database. Which callback function Should I use on_message() callback or message_callback_add()? Which is better in such scenario?

答:
What does "is better" mean for you?

The callback registered with on_message() will get all messages for all your subscriptions, whereas with message_callback_add you can have different callbacks for each topic that you subscribe to.

Do you need your callbacks to do different things based on the topic name? If not, you use on_message, else you use message_callback_add.


问:
React Native App Crash in Production
I recently pushed an update to our React Native app. Everything was running fine, however during the review, Apple rejected the update because the app crashed on boot. I created an Ad-Hoc build and installed the release version on my own device and saw the same behavior. If I run the app in dev mode via XCode, everything works fine.

To create the release build of the app, I would simply archive it on XCode and upload to the app store.

I symbolicated the crash report sent from Apple. Here are the meaningful lines the report:

```<code>Last Exception Backtrace:
0   CoreFoundation                  0x1812a6364 0x181160000 + 1336164
1   libobjc.A.dylib                 0x1804ec528 0x1804e4000 + 34088
2   CoreFoundation                  0x1812a62ac 0x181160000 + 1335980
3   MyApp                           0x1047c2c24 RCTFatal + 1354788 (RCTAssert.m:134)
4   MyApp                           0x1047c08e8 -[RCTExceptionsManager reportFatalException:stack:exceptionId:] + 1345768 (RCTExceptionsManager.m:60)
5   CoreFoundation                  0x1812adcd0 0x181160000 + 1367248
6   CoreFoundation                  0x18118c56c 0x181160000 + 181612
7   CoreFoundation                  0x18119101c 0x181160000 + 200732
8   MyApp                           0x1047d3d9c -[RCTModuleMethod invokeWithBridge:module:arguments:] + 1424796 (RCTModuleMethod.mm:537)
9   MyApp                           0x104813abc facebook::react::invokeInner(RCTBridge*, RCTModuleData*, unsigned int, folly::dynamic const&) + 1686204 (RCTNativeModule.mm:101)
10  MyApp                           0x10481381c invocation function for block in facebook::react::RCTNativeModule::invoke(unsigned int, folly::dynamic&&, int) + 1685532 (RCTNativeModule.mm:73)
11  libdispatch.dylib               0x180c22a54 0x180c21000 + 6740
12  libdispatch.dylib               0x180c22a14 0x180c21000 + 6676
13  libdispatch.dylib               0x180c2c96c 0x180c21000 + 47468
14  libdispatch.dylib               0x180c2d2fc 0x180c21000 + 49916
15  libdispatch.dylib               0x180c2dd20 0x180c21000 + 52512
16  libdispatch.dylib               0x180c3603c 0x180c21000 + 86076
17  libsystem_pthread.dylib         0x180ecaf1c 0x180eca000 + 3868
18  libsystem_pthread.dylib         0x180ecab6c 0x180eca000 + 2924
</code>```

I don't see much meaning information from this report other than a crash occurred. Am I overlooking something obvious?

Any tips/suggestions are greatly appreciated.

答:
Apple will test your application on an iPad, even if your app is build to run on iPhone only.

Maybe you could check if you can reproduce the crash when running it on iPad ?

Title: React Native App Crash in Production

Body:
I recently pushed an update to our React Native app. Everything was running fine, however during the review, Apple rejected the update because the app crashed on boot. I created an Ad-Hoc build and installed the release version on my own device and saw the same behavior. If I run the app in dev mode via XCode, everything works fine.

To create the release build of the app, I would simply archive it on XCode and upload to the app store.

I symbolicated the crash report sent from Apple. Here are the meaningful lines the report:

Last Exception Backtrace:
0   CoreFoundation                  0x1812a6364 0x181160000 + 1336164
1   libobjc.A.dylib                 0x1804ec528 0x1804e4000 + 34088
2   CoreFoundation                  0x1812a62ac 0x181160000 + 1335980
3   MyApp                           0x1047c2c24 RCTFatal + 1354788 (RCTAssert.m:134)
4   MyApp                           0x1047c08e8 -[RCTExceptionsManager reportFatalException:stack:exceptionId:] + 1345768 (RCTExceptionsManager.m:60)
5   CoreFoundation                  0x1812adcd0 0x181160000 + 1367248
6   CoreFoundation                  0x18118c56c 0x181160000 + 181612
7   CoreFoundation                  0x18119101c 0x181160000 + 200732
8   MyApp                           0x1047d3d9c -[RCTModuleMethod invokeWithBridge:module:arguments:] + 1424796 (RCTModuleMethod.mm:537)
9   MyApp                           0x104813abc facebook::react::invokeInner(RCTBridge*, RCTModuleData*, unsigned int, folly::dynamic const&) + 1686204 (RCTNativeModule.mm:101)
10  MyApp                           0x10481381c invocation function for block in facebook::react::RCTNativeModule::invoke(unsigned int, folly::dynamic&&, int) + 1685532 (RCTNativeModule.mm:73)
11  libdispatch.dylib               0x180c22a54 0x180c21000 + 6740
12  libdispatch.dylib               0x180c22a14 0x180c21000 + 6676
13  libdispatch.dylib               0x180c2c96c 0x180c21000 + 47468
14  libdispatch.dylib               0x180c2d2fc 0x180c21000 + 49916
15  libdispatch.dylib               0x180c2dd20 0x180c21000 + 52512
16  libdispatch.dylib               0x180c3603c 0x180c21000 + 86076
17  libsystem_pthread.dylib         0x180ecaf1c 0x180eca000 + 3868
18  libsystem_pthread.dylib         0x180ecab6c 0x180eca000 + 2924

I don't see much meaning information from this report other than a crash occurred. Am I overlooking something obvious?

Any tips/suggestions are greatly appreciated.


问:
How to check if a radio button in each group is checked in jQuery?
Multiple groups or radio buttons

```<code><h1>Question 1</h1>
<input type="radio" name="radio1" value="false" />
<input type="radio" name="radio1" value="true" />

<h1>Question 2</h1>
<input type="radio" name="radio2" value="false" />
<input type="radio" name="radio2" value="true" />
</code>```

How can I check in jQuery that a radio button in each group is checked?

Thank you.

答:
I upvoted the answer by "GG."  However, you don't need to change the
HTML.

Just select by [name] (which should be unique):

```<code>if ($("input[name='radio1']:checked")[0] != undefined &&
    $("input[name='radio2']:checked")[0] != undefined) {
  ...
}
</code>```

Body:
Multiple groups or radio buttons

Question 1

<input type="radio" name="radio1" value="false" />
<input type="radio" name="radio1" value="true" />

Question 2

<input type="radio" name="radio2" value="false" />
<input type="radio" name="radio2" value="true" />

How can I check in jQuery that a radio button in each group is checked?

Thank you.

Body:
I upvoted the answer by "GG."  However, you don't need to change the
HTML.

Just select by [name] (which should be unique):

if ($("input[name='radio1']:checked")[0] != undefined &&
    $("input[name='radio2']:checked")[0] != undefined) {
  ...
}


问:
How to populate reference field in virtual method in Mongoose?
I have following schema.

```<code>var ItemSchema = new Schema({
name : String
,location: {
    address: { type: String, default:''},
    geolocation: {longitude: Number, latitude:Number},
    place : {type: Schema.Types.ObjectId, ref:'Place'}
},
ranking_in_place : Number })
</code>```

Place is a reference to Place schema which has name, city, country etc. fields.

I want to create a virtual for ranking_summary:

```<code>ItemSchema.virtual('ranking_summary').get(function() {
    if(this.ranking_in_place <= 5){
        if(this.ranking_in_place == 1){
            return "Most popular item" + " in " + this.location.place.name
        }
    }
})
</code>```

I cannot get this.location.place.name value because this.location.place is a reference, and not populated. How can I access this value?

答:
I think there is no direct method for doing this. One way you can achieve this is by following the hooks. [Read More]

Here is a sample code. I had a need to calculate the totalTime of tutorial which is made up of videos. So, I had to populate videos and then use their duration to calculate totalTime for a tutorial.

```<code>tutorialSchema.pre('findOne', function (next) {
    this.populate('videos');  // now available as this.ratings in this schema
    next();
});

tutorialSchema.virtual('totalTime').get(function () {
    let times = [];
    times = this.videos.map((v) => {
        return v.duration;
    });
    if(times.length === 0) return 0;
    let totalTime = times.reduce((sum, time) => {
        return sum + time;
    });
    return totalTime;
});
</code>```

Body:
I have following schema.

var ItemSchema = new Schema({
name : String
,location: {
    address: { type: String, default:''},
    geolocation: {longitude: Number, latitude:Number},
    place : {type: Schema.Types.ObjectId, ref:'Place'}
},
ranking_in_place : Number })

Place is a reference to Place schema which has name, city, country etc. fields.

I want to create a virtual for ranking_summary:

ItemSchema.virtual('ranking_summary').get(function() {
    if(this.ranking_in_place <= 5){
        if(this.ranking_in_place == 1){
            return "Most popular item" + " in " + this.location.place.name
        }
    }
})

I cannot get this.location.place.name value because this.location.place is a reference, and not populated. How can I access this value?

Body:
I think there is no direct method for doing this. One way you can achieve this is by following the hooks. [Read More]

Here is a sample code. I had a need to calculate the totalTime of tutorial which is made up of videos. So, I had to populate videos and then use their duration to calculate totalTime for a tutorial.

tutorialSchema.pre('findOne', function (next) {
    this.populate('videos');  // now available as this.ratings in this schema
    next();
});

tutorialSchema.virtual('totalTime').get(function () {
    let times = [];
    times = this.videos.map((v) => {
        return v.duration;
    });
    if(times.length === 0) return 0;
    let totalTime = times.reduce((sum, time) => {
        return sum + time;
    });
    return totalTime;
});


问:
Properly structuring a couchDB app
Use Case

I want to serve multiple customers from 1 couchdb

Each customer will have their own set of data (and a subset of child data - head office as the parent and each location as the
children)

Each customer could have different UI screens

Within each customer different users may have different UI screens

The system will be a couchapp and distributed globally and will use replication

The Options

For each customer store all pages in one _design document and serve the appropriate pages based on user type (permission)

For each customer store each page into it's own _design document

For each customer, store all pages associated with the user permission level in one _design document so that each user type will be served from a different _design document

Also, I've read two books now on couchDB and it's still not clear the advantages of using a _design document as opposed to a normal document to serve the web pages.

UPDATE 1:

I think I will need to give a clearer example.

Company A has a head office in Bangkok with management and administrative (secretaries) staff using the app.  These users will belong to different user groups and have different permissions which will provide them access to different HMTL documents (or the same template doc but serving different content via js).  This company has offices in Pattaya, Phuket and Chang Mai.  At each of these offices they have different user types who will have access to different parts of the app and see different versions of HTML screens.  The local apps will be based on filtered replication.

This couchDB will provide this service to multiple companies structured just like Company A, all from the same db (reason being that we need to be able to aggregate data for all companies and couchDB cannot aggregate across multiple databases since views are db specific if I read correctly.)  However, each master Company could have slight differences to their HTML pages from other master Companies.

So focusing on structure only, my initial idea is to do multiple _design documents, one for each master Company.  In each of these _design documents we store each and every HTML page for that company (which may or may not be the same as other master companies.

Is there a better way to structure this?
Do you see scaling issues when we have say 1000 master companies?

P.S. Even if we can't complete solve ACL issues directly via couchDB we can always do it ourselves so this isn't a primary concern right now.

UPDATE 2:

So after more research I see how the show functions (shows) play a role in this by using templates.  It doesn't fully answer my question,  so I guess, based on this, I am also wondering now if there is ever a situation where you might want to have any other HTML attachement in the _design document other than index.html?

答:
There are two basic solutions for the situation of multiple users, each can see only a subset of the total data.

Use a middle web tier. This is like any other MySQL/PHP or Rails architecture. CouchDB is a data back-end. You have your own user logins and management and do everything yourself.

Use the CouchDB security model. It requires some learning but, hey, you aren't writing your own user and authentication code yourself. To have different data sets for different user, each user has their own database and you replicate (using a filter) only the documents the user can see.

Title: Properly structuring a couchDB app


问:
How to create a fixed and detached menu in jquery
Good morning everyone,

I am working on a menu and would like it to behave a certain way.

When I scroll down, the "TOP" section moves up (this is already working)

I would like the "MY MENU" section to be hidden initially and only appear when   the "TOP" section disappears up when scroll.

and example of what I am trying to achieve can be seen at https://flipkart.com? (on mobile vue)

here is a working fiddle:
https://jsfiddle.net/gad123/j695to5b/1/ (solved)

```<code><div class="container">
<div class="row">

<div class="span">
<div class="wll">
<h3>TOP</h3>
</div>

</div>

</div>
</div>
<div id="nav-wrapper">

<div id="na">
<div id="nav" class="navbar">
<div class="navbar-inner">
<div class="container">
<div class="span12"  style="background:#888;
padding:1em 0 1em 0;">

<span class="navbar-text">
My menu
</span>
</div>
</div>
div>
</div>
</div>

</div>
<div class="container">
<div class="span3">
<h2>some lorem ipsum for scrolling:</h2>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy
eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam
voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet
clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit
amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam
nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed
diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet
clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit
amet.
<div id="detach"><b>test</b></div>

</div>
</div>
</code>```

jquery:

```<code>$('#nav-wrapper').height($("#nav").height());
$('#nav').affix({
offset: $('#nav').position()
});
$('#nav').detached({
offset: $('#detach').position()
});
</code>```

css:

```<code>#nav.affix {
position: fixed;
top: 0;
width: 100%

}

h3{color:red;}
.top{
background:#999;
width: 100%
}

#nav.detached {
position:static;
top:0;
}

#nav > .navbar-inner {
border-left: 0;
border-right: 0;
border-radius: 0;
-webkit-border-radius: 0;
-moz-border-radius: 0;
-o-border-radius: 0;
}

h3{
color:orange
}

.wll{
padding:1em 0 1em 0;
background:#444;
}
</code>```

答:
```<code>$('#nav-wrapper').height($("#nav").height());

if($(".top").height()> $(document).scrollTop()){
    $("#nav").css({"display": "none"});
}

$(document).scroll(function(){
    if($(".top").height()< $(document).scrollTop()){
        $("#nav").css({"display": "block"});
    }
    else{
        $("#nav").css({"display": "none"});
    }
});

$('#nav').affix({
    offset: $('#nav').position()
});

$('#nav').detached({
    offset: $('#detach').position()
});
</code>```

<p>You can compare the actual scroll height with the height of '.top' </p>

Body:
Good morning everyone,

I am working on a menu and would like it to behave a certain way.

When I scroll down, the "TOP" section moves up (this is already working)

I would like the "MY MENU" section to be hidden initially and only appear when   the "TOP" section disappears up when scroll.

and example of what I am trying to achieve can be seen at https://flipkart.com? (on mobile vue)

here is a working fiddle:
https://jsfiddle.net/gad123/j695to5b/1/ (solved)

TOP

My menu

div>

some lorem ipsum for scrolling:

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy
eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam
voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet
clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit
amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam
nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed
diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet
clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit
amet.

test

jquery:

$('#nav-wrapper').height($("#nav").height());
$('#nav').affix({
offset: $('#nav').position()
});
$('#nav').detached({
offset: $('#detach').position()
});

css:

#nav.affix {
position: fixed;
top: 0;
width: 100%

}

h3{color:red;}
.top{
background:#999;
width: 100%
}

#nav.detached {
position:static;
top:0;
}

#nav > .navbar-inner {
border-left: 0;
border-right: 0;
border-radius: 0;
-webkit-border-radius: 0;
-moz-border-radius: 0;
-o-border-radius: 0;
}

h3{
color:orange
}

.wll{
padding:1em 0 1em 0;
background:#444;
}

Body:
$('#nav-wrapper').height($("#nav").height());

if($(".top").height()> $(document).scrollTop()){
    $("#nav").css({"display": "none"});
}

$(document).scroll(function(){
    if($(".top").height()< $(document).scrollTop()){
        $("#nav").css({"display": "block"});
    }
    else{
        $("#nav").css({"display": "none"});
    }
});

$('#nav').affix({
    offset: $('#nav').position()
});

$('#nav').detached({
    offset: $('#detach').position()
});

You can compare the actual scroll height with the height of '.top'


问:
Mapping classes c#
I am writing a tranformer that takes some input and gives an output.I need to call a specific tranformer based on my input type.

```<code>public static myentrypoint( template t);
{
   //I could do something like this.
   switch(t)
   {
        case t1:
         transformt1(..);
        case t2:
         transformt1(..);
         ....
   }
}

Trasform1 : Itransform
{
    tranform1(...);
}

Trasform2 : Itransform
{
    tranform2(...);
}
</code>```

I need to map which function to call based on what my template is. I can do a switch but are there more cleaner ways to do this using some design patterns ? I was thinking a of writing a static dictionary. I am new to OOP so any suggestions would be great.

答:
If template is a class, and each template potentially has a different transform, then why not just include the transform function inside of your template class?</p>

```<code>public static myentrypoint( ITemplate t);
{
   t.transform();
}
</code>```

Title: Mapping classes c#

Body:
I am writing a tranformer that takes some input and gives an output.I need to call a specific tranformer based on my input type.

public static myentrypoint( template t);
{
   //I could do something like this.
   switch(t)
   {
        case t1:
         transformt1(..);
        case t2:
         transformt1(..);
         ....
   }
}

Trasform1 : Itransform
{
    tranform1(...);
}

Trasform2 : Itransform
{
    tranform2(...);
}

I need to map which function to call based on what my template is. I can do a switch but are there more cleaner ways to do this using some design patterns ? I was thinking a of writing a static dictionary. I am new to OOP so any suggestions would be great.

Body:
If template is a class, and each template potentially has a different transform, then why not just include the transform function inside of your template class?

public static myentrypoint( ITemplate t);
{
   t.transform();
}


问:
how to show closest div on hover?
i want to hover over a child element for it to show the NEAREST footer div on tumblr.

```<code><div class="entry">
{block:Posts}
<div class="container">
{block:Text}{/block:Text}
{block:Photo}{/block:Photo}
{block:Text}{/block:Text}
</div>
<div class="footer"></div>
{/block:Posts}
</div>
</code>```

the footer class is to be hidden but i want it so that when i hover over any one of the post type, only the footer of that post shows.

example :

i hover over my text post about something, it'll show the footer of THAT post specifically!

any help would be appreciated!

edit : i think my circumstances weren't properly explained so i updated!

答:
You really do not need JavaScript when a simple CSS hover and next sibling selector can show it.

.two {
   display: none;
}

.one:hover + .two {
  display: block;
}

/* If you want it to stay open if you are on the other div*/
.two:hover {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="one">hi</div>
<div class="two">this</div>

<div class="one">is</div>
<div class="two">an</div>

<div class="one">example</div>
<div class="two">code</div></code>```

Title: how to show closest div on hover?

Body:
i want to hover over a child element for it to show the NEAREST footer div on tumblr.

{block:Posts}

{block:Text}{/block:Text}
{block:Photo}{/block:Photo}
{block:Text}{/block:Text}

{/block:Posts}

the footer class is to be hidden but i want it so that when i hover over any one of the post type, only the footer of that post shows.

example :

i hover over my text post about something, it'll show the footer of THAT post specifically!

any help would be appreciated!

edit : i think my circumstances weren't properly explained so i updated!

Body:
You really do not need JavaScript when a simple CSS hover and next sibling selector can show it.

.two {
   display: none;
}

.one:hover + .two {
  display: block;
}

/* If you want it to stay open if you are on the other div*/
.two:hover {
  display: block;
}

<div class="one">hi</div>
<div class="two">this</div>

<div class="one">is</div>
<div class="two">an</div>

<div class="one">example</div>
<div class="two">code</div>