问:
webrtc with firebase :how to fix black screen on ios/safari
I work on video calling in my web app. I tried [https://github.com/webrtc/FirebaseRTC/tree/solution][1]
example which on https://webrtc.org/getting-started/firebase-rtc-codelab here.

It works in these browsers:

desktop/chrome----->desktop/chrome

desktop/chrome----->desktop/firefox

desktop/firefox----->desktop/firefox

but not Safari I can see just a black screen. It doesn't work.

desktop/chrome---->ios/safari

ios/safari---->ios/safari

actually I see black screen but I think safari get mediastream but cant show.

I have this code in codelab:

```<code> peerConnection.addEventListener('track', event => {//other pc track
      console.log('Got remote track:', event.streams[0]);
       event.streams[0].getTracks().forEach(track => {
        console.log('Add a track to the remoteStream:', track);
        remoteStream.addTrack(track);
      });
    });
</code>```

How can I fix this problem?

答:
I solved problem it work on safari I can get videStream now.
I changed this code in codelab

```<code> peerConnection.addEventListener('track', event => {//other pc track
      console.log('Got remote track:', event.streams[0]);
       event.streams[0].getTracks().forEach(track => {
        console.log('Add a track to the remoteStream:', track);
        remoteStream.addTrack(track);
      });
    });
</code>```

to

```<code>peerConnection.addEventListener('track', event => {//other pc track
      console.log('Got remote track:', event.streams[0]);

        document.querySelector('#remoteVideo').srcObject = event.streams[0];
        console.log(event.streams[0]);
        remoteStream = event.streams[0];

    });
</code>```

I think safari don't support remoteStream.addTrack(track);(remoteStream is a MediaStream obj) I searched about this issue can t find anything.

Body:
I work on video calling in my web app. I tried [https://github.com/webrtc/FirebaseRTC/tree/solution][1]
example which on https://webrtc.org/getting-started/firebase-rtc-codelab here.

It works in these browsers:

desktop/chrome----->desktop/chrome

desktop/chrome----->desktop/firefox

desktop/firefox----->desktop/firefox

but not Safari I can see just a black screen. It doesn't work.

desktop/chrome---->ios/safari

ios/safari---->ios/safari

actually I see black screen but I think safari get mediastream but cant show.

I have this code in codelab:

 peerConnection.addEventListener('track', event => {//other pc track
      console.log('Got remote track:', event.streams[0]);
       event.streams[0].getTracks().forEach(track => {
        console.log('Add a track to the remoteStream:', track);
        remoteStream.addTrack(track);
      });
    });

How can I fix this problem?

Body:
I solved problem it work on safari I can get videStream now.
I changed this code in codelab

 peerConnection.addEventListener('track', event => {//other pc track
      console.log('Got remote track:', event.streams[0]);
       event.streams[0].getTracks().forEach(track => {
        console.log('Add a track to the remoteStream:', track);
        remoteStream.addTrack(track);
      });
    });

to

peerConnection.addEventListener('track', event => {//other pc track
      console.log('Got remote track:', event.streams[0]);

        document.querySelector('#remoteVideo').srcObject = event.streams[0];
        console.log(event.streams[0]);
        remoteStream = event.streams[0];

    });

I think safari don't support remoteStream.addTrack(track);(remoteStream is a MediaStream obj) I searched about this issue can t find anything.


来源: stackexchange

问:
How to ignore/handle Line Feed (0A) while using fread?
I'm currently trying to write a function that will translate each byte of input data into a define constant byte (assembly instruction).

```<code>void toASM(FILE *inputFile, FILE *outputFile) {
    char buffer[16 + sizeof(char)] = "";
    int bytes = 0;
    while ((bytes = fread(buffer, sizeof(char), 16, inputFile))) {   // start reading block of data from stream
        for (int i = 0; i < bytes; i++) {
            if (i == bytes - 1) {
                if((buffer[i] != '\r') && (buffer[i] != '\n')) {
                    fprintf(outputFile, "$%.2X\n", buffer[i]);
                } else {
                    printf("\n");
                }
            } else {
                fprintf(outputFile, "$%.2X,", buffer[i]);
            }
        }
    }
}
</code>```

This function is working correctly the only issue I can't seem to solve is that at the end it will produce a '$0A' which I assume is a Line Feed or maybe a New Line.

My best guess is that my while loop is reading the last line of the input which in result returns '$0A'

Current Output for ABCDEFGHIJKLMNOPQRSTUVWXYZ

```<code>$41,$42,$43,$44,$45,$46,$47,$48,$49,$4A,$4B,$4C,$4D,$4E,$4F,$50
$51,$52,$53,$54,$55,$56,$57,$58,$59,$5A,
</code>```

Output without the check for the Line Feed or New Line

```<code>$41, $42, $43, $44, $45, $46, $47, $48, $49, $4A, $4B, $4C, $4D, $4E, $4F, $50
$51, $52, $53, $54, $55, $56, $57, $58, $59, $5A, $0A
</code>```

My desired Output

```<code>$41, $42, $43, $44, $45, $46, $47, $48, $49, $4A, $4B, $4C, $4D, $4E, $4F, $50
$51, $52, $53, $54, $55, $56, $57, $58, $59, $5A
</code>```

The current issues is the extra ',' but the bigger issue is that if the input file contains multiple lines of data the ASM output will contain random new lines. This is due to my else statement doing the printf("\n");

So I'm wondering if there is a better alternative to do this?

答:
This code shows the technique I usually use.  It considers the comma-space as a prefix to items except the first; the first has an empty string as the prefix (or leading indentation if you want the data indented, or a label, or …).

```<code>#include <stdio.h>

static inline int iseol(unsigned char c) { return (c == '\n' || c == '\r'); }

static
void toASM(FILE *inputFile, FILE *outputFile)
{
    unsigned char buffer[16];
    int bytes;
    while ((bytes = fread(buffer, sizeof(buffer[0]), sizeof(buffer), inputFile)) > 0)
    {
        const char *pad = "";
        for (int i = 0; i < bytes; i++)
        {
            if (!iseol(buffer[i]))
            {
                fprintf(outputFile, "%s$%.2X", pad, buffer[i]);
                pad = ", ";
            }
            else if (pad[0] != '\0')
            {
                printf("\n");
                pad = "";
            }
        }
        if (pad[0] != '\0')
            putchar('\n');
    }
}

int main(void)
{
    toASM(stdin, stdout);
    return 0;
}
</code>```

The iseol() function is probably overkill; using the original test was OK.  Formally, it is a reserved identifier — using is_eol() would be safe, as would isEOL().

The program source was asm67.c, compiled to program asm67.
I test with an input file input with contents:

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZ
</code>```

The simplest test case yields:

```<code>$ asm67 < input
$41, $42, $43, $44, $45, $46, $47, $48, $49, $4A, $4B, $4C, $4D, $4E, $4F, $50
$51, $52, $53, $54, $55, $56, $57, $58, $59, $5A
$
</code>```

That looks like what you requested.  The following shows the output from 4 lines of input each containing the alphabet plus a newline.  If that's not what you want, you should specify the desired output for such cases in the question.  The futzing required to get the desired output is probably not very complex.

```<code>$ cat input input input input | asm67
$41, $42, $43, $44, $45, $46, $47, $48, $49, $4A, $4B, $4C, $4D, $4E, $4F, $50
$51, $52, $53, $54, $55, $56, $57, $58, $59, $5A
$41, $42, $43, $44, $45
$46, $47, $48, $49, $4A, $4B, $4C, $4D, $4E, $4F, $50, $51, $52, $53, $54, $55
$56, $57, $58, $59, $5A
$41, $42, $43, $44, $45, $46, $47, $48, $49, $4A
$4B, $4C, $4D, $4E, $4F, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $5A
$41, $42, $43, $44, $45, $46, $47, $48, $49, $4A, $4B, $4C, $4D, $4E, $4F
$50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $5A
$
</code>```

Note that with the 4 lines of input, one of the 16-byte blocks starts with a newline character; the code's logic with if (pad[0] != '\0') prevents that leaving a blank line in the output.

Providing a function that takes an input file stream and an output file stream is a good idea.  And the test program shows how simple it becomes to make use of standard input and standard output for testing.

ContentLicense: CC BY-SA 4.0

Body:
I'm currently trying to write a function that will translate each byte of input data into a define constant byte (assembly instruction).

void toASM(FILE *inputFile, FILE *outputFile) {
    char buffer[16 + sizeof(char)] = "";
    int bytes = 0;
    while ((bytes = fread(buffer, sizeof(char), 16, inputFile))) {   // start reading block of data from stream
        for (int i = 0; i < bytes; i++) {
            if (i == bytes - 1) {
                if((buffer[i] != '\r') && (buffer[i] != '\n')) {
                    fprintf(outputFile, "$%.2X\n", buffer[i]);
                } else {
                    printf("\n");
                }
            } else {
                fprintf(outputFile, "$%.2X,", buffer[i]);
            }
        }
    }
}

This function is working correctly the only issue I can't seem to solve is that at the end it will produce a '$0A' which I assume is a Line Feed or maybe a New Line.

My best guess is that my while loop is reading the last line of the input which in result returns '$0A'

Current Output for ABCDEFGHIJKLMNOPQRSTUVWXYZ

$41,$42,$43,$44,$45,$46,$47,$48,$49,$4A,$4B,$4C,$4D,$4E,$4F,$50
$51,$52,$53,$54,$55,$56,$57,$58,$59,$5A,

Output without the check for the Line Feed or New Line

$41, $42, $43, $44, $45, $46, $47, $48, $49, $4A, $4B, $4C, $4D, $4E, $4F, $50
$51, $52, $53, $54, $55, $56, $57, $58, $59, $5A, $0A

My desired Output

$41, $42, $43, $44, $45, $46, $47, $48, $49, $4A, $4B, $4C, $4D, $4E, $4F, $50
$51, $52, $53, $54, $55, $56, $57, $58, $59, $5A

The current issues is the extra ',' but the bigger issue is that if the input file contains multiple lines of data the ASM output will contain random new lines. This is due to my else statement doing the printf("\n");

So I'm wondering if there is a better alternative to do this?

Body:
This code shows the technique I usually use.  It considers the comma-space as a prefix to items except the first; the first has an empty string as the prefix (or leading indentation if you want the data indented, or a label, or …).

#include <stdio.h>

static inline int iseol(unsigned char c) { return (c == '\n' || c == '\r'); }

static
void toASM(FILE *inputFile, FILE *outputFile)
{
    unsigned char buffer[16];
    int bytes;
    while ((bytes = fread(buffer, sizeof(buffer[0]), sizeof(buffer), inputFile)) > 0)
    {
        const char *pad = "";
        for (int i = 0; i < bytes; i++)
        {
            if (!iseol(buffer[i]))
            {
                fprintf(outputFile, "%s$%.2X", pad, buffer[i]);
                pad = ", ";
            }
            else if (pad[0] != '\0')
            {
                printf("\n");
                pad = "";
            }
        }
        if (pad[0] != '\0')
            putchar('\n');
    }
}

int main(void)
{
    toASM(stdin, stdout);
    return 0;
}

The iseol() function is probably overkill; using the original test was OK.  Formally, it is a reserved identifier — using is_eol() would be safe, as would isEOL().

The program source was asm67.c, compiled to program asm67.
I test with an input file input with contents:

ABCDEFGHIJKLMNOPQRSTUVWXYZ

The simplest test case yields:

$ asm67 < input
$41, $42, $43, $44, $45, $46, $47, $48, $49, $4A, $4B, $4C, $4D, $4E, $4F, $50
$51, $52, $53, $54, $55, $56, $57, $58, $59, $5A
$

That looks like what you requested.  The following shows the output from 4 lines of input each containing the alphabet plus a newline.  If that's not what you want, you should specify the desired output for such cases in the question.  The futzing required to get the desired output is probably not very complex.

$ cat input input input input | asm67
$41, $42, $43, $44, $45, $46, $47, $48, $49, $4A, $4B, $4C, $4D, $4E, $4F, $50
$51, $52, $53, $54, $55, $56, $57, $58, $59, $5A
$41, $42, $43, $44, $45
$46, $47, $48, $49, $4A, $4B, $4C, $4D, $4E, $4F, $50, $51, $52, $53, $54, $55
$56, $57, $58, $59, $5A
$41, $42, $43, $44, $45, $46, $47, $48, $49, $4A
$4B, $4C, $4D, $4E, $4F, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $5A
$41, $42, $43, $44, $45, $46, $47, $48, $49, $4A, $4B, $4C, $4D, $4E, $4F
$50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $5A
$

Note that with the 4 lines of input, one of the 16-byte blocks starts with a newline character; the code's logic with if (pad[0] != '\0') prevents that leaving a blank line in the output.

Providing a function that takes an input file stream and an output file stream is a good idea.  And the test program shows how simple it becomes to make use of standard input and standard output for testing.


问:
c# read in two bytes from string
HI,

I'm reading a file in as hex and storing it in a string, what I need to do is then read in two chars at a time so say i have a string that contains

313233343536373839

I would need to read in 31 followed by 32 followed by 33

I'm new to c# and programming in general, my book has nothing on it and I can't find an example that explains it well for me, if you could advise me I would be greatful!

答:
```<code>string myString = "313233343536373839";

for (int i=0; i<myString.Length; i+=2)
{
    string myChars = myString.Substring(i, 2);
    // do something with myChars here ...
}
</code>```

Was in the middle of posting this when Darin posted. Hadn't thought about doing it that way. Nice work Darin!

ContentLicense: CC BY-SA 3.0

Title: c# read in two bytes from string

Body:
string myString = "313233343536373839";

for (int i=0; i<myString.Length; i+=2)
{
    string myChars = myString.Substring(i, 2);
    // do something with myChars here ...
}

Was in the middle of posting this when Darin posted. Hadn't thought about doing it that way. Nice work Darin!


问:
Why I get only one element in slot inside v-for?
In my vue application code, I have a swiper component. inside this component I have a v-for and a slot.

In the parent component (Foo) I need to catch the component (baz) I put into slot, by ref. the problem is its return only one element not array as I though so.

How to keep this shape of components and still get the array I expected? is it possible?

import Vue from "vue";

Vue.config.productionTip = false;

const Foo = {
  template: `

    <swiper :items="items">
    <baz ref="baz"/>
    </swiper>

  `,
  data: function() {
    return {
      items: [1, 2, 3, 4, 5]
    };
  },
  mounted: function() {
    this.$nextTick().then(() => {
      console.log({ refs: this.$refs.baz });
    });
  }
};

const Baz = { template: "
im baz
" };

const Swiper = {
  template: `

        <slot></slot>

    `,
  props: ["items"]
};

Vue.component("foo", Foo);
Vue.component("baz", Baz);
Vue.component("swiper", Swiper);

new Vue({
  render: h => h(Foo)
}).$mount("#app");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script></code>```

答: You need to change your structure. Instead of using v-for in swiper template, use it in foo template. Let swiper template handle rendering only a single item. Here's a working example of what you expected: https://codesandbox.io/s/jolly-meninsky-qqe6k


问:
Repeating characters in VIM insert mode
Is there a way of repeating a character while in Vim's insert mode?  For example, say I would like to insert 80 dashes, in something like emacs I would type:

Ctrl+U   8 0 -

The only way I know how to do it in VIM is to exit normal mode for the repeat argument, then go back into insert mode to type the dash, then exit to insert the actual dashes, AND then go back into insert mode to carry on typing.  The sequence is a really long:

Esc 8 0 a - Esc a

It would be nice not to switch in and out of modes.

答:
I did this without exiting the INSERT mode using the below steps.

Enable INSERT mode.

Type one dash "-".

Ctrl + O

lowercase 'v' (to enter -- (insert) VISUAL -- mode)

lowercase 'y' (to copy)

Ctrl + O

Type 80

Then, followed by lowercase 'p' (for paste).

i - Ctrl+o v y Ctrl+o 80 p

This will print all the dashes horizontally in a single line.

Title: Repeating characters in VIM insert mode


问:
upgrading ruby how to
I recently upgraded to ruby 1.8.7.  i'm running Rails 2.3.5 and rubyGems 1.5.2.

ever since I upgraded, every time I want to start the server, i get:

```<code>undefined local variable or method `version_requirements' for #<Rails::GemDependency:0x1022cc1c8> (NameError)
</code>```

this post here advises to downgrade rugyGems to a version below 1.5.0.

downgrading doesn't seem to be the right solution..should I maybe be upgrading Ruby or Rails instead?

Also, if I upgrade to the latest ruby (1.9.2) and rails (3.0)..will my application break?
I have a very large application and can't figure out how to upgrade it without breaking the application..

答:
That thing about version_requirements is a bug in rubygems - confirmed by their creators.
I've also participated in the bug report on the rubygems :)

```<code>gem update --system 1.5.0
</code>```

performs a graceful downgrade until this is fixed.

I ran into this issue with some Rails 2.x applications and once also with 3.0.4 application, but with different error message, again, downgrading rubygems solved it.

Title: upgrading ruby how to

Body:
I recently upgraded to ruby 1.8.7.  i'm running Rails 2.3.5 and rubyGems 1.5.2.

ever since I upgraded, every time I want to start the server, i get:

undefined local variable or method `version_requirements' for #<Rails::GemDependency:0x1022cc1c8> (NameError)

this post here advises to downgrade rugyGems to a version below 1.5.0.

downgrading doesn't seem to be the right solution..should I maybe be upgrading Ruby or Rails instead?

Also, if I upgrade to the latest ruby (1.9.2) and rails (3.0)..will my application break?
I have a very large application and can't figure out how to upgrade it without breaking the application..

Body:
That thing about version_requirements is a bug in rubygems - confirmed by their creators.
I've also participated in the bug report on the rubygems :)

gem update --system 1.5.0

performs a graceful downgrade until this is fixed.

I ran into this issue with some Rails 2.x applications and once also with 3.0.4 application, but with different error message, again, downgrading rubygems solved it.


问:
How to toggle a div that is hidden on page load
I am using the following js to hide and show my div

```<code>function myFunction(test) {
    var x = document.getElementById(test);

    if (x.style.display == "none") {
        //x.style.display = "block";
        x.style.setProperty("display", "block", "important")
    } else {
        //x.style.display = "none";
        x.style.setProperty("display", "none", "important")
    }
}
</code>```

I have all divs hidden on load using a class, which works, but you have to click a link twice to get it to unhide. How can I fix this to unhide on the first click?

The page Im working on is here, you can click on any of the titles to expand some section. (Ignore the formatting, it's very much a work in progress.)

http://thinkularity.eth.link

答:
A very trivial and simple way to solve your problem is to first test if (x.style.display == "block") and if it is anything else to then display the hidden content. Another way is to include the style inline inside the html code so that the style property of the DOM object has some initial property immediately after rendering.

function myFunction(test) {
    var x = document.getElementById(test);
    if (x.style.display == "block") {
        x.style.display = "none";
    } else {
        x.style.display = "block";
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#test {
    display:none;
}</code>```

Click to toggle display

Now you see me

```

Body:
I am using the following js to hide and show my div

function myFunction(test) {
    var x = document.getElementById(test);

    if (x.style.display == "none") {
        //x.style.display = "block";
        x.style.setProperty("display", "block", "important")
    } else {
        //x.style.display = "none";
        x.style.setProperty("display", "none", "important")
    }
}

I have all divs hidden on load using a class, which works, but you have to click a link twice to get it to unhide. How can I fix this to unhide on the first click?

The page Im working on is here, you can click on any of the titles to expand some section. (Ignore the formatting, it's very much a work in progress.)

http://thinkularity.eth.link

Body:
A very trivial and simple way to solve your problem is to first test if (x.style.display == "block") and if it is anything else to then display the hidden content. Another way is to include the style inline inside the html code so that the style property of the DOM object has some initial property immediately after rendering.

function myFunction(test) {
    var x = document.getElementById(test);
    if (x.style.display == "block") {
        x.style.display = "none";
    } else {
        x.style.display = "block";
    }
}

#test {
    display:none;
}

<h3 onclick="myFunction('test')">Click to toggle display</h3><br>
<div id="test">Now you see me</div><br>


问:
How to capture project level data-set in another windows form or crystal report form c#
I have used a dataset in many of my windows forms for datagrid. As you can see i have project level dataset created.

The problem is i would liek to resume that dataset inside code to assing source for crystal report as follow.

```<code>       //sbmsDataSetAllis not recognized

        ReportDocument cryRpt = new ReportDocument();
        cryRpt.Load("rystalReport1.rpt");
        cryRpt.SetDataSource(sbmsDataSetAll.Tables["recent_slide_dataset"].DataSet) ;
        crystalReportViewer1.ReportSource = cryRpt;
        crystalReportViewer1.Refresh();
</code>```

答:
OK, but you need to understand that these dataset items you see in the solution explorer are representing class types(things you can create) not object instances(things you have created) so you can only use object instances in your code

On the form where your dataset is created, with some code like

```<code> sbmsDataSetAll myDataset = new sbmsDatasetAll();
</code>```

is where the instance of the dataset is. It is only on this form's code that you can link it to the report unless you have passed the dataset to another place via method parameters.

You should really pass one of the tables inside the dataset as the crystal report datasource, unless you already told crystal what table name to use (in design mode somewhere - I can't see it in your code). When you work with strongly typed datasets like these you don't need to use the .Tables collection. Every table in the set has a named property for the table:

```<code>    cryRpt.SetDataSource(sbmsDataSetAll.recent_slide_dataset) ;
</code>```

You also don't need to call a table's DataSet Property because that just points back to the dataset the table is in, which you already know when you chose the table:

```<code>cryRpt.SetDataSource(sbmsDataSetAll) ;
</code>```

As another small critique, in c# we use PascalCase of object, property and method names, so your dataset entities should really be named like:

```<code>cryRpt.SetDataSource(SbmsDataSetAll.RecentSlides) ;
</code>```

Body:
I have used a dataset in many of my windows forms for datagrid. As you can see i have project level dataset created.

The problem is i would liek to resume that dataset inside code to assing source for crystal report as follow.

       //sbmsDataSetAllis not recognized

        ReportDocument cryRpt = new ReportDocument();
        cryRpt.Load("rystalReport1.rpt");
        cryRpt.SetDataSource(sbmsDataSetAll.Tables["recent_slide_dataset"].DataSet) ;
        crystalReportViewer1.ReportSource = cryRpt;
        crystalReportViewer1.Refresh();

Body:
OK, but you need to understand that these dataset items you see in the solution explorer are representing class types(things you can create) not object instances(things you have created) so you can only use object instances in your code

On the form where your dataset is created, with some code like

 sbmsDataSetAll myDataset = new sbmsDatasetAll();

is where the instance of the dataset is. It is only on this form's code that you can link it to the report unless you have passed the dataset to another place via method parameters.

You should really pass one of the tables inside the dataset as the crystal report datasource, unless you already told crystal what table name to use (in design mode somewhere - I can't see it in your code). When you work with strongly typed datasets like these you don't need to use the .Tables collection. Every table in the set has a named property for the table:

    cryRpt.SetDataSource(sbmsDataSetAll.recent_slide_dataset) ;

You also don't need to call a table's DataSet Property because that just points back to the dataset the table is in, which you already know when you chose the table:

cryRpt.SetDataSource(sbmsDataSetAll) ;

As another small critique, in c# we use PascalCase of object, property and method names, so your dataset entities should really be named like:

cryRpt.SetDataSource(SbmsDataSetAll.RecentSlides) ;


问:
React Native render white screen when use Context API
I have an issue.
When I don't wrap AuthProvider everything OK. Dont have any problems.
But when I wrap AuthProvider, my Application render white screen @@.
So I check terminal, and see Bundle not running ( normally when render we can see Bundle Loading and Running...) .
How I fix this problem ?
Thank you so much.

createDataContext.js

```<code>   import React, { useReducer } from 'react';

export default (reducer, actions, defaultValue) => {
  const Context = React.createContext();

  const Provider = ({ chilrden }) => {
    const [state, dispatch] = useReducer(reducer, defaultValue);

    const boundActions = {};

    for (let key in actions) {
      boundActions[key] = actions[key](dispatch);
    }

    return (
      <Context.Provider value={{ state, ...boundActions }}>
        {chilrden}
      </Context.Provider>
    );
  };
  return { Context, Provider };
};
</code>```

AuthContext.js

```<code>import createDataContext from './createDataContext';

const authReducer = (state, action) => {
  switch (action.type) {
    default:
      return state;
  }
};

export const { Provider, Context } = createDataContext(
  authReducer,
  {},
  { isSignedIn: true }
);
</code>```

App.js

```<code>import React from 'react';
import {Provider as AuthProvider} from './src/context/AuthContext';
import {
  createAppContainer,
  createSwitchNavigator,
} from 'react-navigation';
import {createBottomTabNavigator} from 'react-navigation-tabs';
import {createStackNavigator} from 'react-navigation-stack';

import AccountScreen from './src/screens/AccountScreen';
import TrackDetailScreen from './src/screens/TrackDetailScreen';
import TrackListScreen from './src/screens/TrackListScreen';
import SigninScreen from './src/screens/SigninScreen';
import SignupScreen from './src/screens/SignupScreen';
import TrackCreateScreen from './src/screens/TrackCreateScreen';

const switchNavigator = createSwitchNavigator({
  loginFlow: createStackNavigator({
    Signup:SignupScreen,
    Signin:SigninScreen
  }),
  mainFlow: createBottomTabNavigator({
    trackListFlow:createStackNavigator({
      TrackList:TrackListScreen,
      TrackDetail:TrackDetailScreen
    }),
    TrackCreate:TrackCreateScreen,
    Account:AccountScreen,
  })
});

const App = createAppContainer(switchNavigator);

export default () => {
  return(
    <AuthProvider>
      <App/>
    </AuthProvider>
  );
};
</code>```

答:
Quick fix:
in createDataContext.js ( const Provider = ({children}) )
Use props instead of {children}
Pass as {props.children}

My quick fix:

```<code>import React, { useReducer } from 'react';

export default (reducer, actions, defaultValue) => {
  const Context = React.createContext();

  const Provider = props => {
    const [state, dispatch] = useReducer(reducer, defaultValue);

    const boundActions = {};

    for (let key in actions) {
      boundActions[key] = actions[key](dispatch);
    }

    console.log(props.children);

    return (
      <Context.Provider value={{ state, ...boundActions }}>
        {props.children}
      </Context.Provider>
    );
  };
  return { Context, Provider };
};
</code>```

Body:
I have an issue.
When I don't wrap AuthProvider everything OK. Dont have any problems.
But when I wrap AuthProvider, my Application render white screen @@.
So I check terminal, and see Bundle not running ( normally when render we can see Bundle Loading and Running...) .
How I fix this problem ?
Thank you so much.

createDataContext.js

   import React, { useReducer } from 'react';

export default (reducer, actions, defaultValue) => {
  const Context = React.createContext();

  const Provider = ({ chilrden }) => {
    const [state, dispatch] = useReducer(reducer, defaultValue);

    const boundActions = {};

    for (let key in actions) {
      boundActions[key] = actions[key](dispatch);
    }

    return (
      <Context.Provider value={{ state, ...boundActions }}>
        {chilrden}
      </Context.Provider>
    );
  };
  return { Context, Provider };
};

AuthContext.js

import createDataContext from './createDataContext';

const authReducer = (state, action) => {
  switch (action.type) {
    default:
      return state;
  }
};

export const { Provider, Context } = createDataContext(
  authReducer,
  {},
  { isSignedIn: true }
);

App.js

import React from 'react';
import {Provider as AuthProvider} from './src/context/AuthContext';
import {
  createAppContainer,
  createSwitchNavigator,
} from 'react-navigation';
import {createBottomTabNavigator} from 'react-navigation-tabs';
import {createStackNavigator} from 'react-navigation-stack';

import AccountScreen from './src/screens/AccountScreen';
import TrackDetailScreen from './src/screens/TrackDetailScreen';
import TrackListScreen from './src/screens/TrackListScreen';
import SigninScreen from './src/screens/SigninScreen';
import SignupScreen from './src/screens/SignupScreen';
import TrackCreateScreen from './src/screens/TrackCreateScreen';

const switchNavigator = createSwitchNavigator({
  loginFlow: createStackNavigator({
    Signup:SignupScreen,
    Signin:SigninScreen
  }),
  mainFlow: createBottomTabNavigator({
    trackListFlow:createStackNavigator({
      TrackList:TrackListScreen,
      TrackDetail:TrackDetailScreen
    }),
    TrackCreate:TrackCreateScreen,
    Account:AccountScreen,
  })
});

const App = createAppContainer(switchNavigator);

export default () => {
  return(
    <AuthProvider>
      <App/>
    </AuthProvider>
  );
};

Body:
Quick fix:
in createDataContext.js ( const Provider = ({children}) )
Use props instead of {children}
Pass as {props.children}

My quick fix:

import React, { useReducer } from 'react';

export default (reducer, actions, defaultValue) => {
  const Context = React.createContext();

  const Provider = props => {
    const [state, dispatch] = useReducer(reducer, defaultValue);

    const boundActions = {};

    for (let key in actions) {
      boundActions[key] = actions[key](dispatch);
    }

    console.log(props.children);

    return (
      <Context.Provider value={{ state, ...boundActions }}>
        {props.children}
      </Context.Provider>
    );
  };
  return { Context, Provider };
};


问:
React Native Expo Camera - Invariant Violation error when trying to start the camera
I am trying to run the following code by I get an Invariant Violation error:

```<code>import React, { Component } from "react";

import { View, Text, TouchableOpacity } from "react-native";

import { Camera, MediaLibrary } from "expo";

import * as Permissions from 'expo-permissions';

class MyCam extends Component {

  state = {

    video: null,

    picture: null,

    recording: false

  };

  _saveVideo = async () => {

    const { video } = this.state;

    const asset = await MediaLibrary.createAssetAsync(video.uri);

    if (asset) {

      this.setState({ video: null });

    }

  };

  _StopRecord = async () => {

    this.setState({ recording: false }, () => {

      this.cam.stopRecording();

    });

  };

  _StartRecord = async () => {

    if (this.cam) {

      this.setState({ recording: true }, async () => {

        const video = await this.cam.recordAsync();

        this.setState({ video });

      });

    }

  };

  toogleRecord = () => {

    const { recording } = this.state;

    if (recording) {

      this._StopRecord();

    } else {

      this._StartRecord();

    }

  };

  render() {

    const { recording, video } = this.state;

    return (

      <Camera

        ref={cam => (this.cam = cam)}

        style={{

          justifyContent: "flex-end",

          alignItems: "center",

          flex: 1,

          width: "100%"

        }}

      >

        {video && (

          <TouchableOpacity

            onPress={this._saveVideo}

            style={{

              padding: 20,

              width: "100%",

              backgroundColor: "#fff"

            }}

          >

            <Text style={{ textAlign: "center" }}>save</Text>

          </TouchableOpacity>

        )}

        <TouchableOpacity

          onPress={this.toogleRecord}

          style={{

            padding: 20,

            width: "100%",

            backgroundColor: recording ? "#ef4f84" : "#4fef97"

          }}

        >

          <Text style={{ textAlign: "center" }}>

            {recording ? "Stop" : "Record"}

          </Text>

        </TouchableOpacity>

      </Camera>

    );

  }

}

class RecVideo extends Component {

  state = {

    showCamera: false

  };

  _showCamera = async () => {

    const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);

    if (status === "granted") {

      this.setState({ showCamera: true });

    }

  };

  render() {

    const { showCamera } = this.state;

    return (

      <View

        style={{

          justifyContent: "center",

          alignItems: "center",

          flex: 1,

          width: "100%"

        }}

      >

        {showCamera ? (

          <MyCam />

        ) : (

          <TouchableOpacity onPress={this._showCamera}>

            <Text> Show Camera </Text>

          </TouchableOpacity>

        )}

      </View>

    );

  }

}

export default RecVideo;
</code>```

This is the error: Invariant Violation

I found this piece of code in here: https://forums.expo.io/t/how-to-record-video/18834

I only made a change on how the permission are imported but the rest is the same.
I'm guessing the error is related to the import since that's what I found online but I don't know how to fix it because everything seems to be right.

答:
```<code>import React from 'react';
import { Text, View, TouchableOpacity,Vibration } from 'react-native';
import * as Permissions from 'expo-permissions';
import { Camera } from 'expo-camera';
import { AsyncStorage } from 'react-native';
import { ToastAndroid } from 'react-native';
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
const PATTERN = [1000, 2000, 3000];
export default class OpenCamera extends React.Component {
    state = {
        hasCameraPermission: null,
        type: Camera.Constants.Type.back,
    };

    async componentDidMount() {
        const { status } = await Permissions.askAsync(Permissions.CAMERA);
        this.setState({ hasCameraPermission: status === 'granted' });
    }

    // get the uri;
    async clicked1() {
         Vibration.vibrate(PATTERN)
        if (this.camera) {
            let photo = await this.camera.takePictureAsync();
            console.log('array>>',photo)
            console.log('image path>>>>>>>', photo.uri)
            await AsyncStorage.setItem('image_path_key', photo.uri);
            if(photo.uri!=null){
                this.props._changeCameraVisbilty(false);
                this.props._setImageData(photo.uri)
            // this.props.navigation.goBack()
            }else{
    ToastAndroid.show('There some problem to taking a photo,please try again', ToastAndroid.SHORT);
}

        }
    };

// _closeCamera=()=>{

// }

// get the photo
async snapPhoto() {
    console.log('Button Pressed');
    if (this.camera) {
       console.log('Taking photo');
       const options = { quality: 1, base64: true, fixOrientation: true,
       exif: true};
       await this.camera.takePictureAsync(options).then(photo => {
          photo.exif.Orientation = 1;
           console.log(photo);
           });
     }
    }

    render() {
        //const { navigate } = this.props.navigation;
        const { hasCameraPermission } = this.state;
        if (hasCameraPermission === null) {
            return <View />;
        } else if (hasCameraPermission === false) {
            return <Text>No access to camera</Text>;
        } else {
            return (
                <View style={{ flex: 1 }}>
                    <Camera style={{ flex: 1 }}
                     ref={ (ref) => {this.camera = ref} }
                      type={this.state.type}  >

                        <View
                            style={{
                                flex: 1,
                                backgroundColor: 'transparent',
                                flexDirection: 'row',
                            }}>
                            <TouchableOpacity
                                style={{
                                    flex: 0.1,
                                    alignSelf: 'flex-end',
                                    alignItems: 'center',
                                }}
                                onPress={() => {
                                    this.setState({
                                        type:
                                            this.state.type === Camera.Constants.Type.back
                                                ? Camera.Constants.Type.front
                                                : Camera.Constants.Type.back,

                                    });
                                }}>
                                <Text style={{ fontSize: 18, marginBottom: 10, color: 'white' }}> Flip </Text>
                            </TouchableOpacity>
                        </View>
                    </Camera>

                    <View style={{flexDirection:'row',alignItems:'center',justifyContent:'center'}}>

<TouchableOpacity
    onPress={this.clicked1.bind(this)} >
    <Text style={{fontSize:hp('3%'),marginTop:hp('2.3%'),marginBottom:hp('2.3%')}}>Take photo</Text>
</TouchableOpacity>

</View>

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

Open custom camera code

Body:
I am trying to run the following code by I get an Invariant Violation error:

import React, { Component } from "react";

import { View, Text, TouchableOpacity } from "react-native";

import { Camera, MediaLibrary } from "expo";

import * as Permissions from 'expo-permissions';

class MyCam extends Component {

  state = {

    video: null,

    picture: null,

    recording: false

  };

  _saveVideo = async () => {

    const { video } = this.state;

    const asset = await MediaLibrary.createAssetAsync(video.uri);

    if (asset) {

      this.setState({ video: null });

    }

  };

  _StopRecord = async () => {

    this.setState({ recording: false }, () => {

      this.cam.stopRecording();

    });

  };

  _StartRecord = async () => {

    if (this.cam) {

      this.setState({ recording: true }, async () => {

        const video = await this.cam.recordAsync();

        this.setState({ video });

      });

    }

  };

  toogleRecord = () => {

    const { recording } = this.state;

    if (recording) {

      this._StopRecord();

    } else {

      this._StartRecord();

    }

  };

  render() {

    const { recording, video } = this.state;

    return (

      <Camera

        ref={cam => (this.cam = cam)}

        style={{

          justifyContent: "flex-end",

          alignItems: "center",

          flex: 1,

          width: "100%"

        }}

      >

        {video && (

          <TouchableOpacity

            onPress={this._saveVideo}

            style={{

              padding: 20,

              width: "100%",

              backgroundColor: "#fff"

            }}

          >

            <Text style={{ textAlign: "center" }}>save</Text>

          </TouchableOpacity>

        )}

        <TouchableOpacity

          onPress={this.toogleRecord}

          style={{

            padding: 20,

            width: "100%",

            backgroundColor: recording ? "#ef4f84" : "#4fef97"

          }}

        >

          <Text style={{ textAlign: "center" }}>

            {recording ? "Stop" : "Record"}

          </Text>

        </TouchableOpacity>

      </Camera>

    );

  }

}

class RecVideo extends Component {

  state = {

    showCamera: false

  };

  _showCamera = async () => {

    const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);

    if (status === "granted") {

      this.setState({ showCamera: true });

    }

  };

  render() {

    const { showCamera } = this.state;

    return (

      <View

        style={{

          justifyContent: "center",

          alignItems: "center",

          flex: 1,

          width: "100%"

        }}

      >

        {showCamera ? (

          <MyCam />

        ) : (

          <TouchableOpacity onPress={this._showCamera}>

            <Text> Show Camera </Text>

          </TouchableOpacity>

        )}

      </View>

    );

  }

}

export default RecVideo;

This is the error: Invariant Violation

I found this piece of code in here: https://forums.expo.io/t/how-to-record-video/18834

I only made a change on how the permission are imported but the rest is the same.
I'm guessing the error is related to the import since that's what I found online but I don't know how to fix it because everything seems to be right.

Body:
import React from 'react';
import { Text, View, TouchableOpacity,Vibration } from 'react-native';
import * as Permissions from 'expo-permissions';
import { Camera } from 'expo-camera';
import { AsyncStorage } from 'react-native';
import { ToastAndroid } from 'react-native';
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
const PATTERN = [1000, 2000, 3000];
export default class OpenCamera extends React.Component {
    state = {
        hasCameraPermission: null,
        type: Camera.Constants.Type.back,
    };

    async componentDidMount() {
        const { status } = await Permissions.askAsync(Permissions.CAMERA);
        this.setState({ hasCameraPermission: status === 'granted' });
    }

    // get the uri;
    async clicked1() {
         Vibration.vibrate(PATTERN)
        if (this.camera) {
            let photo = await this.camera.takePictureAsync();
            console.log('array>>',photo)
            console.log('image path>>>>>>>', photo.uri)
            await AsyncStorage.setItem('image_path_key', photo.uri);
            if(photo.uri!=null){
                this.props._changeCameraVisbilty(false);
                this.props._setImageData(photo.uri)
            // this.props.navigation.goBack()
            }else{
    ToastAndroid.show('There some problem to taking a photo,please try again', ToastAndroid.SHORT);
}

        }
    };

// _closeCamera=()=>{

// }

// get the photo
async snapPhoto() {
    console.log('Button Pressed');
    if (this.camera) {
       console.log('Taking photo');
       const options = { quality: 1, base64: true, fixOrientation: true,
       exif: true};
       await this.camera.takePictureAsync(options).then(photo => {
          photo.exif.Orientation = 1;
           console.log(photo);
           });
     }
    }

    render() {
        //const { navigate } = this.props.navigation;
        const { hasCameraPermission } = this.state;
        if (hasCameraPermission === null) {
            return <View />;
        } else if (hasCameraPermission === false) {
            return <Text>No access to camera</Text>;
        } else {
            return (
                <View style={{ flex: 1 }}>
                    <Camera style={{ flex: 1 }}
                     ref={ (ref) => {this.camera = ref} }
                      type={this.state.type}  >

                        <View
                            style={{
                                flex: 1,
                                backgroundColor: 'transparent',
                                flexDirection: 'row',
                            }}>
                            <TouchableOpacity
                                style={{
                                    flex: 0.1,
                                    alignSelf: 'flex-end',
                                    alignItems: 'center',
                                }}
                                onPress={() => {
                                    this.setState({
                                        type:
                                            this.state.type === Camera.Constants.Type.back
                                                ? Camera.Constants.Type.front
                                                : Camera.Constants.Type.back,

                                    });
                                }}>
                                <Text style={{ fontSize: 18, marginBottom: 10, color: 'white' }}> Flip </Text>
                            </TouchableOpacity>
                        </View>
                    </Camera>

                    <View style={{flexDirection:'row',alignItems:'center',justifyContent:'center'}}>

<TouchableOpacity
    onPress={this.clicked1.bind(this)} >
    <Text style={{fontSize:hp('3%'),marginTop:hp('2.3%'),marginBottom:hp('2.3%')}}>Take photo</Text>
</TouchableOpacity>

</View>

                </View>
            );
        }
    }
}

Open custom camera code


问:
How to create XML object from string using xml-mapping in Ruby
I'm using xml-mapping in Ruby (on Sinatra) for some XML stuff. Generally I follow this tutorial: http://xml-mapping.rubyforge.org/. I can create objects and write them to XML strings using

```<code>login.save_to_xml.to_s
</code>```

But when I try

```<code>login = Login.load_from_xml(xml_string)
</code>```

I get the following error:

```<code>XML::MappingError - no value, and no default value: Attribute username not set (XXPathError: path not found: username):
</code>```

Here is the XML string I receive:

```<code><login><username>ali</username><password>baba</password></login>
</code>```

This is what the class looks like:

```<code>class Login
  include XML::Mapping

  text_node :username, "username"
  text_node :password, "password"
end
</code>```

So the class name is the same, the nodes are named the same. I actually get the exact same string when I create an instance of my object and fill it with ali/baba:

```<code>test = Login.new
test.username = "ali"
test.password = "baba"
p test.save_to_xml.to_s

<login><username>ali</username><password>baba</password></login>
</code>```

What am I missing?

Thanks,
MrB

EDIT:

When I do

```<code>test = login.save_to_xml
</code>```

And then

```<code>login = Login.load_from_xml(test)
</code>```

it works. So the problem seems to be that I'm passing a string, while the method is expecting.. well, something else. There is definitely a load_from_xml(string) method in the rubydocs, so not sure what to pass here. I guess I need some kind of reverse to_s?

答:
It looks like you save_to_xml creates a REXML::Element.  Since that works, you may want to try:

```<code>Login.load_from_xml(REXML::Document.new(xml_string).root)
</code>```

See the section on "choice_node" for a more detailed example http://xml-mapping.rubyforge.org/

Body:
I'm using xml-mapping in Ruby (on Sinatra) for some XML stuff. Generally I follow this tutorial: http://xml-mapping.rubyforge.org/. I can create objects and write them to XML strings using

login.save_to_xml.to_s

But when I try

login = Login.load_from_xml(xml_string)

I get the following error:

XML::MappingError - no value, and no default value: Attribute username not set (XXPathError: path not found: username):

Here is the XML string I receive:

<login><username>ali</username><password>baba</password></login>

This is what the class looks like:

class Login
  include XML::Mapping

  text_node :username, "username"
  text_node :password, "password"
end

So the class name is the same, the nodes are named the same. I actually get the exact same string when I create an instance of my object and fill it with ali/baba:

test = Login.new
test.username = "ali"
test.password = "baba"
p test.save_to_xml.to_s

<login><username>ali</username><password>baba</password></login>

What am I missing?

Thanks,
MrB

EDIT:

When I do

test = login.save_to_xml

And then

login = Login.load_from_xml(test)

it works. So the problem seems to be that I'm passing a string, while the method is expecting.. well, something else. There is definitely a load_from_xml(string) method in the rubydocs, so not sure what to pass here. I guess I need some kind of reverse to_s?

Body:
It looks like you save_to_xml creates a REXML::Element.  Since that works, you may want to try:

Login.load_from_xml(REXML::Document.new(xml_string).root)

See the section on "choice_node" for a more detailed example http://xml-mapping.rubyforge.org/


问:
Can we change wordpress custom walker class first (root) ul tag using PHP by overriding The Walker_Nav_menu
Hey guys using the Wordpress Framework usually I create a custom walker that extends Walker_Nav_menu
in order to make a custom wordpress menu. I did register the Menu location in the functions.php , I did hook up the menu and create a custom_nav_walker and it worked.
 however I cannot change the main ul root tag to put some inline code up there using the navwalker php class without using javascript.

So the nav menu html is something like this.

```<code><ul id="Root-tag-That-I-want-to-modify" class="vertical medium-horizontal menu dropdown" <!--  I WANT TO ECHO CODE HERE USING PHP --> >
<li id="menu-item-146" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item current_page_item menu-item-home active menu-item-146">
<a href="http://Thelink">Item</a></li>
<li id="menu-item-147" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-ancestor current-menu-parent current_page_parent current_page_ancestor menu-item-has-children active has-dropdown menu-item-147"><a href="http://ThesecondLink">submeu</a>
<ul class="0 menu submenu is-dropdown-submenu first-sub vertical"  data-submenu="" role="menu">
<li id="menu-item-153" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item current_page_item menu-item-home active menu-item-153"><a href="http://anotherlink">submeu item</a>
</li></ul></li></ul>
</code>```

I tried to override the start_lvl funtion that is inside the Walker class :

```<code>    function start_lvl( &$output, $depth = 0, $args = array() ) {
      $indent = str_repeat( "\t", $depth );
      $first = ($depth === 0) ? 'first-sub' : '';
      $output .= "\n$indent<ul class=\"$depth menu submenu is-dropdown-submenu $first vertical\"  data-submenu=\"\" role=\"menu\">\n";
     }
</code>```

After printing $depth inside the ul tag I found out that this first UL is not processed by this start_lvl

Where in this class can I override the main UL tag, I checked the wordpress call wp_nav_menu array maybe I missed something ??
I am interested in doing this with PHP without Javascript.

答:
One solution that I found is to change the 'menu_class' parameter when instantiating the walker class , Usually you have :

```<code>wp_nav_menu( array(
        'menu_class'      => 'vertical medium-horizontal menu dropdown',
        'items_wrap'      => '<ul id="%1$s" class="%2$s">%3$s</ul>',
        'depth'           => 0,
        'walker'          => new Custom_Walker_Class()  ));
</code>```

To include some extra line-codes example (data-responsive-menu="accordion medium-dropdown" role="menubar') I changed it to :

```<code>wp_nav_menu( array(
        'menu_class'      => 'vertical medium-horizontal menu dropdown" data-responsive-menu="accordion medium-dropdown" role="menubar',
        'items_wrap'      => '<ul id="%1$s" class="%2$s">%3$s</ul>',
        'depth'           => 0,
        'walker'          => new Custom_Walker_Class()  ));
</code>```

Basically it is shipping all the ul tag inline code inside this parameters string. Since it is getting a string (which is supposed to be just the ul tag classes) and wrapping it in quotes to print it as a wrapper for nav elements in the Html.

Ok So far the idea is good but I couldn't escape the  quotes and I ended with some source code like this :

class=&quot ;vertical medium-horizontal menu dropdown&quot ;  data-responsive-menu=&quot ;  accordion medium-dropdown"  role=&quot ;  menubar&quot ;

What I did to correct things is to :

I stored the wp_nav_menu result into some variable

I encoded that variable into a string (the &quot ; will become ")

I decoded and printed the resulting HTML

```<code>$db = esc_attr('" ');
$inlinecode= esc_attr('vertical medium-horizontal menu dropdown' . $db . ' data-responsive-menu=' . $db . ' accordion medium-dropdown' . $db . ' role=' . $db . ' menubar' . $db . ');

$mainmenu = wp_nav_menu( array(

    'menu_class'      => $inlinecode,
    'echo'            => false,
    'items_wrap'      => '<ul id="%1$s" class="%2$s">%3$s</ul>',
    'depth'           => 0,
        'walker'          => new Walker_Primary()
        ));

        $men_encoded = esc_attr($mainmenu);
        echo html_entity_decode($men_encoded);
</code>```

Body:
Hey guys using the Wordpress Framework usually I create a custom walker that extends Walker_Nav_menu
in order to make a custom wordpress menu. I did register the Menu location in the functions.php , I did hook up the menu and create a custom_nav_walker and it worked.
 however I cannot change the main ul root tag to put some inline code up there using the navwalker php class without using javascript.

So the nav menu html is something like this.

Item

submeu

submeu item

I tried to override the start_lvl funtion that is inside the Walker class :

    function start_lvl( &$output, $depth = 0, $args = array() ) {
      $indent = str_repeat( "\t", $depth );
      $first = ($depth === 0) ? 'first-sub' : '';
      $output .= "\n$indent
\n";
     }

After printing $depth inside the ul tag I found out that this first UL is not processed by this start_lvl

Where in this class can I override the main UL tag, I checked the wordpress call wp_nav_menu array maybe I missed something ??
I am interested in doing this with PHP without Javascript.

Body:
One solution that I found is to change the 'menu_class' parameter when instantiating the walker class , Usually you have :

wp_nav_menu( array(
        'menu_class'      => 'vertical medium-horizontal menu dropdown',
        'items_wrap'      => '<ul id="%1$s" class="%2$s">%3$s</ul>',
        'depth'           => 0,
        'walker'          => new Custom_Walker_Class()  ));

To include some extra line-codes example (data-responsive-menu="accordion medium-dropdown" role="menubar') I changed it to :

wp_nav_menu( array(
        'menu_class'      => 'vertical medium-horizontal menu dropdown" data-responsive-menu="accordion medium-dropdown" role="menubar',
        'items_wrap'      => '<ul id="%1$s" class="%2$s">%3$s</ul>',
        'depth'           => 0,
        'walker'          => new Custom_Walker_Class()  ));

Basically it is shipping all the ul tag inline code inside this parameters string. Since it is getting a string (which is supposed to be just the ul tag classes) and wrapping it in quotes to print it as a wrapper for nav elements in the Html.

Ok So far the idea is good but I couldn't escape the  quotes and I ended with some source code like this :

class=&quot ;vertical medium-horizontal menu dropdown&quot ;  data-responsive-menu=&quot ;  accordion medium-dropdown"  role=&quot ;  menubar&quot ;

What I did to correct things is to :

I stored the wp_nav_menu result into some variable

I encoded that variable into a string (the &quot ; will become ")

I decoded and printed the resulting HTML

$db = esc_attr('" ');
$inlinecode= esc_attr('vertical medium-horizontal menu dropdown' . $db . ' data-responsive-menu=' . $db . ' accordion medium-dropdown' . $db . ' role=' . $db . ' menubar' . $db . ');

$mainmenu = wp_nav_menu( array(

    'menu_class'      => $inlinecode,
    'echo'            => false,
    'items_wrap'      => '<ul id="%1$s" class="%2$s">%3$s</ul>',
    'depth'           => 0,
        'walker'          => new Walker_Primary()
        ));

        $men_encoded = esc_attr($mainmenu);
        echo html_entity_decode($men_encoded);


问:
Bootstrap4 adjacent navbar columns
Here is my code:

```<code><nav class="navbar navbar-expand-lg navbar-light bg-light" role="navigation" id="navbar">
      <div class="container">
          <a class="navbar-brand mynav" href="{% url 'home' %}">Star Social</a>
              <ul class="navbar-nav navbar-right">
                  {% if user.is_authenticated %}

                      <li><a href="">Posts</a></li>
                      <li><a href="">Groups</a></li>
                      <li><a href="">Create Group</a></li>
                      <li><a href="{% url 'accounts:logout' %}">Logout</a></li>

                  {% else %}
                    <li><a href="">Group</a></li>
                    <li><a href="{% url 'accounts:login' %}">Login</a></li>
                    <li><a href="{% url 'accounts:signup' %}">Signup</a></li>
                  {% endif %}
              </ul>
      </div>
  </nav>
</code>```

I have a code like this but when I run the server, I'm getting style like this.

答:
In Your bootstrap code tag you forgot to add class in
 and  and you must replace the class in ul tag navbar-right to ml-auto here i will change

```<code> <nav class="navbar navbar-expand-lg navbar-light bg-light" role="navigation" id="navbar">

          <a class="navbar-brand" href="{% url 'home' %}">Star Social</a>

              <ul class="navbar-nav ml-auto">
                 <!-- {% if user.is_authenticated %} -->
                      <li class="nav-item active"><a class="nav-link" href="">Posts</a></li>
                      <li class="nav-item"><a class="nav-link" href="">Group</a></li>
                      <li class="nav-item"><a class="nav-link" href="">Create Group</a></li>
                      <li class="nav-item active"><a class="nav-link" href="{% url 'accounts:logout' %}">Logout</a></li>

               <!--   {% else %} -->

                      <li class="nav-item"><a class="nav-link" href="">Group</a></li>
                      <li class="nav-item"><a class="nav-link" href="{% url 'accounts:login' %}">Login</a></li>
                      <li class="nav-item"><a class="nav-link" href="{% url 'accounts:signup' %}">Signup</a></li>
       <!--           {% endif %} -->
              </ul>
    </nav>
</code>```

Above try but it not collapse if you want do same please refer a docs of bootstrap here i give link Bootstrap Navbar it work make right so let me know

Title: Bootstrap4 adjacent navbar columns

Body:
Here is my code:

          Star Social

                  {% if user.is_authenticated %}

Posts

Groups

Create Group

Logout

                  {% else %}

Group

Login

Signup

                  {% endif %}

I have a code like this but when I run the server, I'm getting style like this.

Body:
In Your bootstrap code tag you forgot to add class in <li> and <a> and you must replace the class in ul tag navbar-right to ml-auto here i will change

 <nav class="navbar navbar-expand-lg navbar-light bg-light" role="navigation" id="navbar">

          <a class="navbar-brand" href="{% url 'home' %}">Star Social</a>

              <ul class="navbar-nav ml-auto">
                 <!-- {% if user.is_authenticated %} -->
                      <li class="nav-item active"><a class="nav-link" href="">Posts</a></li>
                      <li class="nav-item"><a class="nav-link" href="">Group</a></li>
                      <li class="nav-item"><a class="nav-link" href="">Create Group</a></li>
                      <li class="nav-item active"><a class="nav-link" href="{% url 'accounts:logout' %}">Logout</a></li>

               <!--   {% else %} -->

                      <li class="nav-item"><a class="nav-link" href="">Group</a></li>
                      <li class="nav-item"><a class="nav-link" href="{% url 'accounts:login' %}">Login</a></li>
                      <li class="nav-item"><a class="nav-link" href="{% url 'accounts:signup' %}">Signup</a></li>
       <!--           {% endif %} -->
              </ul>
    </nav>

Above try but it not collapse if you want do same please refer a docs of bootstrap here i give link Bootstrap Navbar it work make right so let me know


问:
Generate Flutter Local Notification when background FCM Triggers
Basically I am trying to make a notification when FCM onBackgroundMessage Triggers.
While doing this I am getting a NullPointerException at the .show(..) method of FlutterLocalNotification Plugin.

Here is my Code:

```<code> FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message");
      },
      onBackgroundMessage: messageHandle,
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");
      },
      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message");
      },
    );
Future<dynamic> messageHandle(Map<String, dynamic> message) async{
  if (message.containsKey("data")) {
    Map data = message['data'];
    String topic;
    if (data.containsKey("topic")) topic = data['topic'];
    if (topic == "VendorNewTrips") {
      String amount = data['amount'];
      String vehicle = data['vehicle'];
      String tripType = data['tripType'];
      String pickUpDate= data['pickUpDate'];
      String pickUpTime = data['pickUpTime'];
      String locations= data['locations'];
      FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      new FlutterLocalNotificationsPlugin();

      new AndroidInitializationSettings('app_icon');
      var bigTextStyleInformation = BigTextStyleInformation(
          'Locations: <b>${locations.replaceAll("\$", " to ")}</b><br>Vehicle: <b>$vehicle</b><br>Trip Type: <b>$tripType</b><br>Pick-Up Date: <b>$pickUpDate</b><br>Pick-Up Time: <b>$pickUpTime</b>',
          htmlFormatBigText: true,
          contentTitle: 'Amount:- <b>Rs $amount</b>',
          htmlFormatContentTitle: true,
          summaryText: 'Trip Details',
          htmlFormatSummaryText: true);
      var androidPlatformChannelSpecifics = AndroidNotificationDetails(
          '1687497218170948721x8',
          'New Trips Notification ',
          'Notification Channel for vendor. All the new trips notifications will arrive here.',
          style: AndroidNotificationStyle.BigText,
          styleInformation: bigTextStyleInformation);
      var platformChannelSpecifics =
      NotificationDetails(androidPlatformChannelSpecifics, null);

      flutterLocalNotificationsPlugin.show(5, 'Let\'s Get Wride!',
          'You Have Got A New Trip!', platformChannelSpecifics,);
    }
  }
  return null;
}

</code>```

```<code>E/MethodChannel#dexterous.com/flutter/local_notifications(15092): Failed to handle method call
E/MethodChannel#dexterous.com/flutter/local_notifications(15092): java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.setSmallIcon(FlutterLocalNotificationsPlugin.java:208)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.createNotification(FlutterLocalNotificationsPlugin.java:180)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.showNotification(FlutterLocalNotificationsPlugin.java:693)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.show(FlutterLocalNotificationsPlugin.java:785)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:714)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:231)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:93)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:642)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at android.os.MessageQueue.next(MessageQueue.java:326)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at android.os.Looper.loop(Looper.java:190)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at android.app.ActivityThread.main(ActivityThread.java:7211)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:575)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:903)
E/flutter (15092): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(error, Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference, null)
E/flutter (15092): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
E/flutter (15092): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:321:33)
E/flutter (15092): <asynchronous suspension>
E/flutter (15092): #2      AndroidFlutterLocalNotificationsPlugin.show (package:flutter_local_notifications/src/platform_flutter_local_notifications.dart:135:21)
E/flutter (15092): #3      FlutterLocalNotificationsPlugin.show (package:flutter_local_notifications/src/flutter_local_notifications_plugin.dart:93:13)
E/flutter (15092): #4      messageHandle (package:wride/SplashScreen/SplashScreen.dart:155:39)
E/flutter (15092): #5      _fcmSetupBackgroundChannel.<anonymous closure> (package:firebase_messaging/firebase_messaging.dart:38:30)
E/flutter (15092): #6      MethodChannel._handleAsMethodCall (package:flutter/src/services/platform_channel.dart:402:55)
E/flutter (15092): #7      MethodChannel.setMethodCallHandler.<anonymous closure> (package:flutter/src/services/platform_channel.dart:370:54)
E/flutter (15092): #8      _DefaultBinaryMessenger.handlePlatformMessage (package:flutter/src/services/binding.dart:200:33)
E/flutter (15092): #9      _invoke3.<anonymous closure> (dart:ui/hooks.dart:303:15)
E/flutter (15092): #10     _rootRun (dart:async/zone.dart:1126:13)
E/flutter (15092): #11     _CustomZone.run (dart:async/zone.dart:1023:19)
E/flutter (15092): #12     _CustomZone.runGuarded (dart:async/zone.dart:925:7)
E/flutter (15092): #13     _invoke3 (dart:ui/hooks.dart:302:10)
E/flutter (15092): #14     _dispatchPlatformMessage (dart:ui/hooks.dart:162:5)
E/flutter (15092):
</code>```

I want to make my own stylish notification when background message triggers because FCM doesnot support Notification Styles.
Please Help!

Edit: I looked into the plugin FlutterLocalNotification and came to know that the NotificationDetails.java Line 151 Interger iconResourceID is null all the time. I don't know what to do now.

答:
Okay, I got to know where is the mistake. I forgot to initialize the flutter local notification plugin with the app_icon. I changed my messageHandle method and it is working now.

```<code>  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
          new FlutterLocalNotificationsPlugin();
      var androidPlatformChannelSpecifics = AndroidNotificationDetails(
          '1687497218170948721x8',
          'New Trips Notification ',
          'Notification Channel for vendor. All the new trips notifications will arrive here.',
          style: AndroidNotificationStyle.BigText,
          icon: "app_icon",
          styleInformation: BigTextStyleInformation(
            "hanji hogya?",//  'Locations: <b>${locations.replaceAll("\$", " to ")}</b><br>Vehicle: <b>$vehicle</b><br>Trip Type: <b>$tripType</b><br>Pick-Up Date: <b>$pickUpDate</b><br>Pick-Up Time: <b>$pickUpTime</b>',
              htmlFormatBigText: true,
              contentTitle: 'Amount:- <b>Rs 22000000</b>',
              htmlFormatContentTitle: true,
              summaryText: 'Trip Details',
              htmlFormatSummaryText: true));
</code>```

Body:
Basically I am trying to make a notification when FCM onBackgroundMessage Triggers.
While doing this I am getting a NullPointerException at the .show(..) method of FlutterLocalNotification Plugin.

Here is my Code:

 FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message");
      },
      onBackgroundMessage: messageHandle,
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");
      },
      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message");
      },
    );
Future<dynamic> messageHandle(Map<String, dynamic> message) async{
  if (message.containsKey("data")) {
    Map data = message['data'];
    String topic;
    if (data.containsKey("topic")) topic = data['topic'];
    if (topic == "VendorNewTrips") {
      String amount = data['amount'];
      String vehicle = data['vehicle'];
      String tripType = data['tripType'];
      String pickUpDate= data['pickUpDate'];
      String pickUpTime = data['pickUpTime'];
      String locations= data['locations'];
      FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      new FlutterLocalNotificationsPlugin();

      new AndroidInitializationSettings('app_icon');
      var bigTextStyleInformation = BigTextStyleInformation(
          'Locations: ${locations.replaceAll("\$", " to ")}
Vehicle: $vehicle
Trip Type: $tripType
Pick-Up Date: $pickUpDate
Pick-Up Time: $pickUpTime',
          htmlFormatBigText: true,
          contentTitle: 'Amount:- Rs $amount',
          htmlFormatContentTitle: true,
          summaryText: 'Trip Details',
          htmlFormatSummaryText: true);
      var androidPlatformChannelSpecifics = AndroidNotificationDetails(
          '1687497218170948721x8',
          'New Trips Notification ',
          'Notification Channel for vendor. All the new trips notifications will arrive here.',
          style: AndroidNotificationStyle.BigText,
          styleInformation: bigTextStyleInformation);
      var platformChannelSpecifics =
      NotificationDetails(androidPlatformChannelSpecifics, null);

      flutterLocalNotificationsPlugin.show(5, 'Let\'s Get Wride!',
          'You Have Got A New Trip!', platformChannelSpecifics,);
    }
  }
  return null;
}

E/MethodChannel#dexterous.com/flutter/local_notifications(15092): Failed to handle method call
E/MethodChannel#dexterous.com/flutter/local_notifications(15092): java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.setSmallIcon(FlutterLocalNotificationsPlugin.java:208)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.createNotification(FlutterLocalNotificationsPlugin.java:180)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.showNotification(FlutterLocalNotificationsPlugin.java:693)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.show(FlutterLocalNotificationsPlugin.java:785)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:714)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:231)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:93)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:642)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at android.os.MessageQueue.next(MessageQueue.java:326)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at android.os.Looper.loop(Looper.java:190)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at android.app.ActivityThread.main(ActivityThread.java:7211)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:575)
E/MethodChannel#dexterous.com/flutter/local_notifications(15092):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:903)
E/flutter (15092): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(error, Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference, null)
E/flutter (15092): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
E/flutter (15092): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:321:33)
E/flutter (15092): <asynchronous suspension>
E/flutter (15092): #2      AndroidFlutterLocalNotificationsPlugin.show (package:flutter_local_notifications/src/platform_flutter_local_notifications.dart:135:21)
E/flutter (15092): #3      FlutterLocalNotificationsPlugin.show (package:flutter_local_notifications/src/flutter_local_notifications_plugin.dart:93:13)
E/flutter (15092): #4      messageHandle (package:wride/SplashScreen/SplashScreen.dart:155:39)
E/flutter (15092): #5      _fcmSetupBackgroundChannel.<anonymous closure> (package:firebase_messaging/firebase_messaging.dart:38:30)
E/flutter (15092): #6      MethodChannel._handleAsMethodCall (package:flutter/src/services/platform_channel.dart:402:55)
E/flutter (15092): #7      MethodChannel.setMethodCallHandler.<anonymous closure> (package:flutter/src/services/platform_channel.dart:370:54)
E/flutter (15092): #8      _DefaultBinaryMessenger.handlePlatformMessage (package:flutter/src/services/binding.dart:200:33)
E/flutter (15092): #9      _invoke3.<anonymous closure> (dart:ui/hooks.dart:303:15)
E/flutter (15092): #10     _rootRun (dart:async/zone.dart:1126:13)
E/flutter (15092): #11     _CustomZone.run (dart:async/zone.dart:1023:19)
E/flutter (15092): #12     _CustomZone.runGuarded (dart:async/zone.dart:925:7)
E/flutter (15092): #13     _invoke3 (dart:ui/hooks.dart:302:10)
E/flutter (15092): #14     _dispatchPlatformMessage (dart:ui/hooks.dart:162:5)
E/flutter (15092):

I want to make my own stylish notification when background message triggers because FCM doesnot support Notification Styles.
Please Help!

Edit: I looked into the plugin FlutterLocalNotification and came to know that the NotificationDetails.java Line 151 Interger iconResourceID is null all the time. I don't know what to do now.

Body:
Okay, I got to know where is the mistake. I forgot to initialize the flutter local notification plugin with the app_icon. I changed my messageHandle method and it is working now.

  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
          new FlutterLocalNotificationsPlugin();
      var androidPlatformChannelSpecifics = AndroidNotificationDetails(
          '1687497218170948721x8',
          'New Trips Notification ',
          'Notification Channel for vendor. All the new trips notifications will arrive here.',
          style: AndroidNotificationStyle.BigText,
          icon: "app_icon",
          styleInformation: BigTextStyleInformation(
            "hanji hogya?",//  'Locations: <b>${locations.replaceAll("\$", " to ")}</b><br>Vehicle: <b>$vehicle</b><br>Trip Type: <b>$tripType</b><br>Pick-Up Date: <b>$pickUpDate</b><br>Pick-Up Time: <b>$pickUpTime</b>',
              htmlFormatBigText: true,
              contentTitle: 'Amount:- <b>Rs 22000000</b>',
              htmlFormatContentTitle: true,
              summaryText: 'Trip Details',
              htmlFormatSummaryText: true));


问:
How do you define an enumeration in 68000 assembly language?
I'm using the assembler that came with the Manx Aztec C compiler (version 5.0) on a Commodore Amiga 500.

I want to code the equivalent of the following C code:

```<code>enum STATUS {
    STATUS_OKAY,
    STATUS_WAITING,
    STATUS_ERROR
};
</code>```

I tried the following—which works—but it seems kind of hokey:

```<code>s_id            set 0
STATUS_OKAY     equ s_id
s_id            set s_id+1
STATUS_WAITING  equ s_id
s_id            equ s_id+1
STATUS_ERROR    equ s_id
</code>```

I know I could do:

```<code>STATUS_OKAY    equ 0
STATUS_WAITING equ 1
STATUS_ERROR   equ 2
</code>```

But I would like to be able to insert and rearrange values without having to manually renumber.

I was thinking I might be able to do something with macros, but I don't have much experience with them.

答:
I'd guess you'd want to write a macro that you can use like AUTONUMBER s_id STATUS_OKAY that takes two args: 2nd is the symbol name to define, 1st is the counter to increment.

You'd want it to expand to something like:

```<code>STATUS_OKAY     equ s_id
s_id            set s_id+1    # post-incr so it uses the initial value of s_id
</code>```

(I don't know that assembler or its syntax for defining macros; I assume that's possible though.)

Some assemblers have a special macro directive for redefining a preprocessor constant, allowing you to increment.  e.g. NASM wouldn't work with foo equ foo+1, you'd need %define.  You used s_id set s_id+1 in most of your lines, but equ in the last one, so that's probably just a typo.

So full usage would look like:

```<code>s_id  set 0       # starting value
AUTONUMBER s_id  STATUS_OKAY
AUTONUMBER s_id  STATUS_WAITING
AUTONUMBER s_id  STATUS_ERROR
</code>```

I put the counter name first because it's the same length every time (and short).  Putting it 2nd required more indenting to avoid ragged columns.  And it puts the unique part of the line at one end, where it's visually more obvious.

Body:
I'm using the assembler that came with the Manx Aztec C compiler (version 5.0) on a Commodore Amiga 500.

I want to code the equivalent of the following C code:

enum STATUS {
    STATUS_OKAY,
    STATUS_WAITING,
    STATUS_ERROR
};

I tried the following—which works—but it seems kind of hokey:

s_id            set 0
STATUS_OKAY     equ s_id
s_id            set s_id+1
STATUS_WAITING  equ s_id
s_id            equ s_id+1
STATUS_ERROR    equ s_id

I know I could do:

STATUS_OKAY    equ 0
STATUS_WAITING equ 1
STATUS_ERROR   equ 2

But I would like to be able to insert and rearrange values without having to manually renumber.

I was thinking I might be able to do something with macros, but I don't have much experience with them.

Body:
I'd guess you'd want to write a macro that you can use like AUTONUMBER s_id STATUS_OKAY that takes two args: 2nd is the symbol name to define, 1st is the counter to increment.

You'd want it to expand to something like:

STATUS_OKAY     equ s_id
s_id            set s_id+1    # post-incr so it uses the initial value of s_id

(I don't know that assembler or its syntax for defining macros; I assume that's possible though.)

Some assemblers have a special macro directive for redefining a preprocessor constant, allowing you to increment.  e.g. NASM wouldn't work with foo equ foo+1, you'd need %define.  You used s_id set s_id+1 in most of your lines, but equ in the last one, so that's probably just a typo.

So full usage would look like:

s_id  set 0       # starting value
AUTONUMBER s_id  STATUS_OKAY
AUTONUMBER s_id  STATUS_WAITING
AUTONUMBER s_id  STATUS_ERROR

I put the counter name first because it's the same length every time (and short).  Putting it 2nd required more indenting to avoid ragged columns.  And it puts the unique part of the line at one end, where it's visually more obvious.


问:
Impact of using AsParallel() and AsSequential() in the same query? C#
I was going through PLINQ in one of the books and it said:

If you have a complex query that can benefit from parallel processing
  but also has some parts that should be done sequentially, you can use
  the AsSequential to stop your query from being processed in parallel.

For Example:

```<code>var parallelResult = numbers.AsParallel().AsOrdered()
    .Where(i => i % 2 == 0).AsSequential();
</code>```

I want to understand why is it allowed and what is the impact on the result? Is it running parallel? Is it running sequential? It isn't making any sense right now.

答:
You may conceptualize a LINQ query as an atomic construct with a single execution plan, but it may be more helpful to conceptualize is as a pipeline consisting of multiple dataflow blocks. The output of each block becomes the input of the next block in the dataflow, and the blocks are processing items concurrently, as soon as they become available. Take a look for example to the next query, consisting of two "blocks" represented by the two Select operators. The first block is configured to process 3 items at a time (in parallel), while to second block is configured to process each item sequentially. The processing duration of each item is 1000 msec for the parallel block, and 500 msec for the sequential block:

```<code>var results = Partitioner
    .Create(Enumerable.Range(1, 10), EnumerablePartitionerOptions.NoBuffering)
    .AsParallel()
    .AsOrdered()
    .WithDegreeOfParallelism(3)
    .WithMergeOptions(ParallelMergeOptions.NotBuffered)
    .Select(x =>
    {
        Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}"
            + $" [{Thread.CurrentThread.ManagedThreadId}] Parallel #{x}");
        Thread.Sleep(1000); // Simulate some CPU-bound work
        return x;
    })
    .AsSequential()
    .Select(x =>
    {
        Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}"
            + $" [{Thread.CurrentThread.ManagedThreadId}] Sequential #{x}");
        Thread.Sleep(500); // Simulate some CPU-bound work
        return x;
    })
    .ToArray();
Console.WriteLine($"Results: {String.Join(", ", results)}");
</code>```

If you run this code you'll get an output like this:

08:32:17.628 [4] Parallel #2
08:32:17.628 [5] Parallel #1
08:32:17.628 [6] Parallel #3
08:32:18.642 [6] Parallel #5
08:32:18.642 [5] Parallel #4
08:32:18.644 [4] Parallel #6
08:32:18.651 [1] Sequential #1
08:32:19.644 [6] Parallel #7
08:32:19.645 [4] Parallel #8
08:32:19.646 [5] Parallel #9
08:32:19.654 [1] Sequential #2
08:32:20.156 [1] Sequential #3
08:32:20.648 [4] Parallel #10
08:32:20.658 [1] Sequential #4
08:32:21.161 [1] Sequential #5
08:32:21.663 [1] Sequential #6
08:32:22.164 [1] Sequential #7
08:32:22.672 [1] Sequential #8
08:32:23.173 [1] Sequential #9
08:32:23.675 [1] Sequential #10
Results: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
```
<p>Notice how the sequential processing is already started before all parallel processing has been completed. To achieve this effect I used the configuration options <code>EnumerablePartitionerOptions.NoBuffering</code> and <code>ParallelMergeOptions.NotBuffered</code>, to prevent the first block from buffering its input and output.</p>
<p>For completeness lets rewrite this query using the TPL Dataflow library. The code becomes more verbose and less fluent, but the control of execution becomes more precise, and also asynchronous workflows become available (PLINQ is not async-friendly):</p>
```var block1 = new TransformBlock<int, int>(async x =>
{
    Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}"
        + $" [{Thread.CurrentThread.ManagedThreadId}] Parallel #{x}");
    await Task.Delay(1000); // Simulate some I/O operation
    return x;
}, new ExecutionDataflowBlockOptions()
{
    MaxDegreeOfParallelism = 3,
    EnsureOrdered = true // redundant since EnsureOrdered is the default
});

var block2 = new TransformBlock<int, int>(async x =>
{
    Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}"
        + $" [{Thread.CurrentThread.ManagedThreadId}] Sequential #{x}");
    await Task.Delay(500); // Simulate some I/O operation
    return x;
}); // MaxDegreeOfParallelism = 1 is the default

block1.LinkTo(block2, new DataflowLinkOptions() { PropagateCompletion = true });

// Feeding the first block
foreach (var x in Enumerable.Range(1, 10))
{
    await block1.SendAsync(x);
}
block1.Complete();

var results = new List<int>(); // Collecting the results is a bit painful
while (await block2.OutputAvailableAsync())
{
    while (block2.TryReceive(out var result))
    {
        results.Add(result);
    }
}
await block2.Completion;
Console.WriteLine($"Results: {String.Join(", ", results)}");
```
<p>Output:</p>
<pre class="lang-xml prettyprint-override"><code>08:59:25.102 [6] Parallel #2
08:59:25.102 [4] Parallel #1
08:59:25.102 [7] Parallel #3
08:59:26.127 [7] Parallel #4
08:59:26.129 [6] Parallel #5
08:59:26.143 [4] Parallel #6
08:59:26.147 [5] Sequential #1
08:59:26.648 [5] Sequential #2
08:59:27.129 [6] Parallel #7
08:59:27.129 [7] Parallel #8
08:59:27.144 [4] Parallel #9
08:59:27.149 [5] Sequential #3
08:59:27.650 [5] Sequential #4
08:59:28.131 [6] Parallel #10
08:59:28.152 [5] Sequential #5
08:59:28.653 [5] Sequential #6
08:59:29.155 [5] Sequential #7
08:59:29.659 [5] Sequential #8
08:59:30.160 [5] Sequential #9
08:59:30.674 [5] Sequential #10
Results: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
</code>```

Body:
I was going through PLINQ in one of the books and it said:

If you have a complex query that can benefit from parallel processing
  but also has some parts that should be done sequentially, you can use
  the AsSequential to stop your query from being processed in parallel.

For Example:

var parallelResult = numbers.AsParallel().AsOrdered()
    .Where(i => i % 2 == 0).AsSequential();

I want to understand why is it allowed and what is the impact on the result? Is it running parallel? Is it running sequential? It isn't making any sense right now.

Body:
You may conceptualize a LINQ query as an atomic construct with a single execution plan, but it may be more helpful to conceptualize is as a pipeline consisting of multiple dataflow blocks. The output of each block becomes the input of the next block in the dataflow, and the blocks are processing items concurrently, as soon as they become available. Take a look for example to the next query, consisting of two "blocks" represented by the two Select operators. The first block is configured to process 3 items at a time (in parallel), while to second block is configured to process each item sequentially. The processing duration of each item is 1000 msec for the parallel block, and 500 msec for the sequential block:

var results = Partitioner
    .Create(Enumerable.Range(1, 10), EnumerablePartitionerOptions.NoBuffering)
    .AsParallel()
    .AsOrdered()
    .WithDegreeOfParallelism(3)
    .WithMergeOptions(ParallelMergeOptions.NotBuffered)
    .Select(x =>
    {
        Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}"
            + $" [{Thread.CurrentThread.ManagedThreadId}] Parallel #{x}");
        Thread.Sleep(1000); // Simulate some CPU-bound work
        return x;
    })
    .AsSequential()
    .Select(x =>
    {
        Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}"
            + $" [{Thread.CurrentThread.ManagedThreadId}] Sequential #{x}");
        Thread.Sleep(500); // Simulate some CPU-bound work
        return x;
    })
    .ToArray();
Console.WriteLine($"Results: {String.Join(", ", results)}");

If you run this code you'll get an output like this:

08:32:17.628 [4] Parallel #2
08:32:17.628 [5] Parallel #1
08:32:17.628 [6] Parallel #3
08:32:18.642 [6] Parallel #5
08:32:18.642 [5] Parallel #4
08:32:18.644 [4] Parallel #6
08:32:18.651 [1] Sequential #1
08:32:19.644 [6] Parallel #7
08:32:19.645 [4] Parallel #8
08:32:19.646 [5] Parallel #9
08:32:19.654 [1] Sequential #2
08:32:20.156 [1] Sequential #3
08:32:20.648 [4] Parallel #10
08:32:20.658 [1] Sequential #4
08:32:21.161 [1] Sequential #5
08:32:21.663 [1] Sequential #6
08:32:22.164 [1] Sequential #7
08:32:22.672 [1] Sequential #8
08:32:23.173 [1] Sequential #9
08:32:23.675 [1] Sequential #10
Results: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Notice how the sequential processing is already started before all parallel processing has been completed. To achieve this effect I used the configuration options EnumerablePartitionerOptions.NoBuffering and ParallelMergeOptions.NotBuffered, to prevent the first block from buffering its input and output.

For completeness lets rewrite this query using the TPL Dataflow library. The code becomes more verbose and less fluent, but the control of execution becomes more precise, and also asynchronous workflows become available (PLINQ is not async-friendly):

var block1 = new TransformBlock<int, int>(async x =>
{
    Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}"
        + $" [{Thread.CurrentThread.ManagedThreadId}] Parallel #{x}");
    await Task.Delay(1000); // Simulate some I/O operation
    return x;
}, new ExecutionDataflowBlockOptions()
{
    MaxDegreeOfParallelism = 3,
    EnsureOrdered = true // redundant since EnsureOrdered is the default
});

var block2 = new TransformBlock<int, int>(async x =>
{
    Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}"
        + $" [{Thread.CurrentThread.ManagedThreadId}] Sequential #{x}");
    await Task.Delay(500); // Simulate some I/O operation
    return x;
}); // MaxDegreeOfParallelism = 1 is the default

block1.LinkTo(block2, new DataflowLinkOptions() { PropagateCompletion = true });

// Feeding the first block
foreach (var x in Enumerable.Range(1, 10))
{
    await block1.SendAsync(x);
}
block1.Complete();

var results = new List<int>(); // Collecting the results is a bit painful
while (await block2.OutputAvailableAsync())
{
    while (block2.TryReceive(out var result))
    {
        results.Add(result);
    }
}
await block2.Completion;
Console.WriteLine($"Results: {String.Join(", ", results)}");

Output:

08:59:25.102 [6] Parallel #2
08:59:25.102 [4] Parallel #1
08:59:25.102 [7] Parallel #3
08:59:26.127 [7] Parallel #4
08:59:26.129 [6] Parallel #5
08:59:26.143 [4] Parallel #6
08:59:26.147 [5] Sequential #1
08:59:26.648 [5] Sequential #2
08:59:27.129 [6] Parallel #7
08:59:27.129 [7] Parallel #8
08:59:27.144 [4] Parallel #9
08:59:27.149 [5] Sequential #3
08:59:27.650 [5] Sequential #4
08:59:28.131 [6] Parallel #10
08:59:28.152 [5] Sequential #5
08:59:28.653 [5] Sequential #6
08:59:29.155 [5] Sequential #7
08:59:29.659 [5] Sequential #8
08:59:30.160 [5] Sequential #9
08:59:30.674 [5] Sequential #10
Results: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10


问:
In Spark, how to do One Hot Encoding for top N frequent values only?
Let, in my dataframe df, I have a column my_category in which I have different values, and I can view the value counts using:

```<code>df.groupBy("my_category").count().show()

value   count
a    197
b    166
c    210
d      5
e      2
f      9
g      3
</code>```

Now, I'd like to apply One Hot Encoding (OHE) on this column, but for the top N frequent values only (say N = 3), and put all the rest infrequent values in a dummy column (say, "default"). E.g., the output should be something like:

```<code>a  b  c  default
0  0  1  0
1  0  0  0
0  1  0  0
1  0  0  0
...
0  0  0  1
0  0  0  1
...
</code>```

How do I do this in Spark/Scala?

Note:
I know how to do this in Python, e.g., by first building a frequent-based dictionary for each unique value, and then create the OHE vector by examining the values one by one, putting the infrequent ones in a "default" column.

答:
A custom function could be written as, to apply One Hot Encoding (OHE) on a particular column, for the top N frequent values only (say N = 3).

It is relatively similar to Python, 1) Building a top n frequent-based Dataframe/Dictionary. 2) Pivot the top n frequent Dataframe i.e create the OHE vector. 3) Left join the given Dataframe and pivoted Dataframe, replace null with 0 i.e the default OHE vector.

```<code>import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.functions.{col, lit, when}
import org.apache.spark.sql.Column

import spark.implicits._
val df = spark
  .sparkContext
  .parallelize(Seq("a", "b", "c", "a", "b", "c", "d", "e", "a", "b", "f", "a", "g", "a", "b", "c", "a", "d", "e", "f", "a", "b", "g", "b", "c", "f", "a", "b", "c"))
  .toDF("value")

val oheEncodedDF = oheEncoding(df, "value", 3)

def oheEncoding(df: DataFrame, colName: String, n: Int): DataFrame = {
  df.createOrReplaceTempView("data")
  val topNDF = spark.sql(s"select $colName, count(*) as count from data group by $colName order by count desc limit $n")

  val pivotTopNDF = topNDF
    .groupBy(colName)
    .pivot(colName)
    .count()
    .withColumn("default", lit(1))

  val joinedTopNDF = df.join(pivotTopNDF, Seq(colName), "left").drop(colName)

  val oheEncodedDF = joinedTopNDF
    .na.fill(0, joinedTopNDF.columns)
    .withColumn("default", flip(col("default")))

   oheEncodedDF
}

def flip(col: Column): Column = when(col === 1, lit(0)).otherwise(lit(1))
</code>```

Body:
Let, in my dataframe df, I have a column my_category in which I have different values, and I can view the value counts using:

df.groupBy("my_category").count().show()

value   count
a    197
b    166
c    210
d      5
e      2
f      9
g      3

Now, I'd like to apply One Hot Encoding (OHE) on this column, but for the top N frequent values only (say N = 3), and put all the rest infrequent values in a dummy column (say, "default"). E.g., the output should be something like:

a  b  c  default
0  0  1  0
1  0  0  0
0  1  0  0
1  0  0  0
...
0  0  0  1
0  0  0  1
...

How do I do this in Spark/Scala?

Note:
I know how to do this in Python, e.g., by first building a frequent-based dictionary for each unique value, and then create the OHE vector by examining the values one by one, putting the infrequent ones in a "default" column.

Body:
A custom function could be written as, to apply One Hot Encoding (OHE) on a particular column, for the top N frequent values only (say N = 3).

It is relatively similar to Python, 1) Building a top n frequent-based Dataframe/Dictionary. 2) Pivot the top n frequent Dataframe i.e create the OHE vector. 3) Left join the given Dataframe and pivoted Dataframe, replace null with 0 i.e the default OHE vector.

import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.functions.{col, lit, when}
import org.apache.spark.sql.Column

import spark.implicits._
val df = spark
  .sparkContext
  .parallelize(Seq("a", "b", "c", "a", "b", "c", "d", "e", "a", "b", "f", "a", "g", "a", "b", "c", "a", "d", "e", "f", "a", "b", "g", "b", "c", "f", "a", "b", "c"))
  .toDF("value")

val oheEncodedDF = oheEncoding(df, "value", 3)

def oheEncoding(df: DataFrame, colName: String, n: Int): DataFrame = {
  df.createOrReplaceTempView("data")
  val topNDF = spark.sql(s"select $colName, count(*) as count from data group by $colName order by count desc limit $n")

  val pivotTopNDF = topNDF
    .groupBy(colName)
    .pivot(colName)
    .count()
    .withColumn("default", lit(1))

  val joinedTopNDF = df.join(pivotTopNDF, Seq(colName), "left").drop(colName)

  val oheEncodedDF = joinedTopNDF
    .na.fill(0, joinedTopNDF.columns)
    .withColumn("default", flip(col("default")))

   oheEncodedDF
}

def flip(col: Column): Column = when(col === 1, lit(0)).otherwise(lit(1))


问:
Can't create a python virtual environment on Ubuntu 18.04
I'm a complete beginner to Ubuntu and I'm trying to create a virtual environment on Ubuntu 18.04. I had one running and it was working just fine, but I don't know what I did and know I cant get it to run.

I deleted my old env/ file and now I'm trying to create a new one using

```<code>python3 -m venv env
</code>```

but I get the following error

Error: Command '['/home/user/app/env/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit s
  tatus 1.

What gives?

答:
just reinstall your python3-venv

```<code>apt-get purge python3-venv

apt-get install python3-venv
</code>```

and then create the virtualenv

```<code> python3.7 -m venv venvTest
</code>```

if you have different version of python3, you should mention the exact python3 version.
  you can also migrate your python3.6 to python3.7 by following guide migrate python3.6 to python3.7

Body:
I'm a complete beginner to Ubuntu and I'm trying to create a virtual environment on Ubuntu 18.04. I had one running and it was working just fine, but I don't know what I did and know I cant get it to run.

I deleted my old env/ file and now I'm trying to create a new one using

python3 -m venv env

but I get the following error

Error: Command '['/home/user/app/env/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit s
  tatus 1.

What gives?

Body:
just reinstall your python3-venv

apt-get purge python3-venv

apt-get install python3-venv

and then create the virtualenv

 python3.7 -m venv venvTest

if you have different version of python3, you should mention the exact python3 version.
  you can also migrate your python3.6 to python3.7 by following guide migrate python3.6 to python3.7