问:
How to make game character (user) move smooth?
in my game i have set my character to move. How it is set is:

```<code>if game_over_state == False:
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_ESCAPE:
            pause = True
            game_paused()
        if event.key == pygame.K_LEFT:
            player_x_change = -2
        if event.key == pygame.K_RIGHT:
            player_x_change = 2
        if event.key == pygame.K_UP:
            player_y_change = -2
        if event.key == pygame.K_DOWN:
            player_y_change = 2

    if event.type == pygame.KEYUP:
        if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT
            player_x_change = 0
        if event.type == pygame.KEYUP:
            player_y_change = 0
</code>```

Is it a way to change this to a while function or something so the character doesn't stop moving when release a arrow-key (even though another arrow-key is held down)?

答:
the issue is the condition in event.type == pygame.KEYUP.

```<code>if event.type == pygame.KEYUP:
   # [...]

   if event.type == pygame.KEYUP:
        player_y_change = 0
</code>```

Just reset either player_x_change or player_y_change, dependent on the key that is released:

if game_over_state == False:
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_ESCAPE:
            pause = True
            game_paused()
        if event.key == pygame.K_LEFT:
            player_x_change = -2
        if event.key == pygame.K_RIGHT:
            player_x_change = 2
        if event.key == pygame.K_UP:
            player_y_change = -2
        if event.key == pygame.K_DOWN:
            player_y_change = 2

    if event.type == pygame.KEYUP:
        if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT
            player_x_change = 0
        if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
            player_y_change = 0
```

<hr>

<p>If you want to handle the keys simultaneously, that means you want to move the player diagonal when 2 keys are pressed and you don't want to that the player stops, when 1 key is released, then I recommend to use <code>pygame.key.get_pressed()</code> rather than the <code>KEYDOWN</code> event:</p>

<pre class="lang-py prettyprint-override"><code>for event in  in pygame.event.get():
    if game_over_state == False:
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                pause = True
                game_paused()

if game_over_state == False:

    keys = pygame.key.get_pressed()

    player_x_change, player_y_change = 0, 0
    if keys[pygame.K_LEFT]:
        player_x_change -= 2
    if keys[pygame.K_RIGHT]:
        player_x_change += 2
    if keys[pygame.K_UP]:
        player_y_change -= 2
    if keys[pygame.K_DOWN]:
        player_y_change += 2
</code>```

Body:
in my game i have set my character to move. How it is set is:

if game_over_state == False:
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_ESCAPE:
            pause = True
            game_paused()
        if event.key == pygame.K_LEFT:
            player_x_change = -2
        if event.key == pygame.K_RIGHT:
            player_x_change = 2
        if event.key == pygame.K_UP:
            player_y_change = -2
        if event.key == pygame.K_DOWN:
            player_y_change = 2

    if event.type == pygame.KEYUP:
        if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT
            player_x_change = 0
        if event.type == pygame.KEYUP:
            player_y_change = 0

Is it a way to change this to a while function or something so the character doesn't stop moving when release a arrow-key (even though another arrow-key is held down)?

Body:
the issue is the condition in event.type == pygame.KEYUP.

if event.type == pygame.KEYUP:
   # [...]

   if event.type == pygame.KEYUP:
        player_y_change = 0

Just reset either player_x_change or player_y_change, dependent on the key that is released:

if game_over_state == False:
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_ESCAPE:
            pause = True
            game_paused()
        if event.key == pygame.K_LEFT:
            player_x_change = -2
        if event.key == pygame.K_RIGHT:
            player_x_change = 2
        if event.key == pygame.K_UP:
            player_y_change = -2
        if event.key == pygame.K_DOWN:
            player_y_change = 2

    if event.type == pygame.KEYUP:
        if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT
            player_x_change = 0
        if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
            player_y_change = 0

If you want to handle the keys simultaneously, that means you want to move the player diagonal when 2 keys are pressed and you don't want to that the player stops, when 1 key is released, then I recommend to use pygame.key.get_pressed() rather than the KEYDOWN event:

for event in  in pygame.event.get():
    if game_over_state == False:
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                pause = True
                game_paused()

if game_over_state == False:

    keys = pygame.key.get_pressed()

    player_x_change, player_y_change = 0, 0
    if keys[pygame.K_LEFT]:
        player_x_change -= 2
    if keys[pygame.K_RIGHT]:
        player_x_change += 2
    if keys[pygame.K_UP]:
        player_y_change -= 2
    if keys[pygame.K_DOWN]:
        player_y_change += 2


来源: stackexchange

问:
How to render elements in react
I have this function which fetches a set of characters and images.

```<code>   const displayCharacters =  async () => {
        if(filteredCharacters !== 'default'){
          const a = filteredCharacters.map(e => e.name);

          const options = {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ 'data' : a })
          };

          const b = await fetch("/image",options)
          return b.json();

        }else{
          return [];
        }
      }
</code>```

The html looks like this :

```<code>  return (
    <div className="App">
      <form>
        <select name="movie" onChange ={handleMovieChange} value={selectedMovie}>
          <option value ="default">Please select a movie</option>
          {movieOptions()}
        </select>

        <select name="species" onChange={handleSpeciesChange} value={selectedSpecies}>
          <option value="default">Please select a species</option>
          {selectedMovie !== 'default' ? speciesOptions() : ''}
        </select>

        <select name="planets" onChange={handlePlanetChange} value={selectedPlanets}>
          <option value="default">Please select a planet</option>
          {selectedSpecies !== 'default' ? planetOptions() : ''}
        </select>
      </form>

      {displayCharacters().then(data=> data.map(char => (<div>{char.name}</div>)))}
    </div>

  );
}
</code>```

But i get an error :

Error: Objects are not valid as a React child (found: [object
  Promise]). If you meant to render a collection of children, use an
  array instead.

答:
What's happening is that React will not resolve a promise in the render. Initially your data fetching function will return a promise object rather than data, which React will not be able to render.

You'll need to set up state to hold first the placeholder data until the promise is resolved, then the data after promise resolution. Check this question for a good solution.

Objects are not valid as a React child (found: [object Promise])

ContentLicense: CC BY-SA 4.0

Title: How to render elements in react

Body:
I have this function which fetches a set of characters and images.

   const displayCharacters =  async () => {
        if(filteredCharacters !== 'default'){
          const a = filteredCharacters.map(e => e.name);

          const options = {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ 'data' : a })
          };

          const b = await fetch("/image",options)
          return b.json();

        }else{
          return [];
        }
      }

The html looks like this :

  return (

      <form>
        <select name="movie" onChange ={handleMovieChange} value={selectedMovie}>
          <option value ="default">Please select a movie</option>
          {movieOptions()}
        </select>

        <select name="species" onChange={handleSpeciesChange} value={selectedSpecies}>
          <option value="default">Please select a species</option>
          {selectedMovie !== 'default' ? speciesOptions() : ''}
        </select>

        <select name="planets" onChange={handlePlanetChange} value={selectedPlanets}>
          <option value="default">Please select a planet</option>
          {selectedSpecies !== 'default' ? planetOptions() : ''}
        </select>
      </form>

      {displayCharacters().then(data=> data.map(char => (
{char.name}
)))}

  );
}

But i get an error :

Error: Objects are not valid as a React child (found: [object
  Promise]). If you meant to render a collection of children, use an
  array instead.


问:
Server response is printed on the browser but not returned to success function in ajax
I am not able to get the response to ajax success call back function. The response form the server is being directly printed on the browser

```<code><body>
    <script>
      $(document).ready(function() {
        $.ajax({
          url: $("#form").attr("action"),
          type: "POST",
          data: $("#form").serialize(),
          success: function(data) {
            alert(data);
          }
        });
      });
    </script>
    <form action="a.php" method="post" id="form">
      <input type="text" name="name" id="name" placeholder="name" />
      <input type="submit" value="submit" />
    </form>
  </body>
</code>```

my php code

```<code><?php
    echo 'hii';
?>
</code>```

答:
Can you Replace AJAX script below mentioned.</p>

```<code><form method="post" id="form">
  <input type="text" name="name" id="name" placeholder="name" />
  <input type="submit" value="submit" />
</form>

 $("#form").submit(function(e) {

    e.preventDefault(); // avoid to execute the actual submit of the form.

    var form = $(this);
    var url = form.attr('action');

    $.ajax({
           type: "POST",
           url: 'a.php',
           data: form.serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // show response from the php script.
           }
         });
});
</code>```

Body:
I am not able to get the response to ajax success call back function. The response form the server is being directly printed on the browser

    <form action="a.php" method="post" id="form">
      <input type="text" name="name" id="name" placeholder="name" />
      <input type="submit" value="submit" />
    </form>

my php code

<?php
    echo 'hii';
?>

Body:
Can you Replace AJAX script below mentioned.

<form method="post" id="form">
  <input type="text" name="name" id="name" placeholder="name" />
  <input type="submit" value="submit" />
</form>

 $("#form").submit(function(e) {

    e.preventDefault(); // avoid to execute the actual submit of the form.

    var form = $(this);
    var url = form.attr('action');

    $.ajax({
           type: "POST",
           url: 'a.php',
           data: form.serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // show response from the php script.
           }
         });
});


问:
Joining records of a Python dictionary (read from JSON) depending on key values and adjust the values of the remaining keys
I produce a JSON file out of a web service I have no control of, and the result is approximately like this:

```<code>{
      "steps": [
        {
          "start_station": "TOYOCHO",
          "end_station": "NIHOMBASHI",
          "start_time": 1598317440.0,
          "end_time": 1598317920.0,
          "duration": 8,
          "train_name": "Tokyo Metro Tozai Line Rapid\u00a0for\u00a0NAKANO",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        },
        {
          "start_station": "NIHOMBASHI",
          "end_station": "OSHIAGE",
          "start_time": 1598318340.0,
          "end_time": 1598319000.0,
          "duration": 11,
          "train_name": "Toei Subway Asakusa Line\u00a0for\u00a0NARITA AIRPORT TERMINAL 1",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        },
        {
          "start_station": "OSHIAGE",
          "end_station": "AOTO",
          "start_time": 1598319120.0,
          "end_time": 1598319420.0,
          "duration": 5,
          "train_name": "Line name change, train goes through",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        },
        {
          "start_station": "AOTO",
          "end_station": "KEISEI-TAKASAGO",
          "start_time": 1598319480.0,
          "end_time": 1598319600.0,
          "duration": 2,
          "train_name": "Line name change, train goes through",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        },
        {
          "start_station": "KEISEI-TAKASAGO",
          "end_station": "SHIBAMATA",
          "start_time": 1598320080.0,
          "end_time": 1598320260.0,
          "duration": 3,
          "train_name": "Keisei Kanamachi Line\u00a0for\u00a0KEISEI-KANAMACHI",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        }
</code>```

Now, I'm reading this as a dictionary with simplejson and I need to remove all the steps where train_name is "Line name change, train goes through", but I need to take into account the fact that they exist.

In other words:

No "train goes through" records should be removed from the final result;

The first record after "train goes through", shoud have the "start_station" field changed to the previous "end_station" of the preceding non-"train goes through" record.

The "end_station" before a "train goes through" entry should be put as the "start_station" of the first following non-"train goes through" entry.

Do the same for "start_time", "end_time"

IOW, if I output the modified JSON, this is what I should expect:

```<code>{
      "steps": [
        {
          "start_station": "TOYOCHO",
          "end_station": "NIHOMBASHI",
          "start_time": 1598317440.0,
          "end_time": 1598317920.0,
          "duration": 8,
          "train_name": "Tokyo Metro Tozai Line Rapid\u00a0for\u00a0NAKANO",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        },
        {
          "start_station": "NIHOMBASHI",
          "end_station": "KEISEI-TAKASAGO",
          "start_time": 1598318340.0,
          "end_time": 1598319600.0,
          "duration": 11, # Will get recalculated
          "train_name": "Toei Subway Asakusa Line\u00a0for\u00a0NARITA AIRPORT TERMINAL 1",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null,
        }
        {
          "start_station": "KEISEI-TAKASAGO",
          "end_station": "SHIBAMATA",
          "start_time": 1598320080.0,
          "end_time": 1598320260.0,
          "duration": 3,
          "train_name": "Keisei Kanamachi Line\u00a0for\u00a0KEISEI-KANAMACHI",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        }
</code>```

The number of "goes through" can be anything, so I can't expect a specific length.

Currently I'm iterating record by record as I need to do some processing:

```<code>import simplejson as json

with open("results.json", "r") as handle:
    data = json.load(handle)

for step in data["steps"]:
    # Process stuff

</code>```

Hence why I'm stuck, because I got lost trying to keep track of the previous "non go through" record.

Is there a non-hacky solution? Note that I also avoid iterating over the dictionary if need be. What I can't do is changing the data (I can add a field to the JSON saying it's a "go through", but no more than that).

Also apologies for the perhaps poorly-worded title, but it's hard to describe in a few words what I mean.

答:
Here's my take on what you're looking for:

How do I process this data?

Considering you're making a web request, I'm thinking the results might be massive and even paginated. My advice to you is to work off figuring out #1 and then work on #2.

For #1, one way to approach this is:

```<code># Process data loop
# I will call the "line name change" the "LNC".
new_steps = []

for step in steps:
    start_station = None
    end_station = None
    last_step = None # represents the last step that is
    if is_lnc(step):
        pass # do nothing. that means we don't include it into new_steps
    else:
        if not start_station:
            start_station = step['start_station']
        else:
            step['start_station'] = start_station
            last_step['end_station'] = step['end_station'] # What about appending this? Well, it's referring to what you've already appended so the data is shared.
        new_steps.append(step)
        last_step = step
</code>```

This code isn't perfect, has missing variables/functions, and might be incorrect. But it might help you get started.

Body:
I produce a JSON file out of a web service I have no control of, and the result is approximately like this:

{
      "steps": [
        {
          "start_station": "TOYOCHO",
          "end_station": "NIHOMBASHI",
          "start_time": 1598317440.0,
          "end_time": 1598317920.0,
          "duration": 8,
          "train_name": "Tokyo Metro Tozai Line Rapid\u00a0for\u00a0NAKANO",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        },
        {
          "start_station": "NIHOMBASHI",
          "end_station": "OSHIAGE",
          "start_time": 1598318340.0,
          "end_time": 1598319000.0,
          "duration": 11,
          "train_name": "Toei Subway Asakusa Line\u00a0for\u00a0NARITA AIRPORT TERMINAL 1",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        },
        {
          "start_station": "OSHIAGE",
          "end_station": "AOTO",
          "start_time": 1598319120.0,
          "end_time": 1598319420.0,
          "duration": 5,
          "train_name": "Line name change, train goes through",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        },
        {
          "start_station": "AOTO",
          "end_station": "KEISEI-TAKASAGO",
          "start_time": 1598319480.0,
          "end_time": 1598319600.0,
          "duration": 2,
          "train_name": "Line name change, train goes through",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        },
        {
          "start_station": "KEISEI-TAKASAGO",
          "end_station": "SHIBAMATA",
          "start_time": 1598320080.0,
          "end_time": 1598320260.0,
          "duration": 3,
          "train_name": "Keisei Kanamachi Line\u00a0for\u00a0KEISEI-KANAMACHI",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        }

Now, I'm reading this as a dictionary with simplejson and I need to remove all the steps where train_name is "Line name change, train goes through", but I need to take into account the fact that they exist.

In other words:

No "train goes through" records should be removed from the final result;

The first record after "train goes through", shoud have the "start_station" field changed to the previous "end_station" of the preceding non-"train goes through" record.

The "end_station" before a "train goes through" entry should be put as the "start_station" of the first following non-"train goes through" entry.

Do the same for "start_time", "end_time"

IOW, if I output the modified JSON, this is what I should expect:

{
      "steps": [
        {
          "start_station": "TOYOCHO",
          "end_station": "NIHOMBASHI",
          "start_time": 1598317440.0,
          "end_time": 1598317920.0,
          "duration": 8,
          "train_name": "Tokyo Metro Tozai Line Rapid\u00a0for\u00a0NAKANO",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        },
        {
          "start_station": "NIHOMBASHI",
          "end_station": "KEISEI-TAKASAGO",
          "start_time": 1598318340.0,
          "end_time": 1598319600.0,
          "duration": 11, # Will get recalculated
          "train_name": "Toei Subway Asakusa Line\u00a0for\u00a0NARITA AIRPORT TERMINAL 1",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null,
        }
        {
          "start_station": "KEISEI-TAKASAGO",
          "end_station": "SHIBAMATA",
          "start_time": 1598320080.0,
          "end_time": 1598320260.0,
          "duration": 3,
          "train_name": "Keisei Kanamachi Line\u00a0for\u00a0KEISEI-KANAMACHI",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        }

The number of "goes through" can be anything, so I can't expect a specific length.

Currently I'm iterating record by record as I need to do some processing:

import simplejson as json

with open("results.json", "r") as handle:
    data = json.load(handle)

for step in data["steps"]:
    # Process stuff

Hence why I'm stuck, because I got lost trying to keep track of the previous "non go through" record.

Is there a non-hacky solution? Note that I also avoid iterating over the dictionary if need be. What I can't do is changing the data (I can add a field to the JSON saying it's a "go through", but no more than that).

Also apologies for the perhaps poorly-worded title, but it's hard to describe in a few words what I mean.

Body:
Here's my take on what you're looking for:

How do I process this data?

Considering you're making a web request, I'm thinking the results might be massive and even paginated. My advice to you is to work off figuring out #1 and then work on #2.

For #1, one way to approach this is:

# Process data loop
# I will call the "line name change" the "LNC".
new_steps = []

for step in steps:
    start_station = None
    end_station = None
    last_step = None # represents the last step that is
    if is_lnc(step):
        pass # do nothing. that means we don't include it into new_steps
    else:
        if not start_station:
            start_station = step['start_station']
        else:
            step['start_station'] = start_station
            last_step['end_station'] = step['end_station'] # What about appending this? Well, it's referring to what you've already appended so the data is shared.
        new_steps.append(step)
        last_step = step

This code isn't perfect, has missing variables/functions, and might be incorrect. But it might help you get started.


问:
Get a list of maximum values per tuple from a list of tuples
I'm just getting into Python, and having some trouble understanding the control flow and iteration logic.

I am trying to create a function which takes a list of tuples, and I want to return a new list with the maximum element per tuple.

I know I'm missing putting the maximum element into a new list, but first I am trying to get that maximum value.

```<code>def max_element_per_tuple(tuple_list):
    maximum = tuple_list[0]

    for item in tuple_list:
        if item > maximum:
            maximum = item

    return maximum

# test it
tuple_list = [(-1,0,1), (10,20,30), (100,50,25), (55,75,65)]
print(max_element_per_tuple(tuple_list))
</code>```

This returns: (100, 50, 25)

Want returned: (1, 30, 100, 75)

Or if a list (?), then: [1, 30, 100, 75]

答:
The issue: max_element_per_tuple(tuple_list) returns the wrong result because it is looking for the max tuple, not the max value in each tuple.

```<code>def max_element_per_tuple(tuple_list):
    maximum = tuple_list[0]  # maximum is = (-1,0,1)

    for item in tuple_list:
        if item > maximum:  # compares the tuples e.g (-1,0,1) == (10,20,30)
            maximum = item

    return maximum  # at the end you have (100,50,25). it's the max tuple
</code>```

Try any of below options:

```<code>tuple_list = [(-1,0,1), (10,20,30), (100,50,25), (55,75,65)]

# Get the max from each tuple using List comprehension
max_items_list  = [max(tuple_item) for tuple_item in tuple_list]   # in a list
max_items_tuple = tuple(max(tuple_item) for tuple_item in tuple_list)   # in a tuple
print(max_items_list)
print(max_items_tuple)

# Get the max from each tuple using For Loop
# Can be used with List only, tuples are immutable

for_max_items_list = list()

for tuple_item in tuple_list:
  max_value = max(tuple_item)  # get the max of each tuple e.g Max((-1,0,1)) = 1
  for_max_items_list.append(max_value)  # add the max to list
print(for_max_items_list)
</code>```

Body:
I'm just getting into Python, and having some trouble understanding the control flow and iteration logic.

I am trying to create a function which takes a list of tuples, and I want to return a new list with the maximum element per tuple.

I know I'm missing putting the maximum element into a new list, but first I am trying to get that maximum value.

def max_element_per_tuple(tuple_list):
    maximum = tuple_list[0]

    for item in tuple_list:
        if item > maximum:
            maximum = item

    return maximum

# test it
tuple_list = [(-1,0,1), (10,20,30), (100,50,25), (55,75,65)]
print(max_element_per_tuple(tuple_list))

This returns: (100, 50, 25)

Want returned: (1, 30, 100, 75)

Or if a list (?), then: [1, 30, 100, 75]

Body:
The issue: max_element_per_tuple(tuple_list) returns the wrong result because it is looking for the max tuple, not the max value in each tuple.

def max_element_per_tuple(tuple_list):
    maximum = tuple_list[0]  # maximum is = (-1,0,1)

    for item in tuple_list:
        if item > maximum:  # compares the tuples e.g (-1,0,1) == (10,20,30)
            maximum = item

    return maximum  # at the end you have (100,50,25). it's the max tuple

Try any of below options:

tuple_list = [(-1,0,1), (10,20,30), (100,50,25), (55,75,65)]

# Get the max from each tuple using List comprehension
max_items_list  = [max(tuple_item) for tuple_item in tuple_list]   # in a list
max_items_tuple = tuple(max(tuple_item) for tuple_item in tuple_list)   # in a tuple
print(max_items_list)
print(max_items_tuple)

# Get the max from each tuple using For Loop
# Can be used with List only, tuples are immutable

for_max_items_list = list()

for tuple_item in tuple_list:
  max_value = max(tuple_item)  # get the max of each tuple e.g Max((-1,0,1)) = 1
  for_max_items_list.append(max_value)  # add the max to list
print(for_max_items_list)


问:
React set className by conditions dynamic
I have a map function which should dynamic show classNames.
In this function i want to set the className dynamic.
I tried to set the className also without the

$

But dosen't also not work

```<code>this.state.antwort.map((item,key) =>
  <Col md={2} key={key} className={' ${item.gender == "Female" ? karteFemale : karteMann}' } >

...

)    }
</code>```

But i got the error, that the classNames are undefined.
So how can i set the classes flexible ?

答:
```<code>className={item.gender === 'Female' ? karteFemale : karteMann}
</code>```

Body:
I have a map function which should dynamic show classNames.
In this function i want to set the className dynamic.
I tried to set the className also without the

$

But dosen't also not work

this.state.antwort.map((item,key) =>
  <Col md={2} key={key} className={' ${item.gender == "Female" ? karteFemale : karteMann}' } >

...

)    }

But i got the error, that the classNames are undefined.
So how can i set the classes flexible ?


问:
How can I check if hidden files exist?
Adobe has the option to download fonts, which is a problem for us in our industry. I found the location for those files and now I want to create a Jamf Smart group to check if fonts have been downloaded.

The file location is /Users/$loggedInUser/Library/Application\ Support/Adobe/CoreSync/plugins/livetype/.r/.

The File names are a combination of numbers. Example: .33805.otf.

So far I have the below but it's not working. I keep getting a False output.

```<code>USERS="`ls /Users | grep -v "Shared"`"

for Adobe in $USERS; do
    if  [[ -a "/Users/$Adobe/Library/Application\ Support/Adobe/CoreSync/plugins/livetype/.r/.[^.]*otf"  ]]  ; then
              echo "True"
    else
              echo "False"
    fi
done
</code>```

答:
You really want to avoid ls here. A more robust and portable solution is to simply loop over the matches.

Out of the box, the shell does not include dot files in general glob results; but if you include a dot as part of the wildcard, it will expand it normally.

You can't use double quotes around a wildcard, though; doing that will change the meaning of * from a wildcard character into a literal asterisk (and similarly for other wildcard characters like ?, [, etc).

for user in /Users/*; do
    case $user in *Shared*) continue;; esac
    for file in "$user/Library/Application Support/Adobe/CoreSync/plugins/livetype/.r/".[!.]*otf; do
        if [[ -a "$file" ]]; then
              echo "True"
        else
              echo "False"
        fi
        break
    done
done
```

The double for loop isn't exactly intuitive, but that's a good way to robustly check if a wildcard matched any files. Start a loop, but only execute the first iteration; if the first file doesn't exist, it means that the shell could not expand the wildcard, and returned it verbatim. (This is the default and legacy Bourne shell behavior; modern shells have nullglob etc which some admins like to enable for all new users.)

Title: How can I check if hidden files exist?

Body:
Adobe has the option to download fonts, which is a problem for us in our industry. I found the location for those files and now I want to create a Jamf Smart group to check if fonts have been downloaded.

The file location is /Users/$loggedInUser/Library/Application\ Support/Adobe/CoreSync/plugins/livetype/.r/.

The File names are a combination of numbers. Example: .33805.otf.

So far I have the below but it's not working. I keep getting a False output.

USERS="`ls /Users | grep -v "Shared"`"

for Adobe in $USERS; do
    if  [[ -a "/Users/$Adobe/Library/Application\ Support/Adobe/CoreSync/plugins/livetype/.r/.[^.]*otf"  ]]  ; then
              echo "True"
    else
              echo "False"
    fi
done

Body:
You really want to avoid ls here. A more robust and portable solution is to simply loop over the matches.

Out of the box, the shell does not include dot files in general glob results; but if you include a dot as part of the wildcard, it will expand it normally.

You can't use double quotes around a wildcard, though; doing that will change the meaning of * from a wildcard character into a literal asterisk (and similarly for other wildcard characters like ?, [, etc).

for user in /Users/*; do
    case $user in *Shared*) continue;; esac
    for file in "$user/Library/Application Support/Adobe/CoreSync/plugins/livetype/.r/".[!.]*otf; do
        if [[ -a "$file" ]]; then
              echo "True"
        else
              echo "False"
        fi
        break
    done
done

The double for loop isn't exactly intuitive, but that's a good way to robustly check if a wildcard matched any files. Start a loop, but only execute the first iteration; if the first file doesn't exist, it means that the shell could not expand the wildcard, and returned it verbatim. (This is the default and legacy Bourne shell behavior; modern shells have nullglob etc which some admins like to enable for all new users.)


问:
jquery ui autocomplete layout / css
I have a css problem with jquery / jquery ui / auto complete

```<code><script type="text/javascript">
  $(function() {
  $("#search").autocomplete({
    source: "autocomplete.php",
    minLength: 2,
    select: function(event, ui) {
      window.location.href = "http://site.com/" + ui.item.id + ".html";
      $("#search").val(ui.item.label);
    }
    })

    .data("autocomplete")._renderItem = function (ul, item) {
       return $('<li class="ui-menu-item-with-icon"></li>')
        .data("item.autocomplete", item)
        .append('<a style="height: 50px;" class="ui-corner-all"><img src="thumb.php?img=' + item.img + '" class="ajaxsearchimage">' + item.label + '</a>')
        .appendTo(ul);
    };
    });
    </script>
    <style>
    span.searchicon
    {
      display: inline-block;
      height: 50px;
      width: 50px;
    }

    .ajaxsearchtext
    {
      padding-left: 60px;
      display: inline-block;
    }
    </style>
</code>```

I would like to align the text on the top
I tryed to put vertical-align:top in the class but it doesn' work.

http://imageshack.us/photo/my-images/4/sansrer.png/

Does someone has a solution ?

Regards

答:
you need to apply the property to the image

```<code>img {vertical-align:text-top;}
</code>```

an example
http://www.w3schools.com/css/tryit.asp?filename=trycss_vertical-align

UPDATE

upon comments I suggest floating the image to the left would be the solution.

```<code>img.SelectedClass { float: left; }
</code>```

ContentLicense: CC BY-SA 3.0

Title: jquery ui autocomplete layout / css

Body:
I have a css problem with jquery / jquery ui / auto complete

I would like to align the text on the top
I tryed to put vertical-align:top in the class but it doesn' work.

http://imageshack.us/photo/my-images/4/sansrer.png/

Does someone has a solution ?

Regards

Body:
you need to apply the property to the image

img {vertical-align:text-top;}

an example
http://www.w3schools.com/css/tryit.asp?filename=trycss_vertical-align

UPDATE

upon comments I suggest floating the image to the left would be the solution.

img.SelectedClass { float: left; }


问:
OrderBy date pipe in Angular?
I have pipe that sorts by array by date property.

Problem is that not each elements has property date in args.key. So there rows should be in bottom of list.

```<code>import {
  Pipe,
  PipeTransform
} from "@angular/core";

@Pipe({
  name: 'sort'
})
export class ArraySortPipe implements PipeTransform {
  transform(records: Array < any > , args ? : {
    key: string,
    direction: boolean,
    type: "int" | "string" | "date"
  }): any {
    return records.sort(function (a: any, b: any) {
      if (args.type === 'date' && args.direction) {
        return new Date(a[args.key]).getTime() - new Date(b[args.key]).getTime();
      }
    });
  };
}
</code>```

How to move properties without date to the bottom of list?

答:
You could ad another return values for the sorting function: if a doesn't have date, return -1. If b doesn't have date, return 1.

Like:

```<code>  transform(records: Array < any > , args ? : {
    key: string,
    direction: boolean,
    type: "int" | "string" | "date"
  }): any {
    return records.sort(function (a: any, b: any) {
      if (args.type === 'date' && args.direction) {
          if(!a[args.key]) {
              return -1;
          }

          if(!b[args.key]) {
              return 1;
          }

          return new Date(a[args.key]).getTime() - new Date(b[args.key]).getTime();
      }
    });
  };
</code>```

(Direction not implemented).

Title: OrderBy date pipe in Angular?

Body:
I have pipe that sorts by array by date property.

Problem is that not each elements has property date in args.key. So there rows should be in bottom of list.

import {
  Pipe,
  PipeTransform
} from "@angular/core";

@Pipe({
  name: 'sort'
})
export class ArraySortPipe implements PipeTransform {
  transform(records: Array < any > , args ? : {
    key: string,
    direction: boolean,
    type: "int" | "string" | "date"
  }): any {
    return records.sort(function (a: any, b: any) {
      if (args.type === 'date' && args.direction) {
        return new Date(a[args.key]).getTime() - new Date(b[args.key]).getTime();
      }
    });
  };
}

How to move properties without date to the bottom of list?

Body:
You could ad another return values for the sorting function: if a doesn't have date, return -1. If b doesn't have date, return 1.

Like:

  transform(records: Array < any > , args ? : {
    key: string,
    direction: boolean,
    type: "int" | "string" | "date"
  }): any {
    return records.sort(function (a: any, b: any) {
      if (args.type === 'date' && args.direction) {
          if(!a[args.key]) {
              return -1;
          }

          if(!b[args.key]) {
              return 1;
          }

          return new Date(a[args.key]).getTime() - new Date(b[args.key]).getTime();
      }
    });
  };

(Direction not implemented).


问:
Proper ways to set the path of my app in Python
I have a question in how to properly create a path in Python (Python 3.x).

I developed a small scraping app in Python with the following directory structure.

root
├── Dockerfile
├── README.md
├── tox.ini
├── src
│   └── myapp
│       ├── __init__.py
│       ├── do_something.py
│       └── do_something_else.py
└── tests
    ├── __init__.py
    ├──  test_do_something.py
    └──  test_do_something_else.py
```

<p>When I want to run my code, I can go to the src directory and do with
<code>python do_something.py</code>
But, because do_something.py has an import statement from do_something_else.py, it fails like:</p>

<pre class="lang-py prettyprint-override"><code>Traceback (most recent call last):
  File "src/myapp/do_something.py", line 1, in <module>
    from src.myapp.do_something_else import do_it
ModuleNotFoundError: No module named 'src'
</code>```

So, I eventually decided to use the following command to specify the python path:
PYTHONPATH=../../ python do_something.py
to make sure that the path is seen.

But, what are the better ways to feed the path so that my app can run?
I want to know this because when I run pytest via tox, the directory that I would run the command tox would be at the root so that tox.ini is seen by tox package. If I do that, then I most likely run into a similar problem due to the Python path not properly set.

Questions I want to ask specifically are:

where should I run my main code when creating my own project like this? root as like python src/myapp/do_something.py? Or, go to the src/myapp directory and run like python do_something.py?

once, the directory where I should execute my program is determined, what is the correct way to import modules from other py file? Is it ok to use from src.myapp.do_something_else import do_it (this means I must add path from src directory)? Or, different way to import?

What are ways I can have my Python recognize the path? I am aware there are several ways to make the pass accessible as below:

a. write export PYTHONPATH=<path_of_my_choice>:$PYTHONPATH to make the
path accessible temporarily, or write that line in my .bashrc to make it permanent (but it's hard to reproduce when I want to automate creating Python environment via ansible or other automation tools)

b. write import sys; sys.path.append(<root>) to have the root as an accessible path

c. use pytest-pythonpath package (but this is not really a generic answer)

Thank you so much for your inputs!

my environment

OS: MacOS and Amazon Linux 2
Python Version: 3.7
Dependency in Python: pytest, tox
```

答:
I would suggest to use setup.py to make this a python package. Then you can install it in development mode python setup.py develop. This way it will be available in your python environment w/o needing to specify the PYTHONPATH.

For testing, you can simply install the package python setup.py install.

Hope that helps.

Body:
I have a question in how to properly create a path in Python (Python 3.x).

I developed a small scraping app in Python with the following directory structure.

root
├── Dockerfile
├── README.md
├── tox.ini
├── src
│   └── myapp
│       ├── __init__.py
│       ├── do_something.py
│       └── do_something_else.py
└── tests
    ├── __init__.py
    ├──  test_do_something.py
    └──  test_do_something_else.py

When I want to run my code, I can go to the src directory and do with
python do_something.py
But, because do_something.py has an import statement from do_something_else.py, it fails like:

Traceback (most recent call last):
  File "src/myapp/do_something.py", line 1, in <module>
    from src.myapp.do_something_else import do_it
ModuleNotFoundError: No module named 'src'

So, I eventually decided to use the following command to specify the python path:
PYTHONPATH=../../ python do_something.py
to make sure that the path is seen.

But, what are the better ways to feed the path so that my app can run?
I want to know this because when I run pytest via tox, the directory that I would run the command tox would be at the root so that tox.ini is seen by tox package. If I do that, then I most likely run into a similar problem due to the Python path not properly set.

Questions I want to ask specifically are:

where should I run my main code when creating my own project like this? root as like python src/myapp/do_something.py? Or, go to the src/myapp directory and run like python do_something.py?

once, the directory where I should execute my program is determined, what is the correct way to import modules from other py file? Is it ok to use from src.myapp.do_something_else import do_it (this means I must add path from src directory)? Or, different way to import?

What are ways I can have my Python recognize the path? I am aware there are several ways to make the pass accessible as below:

a. write export PYTHONPATH=<path_of_my_choice>:$PYTHONPATH to make the
path accessible temporarily, or write that line in my .bashrc to make it permanent (but it's hard to reproduce when I want to automate creating Python environment via ansible or other automation tools)

b. write import sys; sys.path.append(<root>) to have the root as an accessible path

c. use pytest-pythonpath package (but this is not really a generic answer)

Thank you so much for your inputs!

my environment

OS: MacOS and Amazon Linux 2
Python Version: 3.7
Dependency in Python: pytest, tox


问:
Replacing NULL with empty string in jQuery each()?
The parameter fights below is the result from an Ajax call. Some of the data has NULL values. What's a simple way of replacing those values with an empty string?

```<code>    function createFightsTable(fights) {

        $.each(fights, function() {

            $("#professional_fights_table tbody").append("<tr><td class='text-center'>" + this.result  + "</td><td>" + this.record  + "</td><td>" + this.opponent  + "</td><td>" + this.method  + "</td><td>" + this.date  + "</td><td class='text-center'>" + this.round  + "</td><td>" + this.time  + "</td></tr>");
        });
    }
</code>```

答:
It depends on whether it's "NULL" (a string, perhaps coming from a database result set where NULL was converted to a string) or null (the actual null value in JavaScript).

If it's "NULL", you probably want a utility function:

```<code>function blankForNull(s) {
    return s.toUpperCase() === "NULL" ? "" : s;
}
</code>```

Then:

```<code>$("#professional_fights_table tbody").append("<tr><td class='text-center'>" + blankForNull(this.result)  + // ...
</code>```

If it's null, you can use the curiously-powerful || operator or the newer (ES2020) "null coalescing" operator ??:

```<code>$("#professional_fights_table tbody").append("<tr><td class='text-center'>" + (this.result || "")  + // ...
</code>```

or

```<code>$("#professional_fights_table tbody").append("<tr><td class='text-center'>" + (this.result ?? "")  + // ...
</code>```

(You do need the () around it in that concatenation expression.)

Body:
The parameter fights below is the result from an Ajax call. Some of the data has NULL values. What's a simple way of replacing those values with an empty string?

    function createFightsTable(fights) {

        $.each(fights, function() {

            $("#professional_fights_table tbody").append("
" + this.result  + "	" + this.record  + "	" + this.opponent  + "	" + this.method  + "	" + this.date  + "	" + this.round  + "	" + this.time  + "
");
        });
    }

Body:
It depends on whether it's "NULL" (a string, perhaps coming from a database result set where NULL was converted to a string) or null (the actual null value in JavaScript).

If it's "NULL", you probably want a utility function:

function blankForNull(s) {
    return s.toUpperCase() === "NULL" ? "" : s;
}

Then:

$("#professional_fights_table tbody").append("<tr><td class='text-center'>" + blankForNull(this.result)  + // ...

If it's null, you can use the curiously-powerful || operator or the newer (ES2020) "null coalescing" operator ??:

$("#professional_fights_table tbody").append("<tr><td class='text-center'>" + (this.result || "")  + // ...

or

$("#professional_fights_table tbody").append("<tr><td class='text-center'>" + (this.result ?? "")  + // ...

(You do need the () around it in that concatenation expression.)


问:
Data expansion R/Python
I have a large csv file recorded as below,

```<code>name         year         value
brand1       2000         45,000
brand2       2000         42,000
brand3       2000         46,000

brand1       2001         41,600
brand2       2001         49,000
brand4       2001         47,000

brand1       2002         39,000
brand5       2002         40,500
brand3       2002         42,800
</code>```

I would like to turn my large csv as below, such that all unique names that span all the years recorded are captured and their value equated to zero where the names miss in a specific year of recording. See this,

```<code>name       year      value
brand1       2000         45,000
brand2       2000         42,000
brand3       2000         46,000
brand4       2000         0000
brand5       2000         0000

brand1       2001         41,600
brand2       2001         49,000
brand4       2001         47,000
brand3       2001         0000
brand5       2001         0000

brand1       2002         39,000
brand5       2002         40,500
brand3       2002         42,800
brand2       2002         0000
brand4       2000         0000
</code>```

Thoughts?

答:
Here is one solution in R.</p>

```<code>library(tidyverse)

df <- data.frame(name = c("brand1", "brand2", "brand4", "brand5", "brand1"),
                 year = c(2000, 2000, 2000, 2001, 2001),
                 value = c(53, 32, 242, 43, 23))

df1 <- df %>% complete(year, name, fill = list(value = 0))
</code>```

Title: Data expansion R/Python

Body:
I have a large csv file recorded as below,

name         year         value
brand1       2000         45,000
brand2       2000         42,000
brand3       2000         46,000

brand1       2001         41,600
brand2       2001         49,000
brand4       2001         47,000

brand1       2002         39,000
brand5       2002         40,500
brand3       2002         42,800

I would like to turn my large csv as below, such that all unique names that span all the years recorded are captured and their value equated to zero where the names miss in a specific year of recording. See this,

name       year      value
brand1       2000         45,000
brand2       2000         42,000
brand3       2000         46,000
brand4       2000         0000
brand5       2000         0000

brand1       2001         41,600
brand2       2001         49,000
brand4       2001         47,000
brand3       2001         0000
brand5       2001         0000

brand1       2002         39,000
brand5       2002         40,500
brand3       2002         42,800
brand2       2002         0000
brand4       2000         0000

Thoughts?

Body:
Here is one solution in R.

library(tidyverse)

df <- data.frame(name = c("brand1", "brand2", "brand4", "brand5", "brand1"),
                 year = c(2000, 2000, 2000, 2001, 2001),
                 value = c(53, 32, 242, 43, 23))

df1 <- df %>% complete(year, name, fill = list(value = 0))


问:
How to scroll to newly inserted row only when already scrolled to bottom of the table?
I'm building an app where rows containing messages are inserted at the end of a table

```<code>messages.append(message)
let indexPath:IndexPath = IndexPath(row:(messages.count - 1), section:0)
tableView.insertRows(at: [indexPath], with: .none)
</code>```

I then scroll to the bottom of the table

```<code>DispatchQueue.main.async {
    let indexPath = IndexPath(
        row: self.numberOfRows(inSection:  self.numberOfSections - 1) - 1,
        section: self.numberOfSections - 1)
    self.scrollToRow(at: indexPath, at: .bottom, animated: true)
}
</code>```

Like other messaging apps, I would like to modify this so that the autoscrolling only happens if you're already scrolled at the end of the table instead of every time a new message gets inserted.

I've tried several techniques like detecting if the last cell is full visible https://stackoverflow.com/a/9843146/784637, or detecting when scrolled to the bottom https://stackoverflow.com/a/39015301/784637.

However my issue is that because scrollToRow sets animated:true, if a new message comes in but the previous message which came a split second before is still being scrolled down to via scrollToRow, then the autoscrolling to newest message and subsequent messages doesn't occur - ex. the last cell won't be fully visible until the animation is complete, or detecting if you're scrolled to to the bottom will be false until the animation is complete.

Is there any way I can get around this without setting animated: false?

答:
What I would do is insert the row in a batch operation to make use of its completion handler, which serializes the UI update. Then I would check to see which rows are visible to the user and if the last couple of rows are, I think the user is close enough to the bottom of the conversation to force a down scroll.</p>

```<code>let lastRow = IndexPath(row: messages.count - 1, section: 0)

DispatchQueue.main.async {

    self.tableView.performBatchUpdates({
        self.tableView.insertRows(at: [lastRow], with: .bottom)
    }, completion: { (finished) in

        guard finished,
            let visiblePaths = self.tableView.indexPathsForVisibleRows else {
                return
        }

        if visiblePaths.contains([0, messages.count - 2]) || visiblePaths.contains([0, messages.count - 1]) { // last 2 rows are visible

            DispatchQueue.main.async {
                self.tableView.scrollToRow(at: lastRow, at: .bottom, animated: true)
            }

        }

    })

}
</code>```

Body:
I'm building an app where rows containing messages are inserted at the end of a table

messages.append(message)
let indexPath:IndexPath = IndexPath(row:(messages.count - 1), section:0)
tableView.insertRows(at: [indexPath], with: .none)

I then scroll to the bottom of the table

DispatchQueue.main.async {
    let indexPath = IndexPath(
        row: self.numberOfRows(inSection:  self.numberOfSections - 1) - 1,
        section: self.numberOfSections - 1)
    self.scrollToRow(at: indexPath, at: .bottom, animated: true)
}

Like other messaging apps, I would like to modify this so that the autoscrolling only happens if you're already scrolled at the end of the table instead of every time a new message gets inserted.

I've tried several techniques like detecting if the last cell is full visible https://stackoverflow.com/a/9843146/784637, or detecting when scrolled to the bottom https://stackoverflow.com/a/39015301/784637.

However my issue is that because scrollToRow sets animated:true, if a new message comes in but the previous message which came a split second before is still being scrolled down to via scrollToRow, then the autoscrolling to newest message and subsequent messages doesn't occur - ex. the last cell won't be fully visible until the animation is complete, or detecting if you're scrolled to to the bottom will be false until the animation is complete.

Is there any way I can get around this without setting animated: false?

Body:
What I would do is insert the row in a batch operation to make use of its completion handler, which serializes the UI update. Then I would check to see which rows are visible to the user and if the last couple of rows are, I think the user is close enough to the bottom of the conversation to force a down scroll.

let lastRow = IndexPath(row: messages.count - 1, section: 0)

DispatchQueue.main.async {

    self.tableView.performBatchUpdates({
        self.tableView.insertRows(at: [lastRow], with: .bottom)
    }, completion: { (finished) in

        guard finished,
            let visiblePaths = self.tableView.indexPathsForVisibleRows else {
                return
        }

        if visiblePaths.contains([0, messages.count - 2]) || visiblePaths.contains([0, messages.count - 1]) { // last 2 rows are visible

            DispatchQueue.main.async {
                self.tableView.scrollToRow(at: lastRow, at: .bottom, animated: true)
            }

        }

    })

}


问:
How can I force a TD with no content to render its border?
The TD has a DIV inside which I removed using jQuery's fadeOut function, but when it finishes the border disappears too.

I want to avoid that, is there any way other than adding a " " (which causes it to be ugly)?

EDIT: I am using Internet Explorer (6 and 7)

答:
Add a non-breaking space to the cell:

A hack, but a better hack than adding an image.

OwnerDisplayName: Juan Manuel

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Graeme Perrow

Body:
Add a non-breaking space to the cell:

<td>&nbsp;</td>

A hack, but a better hack than adding an image.

OwnerDisplayName: Andrew Robinson

LastEditorDisplayName: Andrew Robinson


问:
Prolog, building list with conditional clauses
I need to do this homework assignment using prolog (SWI-flavor) and cant get my head around some things.

For example, if i want to iterate through a list and add its elements to another, but ONLY if they meet certain condition, how would I go about it? I can add them all, or none, but if I add clause that checks this condition, the whole recursion turns out as "false". I understand why this is, but have no idea how to fix it. Basically what i want is:

```<code>goal(Stuff) :- do_something(X),
               only_do_this_if_something(Y),
               always_do_this(Z).
</code>```

Currently, if only_do_this_if_something(Y) fails, also always_do_this(Z) doesnt happen as the whole goal turns false...

答:
Check the following programming pattern, which is used quite a lot in Prolog:

Iterate through the list, one element at a time

Set a base case for the recursion

In one clause, check whether the conditions apply and do something, then continue with recursion

In the next clause skip the item and continue with recursion

You have to either use the cut (!) to forbid backtracking or explicitly check that the condition do not apply in the latter clause.

Note that you said that you wanted to have an output list with the items for which 'something' applied (which is not what you wrote in your code)...

Applying this pattern to your problem it would look something like this:

```<code>myRecursion([], []). % This is the base case
myRecursion([Item|Tail], [Item|NTail]):-
  something_applies(...),
  do_something(...),
  only_do_this_if_something(...),
  always_do_this(...).
  myRecursion(Tail, NTail).
myRecursion([Item|Tail], NTail):-
  not(something_applies(...)),
  do_something(...),
  always_do_this(...),
  myRecursion(Tail, NTail).
</code>```

Body:
I need to do this homework assignment using prolog (SWI-flavor) and cant get my head around some things.

For example, if i want to iterate through a list and add its elements to another, but ONLY if they meet certain condition, how would I go about it? I can add them all, or none, but if I add clause that checks this condition, the whole recursion turns out as "false". I understand why this is, but have no idea how to fix it. Basically what i want is:

goal(Stuff) :- do_something(X),
               only_do_this_if_something(Y),
               always_do_this(Z).

Currently, if only_do_this_if_something(Y) fails, also always_do_this(Z) doesnt happen as the whole goal turns false...

Body:
Check the following programming pattern, which is used quite a lot in Prolog:

Iterate through the list, one element at a time

Set a base case for the recursion

In one clause, check whether the conditions apply and do something, then continue with recursion

In the next clause skip the item and continue with recursion

You have to either use the cut (!) to forbid backtracking or explicitly check that the condition do not apply in the latter clause.

Note that you said that you wanted to have an output list with the items for which 'something' applied (which is not what you wrote in your code)...

Applying this pattern to your problem it would look something like this:

myRecursion([], []). % This is the base case
myRecursion([Item|Tail], [Item|NTail]):-
  something_applies(...),
  do_something(...),
  only_do_this_if_something(...),
  always_do_this(...).
  myRecursion(Tail, NTail).
myRecursion([Item|Tail], NTail):-
  not(something_applies(...)),
  do_something(...),
  always_do_this(...),
  myRecursion(Tail, NTail).


问:
CI sessions destroy after redirect
Firstly, I want to tell you i have searched a lot but couldn't find a solution to it. Anyways first things first i am a newbie in CI and i have tried to make a login page built in CI using CI sessions.
My Login Controller Function looks like this

```<code>//Validating login from ajax request
function validate_login() {
  $email = $this->input->post('email');
  $password = $this->input->post('password');
  $credential = array('email' => $email, 'password' => sha1($password));
  // Checking login credential for admin
  $query = $this->db->get_where('admin', $credential);
  if ($query->num_rows() > 0) {
      $row = $query->row();
      $_SESSION['admin_login'] =  '1';  // I am using traditional PHP Session Global Variable for Setting Session Variable
      $_SESSION['admin_id'] = $row->admin_id;
      $_SESSION['login_user_id'] = $row->admin_id;
      $_SESSION['name'] =  $row->name;
      $_SESSION['login_type'] = 'admin';
      //echo $this->session->userdata('admin_login');exit; //This is printing the data fine
      redirect(base_url() . 'index.php?admin/dashboard');
  }
</code>```

Now it gets redirected to Admin Controller Dashboard Function

```<code> /***ADMIN DASHBOARD***/
function dashboard()
{
    echo "```";
    print_r($_SESSION); exit;
    if ($this->session->userdata('admin_login') != 1)
        redirect(base_url(), 'refresh');
    $page_data['page_name']  = 'dashboard';
    $page_data['page_title'] = get_phrase('admin_dashboard');
    $this->load->view('backend/index', $page_data);
}
```

<p>Output </p>

```Array
(
 [__ci_last_regenerate] => 1530080373
 )
```

<p>My Autoload.php</p>

```$autoload['libraries'] = array('pagination', 'xmlrpc' , 'form_validation', 'email','upload','paypal','session','database');
```

<p>Also i tried to load the session library on the constructer function of Admin</p>

```function __construct()
{
    parent::__construct();
    $this->load->database();
    $this->load->model('Barcode_model');
    $this->load->model('session');

   /*cache control*/
    $this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
    $this->output->set_header('Pragma: no-cache');
}
```

<p>But nothing seems to work as i am unable to login and redirect to </p>

```if ($this->session->userdata('admin_login') != 1)
    redirect(base_url(), 'refresh');
```

<p>Config.php</p>

```$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 7200;
$config['sess_regenerate_destroy'] = TRUE;

/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix'   = Set a cookie name prefix if you need to avoid collisions
| 'cookie_domain'   = Set to .your-domain.com for site-wide cookies
| 'cookie_path'     = Typically will be a forward slash
| 'cookie_secure'   = Cookie will only be set if a secure HTTPS connection exists.
| 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript)
|
| Note: These settings (with the exception of 'cookie_prefix' and
|       'cookie_httponly') will also affect sessions.
|
*/
$config['cookie_prefix']    = '';
$config['cookie_domain']    = 'localhost';
$config['cookie_path']      = '/';
$config['cookie_secure']    = FALSE;
$config['cookie_httponly']  = FALSE;

/*
```

Is anything missing in my part to be set? Help Appreciated.

答:
there is an issue with session on 3.0.1 version on php 7.1 +

you just need to open session.php file from

system>libraries>Session>Session.php

find the code ini_set('session.name', $params['cookie_name']);

and replace it with this ini_set('session.id', $params['cookie_name']);

hope it will helps you.

Title: CI sessions destroy after redirect

Body:
Firstly, I want to tell you i have searched a lot but couldn't find a solution to it. Anyways first things first i am a newbie in CI and i have tried to make a login page built in CI using CI sessions.
My Login Controller Function looks like this

//Validating login from ajax request
function validate_login() {
  $email = $this->input->post('email');
  $password = $this->input->post('password');
  $credential = array('email' => $email, 'password' => sha1($password));
  // Checking login credential for admin
  $query = $this->db->get_where('admin', $credential);
  if ($query->num_rows() > 0) {
      $row = $query->row();
      $_SESSION['admin_login'] =  '1';  // I am using traditional PHP Session Global Variable for Setting Session Variable
      $_SESSION['admin_id'] = $row->admin_id;
      $_SESSION['login_user_id'] = $row->admin_id;
      $_SESSION['name'] =  $row->name;
      $_SESSION['login_type'] = 'admin';
      //echo $this->session->userdata('admin_login');exit; //This is printing the data fine
      redirect(base_url() . 'index.php?admin/dashboard');
  }

Now it gets redirected to Admin Controller Dashboard Function

 /***ADMIN DASHBOARD***/
function dashboard()
{
    echo "
";
    print_r($_SESSION); exit;
    if ($this->session->userdata('admin_login') != 1)
        redirect(base_url(), 'refresh');
    $page_data['page_name']  = 'dashboard';
    $page_data['page_title'] = get_phrase('admin_dashboard');
    $this->load->view('backend/index', $page_data);
}

Output

Array
(
 [__ci_last_regenerate] => 1530080373
 )

My Autoload.php

$autoload['libraries'] = array('pagination', 'xmlrpc' , 'form_validation', 'email','upload','paypal','session','database');

Also i tried to load the session library on the constructer function of Admin

function __construct()
{
    parent::__construct();
    $this->load->database();
    $this->load->model('Barcode_model');
    $this->load->model('session');

   /*cache control*/
    $this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
    $this->output->set_header('Pragma: no-cache');
}

But nothing seems to work as i am unable to login and redirect to

if ($this->session->userdata('admin_login') != 1)
    redirect(base_url(), 'refresh');

Config.php

$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 7200;
$config['sess_regenerate_destroy'] = TRUE;

/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix'   = Set a cookie name prefix if you need to avoid collisions
| 'cookie_domain'   = Set to .your-domain.com for site-wide cookies
| 'cookie_path'     = Typically will be a forward slash
| 'cookie_secure'   = Cookie will only be set if a secure HTTPS connection exists.
| 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript)
|
| Note: These settings (with the exception of 'cookie_prefix' and
|       'cookie_httponly') will also affect sessions.
|
*/
$config['cookie_prefix']    = '';
$config['cookie_domain']    = 'localhost';
$config['cookie_path']      = '/';
$config['cookie_secure']    = FALSE;
$config['cookie_httponly']  = FALSE;

/*

Is anything missing in my part to be set? Help Appreciated.


问:
OOP Observer Pattern: call notifyListener from outside of the subject
Is it ok for an Observer object to call notifyListeners() on an observable after changing some of its fields? What disadvantages could arise? Usually it's the subjects' responsibility to notify listeners of changes.

I frequently come across the following problem when wrapping model classes in an observable / subject e.g. to make them accessible in UI.

Should my subject notify its listeners whenever any field of the model object is changed or should I provide some kind of method setModel() that takes a new model object as an argument and only then notifies all listeners?

For example:

```<code>class MyData {
  String myString;
  int myInt;
}

class MyDataObservable {
  private MyData data;

  // constructor

  void setString(String string) {
    data.myString = string;
    notifyListeners();
  }

  void setInt(int num) {
    data.myInt = num;
    notifyListeners();
  }

  void notifyListeners() {...}

  void addListener(Observer o) {...}
}
</code>```

I don't like that my subject basically mirrors all the properties of my model .. which is pretty ugly.

```<code>class MyDataObservable {
  private MyData data;

  // constructor

  void setData(MyData data) {
    this.data = data;
    notifyListeners();
  }

  void notifyListeners() {...}

  void addListener(Observer o) {...}
}
</code>```

The downside of this approach is that I have to build a new copy of my data class everytime anything changes, even if it's just a bool flag on my model class.

So my idea was to allow for observers to notify other listeners when they changed something with e.g. an update function.

Are there other, more elegant alternatives?

EDIT

At the moment, making my data class an observable is not an option because I'm using a framework that provides an observable mechanism that can also hold business logic. For that reason I want to decouple my data class and the logic / observable.

答:
In this case I would use inheritance rather than composition: MyData is-a Observable rather than Observable has-a MyData.

```<code>class Observable {
    Collection<Listener> listeners

    void addListener(Listener l) {...}
    void notifyListeners() {...}
}
</code>```

```<code>class MyData extends Observable {
    String myString;
    int myInt;

    void setString(String string) {
        this.myString = string;
        notifyListeners();
    }

    void setInt(int num) {
        this.myInt = num;
        notifyListeners();
    }
}
</code>```

Body:
Is it ok for an Observer object to call notifyListeners() on an observable after changing some of its fields? What disadvantages could arise? Usually it's the subjects' responsibility to notify listeners of changes.

I frequently come across the following problem when wrapping model classes in an observable / subject e.g. to make them accessible in UI.

Should my subject notify its listeners whenever any field of the model object is changed or should I provide some kind of method setModel() that takes a new model object as an argument and only then notifies all listeners?

For example:

class MyData {
  String myString;
  int myInt;
}

class MyDataObservable {
  private MyData data;

  // constructor

  void setString(String string) {
    data.myString = string;
    notifyListeners();
  }

  void setInt(int num) {
    data.myInt = num;
    notifyListeners();
  }

  void notifyListeners() {...}

  void addListener(Observer o) {...}
}

I don't like that my subject basically mirrors all the properties of my model .. which is pretty ugly.

class MyDataObservable {
  private MyData data;

  // constructor

  void setData(MyData data) {
    this.data = data;
    notifyListeners();
  }

  void notifyListeners() {...}

  void addListener(Observer o) {...}
}

The downside of this approach is that I have to build a new copy of my data class everytime anything changes, even if it's just a bool flag on my model class.

So my idea was to allow for observers to notify other listeners when they changed something with e.g. an update function.

Are there other, more elegant alternatives?

EDIT

At the moment, making my data class an observable is not an option because I'm using a framework that provides an observable mechanism that can also hold business logic. For that reason I want to decouple my data class and the logic / observable.

Body:
In this case I would use inheritance rather than composition: MyData is-a Observable rather than Observable has-a MyData.

class Observable {
    Collection<Listener> listeners

    void addListener(Listener l) {...}
    void notifyListeners() {...}
}

class MyData extends Observable {
    String myString;
    int myInt;

    void setString(String string) {
        this.myString = string;
        notifyListeners();
    }

    void setInt(int num) {
        this.myInt = num;
        notifyListeners();
    }
}


问:
How to use f-strings or format in except block?
Trying to write a formatted message in the except block to potentially show the user their entered input and why it's incorrect.

```<code>try:
    rows = int(input("How many rows of odd numbers? >"))
    zero = 10 / rows
except (ValueError, ZeroDivisionError):
    print(f"{rows} is not a valid answer.")
</code>```

This however gives me this error:

```<code>NameError: name 'rows' is not defined
</code>```

Anyway to accomplish what I'm trying to do?

答:
You get an error because rows is still not defined when the exception is raised, but you could do something like:

```<code>rows = input("How many rows of odd numbers? >")
try:
    zero = 10 / int(rows)
except (ValueError, ZeroDivisionError):
    print(f"{rows} is not a valid answer.")
</code>```

Body:
Trying to write a formatted message in the except block to potentially show the user their entered input and why it's incorrect.

try:
    rows = int(input("How many rows of odd numbers? >"))
    zero = 10 / rows
except (ValueError, ZeroDivisionError):
    print(f"{rows} is not a valid answer.")

This however gives me this error:

NameError: name 'rows' is not defined

Anyway to accomplish what I'm trying to do?

Body:
You get an error because rows is still not defined when the exception is raised, but you could do something like:

rows = input("How many rows of odd numbers? >")
try:
    zero = 10 / int(rows)
except (ValueError, ZeroDivisionError):
    print(f"{rows} is not a valid answer.")


问:
How to join lines not starting with specific pattern to the previous line in UNIX?
Please take a look at the sample file and the desired output below to understand what I am looking for.

It can be done with loops in a shell script but I am struggling to get an awk/sed one liner.

SampleFile.txt

These are leaves.
These are branches.
These are greenery which gives
oxygen, provides control over temperature
and maintains cleans the air.
These are tigers
These are bears
and deer and squirrels and other animals.
These are something you want to kill
Which will see you killed in the end.
These are things you must to think to save your tomorrow.
```

<p><strong>Desired output</strong></p>

<pre class="lang-none prettyprint-override"><code>These are leaves.
These are branches.
These are greenery which gives oxygen, provides control over temperature and maintains cleans the air.
These are tigers
These are bears and deer and squirrels and other animals.
These are something you want to kill Which will see you killed in the end.
These are things you must to think to save your tomorrow.
</code>```

答:
Here is a sed program which avoids branches. I tested it with the --posix option. The trick is to use an "anchor" (a string which does not occur in the file):

```<code> sed --posix -n '/^These/!{;s/^/DOES_NOT_OCCUR/;};H;${;x;s/^\n//;s/\nDOES_NOT_OCCUR/ /g;p;}'
</code>```

Explanation:

write DOES_NOT_OCCUR at the beginning of lines not starting with "These":

/^These/!{;s/^/DOES_NOT_OCCUR/;};

append the pattern space to the hold space

H;

If the last line is read, exchange pattern space and hold space

${;x;

Remove the newline at the beginning of the pattern space which is added by the H command when it added the first line to the hold space

s/^\n//;

Replace all newlines followed by DOES_NOT_OCCUR with blanks and print the result

s/\nDOES_NOT_OCCUR/ /g;p;}

Note that the whole file is read in sed's process memory, but with only 4GB this should not be a problem.

Body:
Please take a look at the sample file and the desired output below to understand what I am looking for.

It can be done with loops in a shell script but I am struggling to get an awk/sed one liner.

SampleFile.txt

These are leaves.
These are branches.
These are greenery which gives
oxygen, provides control over temperature
and maintains cleans the air.
These are tigers
These are bears
and deer and squirrels and other animals.
These are something you want to kill
Which will see you killed in the end.
These are things you must to think to save your tomorrow.

Desired output

These are leaves.
These are branches.
These are greenery which gives oxygen, provides control over temperature and maintains cleans the air.
These are tigers
These are bears and deer and squirrels and other animals.
These are something you want to kill Which will see you killed in the end.
These are things you must to think to save your tomorrow.

Body:
Here is a sed program which avoids branches. I tested it with the --posix option. The trick is to use an "anchor" (a string which does not occur in the file):

 sed --posix -n '/^These/!{;s/^/DOES_NOT_OCCUR/;};H;${;x;s/^\n//;s/\nDOES_NOT_OCCUR/ /g;p;}'

Explanation:

write DOES_NOT_OCCUR at the beginning of lines not starting with "These":

/^These/!{;s/^/DOES_NOT_OCCUR/;};

append the pattern space to the hold space

H;

If the last line is read, exchange pattern space and hold space

${;x;

Remove the newline at the beginning of the pattern space which is added by the H command when it added the first line to the hold space

s/^\n//;

Replace all newlines followed by DOES_NOT_OCCUR with blanks and print the result

s/\nDOES_NOT_OCCUR/ /g;p;}

Note that the whole file is read in sed's process memory, but with only 4GB this should not be a problem.


问:
MultiPartMimeStreamFormatException error when importing pbix files using rest-api
So I'm using powershell to automate my power BI reports into my workspace through imports API.
here's the code which I'm using :

```<code>    $PBIXuri="my azure blob storage url",
    $Workspaceurl="https://api.powerbi.com/v1.0/myorg/groups/mygroups/imports?datasetDisplayName=myreportname",
    $AccessToken="my oauth token"

    #download my pbix file from azure blob storage
    $cli = New-Object System.Net.WebClient
    $exportpbix = $cli.DownloadData($PBIXuri)

    $powerBiBody = @'
    --exptest
    Content-Disposition: form-data; name="file";
    Content-Type: application/x-zip-compressed

    {0}
    --exptest--

    '@

    #set my pbix file into request body
    $encoding = [System.Text.Encoding]::GetEncoding('iso-8859-1')
    $body = $powerBiBody -f $encoding.GetString($exportpbix)

    $headers = @{
    "Authorization" = "Bearer " + $AccessToken}

    Invoke-RestMethod -Uri $Workspaceurl -Method Post -Headers $headers -Body $body -ContentType "multipart/form-data; boundary=--exptest"
</code>```

but it always return an error like :

```<code>Invoke-RestMethod :     {"error":
     {"code":"MultiPartMimeStreamFormatException","pbi.error":
       {"code":"MultiPartMimeStreamFormatException",
        "parameters":{},
        "details":[],
        "exceptionCulprit":1
        }
      }
    }
</code>```

where do I went wrong on my code?

答:
I've found the problem.
on my request body, the content-type which I set was "application/x-zip-compressed".
while my pbix file is "application/stream-octet", after I change it my files was imported correctly.</p>

Body:
So I'm using powershell to automate my power BI reports into my workspace through imports API.
here's the code which I'm using :

    $PBIXuri="my azure blob storage url",
    $Workspaceurl="https://api.powerbi.com/v1.0/myorg/groups/mygroups/imports?datasetDisplayName=myreportname",
    $AccessToken="my oauth token"

    #download my pbix file from azure blob storage
    $cli = New-Object System.Net.WebClient
    $exportpbix = $cli.DownloadData($PBIXuri)

    $powerBiBody = @'
    --exptest
    Content-Disposition: form-data; name="file";
    Content-Type: application/x-zip-compressed

    {0}
    --exptest--

    '@

    #set my pbix file into request body
    $encoding = [System.Text.Encoding]::GetEncoding('iso-8859-1')
    $body = $powerBiBody -f $encoding.GetString($exportpbix)

    $headers = @{
    "Authorization" = "Bearer " + $AccessToken}

    Invoke-RestMethod -Uri $Workspaceurl -Method Post -Headers $headers -Body $body -ContentType "multipart/form-data; boundary=--exptest"

but it always return an error like :

Invoke-RestMethod :     {"error":
     {"code":"MultiPartMimeStreamFormatException","pbi.error":
       {"code":"MultiPartMimeStreamFormatException",
        "parameters":{},
        "details":[],
        "exceptionCulprit":1
        }
      }
    }

where do I went wrong on my code?


问:
LINQ- filer as required model and add a list to the select statement
I need to access to the following list.
Mainlist - contains equipmentlist and it will display with the following model.

```<code>public class BTypeModel
{
    public string Image { get; set; }
    public int? id { get; set; }
    public string bName { get; set; }
    public string alterName { get; set; }
    public string number { get; set; }
    public List<MainEquipment> equipment { get; set; }
    public string displayName { get; set; }

}

public class MainEquipment
{
    public int id { get; set; }
    public string name { get; set; }

}
</code>```

My issue is that I can not access the equipemnt list

see as follow

```<code>var available = MainList
     .Where(o => o.bType?.id == placeid)
     .Select(s => new BTypeModel {
      displayName = s.Type.name,
      id = s.id,
      number = s.number,
      Image = s.files.FirstOrDefault()?.Image,
      alterName = s.alternateName,
      equipment=s.mainequipmentlist.Select(a=>a.id), *
</code>```

//The select is what gives the error. no matter if I select the int or the string the error is the same just change

'System.Collections.Generic.IEnumerable' Cannot implicitly
  convert type 'System.Collections.Generic.IEnumerable' to to
  'System.Collections.Generic.List'. An
  explicit conversion exists (are you missing a cast?)

```<code>equipment=s.mainequipmentlist.Select(a=>a.id)
</code>```

I can't get it to display this list -** error is can convert int to a generic list- **

答:
equipment property in BTypeModel class is of type List<MainEquipment>, your equipment=s.mainequipmentlist.Select(a=>a.id) is projecting only ids using Select() method.

equipment=s.mainequipmentlist.Select(a=>a.id) will return IEnumerable and trying to assign it to List<MainEquipment>. This is the reason behind an error.

To fix this issue either assign s.mainequipmentlist to equipment property instead. Or create new property in BTypeModel for equipmentIds of type IEnumerable<int> and assing it projected ids like

```<code>var available = MainList
     .Where(o => o.bType?.id == placeid)
     .Select(s => new BTypeModel {
           ...
           equipment = s.mainequipmentlist,  //Either
           ids = s.mainequipmentlist.Select(a=>a.id) //or solution
           ...
      }
</code>```

Enumerable.Select Method

Body:
I need to access to the following list.
Mainlist - contains equipmentlist and it will display with the following model.

public class BTypeModel
{
    public string Image { get; set; }
    public int? id { get; set; }
    public string bName { get; set; }
    public string alterName { get; set; }
    public string number { get; set; }
    public List<MainEquipment> equipment { get; set; }
    public string displayName { get; set; }

}

public class MainEquipment
{
    public int id { get; set; }
    public string name { get; set; }

}

My issue is that I can not access the equipemnt list

see as follow

var available = MainList
     .Where(o => o.bType?.id == placeid)
     .Select(s => new BTypeModel {
      displayName = s.Type.name,
      id = s.id,
      number = s.number,
      Image = s.files.FirstOrDefault()?.Image,
      alterName = s.alternateName,
      equipment=s.mainequipmentlist.Select(a=>a.id), *

//The select is what gives the error. no matter if I select the int or the string the error is the same just change

'System.Collections.Generic.IEnumerable' Cannot implicitly
  convert type 'System.Collections.Generic.IEnumerable' to to
  'System.Collections.Generic.List'. An
  explicit conversion exists (are you missing a cast?)

equipment=s.mainequipmentlist.Select(a=>a.id)

I can't get it to display this list -** error is can convert int to a generic list- **

Body:
equipment property in BTypeModel class is of type List<MainEquipment>, your equipment=s.mainequipmentlist.Select(a=>a.id) is projecting only ids using Select() method.

equipment=s.mainequipmentlist.Select(a=>a.id) will return IEnumerable and trying to assign it to List<MainEquipment>. This is the reason behind an error.

To fix this issue either assign s.mainequipmentlist to equipment property instead. Or create new property in BTypeModel for equipmentIds of type IEnumerable<int> and assing it projected ids like

var available = MainList
     .Where(o => o.bType?.id == placeid)
     .Select(s => new BTypeModel {
           ...
           equipment = s.mainequipmentlist,  //Either
           ids = s.mainequipmentlist.Select(a=>a.id) //or solution
           ...
      }

Enumerable.Select Method


问:
How do i implement the take function in Haskell using takeWhile?
So in my exam i had to implement the take function in Haskell using the takeWhile.

How can i do this?

What would be the condition in takeWhile so that it will only take the required number of elements from the list?

Because to my understanding in takeWhile the condition refers to the elements of the list, not the number of those.

答:
DONE!!!

Thanks a lot for the help everyone!

I know this could work better but for now this solution worked out.

index function:

```<code>index :: [a] -> [(Int, a)]
index [] = []
index x = index2 x 1

index2 :: [a] -> Int -> [(Int, a)]
index2 [] _ = []
index2 (x:xs) i = (i, x) : index2 xs (i+1)
</code>```

deindex function:

```<code>deindex :: [(Int, a)] -> [a]
deindex [] = []
deindex ((i,x):xs) = x : deindex xs
</code>```

myTake function using takeWhile:

```<code>myTake :: Int -> [a] -> [a]
myTake k _
    | k <= 0 = []
myTake _ [] = []
myTake n list = deindex (takeWhile (\ (x,y) -> x<=n) (index list))
</code>```

Body:
DONE!!!

Thanks a lot for the help everyone!

I know this could work better but for now this solution worked out.

index function:

index :: [a] -> [(Int, a)]
index [] = []
index x = index2 x 1

index2 :: [a] -> Int -> [(Int, a)]
index2 [] _ = []
index2 (x:xs) i = (i, x) : index2 xs (i+1)

deindex function:

deindex :: [(Int, a)] -> [a]
deindex [] = []
deindex ((i,x):xs) = x : deindex xs

myTake function using takeWhile:

myTake :: Int -> [a] -> [a]
myTake k _
    | k <= 0 = []
myTake _ [] = []
myTake n list = deindex (takeWhile (\ (x,y) -> x<=n) (index list))


问:
How to extract a json object only using basic commands like sed/awk in shell?
Like this:
I have a json file with below format:

```<code>{
    "Item": {
        "summary": {
            "B": "ABCDE"
        },
        "name": {
            "S": "sider"
        },
        "age": {
            "N": "1"
        },
        "data": {
            "B": "abcde"
        }
    }
}
</code>```

How can I get the object "Item" only using existed commands like sed/awk without installing any external tools in shell?

expected output:

```<code>{
    "summary": {
        "B": "ABCDE"
    },
    "name": {
        "S": "sider"
    },
    "age": {
        "N": "1"
    },
    "data": {
        "B": "abcde"
    }
}
</code>```

答:
This is what you need:

```<code>sed -n '/^    "Item": {/,/^    }/{s/"Item": //;s/^    //;p}'
</code>```

which essentially build upon Mark's solution by making two substitutions to remove "Item": and de-indent 4 spaces before printing.

Body:
Like this:
I have a json file with below format:

{
    "Item": {
        "summary": {
            "B": "ABCDE"
        },
        "name": {
            "S": "sider"
        },
        "age": {
            "N": "1"
        },
        "data": {
            "B": "abcde"
        }
    }
}

How can I get the object "Item" only using existed commands like sed/awk without installing any external tools in shell?

expected output:

{
    "summary": {
        "B": "ABCDE"
    },
    "name": {
        "S": "sider"
    },
    "age": {
        "N": "1"
    },
    "data": {
        "B": "abcde"
    }
}

Body:
This is what you need:

sed -n '/^    "Item": {/,/^    }/{s/"Item": //;s/^    //;p}'

which essentially build upon Mark's solution by making two substitutions to remove "Item": and de-indent 4 spaces before printing.


问:
Valgrind + C: Handling uninitialized pointers without error
Maybe I got too involved with testing my assignment, but here's my dilemma:

This is my offending function (more or less):

```<code>struct thing{
    char* data;
}

int function(struct thing* arg){
    if(arg->data == NULL)
        return -1;
}
</code>```

This is my offending input:

```<code>struct thing *x = malloc(sizeof(struct thing));
function(x);
</code>```

And valgrind outputs this when I test it:

Conditional jump or move depends on uninitialised value(s)
```

I'm about 99% sure that this is because valgrind has an issue with evaluating x->data when it hasn't been initialized to NULL or malloced. Is there a workaround for this?

答:
You are defining a function like this:

```<code>int function(struct thing *arg) {
    if (arg->data == NULL) {
        // abort here
        return 1;
    } else {
        // use the value here
        return 0;
    }
}
</code>```

Here, Valgrind is right about complaining, because it's impossible to achieve the intended behavior for function(). If arg->data is not explicitly initialized, then its value is indeterminate, and the if statement could execute any of the two branches depending on whichever random value it reads from arg->data.

In general, it's impossible for the function to work correctly, because:

If the check arg->data == NULL fails, the rest of the code will assume that arg->data is not NULL and therefore use the invalid value, most likely causing a crash or other kind of problem.

If the check arg->data == NULL passes, the rest of the code will wrongfully assume that the data is known to be invalid, and do any other kind of thing assuming that data was intended to be NULL, like for example call some cleanup code at the wrong time.

Other than this, if you really want to be pedantic, reading uninitialized variables is actually undefined behavior in C.

The right thing to do in your case is to either use calloc() instead of malloc() or to manually set x->data = NULL right after malloc().

Body:
Maybe I got too involved with testing my assignment, but here's my dilemma:

This is my offending function (more or less):

struct thing{
    char* data;
}

int function(struct thing* arg){
    if(arg->data == NULL)
        return -1;
}

This is my offending input:

struct thing *x = malloc(sizeof(struct thing));
function(x);

And valgrind outputs this when I test it:

Conditional jump or move depends on uninitialised value(s)

I'm about 99% sure that this is because valgrind has an issue with evaluating x->data when it hasn't been initialized to NULL or malloced. Is there a workaround for this?

Body:
You are defining a function like this:

int function(struct thing *arg) {
    if (arg->data == NULL) {
        // abort here
        return 1;
    } else {
        // use the value here
        return 0;
    }
}

Here, Valgrind is right about complaining, because it's impossible to achieve the intended behavior for function(). If arg->data is not explicitly initialized, then its value is indeterminate, and the if statement could execute any of the two branches depending on whichever random value it reads from arg->data.

In general, it's impossible for the function to work correctly, because:

If the check arg->data == NULL fails, the rest of the code will assume that arg->data is not NULL and therefore use the invalid value, most likely causing a crash or other kind of problem.

If the check arg->data == NULL passes, the rest of the code will wrongfully assume that the data is known to be invalid, and do any other kind of thing assuming that data was intended to be NULL, like for example call some cleanup code at the wrong time.

Other than this, if you really want to be pedantic, reading uninitialized variables is actually undefined behavior in C.

The right thing to do in your case is to either use calloc() instead of malloc() or to manually set x->data = NULL right after malloc().


问:
Querying MySQL DB in different VPC and Security Group
I am new to VPC and Security Group Concepts in AWS.

In my project,  there is one EC2 box which is associated with VPC_1 , Security Groups: SG_1 and SG_2 and subnet id: SUBNET1. In this box MySQL database is running.

There is another EC2 box which is associated with VPC_2, Security Groups: SG_3 and SG_4 and subnet id: SUBNET2. Here application is going to run from which I would like to query the MySQL database as mentioned above.

Could anyone please give any pointers regarding this ? Thanks.

答:
There are two ways by which you can access DB from app

With VPC peering (preferable)

Peer both VPC's and whitelist the private app subnet range in db security group.

Public DB instance

Boot the DB in public subnet with public IP and whitelist your app VPC_2 NAT IP(s) in db security group, while using RDS, there is publicly accessible option, need to enable it


问:
Problems with jammit gem on windows x64

Possible Duplicate:

  Ruby 1.9 - no such file to load 'win32/open3'

I am having a problem with jammit gem. When I run "rake", I get a message telling me, there is a problem - part of message:

$ rake -t
(in c:/Ruby187/test)
rake aborted!
no such file to load -- win32/open3
c:/Ruby187/lib/ruby/gems/1.8/gems/activesupport-3.0.6/lib/active_support/dependencies.rb:239
:in require'
c:/Ruby187/lib/ruby/gems/1.8/gems/activesupport-3.0.6/lib/active_support/dependencies.rb:239
:inrequire'

Some info about environment:
OS: Windows 7 64bit
Ruby 1.8.7
GEMS:
jammit (0.6.0)
closure-compiler (1.1.1)
yui-compressor (0.9.6)

If I remove jammit from Gemfile, command rake -t runs without problems.

Thank you for any suggestion!

答:
Add this to your Gemfile:

```<code>gem 'win32-open3'
</code>```

and bundle

Title: Problems with jammit gem on windows x64

Body:
Add this to your Gemfile:

gem 'win32-open3'

and bundle


问:
SQL remove not alphabetic characters from string
I am a beginner in SQL I have a column with strings, I need to remove any character that is not between A-Z and a-z</p>

答:
You can use regexp_replace():

```<code>select regexp_replace(col, '[^a-zA-Z]', '', 'g')
</code>```

Here is a db<>fiddle.

Body:
You can use regexp_replace():

select regexp_replace(col, '[^a-zA-Z]', '', 'g')

Here is a db<>fiddle.


问:
Require parameter of given type based on another parameter in TypeScript
Let's have TypeScript function for sending emails:

enum ETemplate {
  EXAMPLE1, EXAMPLE2
}

function sendEmail(to: string, template: ETemplate, params: IParams): Promise<void>{
  await this.mailService.send(to, template, params);
}

interface IParams {
  // depends on template type (ETemplate)
}
```

How to require params depending on template type I entered? Reason why is because every template have different IParams based on ETemplate.

I know TypeScript have generics but I am not sure if I can achieve this with them...

答:
You don't need to use generics in this case. Use discriminated unions instead: </p>

```<code>enum TemplateType {
    Template1,
    Template2
}

type Template =
    | { type: TemplateType.Template1, params: { aaa: number } }
    | { type: TemplateType.Template2, params: { bbb: string, ccc?: boolean } };

const sendEmail = async (to: string, template: Template): Promise<void> => {
    if (template.type === TemplateType.Template1) {
        template.params.aaa; // number

        return;
    }

    if (template.type === TemplateType.Template2) {
        template.params.bbb; // string
        template.params.ccc; // boolean | undefined

        return;
    }

    template; // never
}

sendEmail("example@example.com", { type: TemplateType.Template1, params: { aaa: 123 } }); // OK
sendEmail("example@example.com", { type: TemplateType.Template2, params: { aaa: 123 } }); // Error as expected
</code>```

Body:
Let's have TypeScript function for sending emails:

enum ETemplate {
  EXAMPLE1, EXAMPLE2
}

function sendEmail(to: string, template: ETemplate, params: IParams): Promise<void>{
  await this.mailService.send(to, template, params);
}

interface IParams {
  // depends on template type (ETemplate)
}

How to require params depending on template type I entered? Reason why is because every template have different IParams based on ETemplate.

I know TypeScript have generics but I am not sure if I can achieve this with them...

Body:
You don't need to use generics in this case. Use discriminated unions instead:

enum TemplateType {
    Template1,
    Template2
}

type Template =
    | { type: TemplateType.Template1, params: { aaa: number } }
    | { type: TemplateType.Template2, params: { bbb: string, ccc?: boolean } };

const sendEmail = async (to: string, template: Template): Promise<void> => {
    if (template.type === TemplateType.Template1) {
        template.params.aaa; // number

        return;
    }

    if (template.type === TemplateType.Template2) {
        template.params.bbb; // string
        template.params.ccc; // boolean | undefined

        return;
    }

    template; // never
}

sendEmail("example@example.com", { type: TemplateType.Template1, params: { aaa: 123 } }); // OK
sendEmail("example@example.com", { type: TemplateType.Template2, params: { aaa: 123 } }); // Error as expected


问:
PHP: Sort an array by the length of its values?
I made an anagram machine and I have an array of positive matches. The trouble is they are all in a different order, I want to be able to sort the array so the longest array values appear first.

Anybody have any ideas on how to do this?

答:
Descending Order:

```<code>$array = ['aa', 'bb', 'c', 'ccc', 'a', 'ertre'];

usort($array, function($a, $b){
   return strlen($a) < strlen($b);
});

var_export($array);

// Output
array (
  0 => 'ertre',
  1 => 'ccc',
  2 => 'aa',
  3 => 'bb',
  4 => 'c',
  5 => 'a',
)

</code>```

Ascending Order:

```<code>$array = ['aa', 'bb', 'c', 'ccc', 'a', 'ertre'];

usort($array, function($a, $b){
   return strlen($a) > strlen($b);
});

// Output
array (
  0 => 'c',
  1 => 'a',
  2 => 'aa',
  3 => 'bb',
  4 => 'ccc',
  5 => 'ertre',
)
</code>```

Body:
Descending Order:

$array = ['aa', 'bb', 'c', 'ccc', 'a', 'ertre'];

usort($array, function($a, $b){
   return strlen($a) < strlen($b);
});

var_export($array);

// Output
array (
  0 => 'ertre',
  1 => 'ccc',
  2 => 'aa',
  3 => 'bb',
  4 => 'c',
  5 => 'a',
)

Ascending Order:

$array = ['aa', 'bb', 'c', 'ccc', 'a', 'ertre'];

usort($array, function($a, $b){
   return strlen($a) > strlen($b);
});

// Output
array (
  0 => 'c',
  1 => 'a',
  2 => 'aa',
  3 => 'bb',
  4 => 'ccc',
  5 => 'ertre',
)