问:
DiscordJS audio playback with multiple streams
I'm trying to create a discord bot using discord.js that is able to both play music and sound effects.

The bot correctly plays music, but when trying to play a sound effect during music playback, the sound effect never starts/ends.

I have the following code for playing sound effects.

```<code>function play(guildID, serverQueue, resource){
    const newAudioPlayer = createAudioPlayer();
    const oldAudioPlayer = serverQueue.audioPlayer;

    const connection = getVoiceConnection(guildID)

    oldAudioPlayer.pause();
    connection.subscribe(newAudioPlayer);

    newAudioPlayer.on(AudioPlayerStatus.Idle, () => {
        console.log("Done playing");
        connection.subscribe(oldAudioPlayer);
        oldAudioPlayer.unpause();
        newAudioPlayer.stop();
    }).on('error', err => {
        console.log("Something went wrong when trying to play sound effect");
        console.log(err);
        connection.subscribe(oldAudioPlayer);
        oldAudioPlayer.unpause();
        newAudioPlayer.stop();
    })

    newAudioPlayer.play(resource);
    console.log("Trying to play");
}
</code>```

I realize that a voice connection can only subscribe to one audioplayer at a time and that an audioplayer can only play one resource at a time. This is why, I create a new temporary audio player called "newAudioPlayer" that will play the short sound effect. I then pause the old audio player and subscribe the connection to the new audio player.

The sound effect is correctly played as long as the oldAudioPlayer has not been used to play a resource before. As soon as the oldAudioPlayer has been used to play a resource, the newAudioPlayer never starts playing the resource. I have checked all the different AudioPlayerStates for the newAudioPlayer, but none of them get triggered.

serverQueue.audioPlayer is initialized when a voice channel is joined, and is always set.

The program does print "Trying to play" but no audio can be heard.

答:
Apparently this is a known issue with discord.js:

https://github.com/discordjs/discord.js/issues/7232

The workaround is to play the local file as a stream if the file for the other audioPlayer is also reading a stream.

Body:
I'm trying to create a discord bot using discord.js that is able to both play music and sound effects.

The bot correctly plays music, but when trying to play a sound effect during music playback, the sound effect never starts/ends.

I have the following code for playing sound effects.

function play(guildID, serverQueue, resource){
    const newAudioPlayer = createAudioPlayer();
    const oldAudioPlayer = serverQueue.audioPlayer;

    const connection = getVoiceConnection(guildID)

    oldAudioPlayer.pause();
    connection.subscribe(newAudioPlayer);

    newAudioPlayer.on(AudioPlayerStatus.Idle, () => {
        console.log("Done playing");
        connection.subscribe(oldAudioPlayer);
        oldAudioPlayer.unpause();
        newAudioPlayer.stop();
    }).on('error', err => {
        console.log("Something went wrong when trying to play sound effect");
        console.log(err);
        connection.subscribe(oldAudioPlayer);
        oldAudioPlayer.unpause();
        newAudioPlayer.stop();
    })

    newAudioPlayer.play(resource);
    console.log("Trying to play");
}

I realize that a voice connection can only subscribe to one audioplayer at a time and that an audioplayer can only play one resource at a time. This is why, I create a new temporary audio player called "newAudioPlayer" that will play the short sound effect. I then pause the old audio player and subscribe the connection to the new audio player.

The sound effect is correctly played as long as the oldAudioPlayer has not been used to play a resource before. As soon as the oldAudioPlayer has been used to play a resource, the newAudioPlayer never starts playing the resource. I have checked all the different AudioPlayerStates for the newAudioPlayer, but none of them get triggered.

serverQueue.audioPlayer is initialized when a voice channel is joined, and is always set.

The program does print "Trying to play" but no audio can be heard.


来源: stackexchange

问:
Getting max values based on sliced column
Let's consider this Dataframe:

```<code>$> df
   a    b
0  6   50
1  2   20
2  9   60
3  4   40
4  5   20
</code>```

I want to compute column D based on:

The max value between:

integer 0

A slice of column B at that row's index

So I have created a column C (all zeroes) in my dataframe in order use DataFrame.max(axis=1). However, short of using apply or looping over the DataFrame, I don't know how to slice the input values. Expected result would be:

```<code>$> df
   a    b  c    d
0  6   50  0   60
1  2   20  0   60
2  9   60  0   60
3  4   40  0   40
4  5   20  0   20
</code>```

So essentially, d's 3rd row is computed (pseudo-code) as max(df[3:,"b"], df[3:,"c"]), and similarly for each row.

Since the input columns (b, c) have already been computed, there has to be a way to slice the input as I calculate each row for D without having to loop, as this is slow.

答:
Seems like this could work: Reverse "B", find cummax, then reverse it back and assign it to "d". Then use where on "d" to see if any value is less than 0:

```<code>df['d'] = df['b'][::-1].cummax()[::-1]
df['d'] = df['d'].where(df['d']>0, 0)
</code>```

We can replace the last line with the one below using clip (thanks @Either), and drop the 2nd reversal (assuming indexes match) making it all a one liner:

```<code>df['d'] = df['b'][::-1].cummax().clip(lower=0)
</code>```

Output:

```<code>   a   b   d
0  6  50  60
1  2  20  60
2  9  60  60
3  4  40  40
4  5  20  20
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Let's consider this Dataframe:

$> df
   a    b
0  6   50
1  2   20
2  9   60
3  4   40
4  5   20

I want to compute column D based on:

The max value between:

integer 0

A slice of column B at that row's index

So I have created a column C (all zeroes) in my dataframe in order use DataFrame.max(axis=1). However, short of using apply or looping over the DataFrame, I don't know how to slice the input values. Expected result would be:

$> df
   a    b  c    d
0  6   50  0   60
1  2   20  0   60
2  9   60  0   60
3  4   40  0   40
4  5   20  0   20

So essentially, d's 3rd row is computed (pseudo-code) as max(df[3:,"b"], df[3:,"c"]), and similarly for each row.

Since the input columns (b, c) have already been computed, there has to be a way to slice the input as I calculate each row for D without having to loop, as this is slow.

Body:
Seems like this could work: Reverse "B", find cummax, then reverse it back and assign it to "d". Then use where on "d" to see if any value is less than 0:

df['d'] = df['b'][::-1].cummax()[::-1]
df['d'] = df['d'].where(df['d']>0, 0)

We can replace the last line with the one below using clip (thanks @Either), and drop the 2nd reversal (assuming indexes match) making it all a one liner:

df['d'] = df['b'][::-1].cummax().clip(lower=0)

Output:

   a   b   d
0  6  50  60
1  2  20  60
2  9  60  60
3  4  40  40
4  5  20  20


问:
debug stack overflow in windows?
So I'm trying to debug this strange problem where a process ends without calling some destructors...

In the VS (2005) debugger, I hit 'Break all' and look around in the call stacks of the threads of the misteriously disappearing process, when I see this:

smells like SO http://img6.imageshack.us/img6/7628/95434880.jpg

This definitely looks like a SO in the making, which would explain why the process runs to its happy place without packing its suitcase first.

The problem is, the VS debugger's call stack only shows what you can see in the image.

So my question is: how can I find where the infinite recursion call starts?

I read somewhere that in Linux you can attach a callback to the SIGSEGV handler and get more info on what's going on.

Is there anything similar on Windows?

答:
Well, you know what thread the problem is on - it might be a simple matter of tracing through it from inception to see where it goes off into the weeds.

Another option is to use one of the debuggers in the Debugging Tools for Windows package - they may be able to show more than the VS debugger (maybe), even if they are generally more complex and difficult to use (actually maybe because of that).

OwnerDisplayName: Cristi Diaconescu

ContentLicense: CC BY-SA 2.5

Title: debug stack overflow in windows?

LastEditorDisplayName: Jason

OwnerDisplayName: Michael Burr


问:
Emacs - cursor misalignment, and disappearing text
I've been using a copy of emacs (in a Debian VM I ssh to with putty) at work for a couple of months now, and up until now everything has been working brilliantly... but this morning I'm trying to edit a file in shell-script-mode, and am seeing some weird behavior with text around the cursor.

Basically, when I type the following ( [ ] represents my cursor):

```<code>export DATABASE[]
</code>```

After I've typed the first few characters of the variable name the export statement disappears and the variable name aligns to the left margin, and all I end up seeing is (with the cursor out in the wilderness):

```<code>DATABASE       []
</code>```

If I then hit CTRL-L, the screen refreshes, and I see the text as it should be displayed... until I start typing, and then the buffer start acting strangly again (characters disappearing, moving, cursor ending up in the wrong place, etc)

I've not, to my knowledge, added anything to my .emacs file since this last worked as I expect it to, so I'm at a loss as to what could be happening here.  It doesn't seem specific to sh-mode either - I've tested a few other file types and observed similar strange behavior.  Are there any emacs afficianados out there who might be able to point me in the right direction to figure out what's wrong here?

Thanks in advance

答:
I'm not sure what to suggest, but this sounds awfully like an issue with the terminal: I suspect that Emacs redraws the current line whenever it changes and I guess it tries to do so incrementally. If something's got out of whack with your terminal, then it seems quite plausible that the current word would get written at the start of the line (all Emacs sent) and your cursor would get abandoned "out in the wilderness" :-)

Obviously, this is a new change. Since it doesn't sound like the sort of issue that would be caused by Elisp configurations in your .emacs, you should check whether you've recently upgraded one of

PuTTY

Emacs version

SSH version (unlikely...)

Then maybe the relevant tool will have something in the changelog (which maybe you can disable via a config?)

One thing you could check: you say this isn't just SH-mode. Is it "any mode with syntax highlighting"? Maybe Emacs just sends over the wire the text with the current colour?

ContentLicense: CC BY-SA 3.0

Body:
I've been using a copy of emacs (in a Debian VM I ssh to with putty) at work for a couple of months now, and up until now everything has been working brilliantly... but this morning I'm trying to edit a file in shell-script-mode, and am seeing some weird behavior with text around the cursor.

Basically, when I type the following ( [ ] represents my cursor):

export DATABASE[]

After I've typed the first few characters of the variable name the export statement disappears and the variable name aligns to the left margin, and all I end up seeing is (with the cursor out in the wilderness):

DATABASE       []

If I then hit CTRL-L, the screen refreshes, and I see the text as it should be displayed... until I start typing, and then the buffer start acting strangly again (characters disappearing, moving, cursor ending up in the wrong place, etc)

I've not, to my knowledge, added anything to my .emacs file since this last worked as I expect it to, so I'm at a loss as to what could be happening here.  It doesn't seem specific to sh-mode either - I've tested a few other file types and observed similar strange behavior.  Are there any emacs afficianados out there who might be able to point me in the right direction to figure out what's wrong here?

Thanks in advance


问:
Spring OSGi integration: ClassCastException when getting osgi service in springContext
New to OSGi. I'm trying to get a service from osgi in Spring. Git link for the code : https://github.com/shinevs/SpringIntegrationTest
Getting ClassCastException.

```<code>java.lang.ClassCastException: com.bundle.Activator cannot be cast to com.myInterface.BundleInterface
    at com.osgi.OSGiLauncher.lambda$0(OSGiLauncher.java:39)
    at org.apache.felix.framework.EventDispatcher.invokeBundleListenerCallback(EventDispatcher.java:915)
    at org.apache.felix.framework.EventDispatcher.fireEventImmediately(EventDispatcher.java:834)
    at org.apache.felix.framework.EventDispatcher.run(EventDispatcher.java:1147)
    at org.apache.felix.framework.EventDispatcher.access$000(EventDispatcher.java:54)
    at org.apache.felix.framework.EventDispatcher$1.run(EventDispatcher.java:102)
    at java.lang.Thread.run(Thread.java:748)
</code>```

I'm trying to initialize an OSGi bundle jar from spring service. OSGi bundle register a service called Activator, once OSGi bundle initialized and Activator created, trying to access the Activator from Spring.

Note : OSGi bundle is another module, it is added part of this project for testing purpose. Spring App only need a OSGi bundle as a jar.

How to run : curl http://localhost:8080/osgi

Issues facing : Spring App while trying to access Activator, it is throwing ClassCastException

Is this due to Different class loaders in spring and osgi. I tried to implement fragment, but that also didn't work.

答:
It seems to me you are trying to exfiltrate a type (com.myInterface.BundleInterface) from inside the OSGi environment to outside into the Spring environment. But the BundleInterface is loaded by the OSGi loader and it unknown to the Spring environment loader. If you have added the test bundle into Spring Boot environment than it will have different class loader than the OSGi environment instance and thus you get the cast failure.

I suggest you avoid trying to use the OSGi environment inside Spring Boot application. I see only pain and suffering in that direction.

Body:
New to OSGi. I'm trying to get a service from osgi in Spring. Git link for the code : https://github.com/shinevs/SpringIntegrationTest
Getting ClassCastException.

java.lang.ClassCastException: com.bundle.Activator cannot be cast to com.myInterface.BundleInterface
    at com.osgi.OSGiLauncher.lambda$0(OSGiLauncher.java:39)
    at org.apache.felix.framework.EventDispatcher.invokeBundleListenerCallback(EventDispatcher.java:915)
    at org.apache.felix.framework.EventDispatcher.fireEventImmediately(EventDispatcher.java:834)
    at org.apache.felix.framework.EventDispatcher.run(EventDispatcher.java:1147)
    at org.apache.felix.framework.EventDispatcher.access$000(EventDispatcher.java:54)
    at org.apache.felix.framework.EventDispatcher$1.run(EventDispatcher.java:102)
    at java.lang.Thread.run(Thread.java:748)

I'm trying to initialize an OSGi bundle jar from spring service. OSGi bundle register a service called Activator, once OSGi bundle initialized and Activator created, trying to access the Activator from Spring.

Note : OSGi bundle is another module, it is added part of this project for testing purpose. Spring App only need a OSGi bundle as a jar.

How to run : curl http://localhost:8080/osgi

Issues facing : Spring App while trying to access Activator, it is throwing ClassCastException

Is this due to Different class loaders in spring and osgi. I tried to implement fragment, but that also didn't work.


问:
How to implement Filter in Material table in Angular?
.HTML:

How to implement the filter in this component as I have implemented it with the expansion table, but my filter is not working.

```<code>    <mat-dialog-content style="width: 63rem; overflow: initial;">
      <div class="searchField">
        <mat-form-field appearance="standard">
          <mat-label>Filter</mat-label>
          <input matInput (keyup)="applyFilter($event)" placeholder="Ex. Tele" #input>
        </mat-form-field>
      </div>

    </mat-dialog-content>
</code>```

.TS:

```<code>    getProductList() {
        this.commonservice.getProdList().subscribe((response: any) => {
          console.log('Response from API is ', response);
          if (response) {
            this.productInfo = response;
            this.dataSource = this.productInfo;
            console.log('Product Info ', this.productInfo);
          }
        }, (error) => {
          console.log('Error is ', error);
        });
      }

    applyFilter(event: Event) {
        const filterValue = (event.target as HTMLInputElement).value;
        this.dataSource.filter = filterValue.trim().toLocaleLowerCase();
        console.log('filtered data ', this.dataSource.filter);
      }

</code>```

答:
Assuming dataSource is an array</p>
```<code>this.dataSource = this.dataSource.filter((d)=>d === filterValue.trim().toLocaleLowerCase());
</code>```

Body:
.HTML:

How to implement the filter in this component as I have implemented it with the expansion table, but my filter is not working.

    <mat-dialog-content style="width: 63rem; overflow: initial;">

        <mat-form-field appearance="standard">
          <mat-label>Filter</mat-label>
          <input matInput (keyup)="applyFilter($event)" placeholder="Ex. Tele" #input>
        </mat-form-field>

    </mat-dialog-content>

.TS:

    getProductList() {
        this.commonservice.getProdList().subscribe((response: any) => {
          console.log('Response from API is ', response);
          if (response) {
            this.productInfo = response;
            this.dataSource = this.productInfo;
            console.log('Product Info ', this.productInfo);
          }
        }, (error) => {
          console.log('Error is ', error);
        });
      }

    applyFilter(event: Event) {
        const filterValue = (event.target as HTMLInputElement).value;
        this.dataSource.filter = filterValue.trim().toLocaleLowerCase();
        console.log('filtered data ', this.dataSource.filter);
      }

Body:
Assuming dataSource is an array

this.dataSource = this.dataSource.filter((d)=>d === filterValue.trim().toLocaleLowerCase());


问:
Measure to apply calculation based on column value (i.e case statement in SQL terms)
very new to DAX here. I'm trying to apply a calculation based on the value or "category" of a column.

I've got the calculation to work but it's only displaying the rows where the calculation criteria is met. What i'd like to do is say IF the value is in "CancelRT", "NoShowRT","FillRate", etc... then perform this calculation, otherwise leave the value in "newunits" be.

The following works but only returns the rows that contain the values specified:

```<code>Percentages =
DIVIDE (
Calculate(
SUM ( MMP_Dashboards_WMH_PBI[NewUnits] ),  MMP_Dashboards_WMH_PBI[Revenue_center]="FillRate" ||MMP_Dashboards_WMH_PBI[Revenue_center]="CancelRT" ||MMP_Dashboards_WMH_PBI[Revenue_center]="NoShowRT" || MMP_Dashboards_WMH_PBI[Revenue_center]="ExamRt"
),

COUNTROWS ( VALUES ( MMP_Dashboards_WMH_PBI[Provider_Finance] ) )
)
</code>```

What I'd like to see is IF Revenue_Center IN ("FilRate","CancelRt","NoshowRT",ExamRt" Then do the calculation, otherwise Just use NewUnits

I've tried playing around with the following but the syntax is definitely off:

```<code>Units=

IF (
    MMP_Dashboards_WMH_PBI[Revenue_center]) IN {"FillRate","CancelRt","NoShowRt","ExamRt"}

DIVIDE (
Calculate(
SUM ( MMP_Dashboards_WMH_PBI[NewUnits] ),
),

COUNTROWS ( VALUES ( MMP_Dashboards_WMH_PBI[Provider_Finance] ) )
)
)
</code>```

Thank you all in advance for any assistance you can provide!

The Data Looks something like this:

```<code>Provider_Finance   Revenue_Center       NewUnits
John               Surgical             47.000
OSBORN             Testing              1.000
RAZDAN             FillRate             1.000
RAZDAN             FillRate             1.000
ANDREW             Exams                120.000

</code>```

When grouped on the report I want to get the average for Razdan based on the revenue center being "FillRate" and taking the count of "Provider Finance" (2) and the other metrics to be left as is:

```<code>Provider_Finance   Revenue_Center       NewUnits
John               Surgical             47.000
OSBORN             Testing              1.000
RAZDAN             FillRate             1.000 --The average
ANDREW             Exams                120.000
</code>```

In my first code example it returns the data set below which works, but only includes the fillrate metric as it's filtering the other non-calculated values out.

```<code>Provider_Finance   Revenue_Center       NewUnits
RAZDAN             FillRate             1.000 --The average
</code>```

答:
Finally got it</p>
```<code>Units =
 SUMX(MMP_Dashboards_WMH_PBI, IF (MMP_Dashboards_WMH_PBI[Revenue_Center]IN {"FillRate","CancelRt","NoShowRt","ExamRt"},
DIVIDE (
Calculate(
SUM ( MMP_Dashboards_WMH_PBI[NewUnits] ), MMP_Dashboards_WMH_PBI[Revenue_Center] IN {"FillRate","CancelRt","NoShowRt","ExamRt"}
),

COUNTROWS ( VALUES ( MMP_Dashboards_WMH_PBI[Provider_Finance] ))
),MMP_Dashboards_WMH_PBI[NewUnits]
))
</code>```

Body:
very new to DAX here. I'm trying to apply a calculation based on the value or "category" of a column.

I've got the calculation to work but it's only displaying the rows where the calculation criteria is met. What i'd like to do is say IF the value is in "CancelRT", "NoShowRT","FillRate", etc... then perform this calculation, otherwise leave the value in "newunits" be.

The following works but only returns the rows that contain the values specified:

Percentages =
DIVIDE (
Calculate(
SUM ( MMP_Dashboards_WMH_PBI[NewUnits] ),  MMP_Dashboards_WMH_PBI[Revenue_center]="FillRate" ||MMP_Dashboards_WMH_PBI[Revenue_center]="CancelRT" ||MMP_Dashboards_WMH_PBI[Revenue_center]="NoShowRT" || MMP_Dashboards_WMH_PBI[Revenue_center]="ExamRt"
),

COUNTROWS ( VALUES ( MMP_Dashboards_WMH_PBI[Provider_Finance] ) )
)

What I'd like to see is IF Revenue_Center IN ("FilRate","CancelRt","NoshowRT",ExamRt" Then do the calculation, otherwise Just use NewUnits

I've tried playing around with the following but the syntax is definitely off:

Units=

IF (
    MMP_Dashboards_WMH_PBI[Revenue_center]) IN {"FillRate","CancelRt","NoShowRt","ExamRt"}

DIVIDE (
Calculate(
SUM ( MMP_Dashboards_WMH_PBI[NewUnits] ),
),

COUNTROWS ( VALUES ( MMP_Dashboards_WMH_PBI[Provider_Finance] ) )
)
)

Thank you all in advance for any assistance you can provide!

The Data Looks something like this:

Provider_Finance   Revenue_Center       NewUnits
John               Surgical             47.000
OSBORN             Testing              1.000
RAZDAN             FillRate             1.000
RAZDAN             FillRate             1.000
ANDREW             Exams                120.000

When grouped on the report I want to get the average for Razdan based on the revenue center being "FillRate" and taking the count of "Provider Finance" (2) and the other metrics to be left as is:

Provider_Finance   Revenue_Center       NewUnits
John               Surgical             47.000
OSBORN             Testing              1.000
RAZDAN             FillRate             1.000 --The average
ANDREW             Exams                120.000

In my first code example it returns the data set below which works, but only includes the fillrate metric as it's filtering the other non-calculated values out.

Provider_Finance   Revenue_Center       NewUnits
RAZDAN             FillRate             1.000 --The average

Body:
Finally got it

Units =
 SUMX(MMP_Dashboards_WMH_PBI, IF (MMP_Dashboards_WMH_PBI[Revenue_Center]IN {"FillRate","CancelRt","NoShowRt","ExamRt"},
DIVIDE (
Calculate(
SUM ( MMP_Dashboards_WMH_PBI[NewUnits] ), MMP_Dashboards_WMH_PBI[Revenue_Center] IN {"FillRate","CancelRt","NoShowRt","ExamRt"}
),

COUNTROWS ( VALUES ( MMP_Dashboards_WMH_PBI[Provider_Finance] ))
),MMP_Dashboards_WMH_PBI[NewUnits]
))


问:
Zend Framework locale and translation problems in form with Zend_Locale, Zend_Translate and Zend_Form
I've been having a few problems with Zend_Locale and Zend_Translate, specifically with htmlentities. But there a couple of other oddities.

Firstly, in the Zend_Locale documentation it states:

Zend Framework allows the usage of an application wide locale. You
  simply set an instance of Zend_Locale to the registry with the key
  'Zend_Locale'. Then this instance will be used within all locale aware
  classes of Zend Framework

This does not seem to work with Zend_Translate, I'm assuming Zend_Translate is not a 'locale aware' class, weird that it isn't but no big problem I just had to set it explicitly. Below is the initLocale() function from my Bootstrap:

```<code>$session = new Zend_Session_Namespace();

// only if locale is explicitly set by user:
if(isset($_GET['locale']) && !empty($_GET['locale'])) {
    $session->locale = $_GET['locale'];
}

$locale = isset($session->locale) ? $session->locale : 'auto';

try {
    $zendLocale = new Zend_Locale($locale);
} catch (Zend_Locale_Exception $e) {
    $zendLocale = new Zend_Locale('en_CA');
}

Zend_Registry::set('Zend_Locale', $zendLocale);

require_once(APPLICATION_PATH . '/languages/translation.php');

$translate = new Zend_Translate(array(
    'adapter' => 'array',
    'content' => $english,
    'locale'  => 'en'
));

$translate->addTranslation(array(
    'content' => $french,
    'locale'  => 'fr'
));

$translate->setLocale($zendLocale->toString());
Zend_Registry::set('translate', $translate);
</code>```

As you can see here, I'm using the array adapter for Zend_Translate. My arrays are defined in translation.php.

Similarly to Zend_Locale in the documentation for Zend_Form (http://framework.zend.com/manual/en/zend.form.i18n.html) it says the easiest way to add translations to Zend_Form is to set a Zend_Translate object in the registry with a key of 'Zend_Translate' - easy, set this up and any of the form labels, error messages, etc. that have a matching translation in the arrays will be translated automagically. Problem is that my french translations have a lot of htmlentities. I could be wrong but I believe that Zend_Form's setLabel method escapes text, so my entities are getting converted twice. I tried removing all entities from the translations but this completely fails and gives me a blank output.

Does anyone have any ideas? htmlentities for translations seems like a major necessity right?

Currently I'm not doing this automatically but I've added an intermediate function to my form which does the following (where $this->_translate is a Zend_Translate object):

```<code>private function getTranslation($str) {
    return html_entity_decode($this->_translate->_($str), ENT_COMPAT, 'UTF-8');
}
</code>```

But this is far from ideal as I have to wrap every setLabel and errorMessage in this first, kind of missing the point of Zend's locale and translation classes.

答:
I've also used Zend_Translate together with the array adapter, to set the labels of a form. I didn't need to encode any character as HTML entities. As far as I know, it's enough to encode them as UTF-8. So, the wrapper you mention shouldn't be necessary.

I'm just adding Zend_Translate to the registry (with the 'Zend_Translate' key, otherwise it won't work), passing the translation keys to setLabel() directly and it works.

Hope that helps...

Body:
I've been having a few problems with Zend_Locale and Zend_Translate, specifically with htmlentities. But there a couple of other oddities.

Firstly, in the Zend_Locale documentation it states:

Zend Framework allows the usage of an application wide locale. You
  simply set an instance of Zend_Locale to the registry with the key
  'Zend_Locale'. Then this instance will be used within all locale aware
  classes of Zend Framework

This does not seem to work with Zend_Translate, I'm assuming Zend_Translate is not a 'locale aware' class, weird that it isn't but no big problem I just had to set it explicitly. Below is the initLocale() function from my Bootstrap:

$session = new Zend_Session_Namespace();

// only if locale is explicitly set by user:
if(isset($_GET['locale']) && !empty($_GET['locale'])) {
    $session->locale = $_GET['locale'];
}

$locale = isset($session->locale) ? $session->locale : 'auto';

try {
    $zendLocale = new Zend_Locale($locale);
} catch (Zend_Locale_Exception $e) {
    $zendLocale = new Zend_Locale('en_CA');
}

Zend_Registry::set('Zend_Locale', $zendLocale);

require_once(APPLICATION_PATH . '/languages/translation.php');

$translate = new Zend_Translate(array(
    'adapter' => 'array',
    'content' => $english,
    'locale'  => 'en'
));

$translate->addTranslation(array(
    'content' => $french,
    'locale'  => 'fr'
));

$translate->setLocale($zendLocale->toString());
Zend_Registry::set('translate', $translate);

As you can see here, I'm using the array adapter for Zend_Translate. My arrays are defined in translation.php.

Similarly to Zend_Locale in the documentation for Zend_Form (http://framework.zend.com/manual/en/zend.form.i18n.html) it says the easiest way to add translations to Zend_Form is to set a Zend_Translate object in the registry with a key of 'Zend_Translate' - easy, set this up and any of the form labels, error messages, etc. that have a matching translation in the arrays will be translated automagically. Problem is that my french translations have a lot of htmlentities. I could be wrong but I believe that Zend_Form's setLabel method escapes text, so my entities are getting converted twice. I tried removing all entities from the translations but this completely fails and gives me a blank output.

Does anyone have any ideas? htmlentities for translations seems like a major necessity right?

Currently I'm not doing this automatically but I've added an intermediate function to my form which does the following (where $this->_translate is a Zend_Translate object):

private function getTranslation($str) {
    return html_entity_decode($this->_translate->_($str), ENT_COMPAT, 'UTF-8');
}

But this is far from ideal as I have to wrap every setLabel and errorMessage in this first, kind of missing the point of Zend's locale and translation classes.


问:
In SQL filter out one column records based on different column condition
I have 2 columns Source_System, SBG_NAME. I want to filter out Source_System Microsiga for SBG_NAME PMT

Data set is like this:

Source_System
SBG_Name

CIP300
PMT

Microsiga
PMT

CIP900
HBT

Microsiga
HBT

The output should be

Source_System
SBG_Name

CIP300
PMT

CIP900
HBT

Microsiga
HBT

答:
```<code>SELECT
"Source_System"
,"SBG_Name"
FROM table

MINUS

SELECT
"Source_System"
,"SBG_Name"
FROM table
WHERE "Source_System" = 'Microsiga' and "SBG_Name" = 'PMT'
</code>```

You could get the result with something like this. This shows all records, except the ones where Source_System is Microsiga and SBG_Name is PMT.

Alternatively this yields the same result and is even more compact:

```<code>SELECT
"Source_System"
,"SBG_Name"
FROM table
WHERE  NOT ("Source_System" = 'Microsiga' and "SBG_Name" = 'PMT')
</code>```

Body:
SELECT
"Source_System"
,"SBG_Name"
FROM table

MINUS

SELECT
"Source_System"
,"SBG_Name"
FROM table
WHERE "Source_System" = 'Microsiga' and "SBG_Name" = 'PMT'

You could get the result with something like this. This shows all records, except the ones where Source_System is Microsiga and SBG_Name is PMT.

Alternatively this yields the same result and is even more compact:

SELECT
"Source_System"
,"SBG_Name"
FROM table
WHERE  NOT ("Source_System" = 'Microsiga' and "SBG_Name" = 'PMT')


问:
How to mount a host directory with non-root ownership
I use build-arg to ensure my container runs with the same UID as my host user:

```<code>--build-arg UID=$(UID)
</code>```

I am mounting a volume with:

```<code>-v $(PWD)/packages:/mnt/packages
</code>```

Because I want my container to produce some output into that directory.

The directory belongs to the host user.

But, not matter what I try, the mountpoint in the container belongs to root. I can correct it with sudo in the running container:

```<code>function correct-mountpoint-permissions () {
  # Hack alert:
  #   When mounting a host volume, it belongs to root, no matter what I do in the host or in the Dockerfile
  #   Here we correct the situation by using sudo. It's not nice, but that's life
  #   Note: the same problem does NOT happen with *named* volumes, but that completely defeats the purpose of
  #   mounting the volume in the first place - which is to produce some output visible on the host.
  #   If I have to start copying from containers to host, mounting volumes offers no benefit
  sudo chown "$USER:$USER" "$PACKAGES"
}
</code>```

But this is just ugly. I should not even need to have sudo installed in the first place, or sudo rights at all in my container.

The alternative is to either mount a named volume, which is difficult to access from the host, or to avoid mounting volumes in the container at all, and just docker cp from it when my container has produced the expected output.

Is there a simple way of mounting a host volume with the right ownership into a container (which means, not root, but my selected UID)

答:
I understand you must be setting a user in your Dockerfile.
Before the user is set , try changing the ownership of the user during the build of the image.</p>
```<code>RUN chown -R myuser:myuser ${PACKAGES_DIR}
USER myuser
</code>```

Body:
I use build-arg to ensure my container runs with the same UID as my host user:

--build-arg UID=$(UID)

I am mounting a volume with:

-v $(PWD)/packages:/mnt/packages

Because I want my container to produce some output into that directory.

The directory belongs to the host user.

But, not matter what I try, the mountpoint in the container belongs to root. I can correct it with sudo in the running container:

function correct-mountpoint-permissions () {
  # Hack alert:
  #   When mounting a host volume, it belongs to root, no matter what I do in the host or in the Dockerfile
  #   Here we correct the situation by using sudo. It's not nice, but that's life
  #   Note: the same problem does NOT happen with *named* volumes, but that completely defeats the purpose of
  #   mounting the volume in the first place - which is to produce some output visible on the host.
  #   If I have to start copying from containers to host, mounting volumes offers no benefit
  sudo chown "$USER:$USER" "$PACKAGES"
}

But this is just ugly. I should not even need to have sudo installed in the first place, or sudo rights at all in my container.

The alternative is to either mount a named volume, which is difficult to access from the host, or to avoid mounting volumes in the container at all, and just docker cp from it when my container has produced the expected output.

Is there a simple way of mounting a host volume with the right ownership into a container (which means, not root, but my selected UID)

Body:
I understand you must be setting a user in your Dockerfile.
Before the user is set , try changing the ownership of the user during the build of the image.

RUN chown -R myuser:myuser ${PACKAGES_DIR}
USER myuser


问:
Extract elements from dynamic list as increases or decreases in python3
Hello i have a dynamic list which increases or decreases accordingly from the extracted data from a site with BeautifulSoup

```<code>mylist = [a,b,c,d,.......]
</code>```

how can i make the following fstring to be dynamic as the list increases or decreases?

```<code>fstr = print(f"the forecast for the week is (choose number): {nl}1. {mylist[0]}{nl}2. {mylist[1]}{nl}3. {mylist[2]}{nl}4. {mylist[3]}{nl}5. Show all week")
</code>```

As you can see i want the elements of mylist to be seperated by \nl (new line) in the fstring and not join it to a string. Is this possible?

the Output is

```<code>the forecast for the week is (choose number):
1. Tuesday 08  2022
2. Wednesday 09  2022
3. Thursday 10  2022
4. Friday 11  2022
</code>```

答:
You could write a loop for your list and put the print statement in that. Something like:

```<code>my_list = ["a","b","c"]
print(f"the forecast for the week is (choose number):")
for idx, word in enumerate(my_list):
    print(f"{str(idx)}. {word}")
print(f"{str(len(my_list))}. Show all week")
</code>```

This should be dynamic for your list

Body:
Hello i have a dynamic list which increases or decreases accordingly from the extracted data from a site with BeautifulSoup

mylist = [a,b,c,d,.......]

how can i make the following fstring to be dynamic as the list increases or decreases?

fstr = print(f"the forecast for the week is (choose number): {nl}1. {mylist[0]}{nl}2. {mylist[1]}{nl}3. {mylist[2]}{nl}4. {mylist[3]}{nl}5. Show all week")

As you can see i want the elements of mylist to be seperated by \nl (new line) in the fstring and not join it to a string. Is this possible?

the Output is

the forecast for the week is (choose number):
1. Tuesday 08  2022
2. Wednesday 09  2022
3. Thursday 10  2022
4. Friday 11  2022

Body:
You could write a loop for your list and put the print statement in that. Something like:

my_list = ["a","b","c"]
print(f"the forecast for the week is (choose number):")
for idx, word in enumerate(my_list):
    print(f"{str(idx)}. {word}")
print(f"{str(len(my_list))}. Show all week")

This should be dynamic for your list


问:
Do I have to use Timeline or Transition to redraw canvas in infinite loop?
I have the following Problem.

I'm am a complete newbie in JavaFX and I am trying to code a Game of Life program.

I have a class "MainView" extending VBox. MainView has an ArrayList "playingField" of the class Field as an attribute, consisting of cells and also a draw() method, which draws rectangles on a Canvas, according to the states of the cells.

Inside of Field I have a transition() method, which changes the state of the cells, according to some defined transition rules.

This is working fine, and I can manually progress by clicking on a button on my primary stage. What I want though, is a possibility to press a button once, and then have indefinite steps of progresses -> applications of the transition()-method and redrawings of the canvas.

If I try to do it in a loop, it works just fine, but of course happens way to fast to recognize the single steps, but when I use Thread.sleep(), the whole application freezes.

I know I have to solve this with either a timeline or a transitions, but I can't really find sufficient informations online on how to inegrate the transition() and draw() methods in an infinite cycle in either one of them.

I hope following snippets will help to make myself more clear:

```<code>public class Main extends Application {
@Override
public void start(Stage primaryStage) {
    try {

        MainView mainView = new MainView();

        Scene scene = new Scene(mainView, 1000, 1032);
        primaryStage.setScene(scene);
        primaryStage.show();
        mainView.draw();

    } catch(Exception e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {
    launch(args);
}
</code>```

}

```<code>public MainView() extends VBox {
    private Button stepButton;
    private Canvas canvas;
    private Field playingField;

    this.stepButton = new Button("progress");
    this.stepButton.setOnAction(ActionEvent -> {
        playingField.fieldTransition();
        draw();
    });

    public void draw() {

    //drawing Rectangles that represent the cells of field on a canvas
        }
    }
}
</code>```

Field class with the transitions() method:

```<code>public class Field implements TransitionRules {

public void fieldTransition(){
    //method to change the state of the cells according to given rules.
    }
}
</code>```

答:
Thank you guys, I made it work.

In mainView I defined a method

```<code>        public void progress() {
        field.fieldTransition();
        draw();
    }
</code>```

And then in Main I did this:

```<code>public class Main extends Application {
@Override
public void start(Stage primaryStage) {
    try {

        MainView mainView = new MainView();

        Scene scene = new Scene(mainView, 1000, 1032);
        primaryStage.setScene(scene);
        primaryStage.show();
        Timeline timeline = new Timeline();
        KeyFrame frame1 = new KeyFrame(Duration.seconds(1.0), e -> mainView.progress());
        timeline.getKeyFrames().add(frame1);
        timeline.setCycleCount(Timeline.INDEFINITE);
        timeline.play();
        mainView.draw();

    } catch(Exception e) {
        e.printStackTrace();
    }
}
</code>```

Im pretty sure I added some unnecessary detours and I'll probably have to work on it much more, but for the first time I made the automatic progress happen.

Also thanks to @James_D for pointing out the other JavaFX-Thread. I didn't find it by myself, but it seems very useful and I will come back to it in the future.

I know for some of you guys its pretty basic to make stuff like this work, but I just started a few days ago with JavaFX and its mechanics are still somewhat confusing for me.

Body:
I have the following Problem.

I'm am a complete newbie in JavaFX and I am trying to code a Game of Life program.

I have a class "MainView" extending VBox. MainView has an ArrayList "playingField" of the class Field as an attribute, consisting of cells and also a draw() method, which draws rectangles on a Canvas, according to the states of the cells.

Inside of Field I have a transition() method, which changes the state of the cells, according to some defined transition rules.

This is working fine, and I can manually progress by clicking on a button on my primary stage. What I want though, is a possibility to press a button once, and then have indefinite steps of progresses -> applications of the transition()-method and redrawings of the canvas.

If I try to do it in a loop, it works just fine, but of course happens way to fast to recognize the single steps, but when I use Thread.sleep(), the whole application freezes.

I know I have to solve this with either a timeline or a transitions, but I can't really find sufficient informations online on how to inegrate the transition() and draw() methods in an infinite cycle in either one of them.

I hope following snippets will help to make myself more clear:

public class Main extends Application {
@Override
public void start(Stage primaryStage) {
    try {

        MainView mainView = new MainView();

        Scene scene = new Scene(mainView, 1000, 1032);
        primaryStage.setScene(scene);
        primaryStage.show();
        mainView.draw();

    } catch(Exception e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {
    launch(args);
}

}

public MainView() extends VBox {
    private Button stepButton;
    private Canvas canvas;
    private Field playingField;

    this.stepButton = new Button("progress");
    this.stepButton.setOnAction(ActionEvent -> {
        playingField.fieldTransition();
        draw();
    });

    public void draw() {

    //drawing Rectangles that represent the cells of field on a canvas
        }
    }
}

Field class with the transitions() method:

public class Field implements TransitionRules {

public void fieldTransition(){
    //method to change the state of the cells according to given rules.
    }
}

Body:
Thank you guys, I made it work.

In mainView I defined a method

        public void progress() {
        field.fieldTransition();
        draw();
    }

And then in Main I did this:

public class Main extends Application {
@Override
public void start(Stage primaryStage) {
    try {

        MainView mainView = new MainView();

        Scene scene = new Scene(mainView, 1000, 1032);
        primaryStage.setScene(scene);
        primaryStage.show();
        Timeline timeline = new Timeline();
        KeyFrame frame1 = new KeyFrame(Duration.seconds(1.0), e -> mainView.progress());
        timeline.getKeyFrames().add(frame1);
        timeline.setCycleCount(Timeline.INDEFINITE);
        timeline.play();
        mainView.draw();

    } catch(Exception e) {
        e.printStackTrace();
    }
}

Im pretty sure I added some unnecessary detours and I'll probably have to work on it much more, but for the first time I made the automatic progress happen.

Also thanks to @James_D for pointing out the other JavaFX-Thread. I didn't find it by myself, but it seems very useful and I will come back to it in the future.

I know for some of you guys its pretty basic to make stuff like this work, but I just started a few days ago with JavaFX and its mechanics are still somewhat confusing for me.


问:
write a function for copying two strings
this code is not printing the copied value of two strings given that are target and source been created above  then a function is created that is stringcopy .</p>
```<code>#include <stdio.h>

int stringcopy(char *target, char *source) {
    char *start = target;

    while (*target != '\0') { // this means while target is not equal to 0 that is null charecter
        *target = *source;
        target++;
        source++;
    }

    *target ='\0';
    return *start;
}

int main() {
    char source[34] = "Harry";
    char target[34];

    char copy = stringcopy(target, source);
    printf("%s", copy);

    return 0;
}
</code>```

答:
*target != '\0' but *target is uninitialized. You mean *source != '\0'.

Next problem: int stringcopy should be char *stringcopy. Your code will appear to work on a 32 bit platform otherwise, but it will blow up x64. You need to return the correct type.

Third problem: char copy = ; should be char *copy = ; I'm guessing you got here by arbitrarily mutating the code to get it to compile due to the second problem.

Forth problem: return *start; should be return start;. Thanks to Gerhardh for catching it.

Body:
this code is not printing the copied value of two strings given that are target and source been created above  then a function is created that is stringcopy .

#include <stdio.h>

int stringcopy(char *target, char *source) {
    char *start = target;

    while (*target != '\0') { // this means while target is not equal to 0 that is null charecter
        *target = *source;
        target++;
        source++;
    }

    *target ='\0';
    return *start;
}

int main() {
    char source[34] = "Harry";
    char target[34];

    char copy = stringcopy(target, source);
    printf("%s", copy);

    return 0;
}


问:
Remove submenu items from navigation flow to get faster to other content when using Tab?
I have a fly-out menu that looks like this:

In HTML, it looks like this:

      Dámské

              Výprodej

              Kemping

              Zobrazit vše pro ženy

          Dámské oblečení

              Trika

              Mikiny

              Svetry

              Bundy

              Kabáty

              Kalhoty

              Vesty

              Funkční prádlo

              Košile

              Capri

              Šaty a sukně

              Kraťasy

          Dámská obuv

              Outdoorová obuv

              Zimní obuv

              Městská obuv

              Sportovní obuv

              Letní obuv

          Dámské doplňky a příslušenství

              Čepice a kšiltovky

              Šály a šátky

              Zimní rukavice

              Ponožky

              Batohy a tašky

              Impregnace a prostředky

              Kemping

      Pánské

              Výprodej

              Kemping

              Zobrazit vše pro muže

          Pánské oblečení

              Trika

              Mikiny

              Svetry

              Bundy

              Kalhoty

              Vesty

              Funkční prádlo

              Košile

              Capri

              Kraťasy

          Pánská obuv

              Outdoorová obuv

              Městská obuv

              Sportovní obuv

              Letní obuv

          Pánské doplňky a příslušenství

              Čepice a kšiltovky

              Šály a šátky

              Ponožky

              Batohy a tašky

              Impregnace a prostředky

              Kemping

      Dětské

              Výprodej

              Kemping

              Zobrazit vše pro děti

          Dětské oblečení

              Trika

              Mikiny

              Bundy

              Kabáty

              Kalhoty

              Vesty

              Funkční prádlo

              Sety

              Capri

              Šaty a sukně

              Kraťasy

          Dětská obuv

              Outdoorová obuv

              Zimní obuv

              Městská obuv

              Sportovní obuv

              Letní obuv

          Dětské doplňky a příslušenství

              Čepice a kšiltovky

              Šály a šátky

              Zimní rukavice

              Ponožky

              Batohy a tašky

              Impregnace a prostředky

              Kemping

      Obuv

              Výprodej

              Zobrazit všechnu obuv

          Dámská obuv

              Outdoorová obuv

              Zimní obuv

              Městská obuv

              Sportovní obuv

              Letní obuv

          Pánská obuv

              Outdoorová obuv

              Městská obuv

              Sportovní obuv

              Letní obuv

          Dětská obuv

              Outdoorová obuv

              Zimní obuv

              Městská obuv

              Sportovní obuv

              Letní obuv

      Doplňky

              Výprodej

              Zobrazit všechny doplňky

          Dámské doplňky a příslušenství

              Čepice a kšiltovky

              Šály a šátky

              Zimní rukavice

              Ponožky

              Batohy a tašky

              Impregnace a prostředky

              Kemping

      Výprodej

        Můj profil

        CZ
        SK

        <input class="c-header__search-input" id="fulltext-search-input" type="text" placeholder="Vyhledat..." maxlength="50" />

        <button class="c-header__search-button" id="fulltext-search-button" title="Vyhledat">

        </button>

```

When I tab over it, the tabbing order looks like this:

It means that every submenu item receives focus. There are a lot of these submenu items, about 120, so it takes some time to tab over them and get to other content, for example to the search box on the right side:

would it make sense to skip all the submenu items? For example setting tabindex="-1" to all of them, so the final tab order would look like this:

It feels like this might improve accessibility because other content is accessible faster when using Tab, especially the search box. All the content accessible via the submenu items could be later accessed from the main categories, so no one would miss any content on the website.

On the other hand, using tabindex="-1" is discouraged on some sites, for example on WebAim.org:

A tabindex="-1" value removes interactive elements from the default navigation flow. In most cases, this would not be desirable.

Remember that tabindex="-1" removes the element from the default navigation flow. Do not assign tabindex="-1" to any element that must be keyboard navigable, such as a link or button that sighted users can click on with the mouse.

I might be missing some reason why this proposed solution of mine is not a good idea. That's what I hope to get some insights on.

答:
Your solution is the correct solution and does indeed improve the accessibility for keyboard users.

If you need some reassurance check the W3 examples for a flyout menu

Much better than tabindex="-1" would just be to add display: none via a CSS class and change the menu item to a <button> (assuming the top level menu item is not a link). Then opening the menu is as simple as toggling the CSS class and avoids any potential errors with managing tabindex.

If the top level item is a link to another page then follow the principles of option 2 and have an additional drop-down icon next to the main link instead (with aria-label="open (menuItemName)" for example).

The final consideration is that once a menu is open that is a "mega menu" style (multiple columns), you should ideally implement arrow key navigation to take you between columns and items.

As for whether pressing Tab should go to the next top level item it is something that I am not sure if there is any guidance on, I personally say yes it should and arrow keys are for navigation within a drop-down, but I would make it a true drop-down with aria-owns on the <button> and aria-expanded for whether it is open or closed.

If you have the knowledge of how to implement WAI-ARIA correctly then that is the best option, if not then making the Esc key close the mega menu and or pressing "up" when at the top of the list to get back to the top level links is a reasonable compromise.

Controversial short term tip

I do have one other thing you can do straight away (I know sometimes there is not the scope to fix things right now) as a stop-gap "solution".

Add tabindex="1" to the search box so it is the first item that receives focus and make sure you have "skip to content" links so people can bypass the menu.

While this certainly does not solve the issue, it does improve accessibility  / UX for keyboard users in the short term while you fix the problem, and although it doesn't follow "logical focus order" it would be a better experience (as a temporary fix).

Something that you can do quickly while you explore a more robust solution to the mega menu with arrow key functionality etc. etc.

I will stress this point one more time, this is a temporary improvement, not a fix!

Body:
I have a fly-out menu that looks like this:

In HTML, it looks like this:

      Dámské

              Výprodej

              Kemping

              Zobrazit vše pro ženy

          Dámské oblečení

              Trika

              Mikiny

              Svetry

              Bundy

              Kabáty

              Kalhoty

              Vesty

              Funkční prádlo

              Košile

              Capri

              Šaty a sukně

              Kraťasy

          Dámská obuv

              Outdoorová obuv

              Zimní obuv

              Městská obuv

              Sportovní obuv

              Letní obuv

          Dámské doplňky a příslušenství

              Čepice a kšiltovky

              Šály a šátky

              Zimní rukavice

              Ponožky

              Batohy a tašky

              Impregnace a prostředky

              Kemping

      Pánské

              Výprodej

              Kemping

              Zobrazit vše pro muže

          Pánské oblečení

              Trika

              Mikiny

              Svetry

              Bundy

              Kalhoty

              Vesty

              Funkční prádlo

              Košile

              Capri

              Kraťasy

          Pánská obuv

              Outdoorová obuv

              Městská obuv

              Sportovní obuv

              Letní obuv

          Pánské doplňky a příslušenství

              Čepice a kšiltovky

              Šály a šátky

              Ponožky

              Batohy a tašky

              Impregnace a prostředky

              Kemping

      Dětské

              Výprodej

              Kemping

              Zobrazit vše pro děti

          Dětské oblečení

              Trika

              Mikiny

              Bundy

              Kabáty

              Kalhoty

              Vesty

              Funkční prádlo

              Sety

              Capri

              Šaty a sukně

              Kraťasy

          Dětská obuv

              Outdoorová obuv

              Zimní obuv

              Městská obuv

              Sportovní obuv

              Letní obuv

          Dětské doplňky a příslušenství

              Čepice a kšiltovky

              Šály a šátky

              Zimní rukavice

              Ponožky

              Batohy a tašky

              Impregnace a prostředky

              Kemping

      Obuv

              Výprodej

              Zobrazit všechnu obuv

          Dámská obuv

              Outdoorová obuv

              Zimní obuv

              Městská obuv

              Sportovní obuv

              Letní obuv

          Pánská obuv

              Outdoorová obuv

              Městská obuv

              Sportovní obuv

              Letní obuv

          Dětská obuv

              Outdoorová obuv

              Zimní obuv

              Městská obuv

              Sportovní obuv

              Letní obuv

      Doplňky

              Výprodej

              Zobrazit všechny doplňky

          Dámské doplňky a příslušenství

              Čepice a kšiltovky

              Šály a šátky

              Zimní rukavice

              Ponožky

              Batohy a tašky

              Impregnace a prostředky

              Kemping

      Výprodej

        Můj profil

        CZ
        SK

        <input class="c-header__search-input" id="fulltext-search-input" type="text" placeholder="Vyhledat..." maxlength="50" />

        <button class="c-header__search-button" id="fulltext-search-button" title="Vyhledat">

        </button>

When I tab over it, the tabbing order looks like this:

It means that every submenu item receives focus. There are a lot of these submenu items, about 120, so it takes some time to tab over them and get to other content, for example to the search box on the right side:

would it make sense to skip all the submenu items? For example setting tabindex="-1" to all of them, so the final tab order would look like this:

It feels like this might improve accessibility because other content is accessible faster when using Tab, especially the search box. All the content accessible via the submenu items could be later accessed from the main categories, so no one would miss any content on the website.

On the other hand, using tabindex="-1" is discouraged on some sites, for example on WebAim.org:

A tabindex="-1" value removes interactive elements from the default navigation flow. In most cases, this would not be desirable.

Remember that tabindex="-1" removes the element from the default navigation flow. Do not assign tabindex="-1" to any element that must be keyboard navigable, such as a link or button that sighted users can click on with the mouse.

I might be missing some reason why this proposed solution of mine is not a good idea. That's what I hope to get some insights on.


问:
How does this variable parameters list function call works?
When a program needs to communicate using Microsoft RPC developers typically write a IDL definition for all methods, for example:

```<code>error_status_t rpcMyInterfaceGetFile( [in] const GUID fileId, [out] BYTE_PIPE filePipe );
</code>```

which is compiled by MIDL compiler and produces a wrapper function:

```<code>/* [fault_status][comm_status] */ error_status_t rpcMyInterfacerGetFile(
/* [in] */ handle_t IDL_handle,
/* [in] */ const GUID fileId,
/* [out] */ BYTE_PIPE filePipe)
{
    CLIENT_CALL_RETURN _RetVal;
    _RetVal = NdrClientCall2(
              ( PMIDL_STUB_DESC  )&IMyInterfaceRpc_StubDesc,
              (PFORMAT_STRING) &MyInterfaceRpc__MIDL_ProcFormatString.Format[SomeNumberHere],
              ( unsigned char * )&IDL_handle);
    return ( error_status_t  )_RetVal.Simple;
}
</code>```

Here the call is forwarded to NdrClientCall2() RPC runtime function that is declared to have ... as the third parameter and does actual job. MyInterfaceRpc__MIDL_ProcFormatString is just a sequence of hardcoded bytes generated by MIDL, so the second parameter is a start of a subsection in that array declared in the same .c file as the wrapper function and having static storage duration.

How do the parameters (fileId and filePipe) get passed into NdrClientCall2()? I don't see them being passed. How do they happen to get from the wrapper to NdrClientCall2()?

答: Without looking too deep into it, it seems to me that by passing the address of the first argument on the stack (&IDL_handle) the implementation of NdrClientCall2 can see the subsequent arguments that are also on the stack. The second argument to NdrClientCall2 indicates the number and size of the varargs.</p>

Body:
When a program needs to communicate using Microsoft RPC developers typically write a IDL definition for all methods, for example:

error_status_t rpcMyInterfaceGetFile( [in] const GUID fileId, [out] BYTE_PIPE filePipe );

which is compiled by MIDL compiler and produces a wrapper function:

/* [fault_status][comm_status] */ error_status_t rpcMyInterfacerGetFile(
/* [in] */ handle_t IDL_handle,
/* [in] */ const GUID fileId,
/* [out] */ BYTE_PIPE filePipe)
{
    CLIENT_CALL_RETURN _RetVal;
    _RetVal = NdrClientCall2(
              ( PMIDL_STUB_DESC  )&IMyInterfaceRpc_StubDesc,
              (PFORMAT_STRING) &MyInterfaceRpc__MIDL_ProcFormatString.Format[SomeNumberHere],
              ( unsigned char * )&IDL_handle);
    return ( error_status_t  )_RetVal.Simple;
}

Here the call is forwarded to NdrClientCall2() RPC runtime function that is declared to have ... as the third parameter and does actual job. MyInterfaceRpc__MIDL_ProcFormatString is just a sequence of hardcoded bytes generated by MIDL, so the second parameter is a start of a subsection in that array declared in the same .c file as the wrapper function and having static storage duration.

How do the parameters (fileId and filePipe) get passed into NdrClientCall2()? I don't see them being passed. How do they happen to get from the wrapper to NdrClientCall2()?


问:
Refactoring JavaScript, shortening variable declaration
I have the following code that works as expected:

```<code>(async () => {
  const first = document.getElementById("first"), second = document.getElementById("second");
  try {
    first.innerHTML = await (await fetch('https://myAPI.com/1')).text();
    second.innerHTML = await (await fetch('https://myAPI.com/2')).text();
  } catch {
    first.innerHTML = 'Error';
    second.innerHTML = 'Error';
  }
})();
</code>```

But I am curious whether there is a way to shorten the declaration of my variables, something like this (which doesn't work):

```<code>(async () => {
  const [first, second] = document.getElementById("[first, second]");
  try {
    first.innerHTML = await (await fetch('https://myAPI.com/1')).text();
    second.innerHTML = await (await fetch('https://myAPI.com/2')).text();
  } catch {
    first.innerHTML = 'Error';
    second.innerHTML = 'Error';
  }
})();
</code>```

Just curious as to whether I can get rid of that second appearance of 'document.getElementById' to make the line more compact.

答:
The most concise way to do it is by using the following:</p>
```<code>const [first, second] = document.querySelectorAll("#first, #second");
</code>```

Body:
I have the following code that works as expected:

(async () => {
  const first = document.getElementById("first"), second = document.getElementById("second");
  try {
    first.innerHTML = await (await fetch('https://myAPI.com/1')).text();
    second.innerHTML = await (await fetch('https://myAPI.com/2')).text();
  } catch {
    first.innerHTML = 'Error';
    second.innerHTML = 'Error';
  }
})();

But I am curious whether there is a way to shorten the declaration of my variables, something like this (which doesn't work):

(async () => {
  const [first, second] = document.getElementById("[first, second]");
  try {
    first.innerHTML = await (await fetch('https://myAPI.com/1')).text();
    second.innerHTML = await (await fetch('https://myAPI.com/2')).text();
  } catch {
    first.innerHTML = 'Error';
    second.innerHTML = 'Error';
  }
})();

Just curious as to whether I can get rid of that second appearance of 'document.getElementById' to make the line more compact.

Body:
The most concise way to do it is by using the following:

const [first, second] = document.querySelectorAll("#first, #second");


问:
How can I select an element and the text that follows it with jQuery?
I'm trying to find a class within a sentence and wrap it along with remainder of the text in the sentence.

What I want:

  text text text text text text text text text text text text text text text
  text text text text text text text text

TEST
 text
  text text text text text text text text text text text text text text text

```
<p>One of the many efforts I've tried:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('.test').each(function() {
  $(this).nextUntil('div').addBack().wrap('<div class="newWrap"></div>');
});</code>```

    text text text text text text text text text text text text text text text
    text text text text text text text text
TEST
 text
    text text text text text text text text text text text text text text text

```

答:
Get next sibling Node

No need to use jQuery. in pure JavaScript:

Use Node.nextSibling to get the next sibling Node

Use Document.createElement() to create a new Element

Use Element.append() to append Nodes to a desired Element

// DOM Utility functions:

const EL = (sel, par) => (par || document).querySelector(sel);
const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop);

// Task:

const EL_test = EL(".test");
const ND_next = EL_test.nextSibling;
const EL_newWrap = ELNew("div", {className: "newWrap"});

EL_newWrap.append(EL_test, ND_next);
EL(".containter").append(EL_newWrap);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div { padding: 10px; outline: 1px solid red; }
.newWrap { background: gold; }</code>```

  aaaa aaaa aaaa aaaa aaaa aaaa

TEST

  bbbb bbbb bbbb bbbb bbbb bbbb

```
</div>
</div>
</p>
<p><strong>Notice:</strong></p>
<p>As per requirement the above will only target the <strong>first Node sibling</strong>, so if you have other elements like <code><br></code> etc, it will not work as expected. So read furhther.</p>
<h2>Get all next sibling Nodes</h2>
<p>A <code>while</code> loop would be necessary in order to reach the end of the parent container and <strong>get all the next siblings</strong>.<br />
In such case the target <code>.test</code> element should be prepended last (after the while loop):</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// DOM Utility functions:

const EL = (sel, par) => (par || document).querySelector(sel);
const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop);

// Task:

const EL_test = EL(".test");
const EL_newWrap = ELNew("div", {className: "newWrap"});

while(EL_test.nextSibling) EL_newWrap.append(EL_test.nextSibling);
EL_newWrap.prepend(EL_test);
EL(".containter").append(EL_newWrap);</code>```

div { padding: 10px; outline: 1px solid red;}
.newWrap { background: gold; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="containter">
  aaaa aaaa aaaa aaaa aaaa aaaa
  <div class="test">TEST</div>
  bbbb <i>bbbb</i> <span>bbbb</span> bbbb <br> bbbb <b>bbbb</b>
</div></code>```

Body:
I'm trying to find a class within a sentence and wrap it along with remainder of the text in the sentence.

What I want:

  text text text text text text text text text text text text text text text
  text text text text text text text text

TEST
 text
  text text text text text text text text text text text text text text text

One of the many efforts I've tried:

$('.test').each(function() {
  $(this).nextUntil('div').addBack().wrap('

');
});

    text text text text text text text text text text text text text text text
    text text text text text text text text
TEST
 text
    text text text text text text text text text text text text text text text

Body:
Get next sibling Node

No need to use jQuery. in pure JavaScript:

Use Node.nextSibling to get the next sibling Node

Use Document.createElement() to create a new Element

Use Element.append() to append Nodes to a desired Element

// DOM Utility functions:

const EL = (sel, par) => (par || document).querySelector(sel);
const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop);

// Task:

const EL_test = EL(".test");
const ND_next = EL_test.nextSibling;
const EL_newWrap = ELNew("div", {className: "newWrap"});

EL_newWrap.append(EL_test, ND_next);
EL(".containter").append(EL_newWrap);

div { padding: 10px; outline: 1px solid red; }
.newWrap { background: gold; }

<div class="containter">
  aaaa aaaa aaaa aaaa aaaa aaaa
  <div class="test">TEST</div>
  bbbb bbbb bbbb bbbb bbbb bbbb
</div>

Notice:

As per requirement the above will only target the first Node sibling, so if you have other elements like <br> etc, it will not work as expected. So read furhther.

Get all next sibling Nodes

A while loop would be necessary in order to reach the end of the parent container and get all the next siblings.

In such case the target .test element should be prepended last (after the while loop):

// DOM Utility functions:

const EL = (sel, par) => (par || document).querySelector(sel);
const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop);

// Task:

const EL_test = EL(".test");
const EL_newWrap = ELNew("div", {className: "newWrap"});

while(EL_test.nextSibling) EL_newWrap.append(EL_test.nextSibling);
EL_newWrap.prepend(EL_test);
EL(".containter").append(EL_newWrap);

div { padding: 10px; outline: 1px solid red;}
.newWrap { background: gold; }

<div class="containter">
  aaaa aaaa aaaa aaaa aaaa aaaa
  <div class="test">TEST</div>
  bbbb <i>bbbb</i> <span>bbbb</span> bbbb <br> bbbb <b>bbbb</b>
</div>


问:
Is there a way to read keypresses from the Enter key?
I have been fooling around in python (v3.9.10) and I have found no way to read keypresses from the enter key and have tkinter do something with that keypress. I am trying to make a dumb little program to show some numbers on my screen for school and want to be able to do it quickly. this is my code so far:

```<code>from tkinter import *

#DEFS
def submit():
    submitted=entrybox.get()
    display.config(text=submitted)

app=Tk()

entrybox=Entry(width=10)

entrybox.place(x=10,y=10)

#display label
display=Label(text=' ')
display.place(x=50,y=50)
display.config(font='Arial 72')

#submit button
subbutton=Button(text='SUBMIT',command=submit)
subbutton.place(x=70,y=10)
</code>```

(Sorry if my code looks really bad I am quite new to python and everything it has to offer)
(I am also sorry for sounding repetitive and/or dumb. Forums such as this aren't familiar to me either)

is there any way to read key presses from the enter key while allowing the rest of my tkinter stuff to run as intended? thanks in advance.

答:
You can use .bind() to do this like so:

```<code>app.bind('<Return>', function)
</code>```

This will call function when enter is pressed. '<return>' denotes the return or enter key, and it calls function when the event of a return keypress occurs.

You could add it to your code like so:

```<code>from tkinter import *

def submit():
    submitted=entrybox.get()
    display.config(text=submitted)

app=Tk()

entrybox=Entry(width=10)

entrybox.place(x=10,y=10)

#display label
display=Label(text=' ')
display.place(x=50,y=50)
display.config(font='Arial 72')

#submit button
subbutton=Button(text='SUBMIT',command=submit)
subbutton.place(x=70,y=10)

app.bind('<Return>', lambda x: submit())
app.mainloop()
</code>```

This will do what you are looking for...

Body:
I have been fooling around in python (v3.9.10) and I have found no way to read keypresses from the enter key and have tkinter do something with that keypress. I am trying to make a dumb little program to show some numbers on my screen for school and want to be able to do it quickly. this is my code so far:

from tkinter import *

#DEFS
def submit():
    submitted=entrybox.get()
    display.config(text=submitted)

app=Tk()

entrybox=Entry(width=10)

entrybox.place(x=10,y=10)

#display label
display=Label(text=' ')
display.place(x=50,y=50)
display.config(font='Arial 72')

#submit button
subbutton=Button(text='SUBMIT',command=submit)
subbutton.place(x=70,y=10)

(Sorry if my code looks really bad I am quite new to python and everything it has to offer)
(I am also sorry for sounding repetitive and/or dumb. Forums such as this aren't familiar to me either)

is there any way to read key presses from the enter key while allowing the rest of my tkinter stuff to run as intended? thanks in advance.

Body:
You can use .bind() to do this like so:

app.bind('<Return>', function)

This will call function when enter is pressed. '<return>' denotes the return or enter key, and it calls function when the event of a return keypress occurs.

You could add it to your code like so:

from tkinter import *

def submit():
    submitted=entrybox.get()
    display.config(text=submitted)

app=Tk()

entrybox=Entry(width=10)

entrybox.place(x=10,y=10)

#display label
display=Label(text=' ')
display.place(x=50,y=50)
display.config(font='Arial 72')

#submit button
subbutton=Button(text='SUBMIT',command=submit)
subbutton.place(x=70,y=10)

app.bind('<Return>', lambda x: submit())
app.mainloop()

This will do what you are looking for...


问:
Serializing an object in typescript with methods and a cyclical reference graph
I have a fairly substantial project in typescript that uses a lot of object-oriented programming, resulting in a nontrivial object graph (including some objects indirectly pointing to themselves).  I now need to serialize this graph to a string.  Is there any way (in typescript) to serialize such a graph without losing information upon de-serialization?

Ideally, I would like a solution with as little mandatory bookkeeping on each new class as possible.

Things I've tried:

JSOG.  This didn't work because when it de-serializes the objects, it just leaves them as type Object, and they lose their methods.

TypedJSON.  This didn't work because it fails with Uncaught TypeError: cyclic object value

An unholy combination of the two: This didn't work because even though I can pass something created by jsog-typescript into TypedJSON, TypedJSON will reject it as not being the correct type.

答: I ended up writing my own serializer</p>

Body: I ended up writing my own serializer


问:
Observable not working with async await function in Doc reader
I am trying to put await on Observable like below:

    documentXFDFRetriever: async () => {
            const rows = await this.annotationsService.getAnnotations(this.userService.getCurrentDocumentId()).toPromise();
            console.log(rows);
            return rows.map(row => row.annotationNode);
          }
```
<p><strong>My Service function:</strong></p>
<pre class="lang-js prettyprint-override"><code>    public getAnnotations(docId): Observable<Annotation[]> {
        const userId = this.userService.getCurrentUserId();
        const annotationsRef = collection(this.firestore, `annotations/${docId}/${userId}`);
        return collectionData(annotationsRef) as Observable<Annotation[]>;
    }

</code>```

But it can't return rows on documentXFDFRetriever function.

I m sure something is missing here on the return observable.

Can anyone help me with this issue?

答:
That's because the observable toPromise helper function waits for the observable to complete (or error) before actually resolving itself.

So to resolve this issue you can take the first emitted value from the Observable to complete it, before calling the toPromise function, like the following:

// import { take } from 'rxjs/operators';

// by using `take` operator, the converted observable will be completed after emitting one value, then being converted to `Promise`.
const rows = await this.annotationsService.getAnnotations(this.userService.getCurrentDocumentId()).pipe(take(1)).toPromise();
```

OR if you are using RxJS 7, you can use the firstValueFrom helper function instead of toPormise one, to achieve the same thing.

For more information:
https://rxjs.dev/deprecations/to-promise

Body:
I am trying to put await on Observable like below:

    documentXFDFRetriever: async () => {
            const rows = await this.annotationsService.getAnnotations(this.userService.getCurrentDocumentId()).toPromise();
            console.log(rows);
            return rows.map(row => row.annotationNode);
          }

My Service function:

    public getAnnotations(docId): Observable<Annotation[]> {
        const userId = this.userService.getCurrentUserId();
        const annotationsRef = collection(this.firestore, `annotations/${docId}/${userId}`);
        return collectionData(annotationsRef) as Observable<Annotation[]>;
    }

But it can't return rows on documentXFDFRetriever function.

I m sure something is missing here on the return observable.

Can anyone help me with this issue?

Body:
That's because the observable toPromise helper function waits for the observable to complete (or error) before actually resolving itself.

So to resolve this issue you can take the first emitted value from the Observable to complete it, before calling the toPromise function, like the following:

// import { take } from 'rxjs/operators';

// by using `take` operator, the converted observable will be completed after emitting one value, then being converted to `Promise`.
const rows = await this.annotationsService.getAnnotations(this.userService.getCurrentDocumentId()).pipe(take(1)).toPromise();

OR if you are using RxJS 7, you can use the firstValueFrom helper function instead of toPormise one, to achieve the same thing.

For more information:
https://rxjs.dev/deprecations/to-promise


问:
PDO Mysql same query but insert to multiple users
I would like through pdo insert multiple (bulk) rows with same value, only diffent is the user_id

I'm passing a array with userIds but i have no idea how to bind them.

```<code><?php
    require_once("db.php");

    $usersId = $jsonData["usersId"];
    $text = $jsonData["text"];

    // Try to fetch the user from the database
    $query = "INSERT INTO posts (user_id, text) VALUES (:usersId, :text)";
    $stmt = $db->prepare($query);

    // Bind value
    $stmt->bindValue(":userId", $userId);
    $stmt->bindValue(":text", $text, PDO::PARAM_STR);

    // Execute
    $result = $stmt->execute();
?>
</code>```

My Tables:

```<code>CREATE TABLE users(
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255)
);

INSERT INTO users (name)
VALUES ("Gregor"),
    ("Liza"),
    ("Matt"),
    ("Bob");

CREATE TABLE posts(
    id INT PRIMARY KEY AUTO_INCREMENT,
    user_id INT,
    text VARCHAR(255)
);
</code>```

答:
You need a loop:

```<code>    require_once("db.php");

    $text = $jsonData["text"];

    // Try to fetch the user from the database
    $query = "INSERT INTO posts (user_id, text) VALUES (:usersId, :text)";
    $stmt = $db->prepare($query);

    // Bind value
    $stmt->bindParam(":userId", $userId);
    $stmt->bindValue(":text", $text, PDO::PARAM_STR);

    // Execute
    foreach ($jsonData["usersId"] as $userId) {
        $result = $stmt->execute();
    }
</code>```

Use bindParam() so it binds to a reference to the variable. That allows you to reassign the variable each time through the loop without re-binding.

Body:
I would like through pdo insert multiple (bulk) rows with same value, only diffent is the user_id

I'm passing a array with userIds but i have no idea how to bind them.

<?php
    require_once("db.php");

    $usersId = $jsonData["usersId"];
    $text = $jsonData["text"];

    // Try to fetch the user from the database
    $query = "INSERT INTO posts (user_id, text) VALUES (:usersId, :text)";
    $stmt = $db->prepare($query);

    // Bind value
    $stmt->bindValue(":userId", $userId);
    $stmt->bindValue(":text", $text, PDO::PARAM_STR);

    // Execute
    $result = $stmt->execute();
?>

My Tables:

CREATE TABLE users(
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255)
);

INSERT INTO users (name)
VALUES ("Gregor"),
    ("Liza"),
    ("Matt"),
    ("Bob");

CREATE TABLE posts(
    id INT PRIMARY KEY AUTO_INCREMENT,
    user_id INT,
    text VARCHAR(255)
);

Body:
You need a loop:

    require_once("db.php");

    $text = $jsonData["text"];

    // Try to fetch the user from the database
    $query = "INSERT INTO posts (user_id, text) VALUES (:usersId, :text)";
    $stmt = $db->prepare($query);

    // Bind value
    $stmt->bindParam(":userId", $userId);
    $stmt->bindValue(":text", $text, PDO::PARAM_STR);

    // Execute
    foreach ($jsonData["usersId"] as $userId) {
        $result = $stmt->execute();
    }

Use bindParam() so it binds to a reference to the variable. That allows you to reassign the variable each time through the loop without re-binding.


问:
Filtering & Sorting Firebase (Firestore) Data on a Flutter App
If my user database is on Firestore and on Registration I ask each users a set of few questions (checkboxes, radio buttons, etc). I want to create a Filter and Sort mechanism where a user is able to filter and sort a list of other users (from Firestore) based on multiple filter parameters sorted according to a particular field.

Is what I want to create even possible on Firebase (FireStore) and Flutter or do I need anything else?

Can anybody please link me to any relating Flutter/Firebase documentation, YouTube videos, or any other relevant content.

答:
You can create multiple filter and ordering in firestore in flutter app.</p>
```<code> QuerySnapshot orderQuerySnapshot = await orderCollection
            .where("status", isEqualTo: status)
            .where("timestamp", isGreaterThanOrEqualTo: lowerDate)
            .where("timestamp", isLessThanOrEqualTo: upperDate)
            .orderBy('timestamp', descending: true)
            .get();
</code>```

Body:
You can create multiple filter and ordering in firestore in flutter app.

 QuerySnapshot orderQuerySnapshot = await orderCollection
            .where("status", isEqualTo: status)
            .where("timestamp", isGreaterThanOrEqualTo: lowerDate)
            .where("timestamp", isLessThanOrEqualTo: upperDate)
            .orderBy('timestamp', descending: true)
            .get();


问:
The 'kotlin-android-extensions' Gradle plugin is deprecated
with the Gradle version 6.2 and Android studio version 4.0.1, I have the deprecation message for the Kotlin-android-extention. any body has any idea how to fix it.

答:
In my opinion, using this plugin is still better than the methods introduced, we just need to pay attention to IDs.
Because With the Android Kotlin Extensions Gradle plugin released in 2017 came Kotlin Synthetics. For every layout file, Kotlin Synthetics creates an autogenerated class containing your view— as simple as that.
You just have to import this plugin in your Gradle file, and you are all set to directly refer to the view reference variables.
It calls findViewById internally only once and then caches it.
This was so convenient and such fun to use, so why is it being deprecated
Let's analyze it.
Pros
No boilerplate code — Just configure it once in your Gradle file and you are all set to go. Kotlin Synthetics will automatically generate a class ready for you to use.
Type safety — All views are picked from your layout file with the type known to it.
Cons
Partial null safety — It is generally null safe as all your views must be present in the layout file for it to generate. But what if you have multiple layout files based on configurations where some views are present in some layout files and missing in some? Here you have to then manually check for null.
Pollutes the namespace — You can have the same view ID in different layouts, and you can accidentally import a view of some other layout, which will later at runtime throw NullPointerException.
Kotlin only — Kotlin Synthetics can only be used with Kotlin. They are not supported with Java. There are still projects that are written in Java and may not be fully migrated to Kotlin yet, and hence Kotlin Synthetics may not be a consistent way of getting the ViewIds in your project.
Because of these issues, Kotlin Synthetics is now being deprecated.

Now it's up to you to decide if you still want to use this plugin like me if you want to fix deprecated warning , you have to avoid using the deprecated method.


问:
Why can't I add or remove a QListWidgetItem?
I have two ListWidget at my ui and I want to move one QListWidgetItem from availableMeasurementsListWidget to selectedMeasurementListWidget

But this won't work for me. Nothing adds into selectedMeasurementListWidget and the item does not removes from availableMeasurementsListWidget. Why?

That only who works is displaying the text of the qDebug() << item->text();

```<code>void ChartSettingsWindow::on_availableMeasurementsListWidget_doubleClicked(const QModelIndex &index)
{
    Q_UNUSED(index);
    QListWidgetItem *item = ui->availableMeasurementsListWidget->currentItem();
    qDebug() << item->text();
   ui->selectedMeasurementListWidget->addItem(item);
    ui->availableMeasurementsListWidget->removeItemWidget(item);
}
</code>```

答:
Note that QListWidget:: removeItemWidget doesn't remove the QListWidgetItem from the QListWidget: it only...

Removes the widget set on the given item.

To remove an item (row) from the list entirely, either delete the item
or use takeItem().

So you probably want something like...

```<code>auto *available = ui->availableMeasurementsListWidget;
auto *selected  = ui->selectedMeasurementListWidget;
auto *item      = available->currentItem();
selected->addItem(available->takeItem(available->indexFromItem(item).row()));
</code>```

Body:
I have two ListWidget at my ui and I want to move one QListWidgetItem from availableMeasurementsListWidget to selectedMeasurementListWidget

But this won't work for me. Nothing adds into selectedMeasurementListWidget and the item does not removes from availableMeasurementsListWidget. Why?

That only who works is displaying the text of the qDebug() << item->text();

void ChartSettingsWindow::on_availableMeasurementsListWidget_doubleClicked(const QModelIndex &index)
{
    Q_UNUSED(index);
    QListWidgetItem *item = ui->availableMeasurementsListWidget->currentItem();
    qDebug() << item->text();
   ui->selectedMeasurementListWidget->addItem(item);
    ui->availableMeasurementsListWidget->removeItemWidget(item);
}

Body:
Note that QListWidget:: removeItemWidget doesn't remove the QListWidgetItem from the QListWidget: it only...

Removes the widget set on the given item.

To remove an item (row) from the list entirely, either delete the item
or use takeItem().

So you probably want something like...

auto *available = ui->availableMeasurementsListWidget;
auto *selected  = ui->selectedMeasurementListWidget;
auto *item      = available->currentItem();
selected->addItem(available->takeItem(available->indexFromItem(item).row()));


问:
Why is PHP explode returning an array of arrays?
I'm using PHP 5.6.31 and executing this very simple explode statement, but it's not behaving as I would expect.

```<code>$mystring = "48-72";
$myarray[] = explode("-",$mystring);
var_dump($myarray);
</code>```

I would expect this to print:

```<code>array(1) {[0]=> string(2) "48" [1]=> string(2) "72" }
</code>```

But instead it prints this:

```<code>array(1) { [0]=> array(2) { [0]=> string(2) "48" [1]=> string(2) "72" } }
</code>```

So now I have to get my values like this:

```<code>$value1 = $result[0][0];
$value2 = $result[0][1];
</code>```

Is this normal behaviour, to return an array of arrays, or is it something I'm doing?

答:
You should change your code to the following :</p>
```<code>$mystring = "48-72";
$myarray = explode("-",$mystring);
var_dump($myarray);
</code>```

Body:
I'm using PHP 5.6.31 and executing this very simple explode statement, but it's not behaving as I would expect.

$mystring = "48-72";
$myarray[] = explode("-",$mystring);
var_dump($myarray);

I would expect this to print:

array(1) {[0]=> string(2) "48" [1]=> string(2) "72" }

But instead it prints this:

array(1) { [0]=> array(2) { [0]=> string(2) "48" [1]=> string(2) "72" } }

So now I have to get my values like this:

$value1 = $result[0][0];
$value2 = $result[0][1];

Is this normal behaviour, to return an array of arrays, or is it something I'm doing?

Body:
You should change your code to the following :

$mystring = "48-72";
$myarray = explode("-",$mystring);
var_dump($myarray);


问:
Failed to parse source map... Error: ENOENT: no such file or directory
The problem is when I run yarn start there are some warnings occur as:

WARNING in ./node_modules/@usedapp/core/dist/esm/src/providers/transactions/reducer.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/Users/mac/Desktop/react-django-nft-marketplace/react_django_nft_marketplace/frontend/frontend/node_modules/@usedapp/core/dist/esm/src/providers/transactions/reducer.js.map' file: Error: ENOENT: no such file or directory, open '/Users/mac/Desktop/react-django-nft-marketplace/react_django_nft_marketplace/frontend/frontend/node_modules/@usedapp/core/dist/esm/src/providers/transactions/reducer.js.map'
 @ ./node_modules/@usedapp/core/dist/esm/src/providers/transactions/provider.js 8:0-47 23:46-64
 @ ./node_modules/@usedapp/core/dist/esm/src/providers/DAppProvider.js 8:0-62 50:29-48
 @ ./node_modules/@usedapp/core/dist/esm/src/providers/index.js 1:0-31 1:0-31
 @ ./node_modules/@usedapp/core/dist/esm/src/index.js 2:0-28 2:0-28
 @ ./src/App.tsx 5:0-54 11:30-42 13:24-37 13:39-54
 @ ./src/index.tsx 7:0-24 11:33-36

102 warnings have detailed information that is not shown.
Use 'stats.errorDetails: true' resp. '--stats-error-details' to show it.

webpack 5.68.0 compiled with 102 warnings in 2298 ms
Files successfully emitted, waiting for typecheck results...
Issues checking in progress...
No issues found.
^C
mbp:frontend mac$
```

I've created the react app by running npx create-react-app frontend --template typescript command. There is also almost the same issue as of my. But it didn't resolve.

答: The issue was solved with the recent update 0.11 of @usedapp/core library.

Body:
The problem is when I run yarn start there are some warnings occur as:

WARNING in ./node_modules/@usedapp/core/dist/esm/src/providers/transactions/reducer.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/Users/mac/Desktop/react-django-nft-marketplace/react_django_nft_marketplace/frontend/frontend/node_modules/@usedapp/core/dist/esm/src/providers/transactions/reducer.js.map' file: Error: ENOENT: no such file or directory, open '/Users/mac/Desktop/react-django-nft-marketplace/react_django_nft_marketplace/frontend/frontend/node_modules/@usedapp/core/dist/esm/src/providers/transactions/reducer.js.map'
 @ ./node_modules/@usedapp/core/dist/esm/src/providers/transactions/provider.js 8:0-47 23:46-64
 @ ./node_modules/@usedapp/core/dist/esm/src/providers/DAppProvider.js 8:0-62 50:29-48
 @ ./node_modules/@usedapp/core/dist/esm/src/providers/index.js 1:0-31 1:0-31
 @ ./node_modules/@usedapp/core/dist/esm/src/index.js 2:0-28 2:0-28
 @ ./src/App.tsx 5:0-54 11:30-42 13:24-37 13:39-54
 @ ./src/index.tsx 7:0-24 11:33-36

102 warnings have detailed information that is not shown.
Use 'stats.errorDetails: true' resp. '--stats-error-details' to show it.

webpack 5.68.0 compiled with 102 warnings in 2298 ms
Files successfully emitted, waiting for typecheck results...
Issues checking in progress...
No issues found.
^C
mbp:frontend mac$

I've created the react app by running npx create-react-app frontend --template typescript command. There is also almost the same issue as of my. But it didn't resolve.