问:
jQuery, use the right selector
I have a div, inside which there is a some text and a number of words surrounded by certain span tags. I want to click on those "spanned" words and have the div slide down, showing an "underlying" div with a text related to that certain spanned word. When i click on the div and not on a spanned word, i want the div to slide back up. Thus i bound some actions to the div and to the class of those spans. however, when i click on a span, the div also gets the click action. How should i change the selectors not to receive a clicking action on the div when i click on the span?

Here is the code:

```<code><div class='mainpage'>
    <p class='common'>bla-bla-bla <span class='footnoted' footnote='f1'>foo bar</span></p>
</div>
</code>```

jQuery code:

```<code>$(document).ready(function(){
    $(".mainpage>.common>.footnoted").click(function(){
        alert('a');
    });

    $(".mainpage").not($(".mainpage>.common>.footnoted")).click(function(){
        alert('b');
    });
});
</code>```

In other words, when i click on "foo bar", i get the "a" and "b" alerts, whereas i want to get only "a". How can i do that?

Thank you in advance.
Timofey.

答:
You need to use

```<code>event.stopPropagation();
</code>```

in the span like so

```<code>$('div').click(function(){alert('div clicked');});

$('div span').click(function(event){
    alert('span clicked')
    event.stopPropagation();
});
</code>```

Live Demo

Reference

Title: jQuery, use the right selector

Body:
I have a div, inside which there is a some text and a number of words surrounded by certain span tags. I want to click on those "spanned" words and have the div slide down, showing an "underlying" div with a text related to that certain spanned word. When i click on the div and not on a spanned word, i want the div to slide back up. Thus i bound some actions to the div and to the class of those spans. however, when i click on a span, the div also gets the click action. How should i change the selectors not to receive a clicking action on the div when i click on the span?

Here is the code:

bla-bla-bla foo bar

jQuery code:

$(document).ready(function(){
    $(".mainpage>.common>.footnoted").click(function(){
        alert('a');
    });

    $(".mainpage").not($(".mainpage>.common>.footnoted")).click(function(){
        alert('b');
    });
});

In other words, when i click on "foo bar", i get the "a" and "b" alerts, whereas i want to get only "a". How can i do that?

Thank you in advance.
Timofey.

Body:
You need to use

event.stopPropagation();

in the span like so

$('div').click(function(){alert('div clicked');});

$('div span').click(function(event){
    alert('span clicked')
    event.stopPropagation();
});

Live Demo

Reference


来源: stackexchange

问:
Recursion in python, without overwriting changed variable
I am trying to write a function that does the following:

If player_hand doesn't have any number that is less than or equal to mana_bank the function should do nothing.

If player_hand has a number that is less than or equal to mana_bank then the function should prompt the user with which number he chooses.

If the number the user chooses is less than mana_bank it should return a list with that number. If the number is more than mana_bank it should call the function again untill he prompts a number that is less than or equal to mana_bank.

Whenever I run the function and the user first prompts a number that is higher than mana_bank the function gets called from within itself, and then even if the user prompts a number lower than or equal to mana_bank, the function returns None instead of the number in a list.

I also tried making the variable player_choice global but it still didn't work.

Would appreciate any guidance.

```<code>def pick_card():
    player_choice_str = 0
    player_choice = []
    for i in player_hand:
        if i <= mana_bank:
            print(player_hand, mana_bank, "Mana available type the name of the card you wish to play ... ")
            player_choice_str = input()
            break
        if not i <= mana_bank:
            return "You don't have enough mana to play a card."
    if int(player_choice_str) > mana_bank:
        print("That card costs " + str(player_choice_str) + " and you only have " + str(mana_bank) + " this round.")
        pick_card()
    if int(player_choice_str) <= mana_bank:
        player_choice.append(player_choice_str)
        return player_choice

player_hand = [4, 8, 8]
mana_bank = 4

print(pick_card())
</code>```

答: Your first problem is that player_choice is defined locally. It will be overwritten in every function call. In addition, you have to evaluate/return the return value of pick_card() in the case when the players choice is greater than the manabank. Otherwise the first called function of the recursion will return None because of the missing return value.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to write a function that does the following:

If player_hand doesn't have any number that is less than or equal to mana_bank the function should do nothing.

If player_hand has a number that is less than or equal to mana_bank then the function should prompt the user with which number he chooses.

If the number the user chooses is less than mana_bank it should return a list with that number. If the number is more than mana_bank it should call the function again untill he prompts a number that is less than or equal to mana_bank.

Whenever I run the function and the user first prompts a number that is higher than mana_bank the function gets called from within itself, and then even if the user prompts a number lower than or equal to mana_bank, the function returns None instead of the number in a list.

I also tried making the variable player_choice global but it still didn't work.

Would appreciate any guidance.

def pick_card():
    player_choice_str = 0
    player_choice = []
    for i in player_hand:
        if i <= mana_bank:
            print(player_hand, mana_bank, "Mana available type the name of the card you wish to play ... ")
            player_choice_str = input()
            break
        if not i <= mana_bank:
            return "You don't have enough mana to play a card."
    if int(player_choice_str) > mana_bank:
        print("That card costs " + str(player_choice_str) + " and you only have " + str(mana_bank) + " this round.")
        pick_card()
    if int(player_choice_str) <= mana_bank:
        player_choice.append(player_choice_str)
        return player_choice

player_hand = [4, 8, 8]
mana_bank = 4

print(pick_card())


问:
how to add token to header in reactjs
I have a web app that I want to use api with. I want to fetch a data that needs a token. I already have the token Ii got the token by running the login function in my postman). The question is: where do I put this token? Some say I need to put it in the headers but I can't find where to make this headers. Here is my code:

```<code>componentDidMount() {
  fetch('API_GOES_HERE', {
    headers: { Authentication: `Bearer ajsbdjabsjhdbfquhjwbeasbdasdjwbqjbds
  }})
 .then(res => res.json())
 .then(json => {
     this.setState({
       contact: json,
       isLoaded: true,
     })
 })
 .catch(err => console.log(err));
}
</code>```

Without the token, the api always returns this {"message":"missing or malformed jwt"}. I already tried this data fetch from postman itself and it works, because I already set the token variable with my token.

I censored the endpoint and the token by changing it to ENDPOINT_API and API_TOKEN. Thanks, any help will be appreciated.

答:
ok i found the solution to this question, i need to put the content-type to the headers it self, and add a https to the API_ENDPOINT, here is the code that works

```<code>fetch(API_ENDPOINT, {
    headers: {
      Authorization: `TOKEN`,
      'Content-Type': 'application/json',
      'Accept': 'application/json'
  }})
 .then(res => res.json())
 .then(json => {
   console.log(json)
     this.setState({
       contact: json,
       isLoaded: true,
     })
 })
 .catch(err => console.log(err));
</code>```

Title: how to add token to header in reactjs

Body:
I have a web app that I want to use api with. I want to fetch a data that needs a token. I already have the token Ii got the token by running the login function in my postman). The question is: where do I put this token? Some say I need to put it in the headers but I can't find where to make this headers. Here is my code:

componentDidMount() {
  fetch('API_GOES_HERE', {
    headers: { Authentication: `Bearer ajsbdjabsjhdbfquhjwbeasbdasdjwbqjbds
  }})
 .then(res => res.json())
 .then(json => {
     this.setState({
       contact: json,
       isLoaded: true,
     })
 })
 .catch(err => console.log(err));
}

Without the token, the api always returns this {"message":"missing or malformed jwt"}. I already tried this data fetch from postman itself and it works, because I already set the token variable with my token.

I censored the endpoint and the token by changing it to ENDPOINT_API and API_TOKEN. Thanks, any help will be appreciated.

Body:
ok i found the solution to this question, i need to put the content-type to the headers it self, and add a https to the API_ENDPOINT, here is the code that works

fetch(API_ENDPOINT, {
    headers: {
      Authorization: `TOKEN`,
      'Content-Type': 'application/json',
      'Accept': 'application/json'
  }})
 .then(res => res.json())
 .then(json => {
   console.log(json)
     this.setState({
       contact: json,
       isLoaded: true,
     })
 })
 .catch(err => console.log(err));


问:
Temporary macro to store another macro and then reverting back
I want to have more control over macros such as assertions (and some logging macros that are not directly under my control). So I decided to do something like this, expecting it to work (in case somebody is wondering, the reason it does not work is that the last undef of MY_ASSERT_COPY invalidates MY_ASSERT right before it).

```<code>#ifndef ENABLE_FULL_ERROR_ASSERTS
#define MY_ASSERT_COPY MY_ASSERT
#undef MY_ASSERT
#define MY_ASSERT
#endif

// Code for my current class, which happens to be header only

#ifndef ENABLE_FULL_ERROR_ASSERTS
#undef MY_ASSERT
#define MY_ASSERT MY_ASSERT_COPY
#undef MY_ASSERT_COPY
#endif
</code>```

Now I know a few ways around it, one being to define another macro for assertions just for that file, which I can then turn off without affecting assertions in any other part of the program. I initially thought this was a really elegant solution (before I found out it did not compile) that will allow me to use MY_ASSERT everywhere and then simply turn it off for particular files.

Since the above doesn't work, is there a workaround that will allow me to selectively kill the macro without affecting the surrounding code and without defining another substitute macro like #define MY_ASSERT_FOR_VECTORS MY_ASSERT

答:
Some compilers provide #pragma push_macroand #pragma pop_macro to save and restore macro state.

Limited portability though.

ContentLicense: CC BY-SA 3.0

Body:
I want to have more control over macros such as assertions (and some logging macros that are not directly under my control). So I decided to do something like this, expecting it to work (in case somebody is wondering, the reason it does not work is that the last undef of MY_ASSERT_COPY invalidates MY_ASSERT right before it).

#ifndef ENABLE_FULL_ERROR_ASSERTS
#define MY_ASSERT_COPY MY_ASSERT
#undef MY_ASSERT
#define MY_ASSERT
#endif

// Code for my current class, which happens to be header only

#ifndef ENABLE_FULL_ERROR_ASSERTS
#undef MY_ASSERT
#define MY_ASSERT MY_ASSERT_COPY
#undef MY_ASSERT_COPY
#endif

Now I know a few ways around it, one being to define another macro for assertions just for that file, which I can then turn off without affecting assertions in any other part of the program. I initially thought this was a really elegant solution (before I found out it did not compile) that will allow me to use MY_ASSERT everywhere and then simply turn it off for particular files.

Since the above doesn't work, is there a workaround that will allow me to selectively kill the macro without affecting the surrounding code and without defining another substitute macro like #define MY_ASSERT_FOR_VECTORS MY_ASSERT


问:
Throwing CInternetException for error 12029
This somewhat links to my previous question. Background details here: Simple HTTP request with C++

Basically I am sending data to a server through an URL with C++. I am now using openURL() function in the CInternetSession class to do it. If the openURL connects to the server successfully, no errors or exceptions are thrown. However, sometimes, in the debugger in Visual C++ 2006, I would get this pop-up

```<code>First-chance exception in myProg.exe (KERNELBASE.DLL):
0xE06D7363: Microsoft C++ Exception.
</code>```

I have set the debug exceptions to "stop always" and in the debug window it shows me

```<code>Warning: throwing CInternetException for error 12029
</code>```

In addition, when I run the program by itself (without the debugger and stuff), I get a pop-up saying debug error.

I understand that this is because the openURL() couldn't make a connection to the specified URL. However, my problem now is I do not want a pop-up to inform me of this. I have put a try catch block around my code but it's still not handling the exception. Here's the code

```<code>    try {
        // Open HTTP file
        pHttpFile =(CHttpFile *) mySession.OpenURL(test1.c_str());
    }
    catch (CInternetException) {
        printf("Received Exception from OpenURL()");
        // Handle exception
    }
</code>```

Am I missing something here!?

答:
I think you should catch CInternetException* instead. For all MFC exceptions is throwed as a pointer.

PS.
You should also use CException::Delete() in your catch block to delete the exception object you just catched if you don't need to throw it again.

Body:
This somewhat links to my previous question. Background details here: Simple HTTP request with C++

Basically I am sending data to a server through an URL with C++. I am now using openURL() function in the CInternetSession class to do it. If the openURL connects to the server successfully, no errors or exceptions are thrown. However, sometimes, in the debugger in Visual C++ 2006, I would get this pop-up

First-chance exception in myProg.exe (KERNELBASE.DLL):
0xE06D7363: Microsoft C++ Exception.

I have set the debug exceptions to "stop always" and in the debug window it shows me

Warning: throwing CInternetException for error 12029

In addition, when I run the program by itself (without the debugger and stuff), I get a pop-up saying debug error.

I understand that this is because the openURL() couldn't make a connection to the specified URL. However, my problem now is I do not want a pop-up to inform me of this. I have put a try catch block around my code but it's still not handling the exception. Here's the code

    try {
        // Open HTTP file
        pHttpFile =(CHttpFile *) mySession.OpenURL(test1.c_str());
    }
    catch (CInternetException) {
        printf("Received Exception from OpenURL()");
        // Handle exception
    }

Am I missing something here!?


问:
How can I create an object that contains instances of a class in Python?
I want to create an object that contains some instances of a class. That object should be some kind of list-generalization of the instances. E.g. I have the following class:

```<code>class car:
    def __init__(self, prize, color)
        self.prize = prize
        self.color = color
</code>```

Now I want to have an object cars that contains many instances of the class car but that I can work with like an instance of car, i.e. cars.prize should return a list of the prizes for all the instances I collected in that object cars.

答:
This answer is inspired by the wonderful Sam idea of using decorators. So please give him the point if you think you are pleased with this chunk of code.

def singleton(all_cars):
    instances = {} # cars instances
    def get_instance():
        if all_cars not in instances:
            # all_cars is created once
            instances[all_cars] = all_cars()
        return instances[all_cars]
    return get_instance

@singleton
class all_cars:
    def __init__(self):
        self.inventory = {}

    @property
    def prizes(self):
        return [e.prize for e in self.inventory.values()]
    @property
    def colors(self):
        return [e.color for e in self.inventory.values()]

class car:
    def __init__(self, prize, color):
        self.prize = prize
        self.color = color

    def register(self):
        # Like class all_cars is a singleton it is instantiate once, reason why dict is saved
        cars = all_cars()
        cars.inventory[len(cars.inventory)] = self

if __name__ == '__main__':
    # Creating cars items
    car1 = car("50", "Blue")
    car2 = car("300", "Red")
    car3 = car("150", "Gray")
    # Register part for cars
    car1.register()
    car2.register()
    car3.register()
    # Like class all_cars is a singleton it is instantiate once, reason why dict is saved
    cars = all_cars()

    print(cars.inventory)
    """{0: <__main__.car object at 0x7f3dbc469400>, ---> This is object car1
    1: <__main__.car object at 0x7f3dbc469518>,  ---> This is object car2
    2: <__main__.car object at 0x7f3dbc469550>}  ---> This is object car3"""
    print(cars.prizes)
    """['50', '300', '150']"""
    print(cars.colors)
    """['Blue', 'Red', 'Gray']"""
```

Body:
I want to create an object that contains some instances of a class. That object should be some kind of list-generalization of the instances. E.g. I have the following class:

class car:
    def __init__(self, prize, color)
        self.prize = prize
        self.color = color

Now I want to have an object cars that contains many instances of the class car but that I can work with like an instance of car, i.e. cars.prize should return a list of the prizes for all the instances I collected in that object cars.


问:
Getting duplicates with BETWEEN query ruby on rails 6
When I attempt to retrieve records with a date range query using record_date >= 'start_date' AND record_date <= 'end_date'. I receive the same records back 3 times. I don't know why this is happening. I'm using ransack gem.

Server log

```<code>Facility load (1.9ms) SELECT "facilities".* FROM "facilities" LEFT OUTER JOIN "chart_records" ON "chart_records"."facility_id" = "facilities"."id" WHERE ("chart_records"."record_date" > = '2020-06-1' AND "chart_records"."record_date" <= '2020-06-04' AND facilities."name"= 'LVHH') ORDER BY "facilities"."id" ASC LIMIT $1 [["LIMIT", 1]]
</code>```

reports_controller.rb

```<code>def chart_report_facility_detail

@d = Facility.ransack(params[:q])
@chart_records = @d.result.includes([:chart_records])

 respond_to do |format|
  format.html
 end
end
</code>```

view/index.html.erb

```<code><% @chart_records.each do |facility| %>
   <% facility.chart_records.between_dates(params[:date_1], params[:date_2]).order(record_date: :desc).distinct.each do |chart_record| %>
 <%= chart_record.attr %>
....
...
<% end %>
<% end %>
</code>```

response: prints out the same record 3 times in a row

How can I make it so that the BETWEEN query only returns each individual record once?

答: I fixed this issue by adding uniq to the original ransack query statement.

Body:
When I attempt to retrieve records with a date range query using record_date >= 'start_date' AND record_date <= 'end_date'. I receive the same records back 3 times. I don't know why this is happening. I'm using ransack gem.

Server log

Facility load (1.9ms) SELECT "facilities".* FROM "facilities" LEFT OUTER JOIN "chart_records" ON "chart_records"."facility_id" = "facilities"."id" WHERE ("chart_records"."record_date" > = '2020-06-1' AND "chart_records"."record_date" <= '2020-06-04' AND facilities."name"= 'LVHH') ORDER BY "facilities"."id" ASC LIMIT $1 [["LIMIT", 1]]

reports_controller.rb

def chart_report_facility_detail

@d = Facility.ransack(params[:q])
@chart_records = @d.result.includes([:chart_records])

 respond_to do |format|
  format.html
 end
end

view/index.html.erb

<% @chart_records.each do |facility| %>
   <% facility.chart_records.between_dates(params[:date_1], params[:date_2]).order(record_date: :desc).distinct.each do |chart_record| %>
 <%= chart_record.attr %>
....
...
<% end %>
<% end %>

response: prints out the same record 3 times in a row

How can I make it so that the BETWEEN query only returns each individual record once?


问:
Postman AssertionError expected: 'value' to equal value
ISSUE:
In Postman I'm running a POST request and trying to assert what I receive in my response body to what is being passed via a CSV file.

The CSV file contains three columns: employee_name, employee_salary, and employee_age. All are set as general for formatting (the default).

The assert works fine for employee_name but when I try to do this for employee_age and employee_salary I get an error like this:
AssertionError: expected '35' to equal 35

Here is the API I'm using.

WHAT I'VE TRIED:
I've tried setting the format of the age and salary cells in the CSV file to text and to number to no avail.

CODE:

```<code>    var jsonData = pm.response.json();

    pm.test("Verify name", function() {
        pm.expect(jsonData.data.name).to.equal(pm.iterationData.get("employee_name"));
    });

    pm.test("Verify age", function() {
        pm.expect(jsonData.data.age).to.equal(pm.iterationData.get("employee_age"));
    });

    pm.test("Verify salary", function() {
        pm.expect(jsonData.data.salary).to.equal(pm.iterationData.get("employee_salary"));
    });
</code>```

Thanks for any help!

Best,
Jason

答:
It's trying the match a string with an Integer so you could wrap the values from the data file with parseInt().

For example, the age would be like this:

pm.expect(jsonData.data.age).to.equal(parseInt(pm.iterationData.get("employee_age")))

Body:
ISSUE:
In Postman I'm running a POST request and trying to assert what I receive in my response body to what is being passed via a CSV file.

The CSV file contains three columns: employee_name, employee_salary, and employee_age. All are set as general for formatting (the default).

The assert works fine for employee_name but when I try to do this for employee_age and employee_salary I get an error like this:
AssertionError: expected '35' to equal 35

Here is the API I'm using.

WHAT I'VE TRIED:
I've tried setting the format of the age and salary cells in the CSV file to text and to number to no avail.

CODE:

    var jsonData = pm.response.json();

    pm.test("Verify name", function() {
        pm.expect(jsonData.data.name).to.equal(pm.iterationData.get("employee_name"));
    });

    pm.test("Verify age", function() {
        pm.expect(jsonData.data.age).to.equal(pm.iterationData.get("employee_age"));
    });

    pm.test("Verify salary", function() {
        pm.expect(jsonData.data.salary).to.equal(pm.iterationData.get("employee_salary"));
    });

Thanks for any help!

Best,
Jason


问:
Can't login with Meteor function loginWithPassword, Unrecognized options for login request [400] error
I'm working on React + Meteor application and can't login using accounts-password package via loginWithPassword function.

The official API says that Unrecognized options for login request [400] error pops up when your user or password is undefined (or, i guess, just do not match the API), but i've checked the arguments and everything seems correct. username and password are strings. Meteor has ability to operate with user object, but this is not working too.
Here's the sample of my code.

```<code>  const submit = useCallback(
(values) => {
  const { email, password } = values;
  const callback = (err) => {
    if (err) {
      console.log(err);
      notifyError();
      return;
    }
    login();
    history.replace(from);
  };
  Meteor.loginWithPassword(email, password, callback);
},
[from, history, login, notifyError]
</code>```

);

Any help appreciated.

答:
It looks like that particular error can occur when there are no login handlers registered.

Have you added the accounts-password package ?

meteor add accounts-password

Body:
I'm working on React + Meteor application and can't login using accounts-password package via loginWithPassword function.

The official API says that Unrecognized options for login request [400] error pops up when your user or password is undefined (or, i guess, just do not match the API), but i've checked the arguments and everything seems correct. username and password are strings. Meteor has ability to operate with user object, but this is not working too.
Here's the sample of my code.

  const submit = useCallback(
(values) => {
  const { email, password } = values;
  const callback = (err) => {
    if (err) {
      console.log(err);
      notifyError();
      return;
    }
    login();
    history.replace(from);
  };
  Meteor.loginWithPassword(email, password, callback);
},
[from, history, login, notifyError]

);

Any help appreciated.


问:
How to load Combobox-items on dropdown

I need to work with an excel workbook, with some worsheets.
To load the available worksheets into a combobox, I need to open the workbook and iterate through all sheets and add them to the combobox. This cost a lot of time, the user needs to wait for. If the user doesn't want to change the preloaded property, this time is waisted. So I only want to fill in the listitems when needed but show the preselected property, that was loaded from a settingsfile on startup of the app.

So is there a way to load the items on dropdown? Or better, how can I bind a command that is triggerd on dropdown, to load the items?

```<code><ComboBox SelectedItem="{Binding Worksheet}" ItemsSource="{Binding WorkSheets}" x:Name="cbWorkSheet" Padding="4">
</code>```

... oh, I know how to bind a command to a button so I need a special tip for the combobox, not for commands in general :)

UPDATE
I solved to trigger the "loading" and the List is filled but I need to show the last selected value (that is loaded on startup as the bound property Worksheet)

```<code><ComboBox
    x:Name="cbWorkSheet"
    SelectedItem="{Binding Worksheet}"
    ItemsSource="{Binding WorkSheets}"
    IsEditable="True"
    Padding="4">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="DropDownOpened" SourceObject="{Binding ElementName=cbWorkSheet}">
                <i:InvokeCommandAction Command="{Binding LoadBACnetWsCombobox}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
</ComboBox>
</code>```

With that Binding, the Combobox remains empty till I dropdown it :(

答:
Original Answer: Incorrect, Posted 2020/06/02:

If you need SelectedItem populated before you open the dropdown, then you should probably change your EventTrigger's EventName from DropDownOpened to be Loaded.

That way, before the combobox is shown to the user, LoadBACnetWsComboBox will run, and hopefully your Worksheet will be set.  Then, the combobox will be shown to the user.

Modified Answer, Posted 2020/06/03:

If you want to just populate the initial displayed text, you can always set the Text property of the combobox.  It will get overridden once you do selections from the drop down.

```<code><ComboBox
   ...
   Text="{Binding MyInitialValue}">
</code>```

Title: How to load Combobox-items on dropdown

Body:
I need to work with an excel workbook, with some worsheets.
To load the available worksheets into a combobox, I need to open the workbook and iterate through all sheets and add them to the combobox. This cost a lot of time, the user needs to wait for. If the user doesn't want to change the preloaded property, this time is waisted. So I only want to fill in the listitems when needed but show the preselected property, that was loaded from a settingsfile on startup of the app.

So is there a way to load the items on dropdown? Or better, how can I bind a command that is triggerd on dropdown, to load the items?

<ComboBox SelectedItem="{Binding Worksheet}" ItemsSource="{Binding WorkSheets}" x:Name="cbWorkSheet" Padding="4">

... oh, I know how to bind a command to a button so I need a special tip for the combobox, not for commands in general :)

UPDATE
I solved to trigger the "loading" and the List is filled but I need to show the last selected value (that is loaded on startup as the bound property Worksheet)

<ComboBox
    x:Name="cbWorkSheet"
    SelectedItem="{Binding Worksheet}"
    ItemsSource="{Binding WorkSheets}"
    IsEditable="True"
    Padding="4">

</ComboBox>

With that Binding, the Combobox remains empty till I dropdown it :(

Body:
Original Answer: Incorrect, Posted 2020/06/02:

If you need SelectedItem populated before you open the dropdown, then you should probably change your EventTrigger's EventName from DropDownOpened to be Loaded.

That way, before the combobox is shown to the user, LoadBACnetWsComboBox will run, and hopefully your Worksheet will be set.  Then, the combobox will be shown to the user.

Modified Answer, Posted 2020/06/03:

If you want to just populate the initial displayed text, you can always set the Text property of the combobox.  It will get overridden once you do selections from the drop down.

<ComboBox
   ...
   Text="{Binding MyInitialValue}">


问:
UIWebview returns error and adds m. to request URL
I´m trying to load a URL to a webview.

Let´s say the url is: http://www.somepage.com/

But for some reason when I load the url in the webview, it adds a m. (URL looks like this: http://m.somepage.com) , it seems like it´s trying to add a mobile version of the website. There isn´t a mobile version of the website, so it´s trying to load a url that doesn´t exist.

In the shouldStartLoadWithRequest delegate method for the webview, it returns the correct URL. In the didFailWithError method I can an error saying: Error Domain=NSURLErrorDomain Code=-1003 "A server with the specified hostname could not be found." UserInfo=0x5a7c670 {NSErrorFailingURLStringKey=http://m.somepage.com

Any idea how I can fix this? Can I replace the m. with www in some way?

答: I am using the UIWebView without any issues. Can you check whether the site you are accessing has code that redirects to a mobile version?</p>


问:
Powershell - How to split a string based on characters?
I have a list of pdf filenames that need to be parsed and ultimately sent to a sql table, with the parse out pieces each in their own column.  How would I split based on a dash '-' and ultimately get it into a table.

What cmdlets would you start with to split on a character?  I need to split based on the dash '-'.

Thanks for the help.

Example File Names:

tester-2458-full_contact_snapshot-20200115_1188.pdf

tester-2458-limited_contact_snapshot-20200119_9330.pdf

Desired Results:

答:
yet another way is to use regex & named capture groups. [grin]

what it does ...

creates a set of file name strings to work with

when ready to use real data, remove the entire #region/#endregion block and use either (Get-ChildItem).Name or another method that gives you plain strings.

iterates thru the collection of file name strings

uses $Null = to suppress the False/True output of the -match call

does a regex match with named capture groups

uses the $Match automatic variable to plug the captured values into the desired properties of a [PSCustomObject]

sends that PSCO out to the $Results collection

displays that on screen

sends it to a CSV for later use

the code ...

```<code>#region >>> fake reading in a list of file names
#    in real life, use (Get-ChildItem).Name
$InStuff = @'
tester-2458-full_contact_snapshot-20200115_1188.pdf
tester-2458-limited_contact_snapshot-20200119_9330.pdf
'@ -split [System.Environment]::NewLine
#endregion >>> fake reading in a list of file names

$Results = foreach ($IS_Item in $InStuff)
    {
    $Null = $IS_Item -match '^(?<User>.+)-(?<AppId>.+)-(?<FileType>.+)-(?<Date>.+)\.pdf$'
    [PSCustomObject]@{
        User = $Matches.User
        AppId = $Matches.AppId
        FileType = $Matches.FileType
        Date = $Matches.Date
        FileName = $IS_Item
        }
    }

# display on screen
$Results

# send to CSV file
$Results |
    Export-Csv -LiteralPath "$env:TEMP\JM1_-_FileReport.csv" -NoTypeInformation
</code>```

output to screen ...

```<code>User     : tester
AppId    : 2458
FileType : full_contact_snapshot
Date     : 20200115_1188
FileName : tester-2458-full_contact_snapshot-20200115_1188.pdf

User     : tester
AppId    : 2458
FileType : limited_contact_snapshot
Date     : 20200119_9330
FileName : tester-2458-limited_contact_snapshot-20200119_9330.pdf
</code>```

content of the C:\Temp\JM1_-_FileReport.csv file ...

```<code>"User","AppId","FileType","Date","FileName"
"tester","2458","full_contact_snapshot","20200115_1188","tester-2458-full_contact_snapshot-20200115_1188.pdf"
"tester","2458","limited_contact_snapshot","20200119_9330","tester-2458-limited_contact_snapshot-20200119_9330.pdf"
</code>```

Body:
yet another way is to use regex & named capture groups. [grin]

what it does ...

creates a set of file name strings to work with

when ready to use real data, remove the entire #region/#endregion block and use either (Get-ChildItem).Name or another method that gives you plain strings.

iterates thru the collection of file name strings

uses $Null = to suppress the False/True output of the -match call

does a regex match with named capture groups

uses the $Match automatic variable to plug the captured values into the desired properties of a [PSCustomObject]

sends that PSCO out to the $Results collection

displays that on screen

sends it to a CSV for later use

the code ...

#region >>> fake reading in a list of file names
#    in real life, use (Get-ChildItem).Name
$InStuff = @'
tester-2458-full_contact_snapshot-20200115_1188.pdf
tester-2458-limited_contact_snapshot-20200119_9330.pdf
'@ -split [System.Environment]::NewLine
#endregion >>> fake reading in a list of file names

$Results = foreach ($IS_Item in $InStuff)
    {
    $Null = $IS_Item -match '^(?<User>.+)-(?<AppId>.+)-(?<FileType>.+)-(?<Date>.+)\.pdf$'
    [PSCustomObject]@{
        User = $Matches.User
        AppId = $Matches.AppId
        FileType = $Matches.FileType
        Date = $Matches.Date
        FileName = $IS_Item
        }
    }

# display on screen
$Results

# send to CSV file
$Results |
    Export-Csv -LiteralPath "$env:TEMP\JM1_-_FileReport.csv" -NoTypeInformation

output to screen ...

User     : tester
AppId    : 2458
FileType : full_contact_snapshot
Date     : 20200115_1188
FileName : tester-2458-full_contact_snapshot-20200115_1188.pdf

User     : tester
AppId    : 2458
FileType : limited_contact_snapshot
Date     : 20200119_9330
FileName : tester-2458-limited_contact_snapshot-20200119_9330.pdf

content of the C:\Temp\JM1_-_FileReport.csv file ...

"User","AppId","FileType","Date","FileName"
"tester","2458","full_contact_snapshot","20200115_1188","tester-2458-full_contact_snapshot-20200115_1188.pdf"
"tester","2458","limited_contact_snapshot","20200119_9330","tester-2458-limited_contact_snapshot-20200119_9330.pdf"


问:
Type.GetProperties(bindingFlags) is not giving fields from parent classes
I am trying to list all the properties in the type as shown below.

I am loading the DLL file using Assembly.LoadFile(dllFilePath).

Getting all properties in assembly using assembly.GetTypes().ToList().

Classes:

```<code>public class A
{
    public int Property1 { get; set; }
    public int Property2 { get; set; }
    public int Property3 { get; set; }
    public int Property4 { get; set; }
}

public class B : A
{
    public int Property5 { get; set; }
}
</code>```

Methods:

```<code>static void Main()
{
    Assembly assembly = Assembly.LoadFile(dllFilePath);
    List<Type> types = assembly.GetTypes().ToList();
    GetAllProperties(typeof(types.FirstOrDefult(a => a.Name == "B")));
}

private void GetAllProperties(Type type)
{
    BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic
        | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Static
        | BindingFlags.FlattenHierarchy;

    // Test 1: No inherited properties.
    PropertyInfo[] propertyInfoList1 = type.GetProperties(bindingFlags);

    List<string> propertyNameList1 = new List<string>();
    foreach (PropertyInfo propertyInfo1 in propertyInfoList1)
    {
        propertyNameList1.Add(propertyInfo1.Name);
    }

    // Test 2: No inherited properties.
    PropertyInfo[] propertyInfoList2 = Activator.CreateInstance(type).GetType().GetProperties(bindingFlags);

    List<string> propertyNameList2 = new List<string>();
    foreach (PropertyInfo propertyInfo2 in propertyInfoList2)
    {
        propertyNameList2.Add(propertyInfo2.Name);
    }

    // Test 3: object has all inherited properties but propertyInfoList doesn't have inherited properties.
    object typeInstance = Activator.CreateInstance(type);
    PropertyInfo[] propertyInfoList3 = typeInstance.GetType().GetProperties(bindingFlags);

    List<string> propertyNameList3 = new List<string>();
    foreach (PropertyInfo propertyInfo3 in propertyInfoList3)
    {
        propertyNameList3.Add(propertyInfo3.Name);
    }
}
</code>```

In Test 3 all parent class properties are visible when I inspect it.

But typeInstance.GetType().GetProperties(bindingFlags) doesn't return all parent class properties.

答: I think you have to remove the flag BindingFlags.DeclaredOnly because the purpose of that flag is exactly to remove the inherited properties from your result.</p>

Body:
I am trying to list all the properties in the type as shown below.

I am loading the DLL file using Assembly.LoadFile(dllFilePath).

Getting all properties in assembly using assembly.GetTypes().ToList().

Classes:

public class A
{
    public int Property1 { get; set; }
    public int Property2 { get; set; }
    public int Property3 { get; set; }
    public int Property4 { get; set; }
}

public class B : A
{
    public int Property5 { get; set; }
}

Methods:

static void Main()
{
    Assembly assembly = Assembly.LoadFile(dllFilePath);
    List<Type> types = assembly.GetTypes().ToList();
    GetAllProperties(typeof(types.FirstOrDefult(a => a.Name == "B")));
}

private void GetAllProperties(Type type)
{
    BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic
        | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Static
        | BindingFlags.FlattenHierarchy;

    // Test 1: No inherited properties.
    PropertyInfo[] propertyInfoList1 = type.GetProperties(bindingFlags);

    List<string> propertyNameList1 = new List<string>();
    foreach (PropertyInfo propertyInfo1 in propertyInfoList1)
    {
        propertyNameList1.Add(propertyInfo1.Name);
    }

    // Test 2: No inherited properties.
    PropertyInfo[] propertyInfoList2 = Activator.CreateInstance(type).GetType().GetProperties(bindingFlags);

    List<string> propertyNameList2 = new List<string>();
    foreach (PropertyInfo propertyInfo2 in propertyInfoList2)
    {
        propertyNameList2.Add(propertyInfo2.Name);
    }

    // Test 3: object has all inherited properties but propertyInfoList doesn't have inherited properties.
    object typeInstance = Activator.CreateInstance(type);
    PropertyInfo[] propertyInfoList3 = typeInstance.GetType().GetProperties(bindingFlags);

    List<string> propertyNameList3 = new List<string>();
    foreach (PropertyInfo propertyInfo3 in propertyInfoList3)
    {
        propertyNameList3.Add(propertyInfo3.Name);
    }
}

In Test 3 all parent class properties are visible when I inspect it.

But typeInstance.GetType().GetProperties(bindingFlags) doesn't return all parent class properties.


问:
Listener for Button press until button is released in android Studio
I am trying to send data via Bluetooth continuously when a button is pressed until it is released, but in my code, I am receiving the data only once when the button is pressed or released.

Here, I am using OnTouchListener with Action_Down and Action_Up.
If someone can help me with it, that would be really great, Thank you.

```<code>fab1.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    TextView d;

                    switch (event.getAction())
                    {
                        case MotionEvent.ACTION_DOWN:data[0]='H';
                            if(connection_check)
                            {
                                d =findViewById(R.id.datacheck);
                                String str=String.valueOf(data)+"\n";
                                d.setText(str);
                                sendData.write(str.getBytes());
                            }
                            else
                                Toast.makeText(getApplicationContext(), "Bluetooth not connected", Toast.LENGTH_LONG).show();
                        break;

                        case MotionEvent.ACTION_UP:
                            data[0]='L';
                            if(connection_check)
                            {
                                d =findViewById(R.id.datacheck);
                                String str=String.valueOf(data)+"\n";
                                d.setText(str);
                                sendData.write(str.getBytes());
                            }
                            else
                                Toast.makeText(getApplicationContext(), "Bluetooth not connected", Toast.LENGTH_LONG).show();

                            break;

                    }
</code>```

答:
Your below code to send the data will be called only once when the user presses the button:

```<code>      data[0]='H';
      if(connection_check)
         {
             d =findViewById(R.id.datacheck);
             String str=String.valueOf(data)+"\n";
             d.setText(str);
             sendData.write(str.getBytes());
         }
      else
        Toast.makeText(getApplicationContext(), "Bluetooth not connected", Toast.LENGTH_LONG).show();
</code>```

You need to create a handler and runnable to call your send function continuously and start and stop it according to the button events.

Runnable:

```<code>Runnable dataSender = new Runnable(){
     @override
     void run(){
       if(isPressed && connection_check)
       {
           d =findViewById(R.id.datacheck);
           String str=String.valueOf(data)+"\n";
           d.setText(str);
           sendData.write(str.getBytes());
           handler.postDelayed(this,100) // for 100 milliseconds
       }
      else
         return
     }
  }
</code>```

Handler:

```<code>Handler handler = new Handler(Looper.getMainLooper())
</code>```

Now create a global boolean variable isPressed set it to false. Now in your onTouchListener set isPressed accordingly and start the runnable using handler.

```<code>fab1.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    TextView d;

                    switch (event.getAction())
                    {
                        case MotionEvent.ACTION_DOWN:
                             isPressed = true
                             handler.post(dataSender) // start the handler
                             break;

                        case MotionEvent.ACTION_UP:
                            isPressed = false //to stop the handler
                            data[0]='L';
                            if(connection_check)
                            {
                                d =findViewById(R.id.datacheck);
                                String str=String.valueOf(data)+"\n";
                                d.setText(str);
                                sendData.write(str.getBytes());
                            }
                            else
                                Toast.makeText(getApplicationContext(), "Bluetooth not connected", Toast.LENGTH_LONG).show();

                            break;

                    }
</code>```

Body:
I am trying to send data via Bluetooth continuously when a button is pressed until it is released, but in my code, I am receiving the data only once when the button is pressed or released.

Here, I am using OnTouchListener with Action_Down and Action_Up.
If someone can help me with it, that would be really great, Thank you.

fab1.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    TextView d;

                    switch (event.getAction())
                    {
                        case MotionEvent.ACTION_DOWN:data[0]='H';
                            if(connection_check)
                            {
                                d =findViewById(R.id.datacheck);
                                String str=String.valueOf(data)+"\n";
                                d.setText(str);
                                sendData.write(str.getBytes());
                            }
                            else
                                Toast.makeText(getApplicationContext(), "Bluetooth not connected", Toast.LENGTH_LONG).show();
                        break;

                        case MotionEvent.ACTION_UP:
                            data[0]='L';
                            if(connection_check)
                            {
                                d =findViewById(R.id.datacheck);
                                String str=String.valueOf(data)+"\n";
                                d.setText(str);
                                sendData.write(str.getBytes());
                            }
                            else
                                Toast.makeText(getApplicationContext(), "Bluetooth not connected", Toast.LENGTH_LONG).show();

                            break;

                    }

Body:
Your below code to send the data will be called only once when the user presses the button:

      data[0]='H';
      if(connection_check)
         {
             d =findViewById(R.id.datacheck);
             String str=String.valueOf(data)+"\n";
             d.setText(str);
             sendData.write(str.getBytes());
         }
      else
        Toast.makeText(getApplicationContext(), "Bluetooth not connected", Toast.LENGTH_LONG).show();

You need to create a handler and runnable to call your send function continuously and start and stop it according to the button events.

Runnable:

Runnable dataSender = new Runnable(){
     @override
     void run(){
       if(isPressed && connection_check)
       {
           d =findViewById(R.id.datacheck);
           String str=String.valueOf(data)+"\n";
           d.setText(str);
           sendData.write(str.getBytes());
           handler.postDelayed(this,100) // for 100 milliseconds
       }
      else
         return
     }
  }

Handler:

Handler handler = new Handler(Looper.getMainLooper())

Now create a global boolean variable isPressed set it to false. Now in your onTouchListener set isPressed accordingly and start the runnable using handler.

fab1.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    TextView d;

                    switch (event.getAction())
                    {
                        case MotionEvent.ACTION_DOWN:
                             isPressed = true
                             handler.post(dataSender) // start the handler
                             break;

                        case MotionEvent.ACTION_UP:
                            isPressed = false //to stop the handler
                            data[0]='L';
                            if(connection_check)
                            {
                                d =findViewById(R.id.datacheck);
                                String str=String.valueOf(data)+"\n";
                                d.setText(str);
                                sendData.write(str.getBytes());
                            }
                            else
                                Toast.makeText(getApplicationContext(), "Bluetooth not connected", Toast.LENGTH_LONG).show();

                            break;

                    }


问:
Original list doesn't show up after a search is made in planets list
I added a searchbar that can search for planets. The searching works. The problem is when I remove the text in the search field it doesn't update the list of planets (they don't come back on the screen).

How can I fix this?

```<code>import React, { PureComponent } from 'react'
import axios from 'axios'

class Home extends PureComponent {
  constructor(props) {
    super(props)

    this.state = {
      planets: [],
    }

    this.handleChange = this.handleChange.bind(this)
  }

  componentDidMount() {
    axios({
      method: 'GET',
      url: 'https://swapi.dev/api/planets/',
    })
      .then(response => {
        console.log(response)
        let planetslist = response.data.results
        this.setState({ planets: planetslist })
      })
      .catch(error => {
        console.log("You've made an error with the planets load charles: ", error)
      })
  }

  handleChange(e) {
    // eslint-disable-next-line
    let planetssearchlist = this.state.planets.filter(planet => {
      if (planet.name) {
        if (planet.name.toLowerCase().includes(e.target.value.toLowerCase())) {
          return true
        }
      }
    })
    this.setState({
      planets: planetssearchlist,
    })
  }

  render() {
    return (
      <div>
        <h1>Star Wars Planets</h1>

        <form>
          <input
            placeholder="searchbar"
            type="text"
            onChange={this.handleChange}
          ></input>
        </form>

        {this.state.planets.map((planet, i) => (
          <p key={i}>{planet.name}</p>
        ))}
      </div>
    )
  }
}

export default Home
</code>```

答:
You should use two variables for storing planets - the ones that you receive from the API callback and the filtered planets.

```<code>this.state = {
  planets: [],
  filteredPlanets: [],
}
</code>```

Set both planets and filteredPlanets to the value you receive from the endpoint so they get displayed initially.

```<code>componentDidMount(){
    axios({
        method: "GET",
        url: "https://swapi.dev/api/planets/"
    })
    .then(response => {
        console.log(response)
        let planetslist = response.data.results;
        this.setState({planets: planetslist, filteredPlanets: [...planetslist]})
    })
    .catch(error => {
        console.log("You've made an error with the planets load charles: ",error)
    })
}
</code>```

When the text gets changed, filter your original planets list.
If there's no text, reset filtered planets

```<code>handleChange(e){
  if (!e.target.value) {
    this.setState(prevState => ({
      filteredPlanets: [...prevState.planets],
    }))
    return
  }
  // eslint-disable-next-line
  let planetssearchlist = this.state.planets.filter(planet => {
       if(planet.name){
          if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
              return true
          }
      }
      return false
  })
  this.setState({
      filteredPlanets: planetssearchlist
  })
}
</code>```

Then map your filteredPlanets in render method

```<code>{
  this.state.filteredPlanets.map((planet,i) => (
    <p key={i}>{planet.name}</p>
  ))
}
</code>```

Body:
I added a searchbar that can search for planets. The searching works. The problem is when I remove the text in the search field it doesn't update the list of planets (they don't come back on the screen).

How can I fix this?

import React, { PureComponent } from 'react'
import axios from 'axios'

class Home extends PureComponent {
  constructor(props) {
    super(props)

    this.state = {
      planets: [],
    }

    this.handleChange = this.handleChange.bind(this)
  }

  componentDidMount() {
    axios({
      method: 'GET',
      url: 'https://swapi.dev/api/planets/',
    })
      .then(response => {
        console.log(response)
        let planetslist = response.data.results
        this.setState({ planets: planetslist })
      })
      .catch(error => {
        console.log("You've made an error with the planets load charles: ", error)
      })
  }

  handleChange(e) {
    // eslint-disable-next-line
    let planetssearchlist = this.state.planets.filter(planet => {
      if (planet.name) {
        if (planet.name.toLowerCase().includes(e.target.value.toLowerCase())) {
          return true
        }
      }
    })
    this.setState({
      planets: planetssearchlist,
    })
  }

  render() {
    return (

Star Wars Planets

        <form>
          <input
            placeholder="searchbar"
            type="text"
            onChange={this.handleChange}
          ></input>
        </form>

        {this.state.planets.map((planet, i) => (

{planet.name}

        ))}

    )
  }
}

export default Home

Body:
You should use two variables for storing planets - the ones that you receive from the API callback and the filtered planets.

this.state = {
  planets: [],
  filteredPlanets: [],
}

Set both planets and filteredPlanets to the value you receive from the endpoint so they get displayed initially.

componentDidMount(){
    axios({
        method: "GET",
        url: "https://swapi.dev/api/planets/"
    })
    .then(response => {
        console.log(response)
        let planetslist = response.data.results;
        this.setState({planets: planetslist, filteredPlanets: [...planetslist]})
    })
    .catch(error => {
        console.log("You've made an error with the planets load charles: ",error)
    })
}

When the text gets changed, filter your original planets list.
If there's no text, reset filtered planets

handleChange(e){
  if (!e.target.value) {
    this.setState(prevState => ({
      filteredPlanets: [...prevState.planets],
    }))
    return
  }
  // eslint-disable-next-line
  let planetssearchlist = this.state.planets.filter(planet => {
       if(planet.name){
          if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
              return true
          }
      }
      return false
  })
  this.setState({
      filteredPlanets: planetssearchlist
  })
}

Then map your filteredPlanets in render method

{
  this.state.filteredPlanets.map((planet,i) => (
    <p key={i}>{planet.name}</p>
  ))
}


问:
Terraform resource isn't reading updated value of another resource correctly
I don't know if this is a Terraform issue or the provider has a bug.

I'm using kubernetes_deployment and kubernetes_config_map.

In kubernetes_deployment I have this:

```<code>template {
  metadata {
    labels = {
      config_version = kubernetes_config_map.myconfig.metadata[0].resource_version
</code>```

This is what happens:

I modify the config file the kubernetes_config_map resource is using
and run apply

Terraform sees the config map resource change but the
kubernetes_deployment resource doesn't show any changes

After I apply I run apply a second time

Now kubernetes_deployment sees the changed value and registers it as a change

This happens with or without an explicit depends_on.

Why is this happening? kubernetes_deployment should be seeing the value has changed and register that as a change too.

答:
I wasn't paying attention to what was happening.

I think this is a bug in the kubernetes_config_map resource.

When the config map data is modified the kubernetes_config_map resource only surfaces a change in the "data" attribute and this is the wrong behavior causing my issue.

If data is modified then the resource_version MUST and will always change, but the resource doesn't register this change. Because of this dependant resources looking at that attribute don't see any changes.

Too bad because that would be a really clear way to to this.

Fortunately until that bug is fixed I can use a hash of the data attribute:

```<code>template {
  metadata {
    labels = {
      config_hash = md5(kubernetes_config_map.myconfig.data)
</code>```

Body:
I don't know if this is a Terraform issue or the provider has a bug.

I'm using kubernetes_deployment and kubernetes_config_map.

In kubernetes_deployment I have this:

template {
  metadata {
    labels = {
      config_version = kubernetes_config_map.myconfig.metadata[0].resource_version

This is what happens:

I modify the config file the kubernetes_config_map resource is using
and run apply

Terraform sees the config map resource change but the
kubernetes_deployment resource doesn't show any changes

After I apply I run apply a second time

Now kubernetes_deployment sees the changed value and registers it as a change

This happens with or without an explicit depends_on.

Why is this happening? kubernetes_deployment should be seeing the value has changed and register that as a change too.

Body:
I wasn't paying attention to what was happening.

I think this is a bug in the kubernetes_config_map resource.

When the config map data is modified the kubernetes_config_map resource only surfaces a change in the "data" attribute and this is the wrong behavior causing my issue.

If data is modified then the resource_version MUST and will always change, but the resource doesn't register this change. Because of this dependant resources looking at that attribute don't see any changes.

Too bad because that would be a really clear way to to this.

Fortunately until that bug is fixed I can use a hash of the data attribute:

template {
  metadata {
    labels = {
      config_hash = md5(kubernetes_config_map.myconfig.data)


问:
SAS Print a value in the log
I just want to print the output of a simple operation to the SAS log.

For instance, how can I see the value of quantile('T', .75, 1000)? Is there a smarter way to check what does quantile('T', .75, 1000) equal to than printing it to the log?

```<code>%let t_value = quantile('T', .75, 1000);
%put &t_value.;
</code>```

Others use a proc procedure as here but I cannot believe I need to create a data set to check a value...

答:
You don't need to create a data set, but another option is a data step with the _null_ data set.

```<code>data _null_;
x = quantile('T', 0.75, 1000);
put x;
run;
</code>```

Title: SAS Print a value in the log

Body:
I just want to print the output of a simple operation to the SAS log.

For instance, how can I see the value of quantile('T', .75, 1000)? Is there a smarter way to check what does quantile('T', .75, 1000) equal to than printing it to the log?

%let t_value = quantile('T', .75, 1000);
%put &t_value.;

Others use a proc procedure as here but I cannot believe I need to create a data set to check a value...

Body:
You don't need to create a data set, but another option is a data step with the _null_ data set.

data _null_;
x = quantile('T', 0.75, 1000);
put x;
run;


问:
Python: How to label this dataset
Hi I have df like this:

```<code>df = pd.DataFrame({'CaseNo':[1,1,1,1,2,2,3,3,3,4,4],
                   'Category':['A','A','IOU','A','B','B','IOU','IOU','IOU','C','IOU']})
</code>```

I'd like to label CaseNo col based on this condition:

For each CaseNo, if there is an occurrence of value 'IOU' in Category column with any values (except 'IOU') preceding it - label 'YES', else label 'NO'.

How can I do this in Python? Expected outcome:

答:
Groupby with a count of IOU is one way to solve it :

```<code>res = (df
       .assign(val = df.groupby('CaseNo').Category.transform(",".join),
               label = lambda x: np.where(x.val.str.count("IOU").eq(1) ,"YES","NO")
              )
       .drop('val',axis=1)
      )

res

    CaseNo  Category    label
0      1       A        YES
1      1       A        YES
2      1      IOU       YES
3      1       A        YES
4      2       B        NO
5      2       B        NO
6      3     IOU        NO
7      3     IOU        NO
8      3     IOU        NO
9      4       C        YES
10     4     IOU        YES
</code>```

Title: Python: How to label this dataset

Body:
Hi I have df like this:

df = pd.DataFrame({'CaseNo':[1,1,1,1,2,2,3,3,3,4,4],
                   'Category':['A','A','IOU','A','B','B','IOU','IOU','IOU','C','IOU']})

I'd like to label CaseNo col based on this condition:

For each CaseNo, if there is an occurrence of value 'IOU' in Category column with any values (except 'IOU') preceding it - label 'YES', else label 'NO'.

How can I do this in Python? Expected outcome:

Body:
Groupby with a count of IOU is one way to solve it :

res = (df
       .assign(val = df.groupby('CaseNo').Category.transform(",".join),
               label = lambda x: np.where(x.val.str.count("IOU").eq(1) ,"YES","NO")
              )
       .drop('val',axis=1)
      )

res

    CaseNo  Category    label
0      1       A        YES
1      1       A        YES
2      1      IOU       YES
3      1       A        YES
4      2       B        NO
5      2       B        NO
6      3     IOU        NO
7      3     IOU        NO
8      3     IOU        NO
9      4       C        YES
10     4     IOU        YES


问:
Upload asset in Google Earth Engine with Python?
I want upload an asset to Earth Engine with Python and I don't want use Google Cloud Storage.

Is there a way to upload a particular file (from my computer) directly to the Google Earth Engine using the command line (or using a Python script)?

答: No. You can only upload from Google Cloud Storage via python. The only way to upload directly from your computer is via the playground.</p>


问:
How to use Google Assistant responses in DialogFlow?
I try to use Link Out Suggestion for Google Assistant response.

I test my app and:

If I set DEFAULT response also works DEFAULT response exactly.

If I set only Link Out Suggestion I have an error that my test app doesn't respond.

What should me do to make work GOOGLE ASSISTANT response exactly, not DEFAULT response?

答:
In addition to the Link Out Suggestion, you must include at least one Simple Response. If you have responses in the Default response section, and you have the "Use responses from the DEFAULT tab as the first response" set on (which you do), it will use those as the Simple Response.

If you have it set off, however, you must set your own Simple Responses for the Google Assistant. You cannot have just a link out suggestion - you must have text that goes along with it.


问:
Firestore multiple queries
I am new in nodejs, I want to multiple queries from Firestore database in nodejs (cloud functions).

Minimum 1 query, maximum 5 only if data.query[0,1...] is defined.

```<code>if(data.query[0] !== undefined)
    {
db.collection('example').doc(data.query[0]).listCollections().then(collections => {
            collections.forEach(collection => {
                console.log('Found subcollection with id:', collection.id);
               allcollections = allcollections + collection.id + '&';
            })
      });
    }

if(data.query[1] !== undefined)
    {
db.collection('example').doc(data.query[1]).listCollections().then(collections => {
            collections.forEach(collection => {
                console.log('Found subcollection with id:', collection.id);
               allcollections = allcollections + collection.id + '&';
            })
      });
    }
</code>```

...
and at the end I return all collections to client.

My problem is each then should return a value, I don't know how to do run all queries and only return results (allcollections) at the end?

Thanks!

答:
You could try to use Promise.all

It would go in the lines:

```<code>var queryPromises = [];

if(data.query[0] !== undefined) {
    var promise = db.collection('example').doc(data.query[0]).listCollections();
    queryPromises.push(promise);
}

if(data.query[1] !== undefined) {
    var promise = db.collection('example').doc(data.query[1]).listCollections();
    queryPromises.push(promise);
}

if(data.query[2] !== undefined) {
    var promise = db.collection('example').doc(data.query[2]).listCollections();
    queryPromises.push(promise);
}

if(data.query[3] !== undefined) {
    var promise = db.collection('example').doc(data.query[3]).listCollections();
    queryPromises.push(promise);
}

if(data.query[4] !== undefined) {
    var promise = db.collection('example').doc(data.query[4]).listCollections();
    queryPromises.push(promise);
}

Promise.all(queryPromises).then(results => {
    // results is an array with the result of each one of the promises
    // Do what you have to do
});
</code>```

Pay attention to this detail from the documentation:

Returned values will be in order of the Promises passed, regardless of
  completion order.

Title: Firestore multiple queries

Body:
I am new in nodejs, I want to multiple queries from Firestore database in nodejs (cloud functions).

Minimum 1 query, maximum 5 only if data.query[0,1...] is defined.

if(data.query[0] !== undefined)
    {
db.collection('example').doc(data.query[0]).listCollections().then(collections => {
            collections.forEach(collection => {
                console.log('Found subcollection with id:', collection.id);
               allcollections = allcollections + collection.id + '&';
            })
      });
    }

if(data.query[1] !== undefined)
    {
db.collection('example').doc(data.query[1]).listCollections().then(collections => {
            collections.forEach(collection => {
                console.log('Found subcollection with id:', collection.id);
               allcollections = allcollections + collection.id + '&';
            })
      });
    }

...
and at the end I return all collections to client.

My problem is each then should return a value, I don't know how to do run all queries and only return results (allcollections) at the end?

Thanks!

Body:
You could try to use Promise.all

It would go in the lines:

var queryPromises = [];

if(data.query[0] !== undefined) {
    var promise = db.collection('example').doc(data.query[0]).listCollections();
    queryPromises.push(promise);
}

if(data.query[1] !== undefined) {
    var promise = db.collection('example').doc(data.query[1]).listCollections();
    queryPromises.push(promise);
}

if(data.query[2] !== undefined) {
    var promise = db.collection('example').doc(data.query[2]).listCollections();
    queryPromises.push(promise);
}

if(data.query[3] !== undefined) {
    var promise = db.collection('example').doc(data.query[3]).listCollections();
    queryPromises.push(promise);
}

if(data.query[4] !== undefined) {
    var promise = db.collection('example').doc(data.query[4]).listCollections();
    queryPromises.push(promise);
}

Promise.all(queryPromises).then(results => {
    // results is an array with the result of each one of the promises
    // Do what you have to do
});

Pay attention to this detail from the documentation:

Returned values will be in order of the Promises passed, regardless of
  completion order.


问:
How can one enable SAML federation in the Cognito Hosted UI without advertising their customer list?
I am building an enterprise app and federating signin using the Cognito Hosted UI solution, and people can sign up individually using any email, but they might also work for a company which has signed an enterprise deal with us and use SSO.

The desired workflow is one in which they input their signin email, then it is checked against our list of SAML Single Sign On providers, and if they match an enterprise client using SSO they are sent to the proper federation page; if they don't match any, they are taken to the general purpose login.

So far, I have successfully used the Hosted UI and the critical idpIdentifier parameter to create the desired behavior successfully. The following React code summarizes how this works:

```<code>    hostedUILogin() {
        const idpIdentifier = this.state.email.split("@")[1];

        let url = `https://${domain}/oauth2/authorize?response_type=code&client_id=${clientId}&redirect_uri=${redirectSignIn}`;

        if (idpIdentifier) {
            url += `&idp_identifier=${idpIdentifier}`;
        }

        window.location.assign(url);

    }
</code>```

This produces the desired effect. When somebody signs in with an email address that ends in "@corporatecustomer.com" they are taken to the SSO page for Corporation's federation. When somebody signs in with "@gmail.com", they are taken to the Cognito Hosted UI.

Unfortunately, the Hosted UI seems to be unable to help itself but to show off our customer list on the left-hand side.

I am unable to discover in the documentation or tutorials any way to use the Cognito Hosted UI without advertising all available SAML providers on the left hand side, thereby giving away our customer list.

I have tried taking away the IDP for this Hosted UI App in the App Client configuration, but then it no longer captures through the idp_identifier successfully.

答: If it helps to you, one of the solutions I found was to create a single User Pool per Corporate Customer</p>

Body:
I am building an enterprise app and federating signin using the Cognito Hosted UI solution, and people can sign up individually using any email, but they might also work for a company which has signed an enterprise deal with us and use SSO.

The desired workflow is one in which they input their signin email, then it is checked against our list of SAML Single Sign On providers, and if they match an enterprise client using SSO they are sent to the proper federation page; if they don't match any, they are taken to the general purpose login.

So far, I have successfully used the Hosted UI and the critical idpIdentifier parameter to create the desired behavior successfully. The following React code summarizes how this works:

    hostedUILogin() {
        const idpIdentifier = this.state.email.split("@")[1];

        let url = `https://${domain}/oauth2/authorize?response_type=code&client_id=${clientId}&redirect_uri=${redirectSignIn}`;

        if (idpIdentifier) {
            url += `&idp_identifier=${idpIdentifier}`;
        }

        window.location.assign(url);

    }

This produces the desired effect. When somebody signs in with an email address that ends in "@corporatecustomer.com" they are taken to the SSO page for Corporation's federation. When somebody signs in with "@gmail.com", they are taken to the Cognito Hosted UI.

Unfortunately, the Hosted UI seems to be unable to help itself but to show off our customer list on the left-hand side.

I am unable to discover in the documentation or tutorials any way to use the Cognito Hosted UI without advertising all available SAML providers on the left hand side, thereby giving away our customer list.

I have tried taking away the IDP for this Hosted UI App in the App Client configuration, but then it no longer captures through the idp_identifier successfully.


问:
XML documentation not found when publishing a .Net Framework web API?
I scratched my head over this one for a few hours. I followed Microsoft's tutorial on adding API documentation. That all worked as expected on my local machine, but when published to my production IIS server, I got an error saying the XmlDocument.xml could not be found. </p>

答:
Although enabling the "XML documentation file" checkbox in the project properties > build > output section does create the file, it does not add it to the project for some reason. That's why the App_Data folder in my solution explorer was empty.

The solution is simple. Right-click on the App_Data folder and select the add existing item option. Select the generated XML documentation file in the "App_Data" folder of your project's build location. Publish again.

I hope someone can find this useful.


问:
Eclipse Template Proposals (aka auto completion) not working
recently the proposals (Ctrl+Space) for Eclipse/Java stopped working, as suggested in the wiki I looked at the Preferences of Content Assist for Java, but all options are checked and still not working, any idea?

EDIT: One error is shown while trying to display proposals: Project facet grails.app has not been defined. It is used in plugin com.springsource.sts.server.tc.core.

答:
Somehow the references to the JDK where broken, so no completions could be made!

UPDATE: Solved by going to Window -> Preferences -> Installed JREs and changing the JDK folder to the right one.


问:
Pandas pd.cut ValueError: Length of values does not match length of index
I have a dataframe and series with the same number of rows.

The result of pd.cut also outputs data with the same shape.

Where am I going wrong?

My dataframe, 37459 rows:

```<code>df.shape

(37459, 124)
</code>```

The column I am trying to cut, 37459 rows:

```<code>df['score']

2        74.390244
4        29.268293
5        45.121951
6        46.341463
7        31.707317
           ...
43502    21.951220
43503     1.219512
43505     3.658537
43506     8.536585
43507    12.195122
Name: score, Length: 37459, dtype: float64
</code>```

And the output of pd.cut:

```<code>pd.cut(df['score'], [0, 33, 66, 100], labels=[1,2,3], retbins=True, right=False)

(2        3
 4        1
 5        2
 6        2
 7        1
         ..
 43502    1
 43503    1
 43505    1
 43506    1
 43507    1
 Name: score, Length: 37459, dtype: category
 Categories (3, int64): [1 < 2 < 3], array([  0,  33,  66, 100]))
</code>```

My attempt to attach the result of pd.cut to the df. I am trying to cut it into three groups and label them [1,2,3]:

```<code>df['score_cut'] = pd.cut(df['score'], [0, 33, 66, 100], labels=[1,2,3], retbins=True, right=False)

ValueError: Length of values does not match length of index
</code>```

Where am I going wrong?

答:
Did you try qcut?</p>

```<code>pd.qcut(df['score'], [0, .33, .66, 1], labels=[1,2,3], retbins=True, right=False)
</code>```

Body:
I have a dataframe and series with the same number of rows.

The result of pd.cut also outputs data with the same shape.

Where am I going wrong?

My dataframe, 37459 rows:

df.shape

(37459, 124)

The column I am trying to cut, 37459 rows:

df['score']

2        74.390244
4        29.268293
5        45.121951
6        46.341463
7        31.707317
           ...
43502    21.951220
43503     1.219512
43505     3.658537
43506     8.536585
43507    12.195122
Name: score, Length: 37459, dtype: float64

And the output of pd.cut:

pd.cut(df['score'], [0, 33, 66, 100], labels=[1,2,3], retbins=True, right=False)

(2        3
 4        1
 5        2
 6        2
 7        1
         ..
 43502    1
 43503    1
 43505    1
 43506    1
 43507    1
 Name: score, Length: 37459, dtype: category
 Categories (3, int64): [1 < 2 < 3], array([  0,  33,  66, 100]))

My attempt to attach the result of pd.cut to the df. I am trying to cut it into three groups and label them [1,2,3]:

df['score_cut'] = pd.cut(df['score'], [0, 33, 66, 100], labels=[1,2,3], retbins=True, right=False)

ValueError: Length of values does not match length of index

Where am I going wrong?

Body:
Did you try qcut?

pd.qcut(df['score'], [0, .33, .66, 1], labels=[1,2,3], retbins=True, right=False)


问:
How to apply a css class in a element that hasn't been rendered yet?
I need to add a css class to an element that when the page is loaded is still not created. It gets created only when the dropdown is open. This is my code below where I loop through a list and add a class to the elements but, as I said, the class '.dropdown-popup-row' is not found because the drop starts closed.

What I'm doing at the moment is verify if '.dropdown-list' exists in the body (if so, it means that the dropdown is open)

```<code>const str = "[0,1,2]";
const arr = JSON.parse(str);

var dropdownList = document.querySelector('.dropdown-list');

if (document.body.contains(dropdownList)) {
    var dropdownElements = document.querySelectorAll('.dropdown-popup-row');

    if(dropdownElements) {

    for(var i = 0; i < arr.length; i++) {
        var disabledIndex = arr[i];
        dropdownElements[disabledIndex].classList.add("-disabled");
    }
}
}
</code>```

this works fine in the browser console with the dropdown open (therefore .dropdown-list is rendered and available in the DOM). I can't figure out a way to add this class to this element. The error I've been getting is: "Uncaught TypeError: Cannot read property 'classList' of undefined".

Thank you guys!

答:
If you have dropDownElements, you should be able to safely iterate over them as opposed to iterating over your list of disabled indexes.  Something like:

```<code>if (document.body.contains(dropdownList)) {
    var dropdownElements = document.querySelectorAll('.dropdown-popup-row');

    // For each dropdown item
    dropdownElements.forEach(function(element, i) {
        // If the index corresponds to one in the list, disable it
        if (arr.includes(i)) {
            element.classList.add("-disabled");
        }
    });
}
</code>```

In your original code, there's the possibility that an index in the array does not match to an item in your dropdown, which could lead to the error you received. For example if there's a 4 in your array and only four elements in your dropdown, dropdownElements[4] will be undefined. In my code above, there's no chance of this because it's iterating over the elements in the dropdown instead.

If the problem is truly that your dropdown elements are only rendered after the dropdown is selected, you might run the above code when dropdownList gets focused or clicked.

Body:
I need to add a css class to an element that when the page is loaded is still not created. It gets created only when the dropdown is open. This is my code below where I loop through a list and add a class to the elements but, as I said, the class '.dropdown-popup-row' is not found because the drop starts closed.

What I'm doing at the moment is verify if '.dropdown-list' exists in the body (if so, it means that the dropdown is open)

const str = "[0,1,2]";
const arr = JSON.parse(str);

var dropdownList = document.querySelector('.dropdown-list');

if (document.body.contains(dropdownList)) {
    var dropdownElements = document.querySelectorAll('.dropdown-popup-row');

    if(dropdownElements) {

    for(var i = 0; i < arr.length; i++) {
        var disabledIndex = arr[i];
        dropdownElements[disabledIndex].classList.add("-disabled");
    }
}
}

this works fine in the browser console with the dropdown open (therefore .dropdown-list is rendered and available in the DOM). I can't figure out a way to add this class to this element. The error I've been getting is: "Uncaught TypeError: Cannot read property 'classList' of undefined".

Thank you guys!

Body:
If you have dropDownElements, you should be able to safely iterate over them as opposed to iterating over your list of disabled indexes.  Something like:

if (document.body.contains(dropdownList)) {
    var dropdownElements = document.querySelectorAll('.dropdown-popup-row');

    // For each dropdown item
    dropdownElements.forEach(function(element, i) {
        // If the index corresponds to one in the list, disable it
        if (arr.includes(i)) {
            element.classList.add("-disabled");
        }
    });
}

In your original code, there's the possibility that an index in the array does not match to an item in your dropdown, which could lead to the error you received. For example if there's a 4 in your array and only four elements in your dropdown, dropdownElements[4] will be undefined. In my code above, there's no chance of this because it's iterating over the elements in the dropdown instead.

If the problem is truly that your dropdown elements are only rendered after the dropdown is selected, you might run the above code when dropdownList gets focused or clicked.


问:
How to display sum result of two column field even if one field is empty in sql?
I am having difficulty to show total value of two fileds in sql. I am getting result of first row but my second row is not showing any result just displaying empty.

Tabel Name: NumberTable

```<code>ID  VALUE1  VALUE2
===================
1   1       2
2   2
</code>```

Sql Query

```<code>Select id, (VALUE1  + VALUE2) as Total_Salary  From NumberTable;
</code>```

The following output that I am getting after running this query

```<code>ID  TOTAL
1    3
2    -
</code>```

But I want output like this:

```<code>ID  TOTAL
1    3
2    2
</code>```

答:
Use coalesce():

```<code>coalesce(value1, 0) + coalesce(value2, 0)
</code>```

The addition operator returns NULL if either argument is NULL.

Body:
I am having difficulty to show total value of two fileds in sql. I am getting result of first row but my second row is not showing any result just displaying empty.

Tabel Name: NumberTable

ID  VALUE1  VALUE2
===================
1   1       2
2   2

Sql Query

Select id, (VALUE1  + VALUE2) as Total_Salary  From NumberTable;

The following output that I am getting after running this query

ID  TOTAL
1    3
2    -

But I want output like this:

ID  TOTAL
1    3
2    2

Body:
Use coalesce():

coalesce(value1, 0) + coalesce(value2, 0)

The addition operator returns NULL if either argument is NULL.


问:
How to add a condition to a variable - GAMS
In the model I'm trying to build, I have a variable defined as:

```<code>Variables
    x(i,j)  number of motors produced in month i to be delivered in month j ;
</code>```

In that variable, j must always be equal or greater than i for it to make sense (you can't produce something in this month to be delivered in the previous month).
However, I have no clue as to how I can properly model this. I've searched and couldn't find an easy solution to this.

Any ideas?

答:
You should use "variables with limited domains" for this, look here for more details, it is a rather new GAMS feature: https://www.gams.com/latest/docs/UG_ModelSolve.html#UG_ModelSolve_LimitedDomain

So, in your example, it would look like this:

```<code>Set limX(i,j) limiting domain of x;

limX(i,j) = ord(j) >= ord(i);

Model m /all, x(limX)/;
...
</code>```

Edit: Corrected syntax of model statement.

Body:
In the model I'm trying to build, I have a variable defined as:

Variables
    x(i,j)  number of motors produced in month i to be delivered in month j ;

In that variable, j must always be equal or greater than i for it to make sense (you can't produce something in this month to be delivered in the previous month).
However, I have no clue as to how I can properly model this. I've searched and couldn't find an easy solution to this.

Any ideas?

Body:
You should use "variables with limited domains" for this, look here for more details, it is a rather new GAMS feature: https://www.gams.com/latest/docs/UG_ModelSolve.html#UG_ModelSolve_LimitedDomain

So, in your example, it would look like this:

Set limX(i,j) limiting domain of x;

limX(i,j) = ord(j) >= ord(i);

Model m /all, x(limX)/;
...

Edit: Corrected syntax of model statement.


问:
Adding text over an image in HTML CSS
I am trying to add text over top of an image on a 'product card' listing. The top left and top right div classes aren't appearing over top of the image. Here is my code:

.cardcontainer {
    position: relative;
}
.top-left {
    position: absolute;
    top: 8px;
    left: 16px;
    background-color: black;
    color: white;
    padding-left: 5px;
    padding-right: 5px;
}
.top-right {
    position: absolute;
    top: 8px;
    right: 16px;
    background-color: black;
    color: white;
    padding-left: 5px;
    padding-right: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="4u">
    <div class="cardcontainer">
        <img src={{ jinja image source }} alt="">
        <div class="top-left">top left text</div>
        <div class="top-right">top right text</div>
        <div class="textbox">
            <!--some stuff here that appears below the image-->
        </div>
    </div>
</section></code>```

Any ideas? thanks for your help!

答:
Based on your code, I'm assuming that you haven't considered that the image could differ in size.
 tags actually consume the whole width of the image. , however, doesn't follow the same rule. If you image is of 300px width, it will maintain that unless specified through the width attribute or style.

You will need to consider adjusting your image's size to match your
 container's width.

Here's an adjusted code you can check out:

```<code><section class="4u">
    <div class="cardcontainer">
        <a href="https://localhost" target="_blank" class="image featured"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/220px-Image_created_with_a_mobile_phone.png"} alt=""></a>
        <div class="top-left">top left text</div>
        <div class="top-right">top right text</div>
        <div class="textbox">
            Here's some text below
        </div>
    </div>
</section>
</code>```

In the style below, I matched the image's width to the .cardcontainer. You can change that anytime of course. I also added style to .textbox to put it on top of the image as you specified.

```<code>.cardcontainer {
    position: relative;
    width: 500px;
}

.cardcontainer img {
  width: 100%;
}

.top-left {
    position: absolute;
    top: 8px;
    left: 16px;
    background-color: black;
    color: white;
    padding-left: 5px;
    padding-right: 5px;
}
.top-right {
    position: absolute;
    top: 8px;
    right: 16px;
    background-color: black;
    color: white;
    padding-left: 5px;
    padding-right: 5px;
}
.textbox {
  position: absolute;
  bottom: 8px;
  background-color: black;
  color: white;
  padding-left: 5px;
  padding-right: 5px;
}
</code>```

You can play with it as well in this link:
https://jsfiddle.net/f7a5ow9q/

Title: Adding text over an image in HTML CSS

Body:
I am trying to add text over top of an image on a 'product card' listing. The top left and top right div classes aren't appearing over top of the image. Here is my code:

.cardcontainer {
    position: relative;
}
.top-left {
    position: absolute;
    top: 8px;
    left: 16px;
    background-color: black;
    color: white;
    padding-left: 5px;
    padding-right: 5px;
}
.top-right {
    position: absolute;
    top: 8px;
    right: 16px;
    background-color: black;
    color: white;
    padding-left: 5px;
    padding-right: 5px;
}

top left text

top right text

Any ideas? thanks for your help!

Body:
Based on your code, I'm assuming that you haven't considered that the image could differ in size. <div> tags actually consume the whole width of the image. <img>, however, doesn't follow the same rule. If you image is of 300px width, it will maintain that unless specified through the width attribute or style.

You will need to consider adjusting your image's size to match your <div> container's width.

Here's an adjusted code you can check out:

<section class="4u">
    <div class="cardcontainer">
        <a href="https://localhost" target="_blank" class="image featured"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/220px-Image_created_with_a_mobile_phone.png"} alt=""></a>
        <div class="top-left">top left text</div>
        <div class="top-right">top right text</div>
        <div class="textbox">
            Here's some text below
        </div>
    </div>
</section>

In the style below, I matched the image's width to the .cardcontainer. You can change that anytime of course. I also added style to .textbox to put it on top of the image as you specified.

.cardcontainer {
    position: relative;
    width: 500px;
}

.cardcontainer img {
  width: 100%;
}

.top-left {
    position: absolute;
    top: 8px;
    left: 16px;
    background-color: black;
    color: white;
    padding-left: 5px;
    padding-right: 5px;
}
.top-right {
    position: absolute;
    top: 8px;
    right: 16px;
    background-color: black;
    color: white;
    padding-left: 5px;
    padding-right: 5px;
}
.textbox {
  position: absolute;
  bottom: 8px;
  background-color: black;
  color: white;
  padding-left: 5px;
  padding-right: 5px;
}

You can play with it as well in this link:
https://jsfiddle.net/f7a5ow9q/


问:
How to make my menu contribution appear after a plug-in menu contribution?
I have defined an Exit command to display on my File menu. However another plug-in is contributing a Open File item on the File menu and this is appearing AFTER my Exit command. I want my Exit command to appear last on the File menu.

I've tried specifying locationURI menu:file?after=org.eclipse.ui.openLocalFile but then my Exit menu item does not display at all. I think this might be because org.eclipse.ui.openLocalFile has not been loaded yet.

I've also tried specifying locationURI menu:file?after=additions but the Open File menu item still displays after mine.

How can I get the menu item order to be Open File and then my Exit command?

答:
You need to put some of the proper group markers in your File menu when you create it.  The order of operations is:

ActionBarAdvisor creates
MenuManagers programatically

org.eclipse.ui.menus are applied

legacy action extensions are applied
(like actionSets)

Open File says it has a menubarPath="file/new.ext".  So however you create your File menu, you must add a group marker for new.ext.  The group markers will allow you to control the contribution order.

See org.eclipse.ui.internal.ide.WorkbenchActionBuilder in org.eclipse.ui.ide for an example of the group markers the eclipse IDE includes.


问:
Adding Attribute to Form Element Using PHP
I'm using a CMS and a form builder extension, the extension allows me to run PHP scripts when on page load.

I'm also able to add custom 'Additional Attributes' to individual elements, the 'Additional Attributes' section is a free text field allowing me to enter custom text e.g. maxlength="20", placeholder="Admin Only" you can see below.

I have a form that contains the following elements (showing only four for brevity, actual form contains many more);

```<code>// user fields
<input type="text" value="" name="form[Name]" id="Name" class="form-control" maxlength="20">
<input type="text" value="" name="form[Address]" id="Address" class="form-control" maxlength="20">
// admin only fields
<input type="text" value="" name="form[AdminName]" id="AdminName" class="form-control" maxlength="20" placeholder="Admin Only">
<input type="text" value="" name="form[AdminComment]" id="AdminComment" class="form-control" maxlength="50" placeholder="Admin Only">
</code>```

Using only PHP (and not a DOM Parser) I need to be able to add the readonly attribute all form elements that are for admins only. In the form above that is the last two inputs.

```<code><?php
    if (userid == something) {
        // add 'readonly' attribute to all admin inputs
    }
?>
</code>```

I was thinking of using str_replace or the form 'Additional Attributes' feature somehow?

I can't use Javascript / JQuery.

答:
The solution I found was to add a custom attribute to the html element e.g. xyz, then use str_replace in order to replace this attribute with readonly.

The form inputs weer generated from a PHP variable $formData.

```<code><input type="text" value="" name="form[Name]" id="Name" class="form-control" maxlength="20" xyz>

<?php
    if (userid == something) {
        str_replace("xyz","readonly",$formData)
    }
?>
</code>```

Body:
I'm using a CMS and a form builder extension, the extension allows me to run PHP scripts when on page load.

I'm also able to add custom 'Additional Attributes' to individual elements, the 'Additional Attributes' section is a free text field allowing me to enter custom text e.g. maxlength="20", placeholder="Admin Only" you can see below.

I have a form that contains the following elements (showing only four for brevity, actual form contains many more);

// user fields
<input type="text" value="" name="form[Name]" id="Name" class="form-control" maxlength="20">
<input type="text" value="" name="form[Address]" id="Address" class="form-control" maxlength="20">
// admin only fields
<input type="text" value="" name="form[AdminName]" id="AdminName" class="form-control" maxlength="20" placeholder="Admin Only">
<input type="text" value="" name="form[AdminComment]" id="AdminComment" class="form-control" maxlength="50" placeholder="Admin Only">

Using only PHP (and not a DOM Parser) I need to be able to add the readonly attribute all form elements that are for admins only. In the form above that is the last two inputs.

<?php
    if (userid == something) {
        // add 'readonly' attribute to all admin inputs
    }
?>

I was thinking of using str_replace or the form 'Additional Attributes' feature somehow?

I can't use Javascript / JQuery.

Body:
The solution I found was to add a custom attribute to the html element e.g. xyz, then use str_replace in order to replace this attribute with readonly.

The form inputs weer generated from a PHP variable $formData.

<input type="text" value="" name="form[Name]" id="Name" class="form-control" maxlength="20" xyz>

<?php
    if (userid == something) {
        str_replace("xyz","readonly",$formData)
    }
?>


问:
Problems to get the data from Ionic Storage
I have a problem with the Ionic-Storage.
I want to save a boolean into the storage. The action is triggered by an ion-toggle. If the toggle is on= true, otherwise false. So I have create a service, which can save and get the data.

Storage-Service.ts

```<code>const ITEM_KEY = 'modal-myworkplace';
[...]

async setItem(value){
  const res = await this.storage.set(ITEM_KEY,value)
   console.log(res)
 }

  async getItem() {
      await this.storage.get(ITEM_KEY).then((name) => {
          console.log('The Keyvalue is: '+name)
      })
  }
</code>```

Here is the problem...
I want to get this data in an component. Like this:
Component.ts

```<code>let saveWorkplace: boolean;
[...]
async setData(){
    await this.storage.getItem().then((name) => {
      console.log("Key: "+ name)
    })
  }
</code>```

I want to get the value from the Storage (true or false) and this should then be defined in saveWorkplace.

If I console.log this properties in the Component.ts I get an undefined object. But if i console.log the property in Storage.ts I get an Value(See Image)

I dont know how I can get only the Value true or false.

I hope anyone can help me

答:
Your getItem() is not returning the value. Change it to:

```<code>async getItem() {
    return await this.storage.get(ITEM_KEY);
}
</code>```

Body:
I have a problem with the Ionic-Storage.
I want to save a boolean into the storage. The action is triggered by an ion-toggle. If the toggle is on= true, otherwise false. So I have create a service, which can save and get the data.

Storage-Service.ts

const ITEM_KEY = 'modal-myworkplace';
[...]

async setItem(value){
  const res = await this.storage.set(ITEM_KEY,value)
   console.log(res)
 }

  async getItem() {
      await this.storage.get(ITEM_KEY).then((name) => {
          console.log('The Keyvalue is: '+name)
      })
  }

Here is the problem...
I want to get this data in an component. Like this:
Component.ts

let saveWorkplace: boolean;
[...]
async setData(){
    await this.storage.getItem().then((name) => {
      console.log("Key: "+ name)
    })
  }

I want to get the value from the Storage (true or false) and this should then be defined in saveWorkplace.

If I console.log this properties in the Component.ts I get an undefined object. But if i console.log the property in Storage.ts I get an Value(See Image)

I dont know how I can get only the Value true or false.

I hope anyone can help me

Body:
Your getItem() is not returning the value. Change it to:

async getItem() {
    return await this.storage.get(ITEM_KEY);
}


问:
How to copy a CakePHP Entity
I'm writing a method that copies an object. Instead of manually setting each property manually, it would be more robust to just loop over the original object's properties...

```<code>//Booo
$new->name = $old->name;
$new->color = $old->color;
...

//Oh yeah...
foreach ($old as $prop=>$val){
    $new->$prop = $val;
}
unset $new->id;
</code>```

It appears that CakePHP entities cannot be iterated over in this way. I tried using $old->toArray(), which basically works... but has the drawback of converting all the associations to arrays also, which is screwing this up for me down stream.

How do I loop over the $old properties without converting all the data types?

Update:
Mark brought to my attention the existence of a __clone() method. Sounds like it does exactly what I need but I'm still figuring out how to use it.

答:
It is actually much easier to use the Table Object:</p>

```<code>// Assuming your model is called "Documents"
// If you are in the Controller, you can just use `$this->Documents`
   instead of fetching the Table from the Registry
use Cake\ORM\TableRegistry;
$table = TableRegistry::getTableLocator()->get('Documents');

// newEntity() creates a new Entity from an array of data
$documentCopy = $table->newEntity(
    // extract() extracts the given properties as an associative array
    $document->extract(
        // getVisible() will get all visible properties as an array
        $document->getVisible()
    )
);
</code>```

Title: How to copy a CakePHP Entity

Body:
I'm writing a method that copies an object. Instead of manually setting each property manually, it would be more robust to just loop over the original object's properties...

//Booo
$new->name = $old->name;
$new->color = $old->color;
...

//Oh yeah...
foreach ($old as $prop=>$val){
    $new->$prop = $val;
}
unset $new->id;

It appears that CakePHP entities cannot be iterated over in this way. I tried using $old->toArray(), which basically works... but has the drawback of converting all the associations to arrays also, which is screwing this up for me down stream.

How do I loop over the $old properties without converting all the data types?

Update:
Mark brought to my attention the existence of a __clone() method. Sounds like it does exactly what I need but I'm still figuring out how to use it.

Body:
It is actually much easier to use the Table Object:

// Assuming your model is called "Documents"
// If you are in the Controller, you can just use `$this->Documents`
   instead of fetching the Table from the Registry
use Cake\ORM\TableRegistry;
$table = TableRegistry::getTableLocator()->get('Documents');

// newEntity() creates a new Entity from an array of data
$documentCopy = $table->newEntity(
    // extract() extracts the given properties as an associative array
    $document->extract(
        // getVisible() will get all visible properties as an array
        $document->getVisible()
    )
);