问:
UIView display order issue?
The problem

When drawing a custom movie player controller on-screen (iOS 4), I use an AVPlayerLayer to display. I wish to composite some overlays on top of the player (ad banners, player controls, etc). At the moment, this works absolutely fine with the following hierarchy:

```
UIView(self.view)\
                 | UIView(controlsView)\
                 *                     | UIView [some movie player controls]
                                       | UIView [some more movie player controls]
                                       *
```

The AVPlayerLayer is a sublayer of self.view. On player load, I add the layer to self.view first and call bringSubviewToFront: on the controlsView, and then detect taps on it and programmatically show/fadeout on a timer/whatever. No issue here.

Now that I have support for dynamically fetching and displaying advertising content, I would like to set up the following hierarchy:

```
UIView(self.view)\
                 | UIImageView (ad banner)
                 | UIImageView (another ad banner)
                 | ...
                 | UIView(controlsView)\
                 *                     | UIView [some movie player controls]
                                       | UIView [some more movie player controls]
                                       *
```

At player load, what I then do is attach to my AVPlayer instance some addBoundaryTimeObserverForTimes:queue:usingBlock: calls to fade the ad banners in and out at appropriate times. As I do this, I add the UIImageViews to self.view as subviews with no explicit ordering (hence they should be drawn on top of everything else), and setHidden:YES on them.

I've NSLog'd and these fade blocks are correctly being executed, setting view.alpha = 1.0f and view.alpha = 0.0f for show and hide respectively on the ad banners, but nothing is appearing at all, even when explicitly setting the UIImage displayed by the view to a known working local image and the frame to (0, 0, 320, 480), plus setting an autoresizingMask of

```<code>UIViewAutoresizingFlexibleTopMargin  |
UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleRightMargin;
</code>```

The UIViewContentMode is default (should be UIViewContentModeScaleToFill).

The 'solution' I've gone with for the problem

This doesn't actually address the issue at all, but I'm now using 0.1% opacity as a replacement for 0% opacity. Effectively hides the element without causing issues, and fadeins/fadeouts are working well.

Troubleshooting

To make sure I wasn't drawing the movie over the top of all non-controls views, I moved the AVPlayerLayer to an additional view, videoView:

```
UIView(self.view)\
                 | UIView(videoView)
                 | UIImageView (ad banner)
                 | UIImageView (another ad banner)
                 | ...
                 | UIView(controlsView)\
                 *                     | UIView [some movie player controls]
                                       | UIView [some more movie player controls]
                                       *
```

I explicitly call sendSubviewToBack:videoView and bringSubviewToFront:controlsView, but still no love. I can see the overlay ads on-screen if I don't call setHidden:YES when I first add them to the view hierarchy. The kicker is this: the ad also disappears at the correct time (in response to overlayImage.alpha = 0.0f in my animation blocks), so I know my animation blocks are fine.

Here is a code snippet to do with adding the ad banners to my movie player's view:

```<code>for(MyCustomAdBannerClass *overlay in overlays)
{
    UIImageView *overlayImage =
    [[UIImageView alloc] initWithImage:
     [UIImage initWithData:
      [NSData dataWithContentsOfURL:[overlay contentURL]]]];
    UIViewAutoresizing autoresizingFlags =
        UIViewAutoresizingNone;
    CGFloat x, y, width, height;
    width = [overlay width];
    height = [overlay height];
    // <snip> set x, y, autoresizing values of the above vars
    [overlayImage setFrame:CGRectMake(x, y, width, height)];
    [overlayImage setAutoresizingMask:autoresizingFlags];
    [self.view addSubview:overlayImage];
}

for(UIView *subview in self.view.subviews)
{
    if(subview == controlsView)
        [self.view bringSubviewToFront:subview];
    else if(subview == videoView)
        [self.view sendSubviewToBack:subview];
    else
        [subview setHidden:YES];
}
</code>```

Here is the code I use for adding the overlay appear/disappear callbacks (overlay is an object with information about when to show the overlay and how long for, overlayImage is the UIImageView containing the actual ad banner):

```<code>[self.player
 addBoundaryTimeObserverForTimes:[NSArray arrayWithObject:
                                  [overlay startTime]]
 queue:dispatch_get_main_queue()
 usingBlock:^{
     [UIView
      animateWithDuration:0.7
      animations:^{
          overlayImage.alpha = 1.0f;
          dispatch_time_t popTime =
          dispatch_time(DISPATCH_TIME_NOW,
                        [overlay duration] * NSEC_PER_SEC);
          dispatch_after(popTime, dispatch_get_main_queue(),
                         ^(void){
                             [UIView
                              animateWithDuration:0.7
                              animations:^{
                                  overlayImage.alpha = 0.0f;
                                  [overlayImage removeFromSuperview];
                              }];
                          }];
                }];
}];
</code>```

As I said, that overlayImage.alpha = 0.0f; call is being executed correctly.

NOTE: Just tried setting overlay.alpha = 0.5f; instead of 0.0f when the views are first added. The overlay FADES IN properly now. So there is something funky going on with making the view 100% invisible which prevents it from being shown again at a later date. No crashes, so it's not just referencing dealloced memory.

Attempted workaround

I tried sending all the ad overlays behind videoView and then when each one was to be shown I called

```<code>[overlayImage removeFromSuperview];
[self.view insertSubview:overlayImage aboveView:videoView];
// dispatch hide animation
</code>```

Still doesn't show them, but still fades properly when I omit setHidden:YES.

答: Note that I am now using 0.001f instead of 0.0f and there are no display issues. I'm still keen to figure out why it does this though.

Title: UIView display order issue?

Body:
The problem

When drawing a custom movie player controller on-screen (iOS 4), I use an AVPlayerLayer to display. I wish to composite some overlays on top of the player (ad banners, player controls, etc). At the moment, this works absolutely fine with the following hierarchy:

UIView(self.view)\
                 | UIView(controlsView)\
                 *                     | UIView [some movie player controls]
                                       | UIView [some more movie player controls]
                                       *

The AVPlayerLayer is a sublayer of self.view. On player load, I add the layer to self.view first and call bringSubviewToFront: on the controlsView, and then detect taps on it and programmatically show/fadeout on a timer/whatever. No issue here.

Now that I have support for dynamically fetching and displaying advertising content, I would like to set up the following hierarchy:

UIView(self.view)\
                 | UIImageView (ad banner)
                 | UIImageView (another ad banner)
                 | ...
                 | UIView(controlsView)\
                 *                     | UIView [some movie player controls]
                                       | UIView [some more movie player controls]
                                       *

At player load, what I then do is attach to my AVPlayer instance some addBoundaryTimeObserverForTimes:queue:usingBlock: calls to fade the ad banners in and out at appropriate times. As I do this, I add the UIImageViews to self.view as subviews with no explicit ordering (hence they should be drawn on top of everything else), and setHidden:YES on them.

I've NSLog'd and these fade blocks are correctly being executed, setting view.alpha = 1.0f and view.alpha = 0.0f for show and hide respectively on the ad banners, but nothing is appearing at all, even when explicitly setting the UIImage displayed by the view to a known working local image and the frame to (0, 0, 320, 480), plus setting an autoresizingMask of

UIViewAutoresizingFlexibleTopMargin  |
UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleRightMargin;

The UIViewContentMode is default (should be UIViewContentModeScaleToFill).

The 'solution' I've gone with for the problem

This doesn't actually address the issue at all, but I'm now using 0.1% opacity as a replacement for 0% opacity. Effectively hides the element without causing issues, and fadeins/fadeouts are working well.

Troubleshooting

To make sure I wasn't drawing the movie over the top of all non-controls views, I moved the AVPlayerLayer to an additional view, videoView:

UIView(self.view)\
                 | UIView(videoView)
                 | UIImageView (ad banner)
                 | UIImageView (another ad banner)
                 | ...
                 | UIView(controlsView)\
                 *                     | UIView [some movie player controls]
                                       | UIView [some more movie player controls]
                                       *

I explicitly call sendSubviewToBack:videoView and bringSubviewToFront:controlsView, but still no love. I can see the overlay ads on-screen if I don't call setHidden:YES when I first add them to the view hierarchy. The kicker is this: the ad also disappears at the correct time (in response to overlayImage.alpha = 0.0f in my animation blocks), so I know my animation blocks are fine.

Here is a code snippet to do with adding the ad banners to my movie player's view:

for(MyCustomAdBannerClass *overlay in overlays)
{
    UIImageView *overlayImage =
    [[UIImageView alloc] initWithImage:
     [UIImage initWithData:
      [NSData dataWithContentsOfURL:[overlay contentURL]]]];
    UIViewAutoresizing autoresizingFlags =
        UIViewAutoresizingNone;
    CGFloat x, y, width, height;
    width = [overlay width];
    height = [overlay height];
    // <snip> set x, y, autoresizing values of the above vars
    [overlayImage setFrame:CGRectMake(x, y, width, height)];
    [overlayImage setAutoresizingMask:autoresizingFlags];
    [self.view addSubview:overlayImage];
}

for(UIView *subview in self.view.subviews)
{
    if(subview == controlsView)
        [self.view bringSubviewToFront:subview];
    else if(subview == videoView)
        [self.view sendSubviewToBack:subview];
    else
        [subview setHidden:YES];
}

Here is the code I use for adding the overlay appear/disappear callbacks (overlay is an object with information about when to show the overlay and how long for, overlayImage is the UIImageView containing the actual ad banner):

[self.player
 addBoundaryTimeObserverForTimes:[NSArray arrayWithObject:
                                  [overlay startTime]]
 queue:dispatch_get_main_queue()
 usingBlock:^{
     [UIView
      animateWithDuration:0.7
      animations:^{
          overlayImage.alpha = 1.0f;
          dispatch_time_t popTime =
          dispatch_time(DISPATCH_TIME_NOW,
                        [overlay duration] * NSEC_PER_SEC);
          dispatch_after(popTime, dispatch_get_main_queue(),
                         ^(void){
                             [UIView
                              animateWithDuration:0.7
                              animations:^{
                                  overlayImage.alpha = 0.0f;
                                  [overlayImage removeFromSuperview];
                              }];
                          }];
                }];
}];

As I said, that overlayImage.alpha = 0.0f; call is being executed correctly.

NOTE: Just tried setting overlay.alpha = 0.5f; instead of 0.0f when the views are first added. The overlay FADES IN properly now. So there is something funky going on with making the view 100% invisible which prevents it from being shown again at a later date. No crashes, so it's not just referencing dealloced memory.

Attempted workaround

I tried sending all the ad overlays behind videoView and then when each one was to be shown I called

[overlayImage removeFromSuperview];
[self.view insertSubview:overlayImage aboveView:videoView];
// dispatch hide animation

Still doesn't show them, but still fades properly when I omit setHidden:YES.


来源: stackexchange

问:
Is there a way to trigger different query while filling the required slots in dialogflow
I have an intent orderPizza and entities as @pizzaOptions @pizzaSize @qty

happy path (working fine)

```<code>user: order 2 pizza
bot: which pizza you want?
user: pepperoni
bot: and pizza size?
user: large
bot: okay! your order for 2 large pepperoni pizza has been placed.
</code>```

CASE_2

```<code>user: order 2 pizza
bot: which pizza you want?
user: which pizza options do you have?
bot: which pizza you want?
</code>```

so in case 2 when user ask for the pizza Options then bot re-prompt the same question

I want bot to answer the user query or bot can present the options (different re-prompt) instead of same re-prompt

is there a way to handle this use case

答:
The best setup for this would be to have 2 intents.

Order pizza intent ("Order x Pizza")

Get Pizza option intent ("What pizza options do you have?")

The reason for this is, because the user is trying to get two completely different results from you bot. When the user asks for Pizza type, they aren't always ordering a pizza, they could just be interested in your available types.

The Get Pizza option intent you just return an response which gives
the user an example of the available pizza types.

If you make sure both these intents don't require any input context,
you should be able to implement the usecase that you are trying to go
for.

If you use this setup and make sure that the parameters aren't set as required, you should be able to switch between these two intents during the slot filling. In the example you gave you can see that you bot in Case2 keeps asking the user about the pizza type, this is because it expects a pizza type entity as input.

Some example conversations would be:

```<code>User: I want to order a pizza.
Bot: Sure, which Pizza do you want? // Order Pizza Intent

User: I don't know, which pizzas do you have?
Bot: We currently sell Pepperoni Pizza and Vegan Pizza, what else can I Help you with?  // Get Pizza Option Intent

User: I'd like to order 2 large Pepperoni Pizzas
Bot: Okay! your order for 2 large pepperoni pizza has been placed. // Order Pizza Intent

</code>```

```<code>User: Hey, what types of pizza do you have? // Order Pizza Intent
Bot: We currently sell Pepperoni Pizza and Vegan Pizza, what else can I help you with? // Get Pizza Option Intent

User: Hhm, I'm looking for something else, I'll go look somewhere else.
Bot: Sorry to hear that, I hope you have a nice day.
</code>```

Slot filling in the webhook

Because we chose to not make the parameters required, we now have save and check all the paramters ourself. Each time the user mentions an order, we should check if it is complete.

```<code>
function orderIntent(conv) {

const pizzaOption = conv.paramters.pizzaOption;
const pizzaSize = conv.parameters.pizzaSize;
const quantity = conv.parameters.qty;

if (!pizzaOption) {
  return conv.ask("Which pizza do you want?");
}

if (!pizzaSize) {
  return conv.ask("Which size pizza do you want?");
}

if (!quantity) {
  return conv.ask("How many pizzas do you want?");
};

</code>```

This will now allow us to prompt the user until they provide all the information to complete the order, if you would use this code, the bot would keep looping until the user mentions a single phrase that includes a pizzaType, pizzaSize and quantity entity.

Because it is unlikely that the user will ever do this, we need to expand the code to allow the order to be split up in multiple steps and understand which step we are in. We will do this by adding context and follow-up intents.

Remembering the users order

Firstly, lets add the follow-up intent. Because we want to be able to split up the reservation, we should add a follow-up intent for each step. My dialogflow agent that I used to test this looks like this:

Each follow-up intent takes one of the entities as a example phrase:

Missing PizzaTypes, @PizzaOption entity as trained phrase

Missing PizzaSize, @PizzaSize entity as trained phrase

Missing Quantity, @system.integer as trained phrase

After setting these up, you need to enable fulfillment for these follow-ups and add them to the same handler as with the order intent. Now that the intents are setup, we need to add the reservation context and save any valid data.

```<code>// All the order follow-ups and the order intent use the same handler.
    app.intent(
      ["Order Intent", "Complete Order - Missing PizzaType", "Complete Order - Missing Pizza Amount", "Complete Order - Missing PizzaSize"],
      (conv) => {

        // Check if any reservation info is available.
        const order = conv.contexts.get("reservation");

        // If the user has already mentioned pizza info, use context, otherwise take it from the user input.
        const pizzaType = order?.parameters.pizzaType ?? conv.parameters.pizzaType;
        const pizzaSize = order?.parameters.pizzaSize ?? conv.parameters.pizzaSize;
        const pizzaAmount = order?.parameters.pizzaAmount ?? conv.parameters.pizzaAmount;

        // Allow the fallback intents to be triggered
        conv.contexts.set("OrderIntent-followup", 2);

        // Validate the input
        if (!pizzaAmount) {
          return conv.ask("How many pizza's would you like to order?");
        }

        // Save input if valid
        conv.contexts.set("reservation", 5, { pizzaAmount });

        if (!pizzaType) {
          return conv.ask("Which pizza would you like?");
        }

        conv.contexts.set("reservation", 5, { pizzaAmount, pizzaType });

        if (!pizzaSize) {
          return conv.ask("What size should your pizza be?");
        }

        return conv.ask(`Alright, your order has been completed: ${pizzaAmount} ${pizzaSize} ${pizzaType}`);
      },
    );

</code>```

The final result

ContentLicense: CC BY-SA 4.0

Body:
I have an intent orderPizza and entities as @pizzaOptions @pizzaSize @qty

happy path (working fine)

user: order 2 pizza
bot: which pizza you want?
user: pepperoni
bot: and pizza size?
user: large
bot: okay! your order for 2 large pepperoni pizza has been placed.

CASE_2

user: order 2 pizza
bot: which pizza you want?
user: which pizza options do you have?
bot: which pizza you want?

so in case 2 when user ask for the pizza Options then bot re-prompt the same question

I want bot to answer the user query or bot can present the options (different re-prompt) instead of same re-prompt

is there a way to handle this use case

Body:
The best setup for this would be to have 2 intents.

Order pizza intent ("Order x Pizza")

Get Pizza option intent ("What pizza options do you have?")

The reason for this is, because the user is trying to get two completely different results from you bot. When the user asks for Pizza type, they aren't always ordering a pizza, they could just be interested in your available types.

The Get Pizza option intent you just return an response which gives
the user an example of the available pizza types.

If you make sure both these intents don't require any input context,
you should be able to implement the usecase that you are trying to go
for.

If you use this setup and make sure that the parameters aren't set as required, you should be able to switch between these two intents during the slot filling. In the example you gave you can see that you bot in Case2 keeps asking the user about the pizza type, this is because it expects a pizza type entity as input.

Some example conversations would be:

User: I want to order a pizza.
Bot: Sure, which Pizza do you want? // Order Pizza Intent

User: I don't know, which pizzas do you have?
Bot: We currently sell Pepperoni Pizza and Vegan Pizza, what else can I Help you with?  // Get Pizza Option Intent

User: I'd like to order 2 large Pepperoni Pizzas
Bot: Okay! your order for 2 large pepperoni pizza has been placed. // Order Pizza Intent

User: Hey, what types of pizza do you have? // Order Pizza Intent
Bot: We currently sell Pepperoni Pizza and Vegan Pizza, what else can I help you with? // Get Pizza Option Intent

User: Hhm, I'm looking for something else, I'll go look somewhere else.
Bot: Sorry to hear that, I hope you have a nice day.

Slot filling in the webhook

Because we chose to not make the parameters required, we now have save and check all the paramters ourself. Each time the user mentions an order, we should check if it is complete.

function orderIntent(conv) {

const pizzaOption = conv.paramters.pizzaOption;
const pizzaSize = conv.parameters.pizzaSize;
const quantity = conv.parameters.qty;

if (!pizzaOption) {
  return conv.ask("Which pizza do you want?");
}

if (!pizzaSize) {
  return conv.ask("Which size pizza do you want?");
}

if (!quantity) {
  return conv.ask("How many pizzas do you want?");
};

This will now allow us to prompt the user until they provide all the information to complete the order, if you would use this code, the bot would keep looping until the user mentions a single phrase that includes a pizzaType, pizzaSize and quantity entity.

Because it is unlikely that the user will ever do this, we need to expand the code to allow the order to be split up in multiple steps and understand which step we are in. We will do this by adding context and follow-up intents.

Remembering the users order

Firstly, lets add the follow-up intent. Because we want to be able to split up the reservation, we should add a follow-up intent for each step. My dialogflow agent that I used to test this looks like this:

Each follow-up intent takes one of the entities as a example phrase:

Missing PizzaTypes, @PizzaOption entity as trained phrase

Missing PizzaSize, @PizzaSize entity as trained phrase

Missing Quantity, @system.integer as trained phrase

After setting these up, you need to enable fulfillment for these follow-ups and add them to the same handler as with the order intent. Now that the intents are setup, we need to add the reservation context and save any valid data.

// All the order follow-ups and the order intent use the same handler.
    app.intent(
      ["Order Intent", "Complete Order - Missing PizzaType", "Complete Order - Missing Pizza Amount", "Complete Order - Missing PizzaSize"],
      (conv) => {

        // Check if any reservation info is available.
        const order = conv.contexts.get("reservation");

        // If the user has already mentioned pizza info, use context, otherwise take it from the user input.
        const pizzaType = order?.parameters.pizzaType ?? conv.parameters.pizzaType;
        const pizzaSize = order?.parameters.pizzaSize ?? conv.parameters.pizzaSize;
        const pizzaAmount = order?.parameters.pizzaAmount ?? conv.parameters.pizzaAmount;

        // Allow the fallback intents to be triggered
        conv.contexts.set("OrderIntent-followup", 2);

        // Validate the input
        if (!pizzaAmount) {
          return conv.ask("How many pizza's would you like to order?");
        }

        // Save input if valid
        conv.contexts.set("reservation", 5, { pizzaAmount });

        if (!pizzaType) {
          return conv.ask("Which pizza would you like?");
        }

        conv.contexts.set("reservation", 5, { pizzaAmount, pizzaType });

        if (!pizzaSize) {
          return conv.ask("What size should your pizza be?");
        }

        return conv.ask(`Alright, your order has been completed: ${pizzaAmount} ${pizzaSize} ${pizzaType}`);
      },
    );

The final result


问:
Is there a printf converter to print in binary format?
I can print with printf as a hex or octal number.  Is there a format tag to print as binary, or arbitrary base?

I am running gcc.

```<code>printf("%d %x %o\n", 10, 10, 10); //prints "10 A 12\n"
printf("%b\n", 10); // prints "%b\n"
</code>```

答:
```<code>// m specifies how many of the low bits are shown.
// Replace m with sizeof(n) below for all bits and
// remove it from the parameter list if you like.

void print_binary(unsigned long n, unsigned long m) {
    static char show[3] = "01";
    unsigned long mask = 1ULL << (m-1);
    while(mask) {
        putchar(show[!!(n&mask)]); mask >>= 1;
    }
    putchar('\n');
}
</code>```

OwnerDisplayName: Brian

Body:
I can print with printf as a hex or octal number.  Is there a format tag to print as binary, or arbitrary base?

I am running gcc.

printf("%d %x %o\n", 10, 10, 10); //prints "10 A 12\n"
printf("%b\n", 10); // prints "%b\n"


问:
jQuery - clone() is not a function
I'm trying to copy some of my elements from this block and paste them in the end:

```<code><div class="brands">
    <img src="brand1.png" alt="1" />
    <img src="brand2.png" alt="2" />
    <img src="brand3.png" alt="3" />
</div>
</code>```

That's what I'm doing:

```<code>for (var i = 0; i < 2; i++) {
    $('.brands img')[i].clone().appendTo('.brands');
}
</code>```

But then I see this in console: TypeError: $(...)[i].clone is not a function, jQuery is uncluded. What's wrong with my code?

答:
When you use

```<code>$("selector")[n]
</code>```

you get the DOM node, not a jquery object (which doesn't have .clone() (it's cloneNode())

Instead use

```<code>$("selector").eq(n)
</code>```

Updated code:

```<code>for (var i = 0; i < 2; i++) {
    $('.brands img').eq(i).clone().appendTo('.brands');
}
</code>```

Title: jQuery - clone() is not a function

Body:
I'm trying to copy some of my elements from this block and paste them in the end:

That's what I'm doing:

for (var i = 0; i < 2; i++) {
    $('.brands img')[i].clone().appendTo('.brands');
}

But then I see this in console: TypeError: $(...)[i].clone is not a function, jQuery is uncluded. What's wrong with my code?

Body:
When you use

$("selector")[n]

you get the DOM node, not a jquery object (which doesn't have .clone() (it's cloneNode())

Instead use

$("selector").eq(n)

Updated code:

for (var i = 0; i < 2; i++) {
    $('.brands img').eq(i).clone().appendTo('.brands');
}


问:
What's the better-practice way to rotate a string by one character in Python?
I'm doing a codecademy task and was wondering which of the following set of code is considered best practice:

The task is to create a function, given a string username , that shifts all letters one to the right.
For example the username : AbeSimp would become pAbeSim, this becomes the password and is stored in the string password.

Here is my code:

```<code>def password_generator(username):
    password = ""
    password = username[-1] + username[:-1]
    return password
</code>```

The Solution code is :

```<code>def password_generator(username):
    password = ""
    for i in range(0, len(user_name)):
       password += user_name[i-1]
    return password
</code>```

Any explanation is appreciated - thanks!

答:
IMO the best-practice version of this would be:

```<code>def password_generator(username: str) -> str:
    """Generate a terrible password by rotating the username."""
    return username[-1] + username[:-1]
</code>```

Get rid of dead code.  Don't make an assignment you're going to overwrite.  Don't use a loop where a slice will do.  And if a variable isn't going to be used more than one place (e.g. in a return statement), no point even giving it a name IMO.

Body:
I'm doing a codecademy task and was wondering which of the following set of code is considered best practice:

The task is to create a function, given a string username , that shifts all letters one to the right.
For example the username : AbeSimp would become pAbeSim, this becomes the password and is stored in the string password.

Here is my code:

def password_generator(username):
    password = ""
    password = username[-1] + username[:-1]
    return password

The Solution code is :

def password_generator(username):
    password = ""
    for i in range(0, len(user_name)):
       password += user_name[i-1]
    return password

Any explanation is appreciated - thanks!

Body:
IMO the best-practice version of this would be:

def password_generator(username: str) -> str:
    """Generate a terrible password by rotating the username."""
    return username[-1] + username[:-1]

Get rid of dead code.  Don't make an assignment you're going to overwrite.  Don't use a loop where a slice will do.  And if a variable isn't going to be used more than one place (e.g. in a return statement), no point even giving it a name IMO.


问:
Javascript – absolute or relative URL in history.pushState
Is there a difference in using an absolute or relative url as the history.pushState url parameter?

```<code>history.pushState(null, null, absolute/relative)
</code>```

I'm asking because the CMS PHP environment handles absolute urls better than relative urls and before I proceed with the code work, I'd like to know if I can even use absolute urls.

The absolute URL is always from the same https origin (the same website basically).

Unfortunately I couldn't find anything on that topic.

答:
Reading Mdn history.pushState() reference

the last parameter, the URL, can be relative or absolute (with the same origin).
If you use relative Url is more Comfortable:
For example if your starting page is:

```<code>https://www.google.com/bar.html
</code>```

and you do:

```<code>history.pushState(null,null,"foo.html");
</code>```

you will get
    https://www.google.com/foo.html

Note that this does not make a request to the server but it changes the url in the location address bar and in location.href

But you can use also an absolute URL according to the documentation

Body:
Is there a difference in using an absolute or relative url as the history.pushState url parameter?

history.pushState(null, null, absolute/relative)

I'm asking because the CMS PHP environment handles absolute urls better than relative urls and before I proceed with the code work, I'd like to know if I can even use absolute urls.

The absolute URL is always from the same https origin (the same website basically).

Unfortunately I couldn't find anything on that topic.

Body:
Reading Mdn history.pushState() reference

the last parameter, the URL, can be relative or absolute (with the same origin).
If you use relative Url is more Comfortable:
For example if your starting page is:

https://www.google.com/bar.html

and you do:

history.pushState(null,null,"foo.html");

you will get
    https://www.google.com/foo.html

Note that this does not make a request to the server but it changes the url in the location address bar and in location.href

But you can use also an absolute URL according to the documentation


问:
wcf netdatacontractserializer exception serialising idictionary with enumeration as key
I am using the NetDataContractSerialiser with WCF. This is working well with all our types being serialised. However, a service I am calling is generating the following exception

The formatter threw an exception while trying to deserialize the message:

There was an error while trying to deserialize parameter http://tempuri.org/:xmlServiceObjIN. The InnerException message was 'The deserializer cannot load the type to deserialize because type 'System.Collections.Generic.EnumEqualityComparer`1[[GrantEd.Common.DomainModel.Code.Enums.enumFundingParameterContextKey, GrantEd.Common.DomainModel.Code, Version=14.0.71.0, Culture=neutral, PublicKeyToken=null]]' could not be found in assembly 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
Check that the type being serialized has the same contract as the type being deserialized and the same assembly is used.'.  Please see InnerException for more details.

The class being serialised has a property defined as

```<code>public IDictionary<enumFundingParameterContextKey, string>  Context { get; set; }
</code>```

the declaration of the enum is

```<code>[Serializable]
public enum enumFundingParameterContextKey
{
    [EnumMemberAttribute()]
    ClientId = 0,
    [EnumMemberAttribute()]
    EntitlementDefinitionId = 1
}
</code>```

which is defined in another assmebly.

When I replace the enumeration with int the class deserialises with no problems. Any ideas why using the enum would result the exception?

The reason for using NetDataContractSerializer was to for type information to be available and avoid having to use KnownType

答: Try to mark enum with [DataContract] instead of [Serializable]. But it looks like the enum type is unknown at all on the client.

ContentLicense: CC BY-SA 3.0

Body:
I am using the NetDataContractSerialiser with WCF. This is working well with all our types being serialised. However, a service I am calling is generating the following exception

The formatter threw an exception while trying to deserialize the message:

There was an error while trying to deserialize parameter http://tempuri.org/:xmlServiceObjIN. The InnerException message was 'The deserializer cannot load the type to deserialize because type 'System.Collections.Generic.EnumEqualityComparer`1[[GrantEd.Common.DomainModel.Code.Enums.enumFundingParameterContextKey, GrantEd.Common.DomainModel.Code, Version=14.0.71.0, Culture=neutral, PublicKeyToken=null]]' could not be found in assembly 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
Check that the type being serialized has the same contract as the type being deserialized and the same assembly is used.'.  Please see InnerException for more details.

The class being serialised has a property defined as

public IDictionary<enumFundingParameterContextKey, string>  Context { get; set; }

the declaration of the enum is

[Serializable]
public enum enumFundingParameterContextKey
{
    [EnumMemberAttribute()]
    ClientId = 0,
    [EnumMemberAttribute()]
    EntitlementDefinitionId = 1
}

which is defined in another assmebly.

When I replace the enumeration with int the class deserialises with no problems. Any ideas why using the enum would result the exception?

The reason for using NetDataContractSerializer was to for type information to be available and avoid having to use KnownType


问:
Automatically Add CloudWatch LogGroup to another LogGroup?
I have a Logger Lambda function that listens on a specific LogGroup and process specific log details.

I would like to attach the newly created LogGroups of other lambdas to that specific LogGroup, so it will process them as well - but since these other lambdas are created automatically, I need to do this automatically. Can I do it? How?

答:
So there's no way to directly replicate the logs stored in a CloudWatch log group to another log group. You could do this by creating a subscription filter with a Lambda function to push the logs from each log group to the common one, but this would increase the costs for CloudWatch.

What I would suggest is either of the following:

Create a subscription filter for each of the log groups used by your Lambda functions to the common Lambda function so that it is triggered when logs are pushed to any of the log groups. This event can be set up after creating each function. Note, you would have to update the function policy of the common Lambda to allow it to be invoked from each log group (or just set up a wildcard).

Push all the logs for all of the functions to a single log group. This would take the least effort, but you would have to figure out how to effectively separate the logs per function (if that is required for your use case).


问:
why babel-loader is part of webpack instead babel itself?
I am learning about how build system works in JavaScript. If babel-loader is transpiler that translates React to JavaScript, why is it part of webpack plugin?

Isn't transpiling and bundling is a separate process?

And is there a resource that explain how all this frameworks fit together and make build system work in detail? I seem to only find high level overview at the official docs.

答:
Webpack is a "module bundler". On its own it does not change the source of a program (note: there are some caveats to this, e.g. minification), only join all the different bits of a large codebase together for easier and more efficient delivery over the Internet (depending on the use case; you may be bundling server-side code, in which case the benefits are mostly around being able to consolidate build tooling).

A webpack loader is used to process files during bundling. It is specific to webpack (you would not use babel-loader without webpack, except maybe in cases of interop with other build tools, but even then it would not used on its own).

In a webpack configuration one specifies a mapping of file extensions to webpack loaders. For example, a common case is to process .ts files using ts-loader. This way, webpack will pass off files with the .ts extension to the TypeScript compiler, and use the output of this compilation in the bundle, instead of the source program.

Babel is a compiler; it takes an ESNext program and produces an equivalent ES3+ compatible program.

babel-loader does what ts-loader does for TypeScript; passes off files to the Babel compiler, and returns the result to be used in the bundle in-place of the original source program.

Isn't transpiling and bundling is a separate process?

Yes. That is why we have "webpack the bundler", and "Babel the compiler/transpiler", and babel-loader to connect the two together. Without babel-loader webpack would not be able to process files through Babel.

Hope that helps.


问:
Django: When print a QuerySet gives an error
I have a table(SavedSchedules) below in the database. hall_n_time and schedule columns stores two python lists as string.

```<code>+----+---------------+-------------+----------+
| id |   lecturer    | hall_n_time | schedule |
+----+---------------+-------------+----------+
|... |      ...      |     ...     |    ...   |
+----+---------------+-------------+----------+
</code>```

I have below script in views.py:

```<code>lec_name = User.objects.filter(username=request.session['logged_username']).values_list('lecturer_name', flat=True)
print(lec_name)
</code>```

This gives OUTPUT:

```<code><QuerySet ['A. B. C. Watson']>
</code>```

But EXPECTED OUTPUT:

```<code>A. B. C. Watson
</code>```

Then I tried below script:

```<code>lec_name = User.objects.filter(username=request.session['logged_username']).values_list('lecturer_name', flat=True)
schedule_data = SavedSchedules.objects.filter(lecturer=lec_name)
print(schedule_data)
</code>```

It gives below ERROR when I execute it:

```<code>Traceback (most recent call last):
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\Web Projects\CIS_ALTG\altg\altg_app\views.py", line 497, in profile
    print(schedule_data)
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 252, in __repr__
    data = list(self[:REPR_OUTPUT_SIZE + 1])
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 276, in __iter__
    self._fetch_all()
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 1261, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 57, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1124, in execute_sql
    sql, params = self.as_sql()
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 498, in as_sql
    where, w_params = self.compile(self.where) if self.where is not None else ("", [])
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 415, in compile
    sql, params = node.as_sql(self, self.connection)
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\where.py", line 81, in as_sql
    sql, params = compiler.compile(child)
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 415, in compile
    sql, params = node.as_sql(self, self.connection)
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\lookups.py", line 177, in as_sql
    rhs_sql, rhs_params = self.process_rhs(compiler, connection)
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\lookups.py", line 270, in process_rhs
    'The QuerySet value for an exact lookup must be limited to '
ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing.
[30/Apr/2020 17:26:37] "GET /profile/ HTTP/1.1" 500 122259
</code>```

I'm new to Django and I have no idea why it gives this kind of error. Can someone explain why this happens and how to solve these issues? I appreciate your help. I'm using Python 3.7.4, Django 3.0.1

答:
Using values_list will still give you a queryset, but it has a list inside. you can get the values as a pure list using:

```<code>lec_name = list(User.objects.filter(username=request.session['logged_username']).values_list('lecturer_name', flat=True))[0]
print(lec_name)
</code>```

This gets the first element in the list, which should be your lecturer name.

The issue with

```<code>schedule_data = SavedSchedules.objects.filter(lecturer=lec_name)
print(schedule_data)
</code>```

is that in your current form, lec_name is a queryset/list, and SavedSchedules can't look for objects where its lecturer = a list. Either use my modification above to get a single lecturer, or use this syntax to get SavedSchedules where the lecturer is from a list:

```<code>schedule_data = SavedSchedules.objects.filter(lecturer__in=lec_list)
</code>```

Hope those suggestions help, happy coding!

Body:
I have a table(SavedSchedules) below in the database. hall_n_time and schedule columns stores two python lists as string.

+----+---------------+-------------+----------+
| id |   lecturer    | hall_n_time | schedule |
+----+---------------+-------------+----------+
|... |      ...      |     ...     |    ...   |
+----+---------------+-------------+----------+

I have below script in views.py:

lec_name = User.objects.filter(username=request.session['logged_username']).values_list('lecturer_name', flat=True)
print(lec_name)

This gives OUTPUT:

<QuerySet ['A. B. C. Watson']>

But EXPECTED OUTPUT:

A. B. C. Watson

Then I tried below script:

lec_name = User.objects.filter(username=request.session['logged_username']).values_list('lecturer_name', flat=True)
schedule_data = SavedSchedules.objects.filter(lecturer=lec_name)
print(schedule_data)

It gives below ERROR when I execute it:

Traceback (most recent call last):
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\Web Projects\CIS_ALTG\altg\altg_app\views.py", line 497, in profile
    print(schedule_data)
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 252, in __repr__
    data = list(self[:REPR_OUTPUT_SIZE + 1])
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 276, in __iter__
    self._fetch_all()
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 1261, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 57, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1124, in execute_sql
    sql, params = self.as_sql()
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 498, in as_sql
    where, w_params = self.compile(self.where) if self.where is not None else ("", [])
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 415, in compile
    sql, params = node.as_sql(self, self.connection)
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\where.py", line 81, in as_sql
    sql, params = compiler.compile(child)
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 415, in compile
    sql, params = node.as_sql(self, self.connection)
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\lookups.py", line 177, in as_sql
    rhs_sql, rhs_params = self.process_rhs(compiler, connection)
  File "C:\Users\BhathiyaTK\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\lookups.py", line 270, in process_rhs
    'The QuerySet value for an exact lookup must be limited to '
ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing.
[30/Apr/2020 17:26:37] "GET /profile/ HTTP/1.1" 500 122259

I'm new to Django and I have no idea why it gives this kind of error. Can someone explain why this happens and how to solve these issues? I appreciate your help. I'm using Python 3.7.4, Django 3.0.1

Body:
Using values_list will still give you a queryset, but it has a list inside. you can get the values as a pure list using:

lec_name = list(User.objects.filter(username=request.session['logged_username']).values_list('lecturer_name', flat=True))[0]
print(lec_name)

This gets the first element in the list, which should be your lecturer name.

The issue with

schedule_data = SavedSchedules.objects.filter(lecturer=lec_name)
print(schedule_data)

is that in your current form, lec_name is a queryset/list, and SavedSchedules can't look for objects where its lecturer = a list. Either use my modification above to get a single lecturer, or use this syntax to get SavedSchedules where the lecturer is from a list:

schedule_data = SavedSchedules.objects.filter(lecturer__in=lec_list)

Hope those suggestions help, happy coding!


问:
Is there something like Siri Shortcuts for Google Assistant?
As I previously did with my iPhone I'd like to tell my Android phone: "Ok Google, open my main door"

that called a webhook url that then opened my front door.

How can I accomplish that with Google Assistant? Is there something like Shortcuts so I can set a phrase that then just calls an url?

btw: I tried it with google assistant action - hwr, there you can only publish your actions publicly.
I also tried "Routines" but as the action it does not open websites with the "open website" command that have a subdomain or a port set, which my url does.

答: You can use IFTTT to create an "Applet" that accepts commands that you've defined from your Google Assistant and sends an HTTP command that you choose.</p>


问:
java.io.IOException: Media was not found in the extent report while attacthing the screenshot in html report
I get the screenshot in base64 format and while executing the test class ;it shows the error of Media was not found. Could anyone please do let me know where i am lacking in the code

Code:

```<code>public static String captureScreenAsBase64(WebDriver driver, String screenshotName) throws IOException {
        try {
            TakesScreenshot newScreen = (TakesScreenshot) driver;
            String scnShot = newScreen.getScreenshotAs(OutputType.BASE64);
            return "data:image/jpg;base64, " + scnShot ;
        } catch (WebDriverException e) {
            e.printStackTrace();
        }
        return screenshotName;
    }
@AfterMethod(alwaysRun = true)
public void getResult(ITestResult result) throws Exception {
    if (result.getStatus() == ITestResult.FAILURE) {
        logger.log(Status.FAIL,
                MarkupHelper.createLabel(result.getName() + " - Test Case Failed", ExtentColor.RED));
        logger.log(Status.FAIL,
                MarkupHelper.createLabel(result.getThrowable() + " - Test Case Failed", ExtentColor.RED));

        String screenshotPath = TestUtil.captureScreenAsBase64(driver, result.getName());
        logger.fail("Snapshot below: " + logger.addScreenCaptureFromPath(screenshotPath));

    } else if (result.getStatus() == ITestResult.SKIP) {
        logger.log(Status.SKIP,
                MarkupHelper.createLabel(result.getName() + " - Test Case Skipped", ExtentColor.ORANGE));
    } else if (result.getStatus() == ITestResult.SUCCESS) {
        logger.log(Status.PASS,
                MarkupHelper.createLabel(result.getName() + " Test Case PASSED", ExtentColor.GREEN));
    }
    extent.flush();
}

Exception:
java.io.IOException: Media was not found
</code>```

答:
Try using an allure report. It is an open-source report as well and it supports multithreading in appium unlike extent report. The following code will attach a screenshot to the allure report on test failure,</p>

```<code>public class TestListener implements ITestListener {
...
@Override
    public void onTestFailure(ITestResult iTestResult) {
            try {
                byte[] screenShot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
                Allure.getLifecycle().addAttachment(your-screensout-filename, "image/png", "png", screenShot);
            } catch (Exception e) {
                e.printStackTrace();
                log("Exception occured while taking the screenshot");
            }
        }
...
}
</code>```

Body:
I get the screenshot in base64 format and while executing the test class ;it shows the error of Media was not found. Could anyone please do let me know where i am lacking in the code

Code:

public static String captureScreenAsBase64(WebDriver driver, String screenshotName) throws IOException {
        try {
            TakesScreenshot newScreen = (TakesScreenshot) driver;
            String scnShot = newScreen.getScreenshotAs(OutputType.BASE64);
            return "data:image/jpg;base64, " + scnShot ;
        } catch (WebDriverException e) {
            e.printStackTrace();
        }
        return screenshotName;
    }
@AfterMethod(alwaysRun = true)
public void getResult(ITestResult result) throws Exception {
    if (result.getStatus() == ITestResult.FAILURE) {
        logger.log(Status.FAIL,
                MarkupHelper.createLabel(result.getName() + " - Test Case Failed", ExtentColor.RED));
        logger.log(Status.FAIL,
                MarkupHelper.createLabel(result.getThrowable() + " - Test Case Failed", ExtentColor.RED));

        String screenshotPath = TestUtil.captureScreenAsBase64(driver, result.getName());
        logger.fail("Snapshot below: " + logger.addScreenCaptureFromPath(screenshotPath));

    } else if (result.getStatus() == ITestResult.SKIP) {
        logger.log(Status.SKIP,
                MarkupHelper.createLabel(result.getName() + " - Test Case Skipped", ExtentColor.ORANGE));
    } else if (result.getStatus() == ITestResult.SUCCESS) {
        logger.log(Status.PASS,
                MarkupHelper.createLabel(result.getName() + " Test Case PASSED", ExtentColor.GREEN));
    }
    extent.flush();
}

Exception:
java.io.IOException: Media was not found

Body:
Try using an allure report. It is an open-source report as well and it supports multithreading in appium unlike extent report. The following code will attach a screenshot to the allure report on test failure,

public class TestListener implements ITestListener {
...
@Override
    public void onTestFailure(ITestResult iTestResult) {
            try {
                byte[] screenShot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
                Allure.getLifecycle().addAttachment(your-screensout-filename, "image/png", "png", screenShot);
            } catch (Exception e) {
                e.printStackTrace();
                log("Exception occured while taking the screenshot");
            }
        }
...
}


问:
Pure Java alternative to database / cache for storing records
I have created an application sold to customers, some of which are hardware manufacturers with fixed constraints (slow CPU). The app has to be in java, so that it can be easily installed as a single package.

The application is multithreaded and maintains audio records. In this particular case all we have is INSERT SOMEDATA FOR RECORD, each record representing an audio file (and this can be done by different threads), and then later on we have SELECT SOMEDATA WHERE IDS in (x, y, z) by an single thread, then 3rd step is we actually DELETE all the data in this table.

The main constraint is cpu, slow single cpu. Memory is also a constraint, but only in that the application is designed so it can process an unlimited number of files, and so even if had lots of memory would eventually run out if all stored in memory rather than utilizing the disk.

In my Java application I started off using the H2 database to store all my data. But the software has to run on some slow single cpu servers so I want to reduce the cpu cycles used, and one area I want to look again is the database.

In many cases I am inserting data into database simply for the purposes of keeping the data off the heap otherwise would run out of memory, then later on we retrieve the data, we never have to UPDATE the data.

So I considered using a cache like ehCache but that has two problems:

It doesn't guarantee the data will not be thrown away (If the cache gets full)

I can only retrieve records one at a time, whereas with relational database I can retrieve a batch of records, this looks like a potential bottleneck.

What is an alternative that solves these issues ?

答:
From your question and the comments made on Mark Bramniks answer I understood this:

CPU constraint: very slow cpu, solution should not be cpu intensive

Memory constraint: Not all data can be in memory

Disk constraint: very slow disk, solution should not read/write lots of data from disk

These are very strict constraints. Usually you "trade" cpu vs memory or memory vs disk. In your case these are all constraint. You mentioned you looked at ehCache, however I think this solution (and possibly others such as memcached) are not more lightweight than H2.

One solution you could try is MappedByteBuffer. This class makes it possible to have parts of a file in memory and will swap those parts when needed. But this comes at a cost, it is not an easy beast to tame. You will need to write your own algorithm to locate the data you need. Please consider how much time it will take you to get it working vs the additional cost of a bigger machine. Sometimes better hardware is the solution.


问:
What will be the SQL query for ordering dates with respect to day name starting with tuesday?
It should order it by week day names i.e., tuesdays come first, wednesdays next, and so on.

Here's what I have done:

```<code>SELECT hire_date, TO_CHAR(hire_date,'Day')
FROM employee
ORDER BY TO_CHAR(hire_date,'Day');

</code>```

but it doesn't start ordering from tuesday...

答:
Hmmm . . . You can keep the weekdays together and order them by including the weekday number:

```<code>SELECT hire_date, TO_CHAR(hire_date, 'Day')
FROM employee
ORDER BY TO_CHAR(hire_date, 'D'), hire_date
</code>```

Unfortunately, this will start on Sunday or Monday, in most cases.  You can adjust for your particular setting by subtracting one or two days:

```<code>SELECT hire_date, TO_CHAR(hire_date, 'Day')
FROM employee
ORDER BY TO_CHAR(hire_date - interval '1' day, 'D'), hire_date
</code>```

Or you can be explicit:

```<code>SELECT hire_date, TO_CHAR(hire_date, 'Day')
FROM employee
ORDER BY TO_CHAR(hire_date - interval '1' day, 'D', 'NLS_TERRITORY = 'AMERICA'), hire_date
</code>```

Body:
It should order it by week day names i.e., tuesdays come first, wednesdays next, and so on.

Here's what I have done:

SELECT hire_date, TO_CHAR(hire_date,'Day')
FROM employee
ORDER BY TO_CHAR(hire_date,'Day');

but it doesn't start ordering from tuesday...

Body:
Hmmm . . . You can keep the weekdays together and order them by including the weekday number:

SELECT hire_date, TO_CHAR(hire_date, 'Day')
FROM employee
ORDER BY TO_CHAR(hire_date, 'D'), hire_date

Unfortunately, this will start on Sunday or Monday, in most cases.  You can adjust for your particular setting by subtracting one or two days:

SELECT hire_date, TO_CHAR(hire_date, 'Day')
FROM employee
ORDER BY TO_CHAR(hire_date - interval '1' day, 'D'), hire_date

Or you can be explicit:

SELECT hire_date, TO_CHAR(hire_date, 'Day')
FROM employee
ORDER BY TO_CHAR(hire_date - interval '1' day, 'D', 'NLS_TERRITORY = 'AMERICA'), hire_date


问:
Kafka streams Exception: org.apache.kafka.streams.errors.StreamsException - Deserialization exception handler
I am trying to implement a simple counter with kafka streams. It takes a key value and adds new values if the same key comes.

This is the code I wrote so far

```<code>package exercises;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.Produced;

import java.util.Properties;

public class LiveCounter {
    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.setProperty(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        properties.setProperty(StreamsConfig.APPLICATION_ID_CONFIG, "live-counter-2");
        properties.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
        properties.setProperty(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.StringSerde.class.getName());
        properties.setProperty(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.LongSerde.class.getName());
        properties.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0);

        StreamsBuilder builder = new StreamsBuilder();
        KStream<String, String> textLine = builder.stream("counter-in");

        KStream<String, Long> words = textLine
                .filter((k, v) -> {
                    try {
                        String[] arr = v.split(" ");
                        Long.parseLong(arr[1]);
                        return true;
                    } catch (NumberFormatException e) {
                        return false;
                    }
                })
                .selectKey((k, v) -> v.split(" ")[0])
                .mapValues((k, v) -> Long.parseLong(v.split(" ")[1]))
                .groupByKey()
                .reduce(Long::sum)
                .toStream();
        words.to("counter-out", Produced.with(Serdes.String(), Serdes.Long()));

        KafkaStreams streams = new KafkaStreams(builder.build(), properties);
        streams.start();

        System.out.println(streams.toString());

        Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
    }
}
</code>```

As we can see the topology is simple. It takes a textline and changes the key and then finally adds all the values for key groups with the reduce function.

I tried streaming until mapValues and it was working. But this code block is causing the problem

```<code>.groupByKey()
.reduce(Long::sum)
.toStream();
</code>```

This is the stacktrace

```<code>live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] ERROR org.apache.kafka.streams.errors.LogAndFailExceptionHandler - Exception caught during Deserialization, taskId: 0_0, topic: counter-in, partition: 0, offset: 1
org.apache.kafka.common.errors.SerializationException: Size of data received by LongDeserializer is not 8
[live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] ERROR org.apache.kafka.streams.processor.internals.StreamThread - stream-thread [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] Encountered the following unexpected Kafka exception during processing, this usually indicate Streams internal errors:
org.apache.kafka.streams.errors.StreamsException: Deserialization exception handler is set to fail upon a deserialization error. If you would rather have the streaming pipeline continue after a deserialization error, please set the default.deserialization.exception.handler appropriately.
    at org.apache.kafka.streams.processor.internals.RecordDeserializer.deserialize(RecordDeserializer.java:80)
    at org.apache.kafka.streams.processor.internals.RecordQueue.updateHead(RecordQueue.java:175)
    at org.apache.kafka.streams.processor.internals.RecordQueue.addRawRecords(RecordQueue.java:112)
    at org.apache.kafka.streams.processor.internals.PartitionGroup.addRawRecords(PartitionGroup.java:162)
    at org.apache.kafka.streams.processor.internals.StreamTask.addRecords(StreamTask.java:765)
    at org.apache.kafka.streams.processor.internals.StreamThread.addRecordsToTasks(StreamThread.java:943)
    at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:764)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:697)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:670)
Caused by: org.apache.kafka.common.errors.SerializationException: Size of data received by LongDeserializer is not 8
[live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] INFO org.apache.kafka.streams.processor.internals.StreamThread - stream-thread [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] State transition from RUNNING to PENDING_SHUTDOWN
[live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] INFO org.apache.kafka.streams.processor.internals.StreamThread - stream-thread [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] Shutting down
[live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] INFO org.apache.kafka.clients.consumer.KafkaConsumer - [Consumer clientId=live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1-restore-consumer, groupId=null] Unsubscribed all topics or patterns and assigned partitions
[live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] INFO org.apache.kafka.clients.producer.KafkaProducer - [Producer clientId=live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1-producer] Closing the Kafka producer with timeoutMillis = 9223372036854775807 ms.
[live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] INFO org.apache.kafka.streams.processor.internals.StreamThread - stream-thread [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] State transition from PENDING_SHUTDOWN to DEAD
[live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] INFO org.apache.kafka.streams.KafkaStreams - stream-client [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67] State transition from RUNNING to ERROR
[live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] ERROR org.apache.kafka.streams.KafkaStreams - stream-client [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67] All stream threads have died. The instance will be in error state and should be closed.
[live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] INFO org.apache.kafka.streams.processor.internals.StreamThread - stream-thread [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] Shutdown complete
Exception in thread "live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1" org.apache.kafka.streams.errors.StreamsException: Deserialization exception handler is set to fail upon a deserialization error. If you would rather have the streaming pipeline continue after a deserialization error, please set the default.deserialization.exception.handler appropriately.
    at org.apache.kafka.streams.processor.internals.RecordDeserializer.deserialize(RecordDeserializer.java:80)
    at org.apache.kafka.streams.processor.internals.RecordQueue.updateHead(RecordQueue.java:175)
    at org.apache.kafka.streams.processor.internals.RecordQueue.addRawRecords(RecordQueue.java:112)
    at org.apache.kafka.streams.processor.internals.PartitionGroup.addRawRecords(PartitionGroup.java:162)
    at org.apache.kafka.streams.processor.internals.StreamTask.addRecords(StreamTask.java:765)
    at org.apache.kafka.streams.processor.internals.StreamThread.addRecordsToTasks(StreamThread.java:943)
    at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:764)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:697)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:670)
Caused by: org.apache.kafka.common.errors.SerializationException: Size of data received by LongDeserializer is not 8
[Thread-1] INFO org.apache.kafka.streams.KafkaStreams - stream-client [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67] State transition from ERROR to PENDING_SHUTDOWN
[kafka-streams-close-thread] INFO org.apache.kafka.streams.processor.internals.StreamThread - stream-thread [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] Informed to shut down
[kafka-streams-close-thread] INFO org.apache.kafka.streams.KafkaStreams - stream-client [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67] State transition from PENDING_SHUTDOWN to NOT_RUNNING
[Thread-1] INFO org.apache.kafka.streams.KafkaStreams - stream-client [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67] Streams client stopped completely
</code>```

Any help would be appreciated. Thanks in advance

答:
Since your input topic, counter-in, consists of messages that are Strings, and your default value serializer is LongSerde, you need to tell Kafka Streams to deserialize the value as a string as follows:

```<code>KStream<String, String> textLine = builder.stream("counter-in", Consumed.with(Serdes.String(), Serdes.String()));
</code>```

Body:
I am trying to implement a simple counter with kafka streams. It takes a key value and adds new values if the same key comes.

This is the code I wrote so far

package exercises;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.Produced;

import java.util.Properties;

public class LiveCounter {
    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.setProperty(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        properties.setProperty(StreamsConfig.APPLICATION_ID_CONFIG, "live-counter-2");
        properties.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
        properties.setProperty(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.StringSerde.class.getName());
        properties.setProperty(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.LongSerde.class.getName());
        properties.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0);

        StreamsBuilder builder = new StreamsBuilder();
        KStream<String, String> textLine = builder.stream("counter-in");

        KStream<String, Long> words = textLine
                .filter((k, v) -> {
                    try {
                        String[] arr = v.split(" ");
                        Long.parseLong(arr[1]);
                        return true;
                    } catch (NumberFormatException e) {
                        return false;
                    }
                })
                .selectKey((k, v) -> v.split(" ")[0])
                .mapValues((k, v) -> Long.parseLong(v.split(" ")[1]))
                .groupByKey()
                .reduce(Long::sum)
                .toStream();
        words.to("counter-out", Produced.with(Serdes.String(), Serdes.Long()));

        KafkaStreams streams = new KafkaStreams(builder.build(), properties);
        streams.start();

        System.out.println(streams.toString());

        Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
    }
}

As we can see the topology is simple. It takes a textline and changes the key and then finally adds all the values for key groups with the reduce function.

I tried streaming until mapValues and it was working. But this code block is causing the problem

.groupByKey()
.reduce(Long::sum)
.toStream();

This is the stacktrace

live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] ERROR org.apache.kafka.streams.errors.LogAndFailExceptionHandler - Exception caught during Deserialization, taskId: 0_0, topic: counter-in, partition: 0, offset: 1
org.apache.kafka.common.errors.SerializationException: Size of data received by LongDeserializer is not 8
[live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] ERROR org.apache.kafka.streams.processor.internals.StreamThread - stream-thread [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] Encountered the following unexpected Kafka exception during processing, this usually indicate Streams internal errors:
org.apache.kafka.streams.errors.StreamsException: Deserialization exception handler is set to fail upon a deserialization error. If you would rather have the streaming pipeline continue after a deserialization error, please set the default.deserialization.exception.handler appropriately.
    at org.apache.kafka.streams.processor.internals.RecordDeserializer.deserialize(RecordDeserializer.java:80)
    at org.apache.kafka.streams.processor.internals.RecordQueue.updateHead(RecordQueue.java:175)
    at org.apache.kafka.streams.processor.internals.RecordQueue.addRawRecords(RecordQueue.java:112)
    at org.apache.kafka.streams.processor.internals.PartitionGroup.addRawRecords(PartitionGroup.java:162)
    at org.apache.kafka.streams.processor.internals.StreamTask.addRecords(StreamTask.java:765)
    at org.apache.kafka.streams.processor.internals.StreamThread.addRecordsToTasks(StreamThread.java:943)
    at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:764)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:697)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:670)
Caused by: org.apache.kafka.common.errors.SerializationException: Size of data received by LongDeserializer is not 8
[live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] INFO org.apache.kafka.streams.processor.internals.StreamThread - stream-thread [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] State transition from RUNNING to PENDING_SHUTDOWN
[live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] INFO org.apache.kafka.streams.processor.internals.StreamThread - stream-thread [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] Shutting down
[live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] INFO org.apache.kafka.clients.consumer.KafkaConsumer - [Consumer clientId=live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1-restore-consumer, groupId=null] Unsubscribed all topics or patterns and assigned partitions
[live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] INFO org.apache.kafka.clients.producer.KafkaProducer - [Producer clientId=live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1-producer] Closing the Kafka producer with timeoutMillis = 9223372036854775807 ms.
[live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] INFO org.apache.kafka.streams.processor.internals.StreamThread - stream-thread [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] State transition from PENDING_SHUTDOWN to DEAD
[live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] INFO org.apache.kafka.streams.KafkaStreams - stream-client [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67] State transition from RUNNING to ERROR
[live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] ERROR org.apache.kafka.streams.KafkaStreams - stream-client [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67] All stream threads have died. The instance will be in error state and should be closed.
[live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] INFO org.apache.kafka.streams.processor.internals.StreamThread - stream-thread [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] Shutdown complete
Exception in thread "live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1" org.apache.kafka.streams.errors.StreamsException: Deserialization exception handler is set to fail upon a deserialization error. If you would rather have the streaming pipeline continue after a deserialization error, please set the default.deserialization.exception.handler appropriately.
    at org.apache.kafka.streams.processor.internals.RecordDeserializer.deserialize(RecordDeserializer.java:80)
    at org.apache.kafka.streams.processor.internals.RecordQueue.updateHead(RecordQueue.java:175)
    at org.apache.kafka.streams.processor.internals.RecordQueue.addRawRecords(RecordQueue.java:112)
    at org.apache.kafka.streams.processor.internals.PartitionGroup.addRawRecords(PartitionGroup.java:162)
    at org.apache.kafka.streams.processor.internals.StreamTask.addRecords(StreamTask.java:765)
    at org.apache.kafka.streams.processor.internals.StreamThread.addRecordsToTasks(StreamThread.java:943)
    at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:764)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:697)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:670)
Caused by: org.apache.kafka.common.errors.SerializationException: Size of data received by LongDeserializer is not 8
[Thread-1] INFO org.apache.kafka.streams.KafkaStreams - stream-client [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67] State transition from ERROR to PENDING_SHUTDOWN
[kafka-streams-close-thread] INFO org.apache.kafka.streams.processor.internals.StreamThread - stream-thread [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67-StreamThread-1] Informed to shut down
[kafka-streams-close-thread] INFO org.apache.kafka.streams.KafkaStreams - stream-client [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67] State transition from PENDING_SHUTDOWN to NOT_RUNNING
[Thread-1] INFO org.apache.kafka.streams.KafkaStreams - stream-client [live-counter-2-9a694aa5-589d-4d2f-8e1c-ff64b6e05b67] Streams client stopped completely

Any help would be appreciated. Thanks in advance

Body:
Since your input topic, counter-in, consists of messages that are Strings, and your default value serializer is LongSerde, you need to tell Kafka Streams to deserialize the value as a string as follows:

KStream<String, String> textLine = builder.stream("counter-in", Consumed.with(Serdes.String(), Serdes.String()));


问:
Speed up compilation and bench-marking of schedules
I am making a program that is bench-marking a lot of generated schedules for a particular algorithm. But that is taking a lot of time, for the most part due to the compilation of each schedule. And I was wondering If there are any ways to speed up this process.

For example using AOT compilation or generators, but I don't think it is possible to give a generator different schedules after it has been created? (E.g. have the schedule as an input parameter.)

Or are there any compiler flags that can give a significant speed-up?

However I also saw that in the autoscheduler a cost-model is used to predict the execution time of a schedule, this would solve my problem. But I cannot figure out if it is possible or how to use this cost model in my own program, and if it only works for schedules that the autoscheduler generated or for every schedule.

答:
Unfortunately there's no great answer. The bulk of the compile time is in Halide lowering and in LLVM, which must be done separately for every schedule, so just reusing a Generator won't help you. You can use Func::specialize on a boolean input param to switch between schedules at runtime, but that doesn't save you much compile time relative to compiling the options separately.

The cost model in the autoscheduler is specific to its representation of the subspace of Halide schedules that it explores, and wouldn't work on arbitrary Halide schedules.

There's one trick that might help: If your algorithm is long and complicated, and you know where some of the compute_roots should be (e.g. the last thing before a conv layer), then you can break your algorithm into multiple pieces and independently search over schedules for each. Compiling smaller algorithms is moderately faster, but more importantly this will make the overall search more efficient in terms of the number of samples it needs to take.


问:
Hiding Combo Items In CComboBox
Is it possible to hide particular Items in the MFC Combo Box?

I have a list which contains 5 items ALPHA-0, BETA-1, GAMA-2, DELTA-3, OMEGA-4 stored in the vector

```<code>vector<string> mListItems;
CComboBox m_List1;
CComboBox m_List2;
</code>```

I am using this vector to populate the two combo boxes.
In m_List1 it should populate all the 5 items but in m_List2 it should populate all items but should not show GAMA.
Here index for each is used in the code for each index different business logic is implemented. So I can't remove the items GAMA from second list.

Please do you have any suggestions to help me with this?

Is it possible to do this?

答:
Combo boxes show whatever items you add in them. If an item was added, it will be displayed.

So if you want to hide some items, you need to remove them from the combo. This can be done through DeleteString from CComboBox.

Title: Hiding Combo Items In CComboBox

Body:
Is it possible to hide particular Items in the MFC Combo Box?

I have a list which contains 5 items ALPHA-0, BETA-1, GAMA-2, DELTA-3, OMEGA-4 stored in the vector

vector<string> mListItems;
CComboBox m_List1;
CComboBox m_List2;

I am using this vector to populate the two combo boxes.
In m_List1 it should populate all the 5 items but in m_List2 it should populate all items but should not show GAMA.
Here index for each is used in the code for each index different business logic is implemented. So I can't remove the items GAMA from second list.

Please do you have any suggestions to help me with this?

Is it possible to do this?


问:
How to use shinyFiles package within Shiny Modules - Namespace Issue?
I'm having trouble using the "shinyFilesButton()" and "shinyFilesChoose()" functionality within modules in R shiny.

I believe my issue is related to the namespace functions ("ns()") that effectively create new, unique ids within the modules.

Where do I put the ns() call within the shinyFiles functions? How do I handle this issue on the server side?

I've mocked up an example, with code shown below.  The app just selects a file and tells you the info on what you selected. Note that currently no ns() calls are used with any shinyFiles functions. (I've tried wrapping the shinyFilesButton()'s id in the ns(), but then it doesn't match with the shinyFileChoose.)

Currently, this app below will show me files, but only in the root directory. I can't delve deeper into other directories. Additionally, the select button will highlight, but nothing will happen when used.

Edit: I've update the code with an attempt at using the namespaces, per suggestions in the comments. I'm using the ns() function in the shinyFilesButton() call (ui side) and nothing in the server side.

Now I can't see any files when using the file chooser.

Any help?

Below is my code for the app.r file:

```<code>#App.R
#Demonstrate issues with ShinyFiles and namesspaces in modules

library(shiny)
library(shinyFiles)

source("shinyFiles_module.R")

server <- function(input, output, session) {
  #module Way
  callModule(sample,
             id="testid",
             root_dirs=c(root_on_mac="/Users/Ryan/Desktop/"))
}

ui <- fluidPage(
  tagList(
    h2("Module Way"),
    sample_UI(id = "testid",
              label = "shiny file test")
  )
)

shinyApp(ui = ui, server = server)
</code>```

And for the module:

```<code>#Sample shinyFiles Module
#trying to get File path using ShinyFiles within a Module

library(shiny)
library(shinyFiles)

#Settings UI function:
# Module UI function
sample_UI <- function(id, label = "Shiny file test") {
  # Create a namespace function using the provided id
  ns <- NS(id)

  #begin UI (wrap all input/ouput in ns() call)
  tagList(
    strong("Selected Location: "), verbatimTextOutput(ns("file_path")),
    shinyFilesButton(
      id=ns("get_file_path"),
      label="Click Here to Select",
      title="Select a file",
      multiple= FALSE,
      buttonType = "default",
      class = NULL)
  )
}

# Module server function
sample <- function(input,
                   output,
                   session,
                   root_dirs,
                   id_value) {

  shinyFileChoose(input, id="get_file_path", roots=root_dirs, session=session)

  output$file_path <- renderPrint({
    parseFilePaths(roots=root_dirs, input$get_file_path)
  })
}
</code>```

答:
I have the same issue and I resolve it by following Carl's suggestion:

use ns() in ui

remove ns() in server

I am using R3.6.1 and it works. In R3.4 it has problem navigate into the subfolders.

```<code>library(shiny)
library(shinyFiles)

#Settings UI function:
# Module UI function
sample_UI <- function(id, label = "Shiny file test") {
  # Create a namespace function using the provided id
  ns <- NS(id)

  #begin UI (wrap all input/ouput in ns() call)
  tagList(
    strong("Selected Location: "), verbatimTextOutput(ns("file_path")),
    shinyFilesButton(
      id=ns("get_file_path"),
      label="Click Here to Select",
      title="Select a file",
      multiple= FALSE,
      buttonType = "default",
      class = NULL)
  )
}

# Module server function
sample <- function(input,
                   output,
                   session,
                   root_dirs,
                   id_value) {

  shinyFileChoose(input, id="get_file_path", roots=root_dirs, session=session)

  output$file_path <- renderPrint({
    parseFilePaths(roots=root_dirs, input$get_file_path)
  })
}
</code>```

Body:
I'm having trouble using the "shinyFilesButton()" and "shinyFilesChoose()" functionality within modules in R shiny.

I believe my issue is related to the namespace functions ("ns()") that effectively create new, unique ids within the modules.

Where do I put the ns() call within the shinyFiles functions? How do I handle this issue on the server side?

I've mocked up an example, with code shown below.  The app just selects a file and tells you the info on what you selected. Note that currently no ns() calls are used with any shinyFiles functions. (I've tried wrapping the shinyFilesButton()'s id in the ns(), but then it doesn't match with the shinyFileChoose.)

Currently, this app below will show me files, but only in the root directory. I can't delve deeper into other directories. Additionally, the select button will highlight, but nothing will happen when used.

Edit: I've update the code with an attempt at using the namespaces, per suggestions in the comments. I'm using the ns() function in the shinyFilesButton() call (ui side) and nothing in the server side.

Now I can't see any files when using the file chooser.

Any help?

Below is my code for the app.r file:

#App.R
#Demonstrate issues with ShinyFiles and namesspaces in modules

library(shiny)
library(shinyFiles)

source("shinyFiles_module.R")

server <- function(input, output, session) {
  #module Way
  callModule(sample,
             id="testid",
             root_dirs=c(root_on_mac="/Users/Ryan/Desktop/"))
}

ui <- fluidPage(
  tagList(
    h2("Module Way"),
    sample_UI(id = "testid",
              label = "shiny file test")
  )
)

shinyApp(ui = ui, server = server)

And for the module:

#Sample shinyFiles Module
#trying to get File path using ShinyFiles within a Module

library(shiny)
library(shinyFiles)

#Settings UI function:
# Module UI function
sample_UI <- function(id, label = "Shiny file test") {
  # Create a namespace function using the provided id
  ns <- NS(id)

  #begin UI (wrap all input/ouput in ns() call)
  tagList(
    strong("Selected Location: "), verbatimTextOutput(ns("file_path")),
    shinyFilesButton(
      id=ns("get_file_path"),
      label="Click Here to Select",
      title="Select a file",
      multiple= FALSE,
      buttonType = "default",
      class = NULL)
  )
}

# Module server function
sample <- function(input,
                   output,
                   session,
                   root_dirs,
                   id_value) {

  shinyFileChoose(input, id="get_file_path", roots=root_dirs, session=session)

  output$file_path <- renderPrint({
    parseFilePaths(roots=root_dirs, input$get_file_path)
  })
}

Body:
I have the same issue and I resolve it by following Carl's suggestion:

use ns() in ui

remove ns() in server

I am using R3.6.1 and it works. In R3.4 it has problem navigate into the subfolders.

library(shiny)
library(shinyFiles)

#Settings UI function:
# Module UI function
sample_UI <- function(id, label = "Shiny file test") {
  # Create a namespace function using the provided id
  ns <- NS(id)

  #begin UI (wrap all input/ouput in ns() call)
  tagList(
    strong("Selected Location: "), verbatimTextOutput(ns("file_path")),
    shinyFilesButton(
      id=ns("get_file_path"),
      label="Click Here to Select",
      title="Select a file",
      multiple= FALSE,
      buttonType = "default",
      class = NULL)
  )
}

# Module server function
sample <- function(input,
                   output,
                   session,
                   root_dirs,
                   id_value) {

  shinyFileChoose(input, id="get_file_path", roots=root_dirs, session=session)

  output$file_path <- renderPrint({
    parseFilePaths(roots=root_dirs, input$get_file_path)
  })
}


问:
How to custom components folder path in laravel?
My view folders is like

```<code>views/
└── web/
    ├── Frontend
    │   ├── layout
    │   ├── admin
    │   ├── profile
    │
    └── Backend
        ├── layout
        ├── user
        ├── post
</code>```

I need to make it like this:

```<code>views/
└── web/
    ├── Frontend
    │   ├── layout
    │   ├── admin
    │   ├── components
    │
    └── Backend
        ├── layout
        ├── user
        ├── components
</code>```

each section has his owncomponents

Is there any way to achieve to this point ?

答:
As you would do for views, you can use the dot notation to specify the path, and so if you have a component called item.blade.php inside views/web/Frontend/components you can use

```<code>@component('web.Frontend.components.item', [...])
   ...
@endcomponent
</code>```

Then in order to bind variables from the view to the component, you just need to pass them in the array.

Example, in your view you have a $var1 which in the component has $var2 as name, you just need to pass it like this:

```<code>@component('web.Frontend.components.item', ['var1'=>$var2])
   ...
@endcomponent
</code>```

Body:
My view folders is like

views/
└── web/
    ├── Frontend
    │   ├── layout
    │   ├── admin
    │   ├── profile
    │
    └── Backend
        ├── layout
        ├── user
        ├── post

I need to make it like this:

views/
└── web/
    ├── Frontend
    │   ├── layout
    │   ├── admin
    │   ├── components
    │
    └── Backend
        ├── layout
        ├── user
        ├── components

each section has his owncomponents

Is there any way to achieve to this point ?

Body:
As you would do for views, you can use the dot notation to specify the path, and so if you have a component called item.blade.php inside views/web/Frontend/components you can use

@component('web.Frontend.components.item', [...])
   ...
@endcomponent

Then in order to bind variables from the view to the component, you just need to pass them in the array.

Example, in your view you have a $var1 which in the component has $var2 as name, you just need to pass it like this:

@component('web.Frontend.components.item', ['var1'=>$var2])
   ...
@endcomponent


问:
SQL update query not updating table data
Here is my code and it shows successful but it does not update row in table.</p>

```<code>cm = new SqlCommand("update table_products set pname = @pname, pdesc = @pdesc, bid = @bid, cid = @cid, cost = @cost, price = @price, reorder = @reorder where pcode like @pcode", con);

cm.Parameters.AddWithValue("@pcode", tft_pcode.Text);
cm.Parameters.AddWithValue("@barcode", tft_barcode.Text);
cm.Parameters.AddWithValue("@pname", tft_pname.Text);
cm.Parameters.AddWithValue("@pdesc", tft_pdescription.Text);
cm.Parameters.AddWithValue("@bid", bid);
cm.Parameters.AddWithValue("@cid", cid);
cm.Parameters.AddWithValue("@cost", Double.Parse(tft_cost.Text));
cm.Parameters.AddWithValue("@price", Double.Parse(tft_price.Text));
cm.Parameters.AddWithValue("@reorder", int.Parse(tft_reorder.Text));

cm.ExecuteNonQuery();
con.Close();

MessageBox.Show("Product updated successfully");
</code>```

答:
I solved the issue
The problem was that i was trying to match pcode(application) with pcode(database), which wasn't doing so.
That was because when my update form was loading i had the pcode generate method in its event, so i was matching with old pcode value , what it actually was doing is that, it was matching with newly generated pcode.
So i removed pcode generate method from form_load event and the issue was solved.
Thank you All for your time.</p>

Body:
Here is my code and it shows successful but it does not update row in table.

cm = new SqlCommand("update table_products set pname = @pname, pdesc = @pdesc, bid = @bid, cid = @cid, cost = @cost, price = @price, reorder = @reorder where pcode like @pcode", con);

cm.Parameters.AddWithValue("@pcode", tft_pcode.Text);
cm.Parameters.AddWithValue("@barcode", tft_barcode.Text);
cm.Parameters.AddWithValue("@pname", tft_pname.Text);
cm.Parameters.AddWithValue("@pdesc", tft_pdescription.Text);
cm.Parameters.AddWithValue("@bid", bid);
cm.Parameters.AddWithValue("@cid", cid);
cm.Parameters.AddWithValue("@cost", Double.Parse(tft_cost.Text));
cm.Parameters.AddWithValue("@price", Double.Parse(tft_price.Text));
cm.Parameters.AddWithValue("@reorder", int.Parse(tft_reorder.Text));

cm.ExecuteNonQuery();
con.Close();

MessageBox.Show("Product updated successfully");


问:
Find the first 300 members of the server
I want to create a bot that can tell me the list of the first 300 members of my server. Is this possible with Discord.js? Any help would be appreciated. I just don't know where to start</p>

答:
Like syntle asked it depends which kinda but, here's the first 300 to fetch:
Might not work since there might be an already set limit of members you can fetch

const members = await <Guild>.members.fetch({ limit: 300 });
//or if you are fine with cached
const members = <Guild>.members.cache.array();
members.length = 300;
```


问:
Is there a way to bring all definitions in a C++ struct/class into scope without deriving from it?
Musing on a Sunday...

Deriving from a class brings all names from the base class into the scope of the derived class. However, it also adds the base class non-static data members to every instance of the derived class.

Is there a way to achieve the former without the latter? I'm asking in the interest of concise notation.

Obviously, when the base class doesn't have any data members, I get what I want. There are quite a few empty classes or class templates in the standard library defined to do just that - inject names summarily into a class scope through inheritance. There's even the empty base class optimization to make this as cheap as possible.

But if I wanted to do the same with a non-empty base class, I would be tempted to employ something like:

struct Bar {
    using struct Foo;
};
```

<p>But, alas, that's not supported by C++. My question is, is there another way to achieve the same which I overlooked?</p>

<p>To provide a more complete example:</p>

<pre class="lang-cpp prettyprint-override"><code>struct Foo {
    enum { some_constant=42 };

    // data members follow here ...
};

struct Bar {
    using class Foo;   // this doesn't compile

    int f();
};

int Bar::f() {
    return some_constant;   // I want to use the constant directly, without Foo::
}
</code>```

One clumsy way could be to split the definitions in Foo into two classes, one with the constants (which would be an empty class I could derive from without penalty) and the other with the data members, but that looks rather like an inelegant hack to me.

If there isn't a clean way to achieve this, maybe someone can provide a rationale for why it doesn't exist, or perhaps shouldn't exist.

答:
Deriving from a class brings all names from the base class into the scope of the derived class.

Let me stop you there. Yes, it is true that inheriting from a base class causes the (non-private) names in the base class to be accessible from the derived class definition. However, that's not why you inherit from a base class; that's merely the mechanism by which inheritance achieves its goal.

To publicly inherit from a base class is to make a statement about the relationship between the derived and base classes. You're saying that every instance of the derived class should behave like the base class in virtually all ways. Even virtual function overriding still carries with it the expectation that the derived class implementations of these methods are conceptually doing the same job, just in a way appropriate for that derived class.

This is true even of mixin-style base classes, where the base class is used to define common functionality that is imported into a particular derived class. In such interfaces, there is little expectation of a user explicitly talking to base class definitions. But this provision of common functionality is ultimately still based on the semantic idea of a derived class being a base class. And that's very important for many of them to do their job.

Consider what is probably the most prominent mixin in the C++ standard library: std::enable_shared_from_this<T>. It has non-static data members, without which it couldn't actually provide the functionality it does (well, it could, but you would have to provide some interface in your derived class to store them, so it may as well do it).

This is true of private inheritance, though there is some modification. While to the outside world, the derived class is just a derived class, to the class definition itself, it still remains a base class. It remains wholly a base class, along with all the baggage that comes along with it.

Do not mistake the mechanism for the meaning. Mechanisms are important; don't get me wrong. But those mechanisms exist to facilitate meaning.

Having a class contain everything of some other class except the non-static data members is, semantically, nonsense. It doesn't mean anything about the relationship between the types. And you've essentially admitted that the main reason you want this is so that you don't have to scope-qualify the names defined in the "base" class.

This is a mechanical reason, not a semantic one. You shouldn't employ a semantic tool like inheritance to escape the mechanical consequences of how you have chosen to design your types.

Body:
Musing on a Sunday...

Deriving from a class brings all names from the base class into the scope of the derived class. However, it also adds the base class non-static data members to every instance of the derived class.

Is there a way to achieve the former without the latter? I'm asking in the interest of concise notation.

Obviously, when the base class doesn't have any data members, I get what I want. There are quite a few empty classes or class templates in the standard library defined to do just that - inject names summarily into a class scope through inheritance. There's even the empty base class optimization to make this as cheap as possible.

But if I wanted to do the same with a non-empty base class, I would be tempted to employ something like:

struct Bar {
    using struct Foo;
};

But, alas, that's not supported by C++. My question is, is there another way to achieve the same which I overlooked?

To provide a more complete example:

struct Foo {
    enum { some_constant=42 };

    // data members follow here ...
};

struct Bar {
    using class Foo;   // this doesn't compile

    int f();
};

int Bar::f() {
    return some_constant;   // I want to use the constant directly, without Foo::
}

One clumsy way could be to split the definitions in Foo into two classes, one with the constants (which would be an empty class I could derive from without penalty) and the other with the data members, but that looks rather like an inelegant hack to me.

If there isn't a clean way to achieve this, maybe someone can provide a rationale for why it doesn't exist, or perhaps shouldn't exist.