问:
jQuery: remove not selected choices before appending new via AJAX for Chosen JS
I have my ChosenJS multiselect input, where I get options dynamically via AJAX:

```<code>  $("#offer_tags").chosen({
    max_selected_options: 30,
    max_shown_results: 30,
  });

  $("#offer_tags_chosen input").autocomplete({
      minLength: 3,
      source: function( request, response ) {
          $.ajax({
              url: "/common/offer_tags?search="+request.term,
              dataType: "json",
              beforeSend: function(){}
          }).done(function( data ) {
                  response(
                    $('#offer_tags_chosen ul.chosen-results').each(function () {
                      console.log(this);
                    }),
                    $('#offer_tags').append('<option>' + request.term + '</option>'),

                    $.map( data, function( item ) {
                      $('#offer_tags').append('<option value='+ item.id +'>' + item.name + '</option>');
                    })
                  );
                  $("#offer_tags").trigger("chosen:updated");
          });

      }
  });
</code>```

At the moment it looks like everything works fine, however I'd like to remove not selected choices before new options are appended.

So far my idea has been to access ul.chosen-results and then remove all li.active-results

With this piece of code

```<code>$('#offer_tags_chosen ul.chosen-results').each(function () {
  console.log(this);
})
</code>```

I can get ul.chosen-results in my console:

```<code><ul class="chosen-results">
  <li class="active-result" data-option-array-index="0" style="">myvalue</li>
  <li class="active-result" data-option-array-index="1" style="">othervalue</li>
  <li class="active-result" data-option-array-index="2" style="">thirdvalue</li>
</ul>
</code>```

however when I try to access children with something like this:

```<code>$('#offer_tags_chosen ul.chosen-results').each(function () {
  console.log($(this).children());
})
</code>```

it gives me this:

```<code>w.fn.init [li.no-results, prevObject: w.fn.init(1)]
0: li.no-results
length: 1
prevObject: w.fn.init [ul.chosen-results]
__proto__: Object(0)
</code>```

Whan am I doing wrong, please? How can I remove options which are not selected before appending new options? I need to keep selected choices in place - no remove.

Update

My HTML looks like this:

```<code><div class="chosen-container chosen-container-multi" style="width: 936px;"
      title="" id="offer_tags_chosen">
  <ul class="chosen-choices">
    <li class="search-field">
      <input type="text" value="Please, select (multiple allowed)"
             class="default ui-autocomplete-input" autocomplete="off"
             style="width: 215.387px;">
    </li>
  </ul>
  <div class="chosen-drop">
    <ul class="chosen-results">
      <li class="active-result" data-option-array-index="0" style="">myvalue</li>
      <li class="active-result" data-option-array-index="1" style="">othervalue</li>
      <li class="active-result" data-option-array-index="2" style="">thirdvalue</li>
    </ul>
  </div>
</div>
</code>```

console.log($(this).children().get()); gives me:

```<code>[li.no-results]
0: li.no-results
length: 1
__proto__: Array(0)
</code>```

答:
Not from ul loop start from li.

$('#offer_tags_chosen ul.chosen-results li'.

Try get() with not selector like below. I add class result-selected on 4th li value which is not appear on console.

$('#offer_tags_chosen ul.chosen-results li').not('.result-selected').each(function() {
  console.log($(this).get());
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="chosen-container chosen-container-multi" style="width: 936px;" title="" id="offer_tags_chosen">
  <ul class="chosen-choices">
    <li class="search-field">
      <input type="text" value="Please, select (multiple allowed)" class="default ui-autocomplete-input" autocomplete="off" style="width: 215.387px;">
    </li>
  </ul>
  <div class="chosen-drop">
    <ul class="chosen-results">

      <li class="active-result" data-option-array-index="0" style="">Select</li>
      <li class="active-result" data-option-array-index="1" style="">othervalue</li>
      <li class="active-result" data-option-array-index="2" style="">thirdvalue</li>
      <li class="active-result result-selected" data-option-array-index="4" style="">4thvalue</li>
    </ul>
  </div>
</div></code>```

Body:
I have my ChosenJS multiselect input, where I get options dynamically via AJAX:

  $("#offer_tags").chosen({
    max_selected_options: 30,
    max_shown_results: 30,
  });

  $("#offer_tags_chosen input").autocomplete({
      minLength: 3,
      source: function( request, response ) {
          $.ajax({
              url: "/common/offer_tags?search="+request.term,
              dataType: "json",
              beforeSend: function(){}
          }).done(function( data ) {
                  response(
                    $('#offer_tags_chosen ul.chosen-results').each(function () {
                      console.log(this);
                    }),
                    $('#offer_tags').append('<option>' + request.term + '</option>'),

                    $.map( data, function( item ) {
                      $('#offer_tags').append('<option value='+ item.id +'>' + item.name + '</option>');
                    })
                  );
                  $("#offer_tags").trigger("chosen:updated");
          });

      }
  });

At the moment it looks like everything works fine, however I'd like to remove not selected choices before new options are appended.

So far my idea has been to access ul.chosen-results and then remove all li.active-results

With this piece of code

$('#offer_tags_chosen ul.chosen-results').each(function () {
  console.log(this);
})

I can get ul.chosen-results in my console:

myvalue

othervalue

thirdvalue

however when I try to access children with something like this:

$('#offer_tags_chosen ul.chosen-results').each(function () {
  console.log($(this).children());
})

it gives me this:

w.fn.init [li.no-results, prevObject: w.fn.init(1)]
0: li.no-results
length: 1
prevObject: w.fn.init [ul.chosen-results]
__proto__: Object(0)

Whan am I doing wrong, please? How can I remove options which are not selected before appending new options? I need to keep selected choices in place - no remove.

Update

My HTML looks like this:

      <input type="text" value="Please, select (multiple allowed)"
             class="default ui-autocomplete-input" autocomplete="off"
             style="width: 215.387px;">

myvalue

othervalue

thirdvalue

console.log($(this).children().get()); gives me:

[li.no-results]
0: li.no-results
length: 1
__proto__: Array(0)

Body:
Not from ul loop start from li.

$('#offer_tags_chosen ul.chosen-results li'.

Try get() with not selector like below. I add class result-selected on 4th li value which is not appear on console.

$('#offer_tags_chosen ul.chosen-results li').not('.result-selected').each(function() {
  console.log($(this).get());
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="chosen-container chosen-container-multi" style="width: 936px;" title="" id="offer_tags_chosen">
  <ul class="chosen-choices">
    <li class="search-field">
      <input type="text" value="Please, select (multiple allowed)" class="default ui-autocomplete-input" autocomplete="off" style="width: 215.387px;">
    </li>
  </ul>
  <div class="chosen-drop">
    <ul class="chosen-results">

      <li class="active-result" data-option-array-index="0" style="">Select</li>
      <li class="active-result" data-option-array-index="1" style="">othervalue</li>
      <li class="active-result" data-option-array-index="2" style="">thirdvalue</li>
      <li class="active-result result-selected" data-option-array-index="4" style="">4thvalue</li>
    </ul>
  </div>
</div>


来源: stackexchange

问:
How to use BitmapDescriptor.fromAssetImage() to set a custom Marker icon?
I'm trying to set a custom icon for the markers of my map, in my Flutter app. Since BitmapDescriptor.fromAsset() is deprecated, I'm sruggling to find how to use BitmapDescriptor.fromAssetImage().

I did not find any doc or Stackoverflow question about this.

This is the current way I'm creating it (without the custom image):

Marker(
          markerId: MarkerId(pos.toString()),
          position: pos,
          infoWindow: InfoWindow(
            title: store['store_name'],
            snippet: '',
          ),
          icon: BitmapDescriptor.defaultMarker));
```

答:
Define a field in Class:

```<code>BitmapDescriptor myIcon;
</code>```

Retrieve icon before the Map is ready.

```<code>@override
void initState() {
    BitmapDescriptor.fromAssetImage(
        ImageConfiguration(size: Size(48, 48)), 'assets/my_icon.png')
        .then((onValue) {
      myIcon = onValue;
    });
 }
</code>```

set the Icon:

```<code>icon: myIcon;
</code>```

Make sure you have set the icon in Flutter section of pubspec.yaml

```<code> assets:
    - assets/my_icon.png
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Define a field in Class:

BitmapDescriptor myIcon;

Retrieve icon before the Map is ready.

@override
void initState() {
    BitmapDescriptor.fromAssetImage(
        ImageConfiguration(size: Size(48, 48)), 'assets/my_icon.png')
        .then((onValue) {
      myIcon = onValue;
    });
 }

set the Icon:

icon: myIcon;

Make sure you have set the icon in Flutter section of pubspec.yaml

 assets:
    - assets/my_icon.png


问:
Adding OverlayEntry in Flutter
I am trying to insert a Container to the Overlay, but I had an error with this code.

```<code>class _MyHomePageState extends State<MyHomePage> {
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final entry = OverlayEntry(builder: (BuildContext overlayContext) {
      return Container(
        height: 50.0,
        width: 50.0,
        color: Colors.blue,
      );
    });
    _addOverlay(entry);
  }

  void _addOverlay(OverlayEntry entry) async {
    Overlay.of(context).insert(entry);
  }

  @override
  Widget build(BuildContext context) {
   return Scaffold(
      appBar: AppBar(
        title: Text('Flutter'),
      ),
      body: Center(),
    );
  }
}
</code>```

This is error

setState() or markNeedsBuild() called during build. This Overlay widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase...

Thank you in advance.

答:
Just share some of my findings. I am about to implement overlay in my app too. So found this SO question by searching.

Many people build overlay before the normal widget. For example, in your code, the overlay insert in didChangeDependencies is called before building the Scaffold. This is the cause of all the async problems. I found people do this (couple the overlay insert and corresponding normal widget in a stateful widget) is because they want to find the corresponding child widget's position, but the child widget is build after the overlay insert call, thus the overlay insert has to be in an async function.

But If you just call overlay insert after building the normal widget (make overlay insert call independent from building the base widget. Separate/decouple them), you won't need any async or Timer functions at all. In my current implementation, I separate them just to make the code safe (I feel it's safer). So no need for any async calls.

Title: Adding OverlayEntry in Flutter

Body:
I am trying to insert a Container to the Overlay, but I had an error with this code.

class _MyHomePageState extends State<MyHomePage> {
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final entry = OverlayEntry(builder: (BuildContext overlayContext) {
      return Container(
        height: 50.0,
        width: 50.0,
        color: Colors.blue,
      );
    });
    _addOverlay(entry);
  }

  void _addOverlay(OverlayEntry entry) async {
    Overlay.of(context).insert(entry);
  }

  @override
  Widget build(BuildContext context) {
   return Scaffold(
      appBar: AppBar(
        title: Text('Flutter'),
      ),
      body: Center(),
    );
  }
}

This is error

setState() or markNeedsBuild() called during build. This Overlay widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase...

Thank you in advance.


问:
Remove color change after click in bootstrap button
```<code><button type="button" style="line-height: 0.4em;text-align: left;height:35px" class=" btn btn-success  btn-block">></button>
</code>```

After clicked the color of the button changes a little darker indicating that it has been clicked and the button will return to normal color when clicked the mouse in the page's body. I want to suppress this effect. I tried box-shadow:none and shadow-none as well but it didn't work.
How can I achieve this?

答:
You can use :active pseudo class on the button:

```<code>.button_class_name:active {
 background-color: red;
}
</code>```

Body:
<button type="button" style="line-height: 0.4em;text-align: left;height:35px" class=" btn btn-success  btn-block">></button>

After clicked the color of the button changes a little darker indicating that it has been clicked and the button will return to normal color when clicked the mouse in the page's body. I want to suppress this effect. I tried box-shadow:none and shadow-none as well but it didn't work.
How can I achieve this?

Body:
You can use :active pseudo class on the button:

.button_class_name:active {
 background-color: red;
}


问:
Converting sql result into Serializable JSON
I use python. I create a cloud function to return results from the search query connected with PostgreSQL.  I swear the sql is connect. When it comes to retuning fetch result  from the sql, it says the row object is not serialisable JSON . How should I convert this row results into json ?

Here is my code

```<code>def freebie(request):

  engine = create_engine('postgresql://ABC' , echo=True)

  conn = engine.connect()

  x_sql = sa.text('''
            SELECT user_label from "database"."user"
            WHERE "_id" = :userId
        ''')

  record = conn.execute(x_sql, userId = '82f3f82f-5bae-45d3-971f-b4af3a06182f',
            current_time = datetime.now(), ).fetchall()

  user_labbel = record[0][0]

  campaign_sql = sa.text('''
            SELECT * from "database"."user_fav_books"
            WHERE "user_label" = :campaign_id
        ''')

  result = conn.execute(campaign_sql, campaign_id = user_labbel,
            current_time = datetime.now(), ).fetchall()

  if len(result) == 0 :
    return "No result"
  else:
    return json.dump(result, indent=4 , check_circular=True)
</code>```

答:
You can convert each row in the result to a dict, then serialise as json.  Note you don't need to call fetchall on the connection result

```<code>result = conn.execute(campaign_sql, campaign_id = user_labbel,
          current_time = datetime.now(), )
dicts = [dict(row) for row in result]
j = json.dumps(dicts)
</code>```

Alternatively, as you are using Postgresql, you can use its JSON aggregation functions to build the data (the return value will be a list of dicts, and should be directly serialisable).

stmt = """\
SELECT json_agg(row_to_json(user_fav_books)) AS data
  FROM user_fav_books
  WHERE user_label = :campaign_id
"""
campaign_id = random.choice(labels)

with engine.connect() as conn:
    result = conn.execute(sa.text(stmt), {'campaign_id': campaign_id}).scalar_one()
```

Body:
I use python. I create a cloud function to return results from the search query connected with PostgreSQL.  I swear the sql is connect. When it comes to retuning fetch result  from the sql, it says the row object is not serialisable JSON . How should I convert this row results into json ?

Here is my code

def freebie(request):

  engine = create_engine('postgresql://ABC' , echo=True)

  conn = engine.connect()

  x_sql = sa.text('''
            SELECT user_label from "database"."user"
            WHERE "_id" = :userId
        ''')

  record = conn.execute(x_sql, userId = '82f3f82f-5bae-45d3-971f-b4af3a06182f',
            current_time = datetime.now(), ).fetchall()

  user_labbel = record[0][0]

  campaign_sql = sa.text('''
            SELECT * from "database"."user_fav_books"
            WHERE "user_label" = :campaign_id
        ''')

  result = conn.execute(campaign_sql, campaign_id = user_labbel,
            current_time = datetime.now(), ).fetchall()

  if len(result) == 0 :
    return "No result"
  else:
    return json.dump(result, indent=4 , check_circular=True)

Body:
You can convert each row in the result to a dict, then serialise as json.  Note you don't need to call fetchall on the connection result

result = conn.execute(campaign_sql, campaign_id = user_labbel,
          current_time = datetime.now(), )
dicts = [dict(row) for row in result]
j = json.dumps(dicts)

Alternatively, as you are using Postgresql, you can use its JSON aggregation functions to build the data (the return value will be a list of dicts, and should be directly serialisable).

stmt = """\
SELECT json_agg(row_to_json(user_fav_books)) AS data
  FROM user_fav_books
  WHERE user_label = :campaign_id
"""
campaign_id = random.choice(labels)

with engine.connect() as conn:
    result = conn.execute(sa.text(stmt), {'campaign_id': campaign_id}).scalar_one()


问:
PHP array sort with forced the first row
How to sort an array at PHP to force selected row as a first ?

My array is

```<code>array[]=array(id=>'a', content=>'lemon');
array[]=array(id=>'b', content=>'apple');
array[]=array(id=>'c', content=>'banana');
array[]=array(id=>'d', content=>'cherry');
</code>```

How to sort the array to force

```<code>array[]=array(id=>'b', content=>'apple');
</code>```

as a first row and doesn't matter the rest (apple is the key).

And in other example turn sort to get

```<code>array[]=array(id=>'d', content=>'cherry');
</code>```

as a first row and doesn't matter the rest (cherry is the key).

答:
One other option - if id:content is one to one, we can index the array by content and merge with an array with a single empty "apple" key (or whichever content value you're looking for).

```<code>$array = array_merge(['apple' => []], array_column($array, null, 'content'));
</code>```

If the resulting string keys are undesirable the array can be reindexed with array_values.

If the array only contains id and content and id:content is in fact one to one, a "dictionary" of key-value pairs will be handier to deal with than a list of rows like this and it would probably be better to set the array up that way to begin with if possible.

If id:content is not one to one, then... never mind. ;-)

Body:
How to sort an array at PHP to force selected row as a first ?

My array is

array[]=array(id=>'a', content=>'lemon');
array[]=array(id=>'b', content=>'apple');
array[]=array(id=>'c', content=>'banana');
array[]=array(id=>'d', content=>'cherry');

How to sort the array to force

array[]=array(id=>'b', content=>'apple');

as a first row and doesn't matter the rest (apple is the key).

And in other example turn sort to get

array[]=array(id=>'d', content=>'cherry');

as a first row and doesn't matter the rest (cherry is the key).

Body:
One other option - if id:content is one to one, we can index the array by content and merge with an array with a single empty "apple" key (or whichever content value you're looking for).

$array = array_merge(['apple' => []], array_column($array, null, 'content'));

If the resulting string keys are undesirable the array can be reindexed with array_values.

If the array only contains id and content and id:content is in fact one to one, a "dictionary" of key-value pairs will be handier to deal with than a list of rows like this and it would probably be better to set the array up that way to begin with if possible.

If id:content is not one to one, then... never mind. ;-)


问:
Jodatime start of day and end of day
I want to create an interval between the beginning of the week, and the end of the current week.

I have the following code, borrowed from this answer:

```<code>private LocalDateTime calcNextSunday(LocalDateTime d) {
    if (d.getDayOfWeek() > DateTimeConstants.SUNDAY) {
        d = d.plusWeeks(1);
    }
    return d.withDayOfWeek(DateTimeConstants.SUNDAY);
}

private LocalDateTime calcPreviousMonday(LocalDateTime d) {
    if (d.getDayOfWeek() < DateTimeConstants.MONDAY) {
        d = d.minusWeeks(1);
    }
    return d.withDayOfWeek(DateTimeConstants.MONDAY);
}
</code>```

But now I want the Monday LocalDateTime to  be at 00:00:00, and the Sunday LocalDateTime at 23:59:59. How would I do this?

答:
```<code>begin = d
    // Go to previous or same Sunday
    .with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY))
    // Beginning of day
    .truncatedTo(ChronoUnit.DAYS)

end = d
    // Go to next Sunday
    .with(TemporalAdjusters.next(DayOfWeek.SUNDAY))
    // Beginning of day
    .truncatedTo(ChronoUnit.DAYS)
</code>```

I also think it is a bad idea to represent the end of week interval with small amount of time before the actual, exclusive end. It is better to treat begin as inclusive, and end as exclusive instead (when doing comparisons etc.).

ContentLicense: CC BY-SA 3.0

Title: Jodatime start of day and end of day

Body:
I want to create an interval between the beginning of the week, and the end of the current week.

I have the following code, borrowed from this answer:

private LocalDateTime calcNextSunday(LocalDateTime d) {
    if (d.getDayOfWeek() > DateTimeConstants.SUNDAY) {
        d = d.plusWeeks(1);
    }
    return d.withDayOfWeek(DateTimeConstants.SUNDAY);
}

private LocalDateTime calcPreviousMonday(LocalDateTime d) {
    if (d.getDayOfWeek() < DateTimeConstants.MONDAY) {
        d = d.minusWeeks(1);
    }
    return d.withDayOfWeek(DateTimeConstants.MONDAY);
}

But now I want the Monday LocalDateTime to  be at 00:00:00, and the Sunday LocalDateTime at 23:59:59. How would I do this?

Body:
begin = d
    // Go to previous or same Sunday
    .with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY))
    // Beginning of day
    .truncatedTo(ChronoUnit.DAYS)

end = d
    // Go to next Sunday
    .with(TemporalAdjusters.next(DayOfWeek.SUNDAY))
    // Beginning of day
    .truncatedTo(ChronoUnit.DAYS)

I also think it is a bad idea to represent the end of week interval with small amount of time before the actual, exclusive end. It is better to treat begin as inclusive, and end as exclusive instead (when doing comparisons etc.).


问:
I want to copy the $friendname=$_POST['friendname']; value to the next page when if statement works and echo there
I want to copy friendname from this page  to the next page and echo there .
the problem is that it is showinh undefined vairable .
The goal is to echo the same friendname value to the next page i.e form2.php and echo there

```<code><?php

    include("config.php");
    session_start();
    $user=$_POST['username'];//username
    $friendname=$_POST['friendname'];//friendname
    $years=$_POST['years'];
    $nickname=$_POST['nickname'];
    $place=$_POST['place'];//username

    $sql = "INSERT INTO data (username,friendname,years,nickname,place)
                VALUES ('$user', '$friendname', '$years','$nickname','$place')";

    if ($con->query($sql) === TRUE) {
        $_POST['friendname']=$frnd;//username
        header('location: ../form2.php');
    } else {
        echo "Error: " . $sql . "<br>" . $con->error;
    }
    $con->close();
?>
</code>```

this is what i have tried but not working
insert.php

```<code><?php

    include("config.php");
    session_start();
    $user=$_POST['username'];//username
    $friendname=$_POST['friendname'];//friendname
    $years=$_POST['years']
    $nickname=$_POST['nickname'];
    $place=$_POST['place'];

    $sql = "INSERT INTO data (username,friendname,years,nickname,place)
            VALUES ('$user', '$friendname', '$years','$nickname','$place')";

    if ($con->query($sql) === TRUE) {
        $_POST['friendname']=$frnd;//username
        header('location: ../form2.php');
    } else {
        echo "Error: " . $sql . "<br>" . $con->error;
    }
    $con->close();
?>
</code>```

form2.php

```<code><?php
    session_start();
    if (!isset($_SESSION['username'])) {

    }
    if (isset($_GET['logout'])) {

    }
?>

<html>
    <body>
        <p><?php echo $_SESSION['username']; ?></p>
        <h4>Enter some details for your friend <?php echo $frnd;?></h4>
        <form>
        </form>
    </body>
</html>
</code>```

NOtice:undefined index variable frnd on line number

答:
file2.php

```<code><?php
session_start();
$frnd = $_SESSION['friendname'];

?>

<html>
    <body>
        <p><?php echo $_SESSION['username']; ?></p>
        <h4>Enter some details for your friend <?php echo $frnd;?></h4>
        <form>
        </form>
    </body>
</html>
</code>```

Body:
I want to copy friendname from this page  to the next page and echo there .
the problem is that it is showinh undefined vairable .
The goal is to echo the same friendname value to the next page i.e form2.php and echo there

<?php

    include("config.php");
    session_start();
    $user=$_POST['username'];//username
    $friendname=$_POST['friendname'];//friendname
    $years=$_POST['years'];
    $nickname=$_POST['nickname'];
    $place=$_POST['place'];//username

    $sql = "INSERT INTO data (username,friendname,years,nickname,place)
                VALUES ('$user', '$friendname', '$years','$nickname','$place')";

    if ($con->query($sql) === TRUE) {
        $_POST['friendname']=$frnd;//username
        header('location: ../form2.php');
    } else {
        echo "Error: " . $sql . "
" . $con->error;
    }
    $con->close();
?>

this is what i have tried but not working
insert.php

<?php

    include("config.php");
    session_start();
    $user=$_POST['username'];//username
    $friendname=$_POST['friendname'];//friendname
    $years=$_POST['years']
    $nickname=$_POST['nickname'];
    $place=$_POST['place'];

    $sql = "INSERT INTO data (username,friendname,years,nickname,place)
            VALUES ('$user', '$friendname', '$years','$nickname','$place')";

    if ($con->query($sql) === TRUE) {
        $_POST['friendname']=$frnd;//username
        header('location: ../form2.php');
    } else {
        echo "Error: " . $sql . "
" . $con->error;
    }
    $con->close();
?>

form2.php

<?php
    session_start();
    if (!isset($_SESSION['username'])) {

    }
    if (isset($_GET['logout'])) {

    }
?>

<?php echo $_SESSION['username']; ?>

Enter some details for your friend <?php echo $frnd;?>

        <form>
        </form>

NOtice:undefined index variable frnd on line number

Body:
file2.php

<?php
session_start();
$frnd = $_SESSION['friendname'];

?>

<html>
    <body>
        <p><?php echo $_SESSION['username']; ?></p>
        <h4>Enter some details for your friend <?php echo $frnd;?></h4>
        <form>
        </form>
    </body>
</html>


问:
Ensuring template argument type matches that of its variadic constructor
I would like to have a class like this:

```<code>template<typename T>
struct Foo {
    T* data_;

    template<typename... Ts, std::enable_if<std::is_same<T,Ts>...>...>
    explicit Foo(Ts...ts) : data_{ ts... } {}
};
</code>```

However; something with the syntax is wrong, and I'm not sure if you can set parameters into a pointer directly like this upon initialization.

What I would like for this to do is simply this:

```<code>Foo<int> f1{ 1, 3, 5, 7 }; // Or
// Foo<int> f1( 1, 3, 5 7 );
// f1.data_[0] = 1
// f1.data_[1] = 3
// f1.data_[2] = 5
// f1.data_[3] = 7
// f1.data_[4] = ... not our memory either garbage or undefined...

Foo<float> f2{ 3.5f, 7.2f, 9.8f }; // Or
// Foo<float> f2( 3.5f, 7.2f, 9.8f );
// f2.data_[0] = 3.5
// f2.data_[1] = 7.2
// f2.data_[2] = 9.8
// f2.data_[3] = ... not our memory
</code>```

I would also like to have the constructor check to make sure that each and every parameter that is passed into the constructor is of type <T>; simply put for each Ts it must be a T.

I might be overthinking this but for the life of me I can not get this or something similar to compile. I don't know if it's within enable_if, is_same or through the class's initializer list and trying to store the contents into a pointer. I don't know if I should use an array of T instead but the array's size won't be known until the arguments are passed into the constructor. I'm also trying to do this without using a basic container such as std::vector; it's more for self education than practical source code. I just want to see how this could be done with raw pointers.

Edit

I've changed my class to something like this:

```<code>template<typename T>
struct Foo {
    T* data_;

    template<typename... Ts, std::enable_if_t<std::is_same<T, Ts...>::value>* = nullptr>
    explicit Foo( const Ts&&... ts ) : data_{ std::move(ts)... } {}
 };
</code>```

And when trying to use it:

```<code> int a = 1, b = 3, c = 5, d = 7;
 Foo<int> f1( a, b, c, d );
 Foo<int> f2{ a, b, c, d };
</code>```

I'm a little closer with this iteration; but they both give different compiler errors.

The first being: C2661: "No overloaded function takes 4 arguments"

And the second:  C2440: "initializing, cannot convert from initializer list to Container, no constructor could take the source type, or constructor overload resolution was ambiguous."

答:
std::is_same only compares two types, and you can't use pack expansions to declare multiple template parameters.  That means you'll need to pull all of your std::is_same checks out into another check:

```<code>template <typename T, typename... Ts>
struct all_same : std::bool_constant<(std::is_same<T, Ts>::value && ...)> {};

template <typename T>
struct Foo
{
    std::vector<T> data_;

    template <typename... Ts, std::enable_if_t<all_same<T, std::decay_t<Ts>...>::value>* = nullptr>
    Foo(Ts&&... ts)
        : data_{std::forward<Ts>(ts)...}
    {
    }
};
</code>```

Live Demo

You also need to allocate memory for your data_ array.  Here I've used std::vector to take care of that allocation for me, but you could use new[] and delete[] to manage it yourself if you really want to.

Body:
I would like to have a class like this:

template<typename T>
struct Foo {
    T* data_;

    template<typename... Ts, std::enable_if<std::is_same<T,Ts>...>...>
    explicit Foo(Ts...ts) : data_{ ts... } {}
};

However; something with the syntax is wrong, and I'm not sure if you can set parameters into a pointer directly like this upon initialization.

What I would like for this to do is simply this:

Foo<int> f1{ 1, 3, 5, 7 }; // Or
// Foo<int> f1( 1, 3, 5 7 );
// f1.data_[0] = 1
// f1.data_[1] = 3
// f1.data_[2] = 5
// f1.data_[3] = 7
// f1.data_[4] = ... not our memory either garbage or undefined...

Foo<float> f2{ 3.5f, 7.2f, 9.8f }; // Or
// Foo<float> f2( 3.5f, 7.2f, 9.8f );
// f2.data_[0] = 3.5
// f2.data_[1] = 7.2
// f2.data_[2] = 9.8
// f2.data_[3] = ... not our memory

I would also like to have the constructor check to make sure that each and every parameter that is passed into the constructor is of type <T>; simply put for each Ts it must be a T.

I might be overthinking this but for the life of me I can not get this or something similar to compile. I don't know if it's within enable_if, is_same or through the class's initializer list and trying to store the contents into a pointer. I don't know if I should use an array of T instead but the array's size won't be known until the arguments are passed into the constructor. I'm also trying to do this without using a basic container such as std::vector; it's more for self education than practical source code. I just want to see how this could be done with raw pointers.

Edit

I've changed my class to something like this:

template<typename T>
struct Foo {
    T* data_;

    template<typename... Ts, std::enable_if_t<std::is_same<T, Ts...>::value>* = nullptr>
    explicit Foo( const Ts&&... ts ) : data_{ std::move(ts)... } {}
 };

And when trying to use it:

 int a = 1, b = 3, c = 5, d = 7;
 Foo<int> f1( a, b, c, d );
 Foo<int> f2{ a, b, c, d };

I'm a little closer with this iteration; but they both give different compiler errors.

The first being: C2661: "No overloaded function takes 4 arguments"

And the second:  C2440: "initializing, cannot convert from initializer list to Container, no constructor could take the source type, or constructor overload resolution was ambiguous."

Body:
std::is_same only compares two types, and you can't use pack expansions to declare multiple template parameters.  That means you'll need to pull all of your std::is_same checks out into another check:

template <typename T, typename... Ts>
struct all_same : std::bool_constant<(std::is_same<T, Ts>::value && ...)> {};

template <typename T>
struct Foo
{
    std::vector<T> data_;

    template <typename... Ts, std::enable_if_t<all_same<T, std::decay_t<Ts>...>::value>* = nullptr>
    Foo(Ts&&... ts)
        : data_{std::forward<Ts>(ts)...}
    {
    }
};

Live Demo

You also need to allocate memory for your data_ array.  Here I've used std::vector to take care of that allocation for me, but you could use new[] and delete[] to manage it yourself if you really want to.


问:
hive date cast issue
Hi in my Hive table I have a column with the date values like this .

```<code>cl1
31102019000000
30112019000000
31122019000000
</code>```

I have tried to convert the column values to date format like this

```<code>Select from_unixtime(unix_timestamp(cl1,'yyyy/MM/dd'),'yyyy-MM-dd') from table1;
</code>```

it prints NUll. Any help will be appreciated.

答:
You said you have dates in dd-mm-yyyy but then posted data that doesn't have any hyphens in at all

Assuming 31102019000000 is 31-oct-2019 00:00:00

```<code>Select from_unixtime(unix_timestamp(cl1,'ddMMyyyyHHmmss'),'yyyy-MM-dd') from ...
</code>```

Match the format string to the data..

Title: hive date cast issue

Body:
Hi in my Hive table I have a column with the date values like this .

cl1
31102019000000
30112019000000
31122019000000

I have tried to convert the column values to date format like this

Select from_unixtime(unix_timestamp(cl1,'yyyy/MM/dd'),'yyyy-MM-dd') from table1;

it prints NUll. Any help will be appreciated.

Body:
You said you have dates in dd-mm-yyyy but then posted data that doesn't have any hyphens in at all

Assuming 31102019000000 is 31-oct-2019 00:00:00

Select from_unixtime(unix_timestamp(cl1,'ddMMyyyyHHmmss'),'yyyy-MM-dd') from ...

Match the format string to the data..


问:
Eliminate a public script from tradingview
I want to change or eliminate a public script from tradingview that I published, How can I do do this?.</p>

答:
Tradingview does not remove ideas and scripts after they are published. But you can delete your publication within 15 minutes. Otherwise, you can no longer delete it. FAQ

To update a script, simply click on the Publish Script button and select Update Existing Script and choose the script you want to update. After that you can publish a new version.


问:
How to know if text string is facebook url, email adress or other uri?
I'm creating a system to sign up for different events. For each event it stores an address which can be one of the following:

Facebook resource (basically URL starting with "facebook.com")

E-mail address (any valid e-mail)

Another URL

(bogus/thrash/etc)

The 4th is not important.

I need to do different things depending on the type of adress (FB API/send e-mail/POST a form). I was thinking about just storing what type it is but I first want to ask if there is some regexp or similar to know what type it is.

The first one is easy, just check if it starts with "http://www.facebook.com". For the others I thought about looking for tokens like "http://" or "@" but then I thought both can contain both of those.

答:
First, @zespri is correct in his comment - it's a much better design to store the actual type. Even if you use the regular expressions I suggest below, things could still break in the future.

But yes, it's possible to use regex in this case:

The following regex is the quintessential email detector. It's much safer to use than just an '@' sign:

```
([a-zA-Z]+[a-zA-Z0-9._+\-]{3,}(?:@|%40)[a-zA-Z0-9]+[a-zA-Z0-9\.\-]?(?:\.[a-zA-Z]+)+)
```

The following three find facebook profiles and pages.
You can get rid of the suffix to stay with just the facebook domain(s), or do some further research and edits to limit to other kinds of facebook resources:

```
facebook\.(?:com?\.|net\.)?[a-z]{2,3}/.+\?id=(\d+)
facebook\.(?:com?\.|net\.)?[a-z]{2,3}/p\.php.+i=(\d+)
facebook\.(?:com?\.|net\.)?[a-z]{2,3}/(\w[\w\.\-]+\w)(?:$|[/\?#])
```

Avoid the 'http://www.' prefix - you never know what subdomain may be used, plus they're often omitted.
Also note that there are more tld's to facebook than just the .com

For 'other' URLs, you could just look for the anchor ```^https?://```
It's unclear from your question whether users enter these into your system, or whether it's done in an uncontrolled manner. Note that people often omit the http prefix, so this isn't really a reliable way to detect URLs.

If you're looking for URLs as links within HTML pages they can be more reliably detected by searching for anchors:

```<code><a\s+(?:.*?)href=['"]?(https?://[^'^"^\s]+)(?:.*?)>
</code>```

Body:
First, @zespri is correct in his comment - it's a much better design to store the actual type. Even if you use the regular expressions I suggest below, things could still break in the future.

But yes, it's possible to use regex in this case:

The following regex is the quintessential email detector. It's much safer to use than just an '@' sign:

([a-zA-Z]+[a-zA-Z0-9._+\-]{3,}(?:@|%40)[a-zA-Z0-9]+[a-zA-Z0-9\.\-]?(?:\.[a-zA-Z]+)+)

The following three find facebook profiles and pages.
You can get rid of the suffix to stay with just the facebook domain(s), or do some further research and edits to limit to other kinds of facebook resources:

facebook\.(?:com?\.|net\.)?[a-z]{2,3}/.+\?id=(\d+)
facebook\.(?:com?\.|net\.)?[a-z]{2,3}/p\.php.+i=(\d+)
facebook\.(?:com?\.|net\.)?[a-z]{2,3}/(\w[\w\.\-]+\w)(?:$|[/\?#])

Avoid the 'http://www.' prefix - you never know what subdomain may be used, plus they're often omitted.
Also note that there are more tld's to facebook than just the .com

For 'other' URLs, you could just look for the anchor
^https?://

It's unclear from your question whether users enter these into your system, or whether it's done in an uncontrolled manner. Note that people often omit the http prefix, so this isn't really a reliable way to detect URLs.

If you're looking for URLs as links within HTML pages they can be more reliably detected by searching for anchors:

<a\s+(?:.*?)href=['"]?(https?://[^'^"^\s]+)(?:.*?)>


问:
The background image for my website gets out of proportion when viewed in phones and other small screen sizes
I'm having issues with re-sizing my background image in CSS to fit other smaller screens than the intended screen size of my laptop

I have already tried 'background-size: contain' and 'background-repeat : no-repeat'. still, the background image blew out of proportion. I have a set of parameters for the image, which is 'height: 100vh;'

```<code>/* with this, only a fraction of image is seen in phone */

header {
    background - image: -webkit - linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - image: linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - size: cover;
    height: 100 vh;
    background - position: center;
    background - repeat: no - repeat;
    background - attachment: fixed;
}

/* with this a grey background appears in phone screens */
header {
    background - image: -webkit - linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - image: linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - size: contain;
    height: 100 vh;

    background - position: center;
    background - repeat: no - repeat;
    background - attachment: fixed;
}
</code>```

I expect the image to fit all screen sizes without zooming in and blurring, but the results always blew out of proportion.

答:
Same problem was with my code ,i just add one line:

```<code>.your-class {
height: 100vh;
    }
</code>```

vh is viewport height. This will automatically scale to fit the device' browser window.

Check more here: How to make a div 100% height of the browser window?

Body:
I'm having issues with re-sizing my background image in CSS to fit other smaller screens than the intended screen size of my laptop

I have already tried 'background-size: contain' and 'background-repeat : no-repeat'. still, the background image blew out of proportion. I have a set of parameters for the image, which is 'height: 100vh;'

/* with this, only a fraction of image is seen in phone */

header {
    background - image: -webkit - linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - image: linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - size: cover;
    height: 100 vh;
    background - position: center;
    background - repeat: no - repeat;
    background - attachment: fixed;
}

/* with this a grey background appears in phone screens */
header {
    background - image: -webkit - linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - image: linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - size: contain;
    height: 100 vh;

    background - position: center;
    background - repeat: no - repeat;
    background - attachment: fixed;
}

I expect the image to fit all screen sizes without zooming in and blurring, but the results always blew out of proportion.

Body:
Same problem was with my code ,i just add one line:

.your-class {
height: 100vh;
    }

vh is viewport height. This will automatically scale to fit the device' browser window.

Check more here: How to make a div 100% height of the browser window?


问:
when console log of array object that been reverse and join that return a letter
I have an array with 2 object and when reverse and join this array and consoled log with first or second index , that return letter like 'j', 'b'

list = [{
    name: 'anne',
    age: 20,
    gender: 'F'
  },
  {
    name: 'david',
    age: 50,
    gender: 'M'
  },
  {
    name: 'mark',
    age: 33,
    gender: 'M'
  },
]

var val = this.list.slice().reverse().join('');

console.log('val ==> ', val[2]) // val ==>  b```

what is this b ?

答:
Because you're using join(""), that calls the toString method on every item in the array - they happen to be objects, and the toString method of an object returns [object Object]:

let obj = {};
console.log(obj.toString());```
</div>
</div>
</p>

<p>You can avoid this issue by mapping with <code>JSON.stringify</code> first.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var list = [{name:'anne',age:20,gender:'F'},{name:'david',age:50,gender:'M'},{name:'mark',age:33,gender:'M'}];
const res = this.list.slice().reverse().map(JSON.stringify).join('');
console.log("res[2] ===> ", res[2]); //Returns "n" because {"n are the first three characters in the string
console.log(res);</code>```

.as-console-wrapper { max-height: 100% !important; top: auto; }```
</div>
</div>
</p>

<p>Note that the above still returns a character. If you want to get an object, remove the <code>join</code> and <code>map</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var list = [{name:'anne',age:20,gender:'F'},{name:'david',age:50,gender:'M'},{name:'mark',age:33,gender:'M'}];
const res = this.list.slice().reverse();
console.log("res[2] ===> ", res[2]); //Returns "n" because {"n are the first three characters in the string
console.log(res);</code>```

.as-console-wrapper { max-height: 100% !important; top: auto; }```

Body:
I have an array with 2 object and when reverse and join this array and consoled log with first or second index , that return letter like 'j', 'b'

list = [{
    name: 'anne',
    age: 20,
    gender: 'F'
  },
  {
    name: 'david',
    age: 50,
    gender: 'M'
  },
  {
    name: 'mark',
    age: 33,
    gender: 'M'
  },
]

var val = this.list.slice().reverse().join('');

console.log('val ==> ', val[2]) // val ==>  b

what is this b ?

Body:
Because you're using join(""), that calls the toString method on every item in the array - they happen to be objects, and the toString method of an object returns [object Object]:

let obj = {};
console.log(obj.toString());

You can avoid this issue by mapping with JSON.stringify first.

var list = [{name:'anne',age:20,gender:'F'},{name:'david',age:50,gender:'M'},{name:'mark',age:33,gender:'M'}];
const res = this.list.slice().reverse().map(JSON.stringify).join('');
console.log("res[2] ===> ", res[2]); //Returns "n" because {"n are the first three characters in the string
console.log(res);

.as-console-wrapper { max-height: 100% !important; top: auto; }

Note that the above still returns a character. If you want to get an object, remove the join and map:

var list = [{name:'anne',age:20,gender:'F'},{name:'david',age:50,gender:'M'},{name:'mark',age:33,gender:'M'}];
const res = this.list.slice().reverse();
console.log("res[2] ===> ", res[2]); //Returns "n" because {"n are the first three characters in the string
console.log(res);

.as-console-wrapper { max-height: 100% !important; top: auto; }


问:
Calcite parse sql into parts for mult data source
In my case I'm querying data from multi data source(like csv+mysql) via a single sql. How can I distinguish the data source for tables and detect what columns are queried on tables by using Calcite? (Meta data of data source available)

Result that I required is something like:

 - TableA(col1, col2, col3)  -> Data source CSV

 - TableB(col1, colx, coly)  -> Data source Mysql

My case is something like what Apache Drill(uses Calcite) does, I tried read Drill source code but I cannot find the way how Drill decides the relations.

String sql = "select c.c1, m.c2 from csv.tbl as c, mysql.schema.tbl as m where c.id = m.id”;

Frameworks.ConfigBuilder configBuilder = Frameworks.newConfigBuilder();
configBuilder.defaultSchema(`my SchemaPlus here`);
FrameworkConfig frameworkConfig = configBuilder.build();
Planner planner = Frameworks.getPlanner(frameworkConfig);

SqlNode sqlNode = planner.parse(sql);
planner.validate(sqlNode);
RelRoot relRoot = planner.rel(sqlNode);
```

This is what now I have, but it seems nothing I wanted there ~_~|||

thannks a lot.

答:
If your questions is whether Calcite can automatically decipher what columns you're using if you don't put that information in your SQL query, it can't. It will assume you're using your default schema and try to map it there. If you're using multiple schemas, it's stupid (not in the bad way) and you have to tell it what to do. You have to write your SQL query so that it contains that information, just like you did.

If you want to extract that information, you have to do it using RelVisitor, like I did in my master thesis. You can find the code here and the related issue here

Body:
In my case I'm querying data from multi data source(like csv+mysql) via a single sql. How can I distinguish the data source for tables and detect what columns are queried on tables by using Calcite? (Meta data of data source available)

Result that I required is something like:

 - TableA(col1, col2, col3)  -> Data source CSV

 - TableB(col1, colx, coly)  -> Data source Mysql

My case is something like what Apache Drill(uses Calcite) does, I tried read Drill source code but I cannot find the way how Drill decides the relations.

String sql = "select c.c1, m.c2 from csv.tbl as c, mysql.schema.tbl as m where c.id = m.id”;

Frameworks.ConfigBuilder configBuilder = Frameworks.newConfigBuilder();
configBuilder.defaultSchema(`my SchemaPlus here`);
FrameworkConfig frameworkConfig = configBuilder.build();
Planner planner = Frameworks.getPlanner(frameworkConfig);

SqlNode sqlNode = planner.parse(sql);
planner.validate(sqlNode);
RelRoot relRoot = planner.rel(sqlNode);

This is what now I have, but it seems nothing I wanted there ~_~|||

thannks a lot.


问:
How do I programmatically set the position of an SKNode within an ARSKView scene?
I have an ARSKView scene containing some SKLabelNode items. The result can be seen here: https://sendvid.com/35ded50d

I want to write some code that loops over all of the nodes 60 times per second and updates their position. I don't want to use SKAction to move the nodes over time, I just want to set their 3D position to a specific value. How do I do this?

Some related questions:

Move SKSpriteNode by Y - Swift 2 + SpriteKit

How do I programmatically move an ARAnchor?

But these questions don't seem to give a clear, simple answer to "How do I update the 3D position of an SKNode programmatically 60 times per second?"

Note that setting the .position property doesn't seem to work. It doesn't do anything.

答:
Destroy and re-create the ARAnchor associated with an SKNode. Set the new ARAnchor to the position you want to move the node to.

Note that you do not need to remove or recreate the SKNode itself. Just return the already-existing SKNode in the ARSKViewDelegate.


问:
Need help Centering some Content
I have two boxes set up and i wanted to put some buttons and text in the middle but when ever I try to add text there it makes the far right box go down one. I want them to stay aligned.

I tried adding another  between the 2 boxes but this did not work. im new at html so im not sure how to format this.

    <!Doctype html>

        <title> Basic Clicker</title>
        <link rel="stylesheet" href="css/style.css" />

Home

SkillTree

Equipment

Pets

Skills

Quests

                <title>HTML div</title>

                                              Inventory

                    Bronze: 0

                    Silver: 0

                    Gold: 0

                    Diamond: 0

                                                 Skills

                    Strength: Lv 1 0 / 100

                    Magic: Lv 1 0 / 100

                        <button onclick="Magicexp()">Click Me!</button>

    ```

I expect the buttons / words I want to put in the middle of these 2 boxes to not upset the alignment. But my actual output is words and buttons move the far right box down.

答:
I added a flexbox to your code. I hope this was helpful.

<title> Basic Clicker</title>
<link rel="stylesheet" href="css/style.css" />

Inventory

Bronze: 0

Silver: 0

Gold: 0

Diamond: 0

Skills

Strength: Lv 1 0 / 100

Magic: Lv 1 0 / 100

              <button onclick="Magicexp()">Click Me!</button>

content

```

If you have any questions, go ahead!

Title: Need help Centering some Content

Body:
I have two boxes set up and i wanted to put some buttons and text in the middle but when ever I try to add text there it makes the far right box go down one. I want them to stay aligned.

I tried adding another  between the 2 boxes but this did not work. im new at html so im not sure how to format this.

    <!Doctype html>

        <title> Basic Clicker</title>
        <link rel="stylesheet" href="css/style.css" />

Home

SkillTree

Equipment

Pets

Skills

Quests

                <title>HTML div</title>

                                              Inventory

                    Bronze: 0

                    Silver: 0

                    Gold: 0

                    Diamond: 0

                                                 Skills

                    Strength: Lv 1 0 / 100

                    Magic: Lv 1 0 / 100

                        <button onclick="Magicexp()">Click Me!</button>

I expect the buttons / words I want to put in the middle of these 2 boxes to not upset the alignment. But my actual output is words and buttons move the far right box down.

Body:
I added a flexbox to your code. I hope this was helpful.

<html>
<head>
<title> Basic Clicker</title>
<link rel="stylesheet" href="css/style.css" />
<style>
.flex-container {
    display: flex;
    align-items: stretch;
}

.flex-container>div {
    width: 600px; /*change the max columb width*/
    background-color: #f1f1f1;
    border: 15px solid green;
    background:white;
    margin: 10px;
    text-align: center;
    font-size: 15px;
}
</style>
</head>
<body>
    <div class="main_container">
        <div class="flex-container">
            <div style="order: 1">
              <p><b>Inventory</b></p>
              <p>Bronze: <span id="Bronze">0</span></p>
              <p>Silver: <span id="Bronze">0</span></p>
              <p>Gold: <span id="Bronze">0</span></p>
              <p>Diamond: <span id="Bronze">0</span></p>
            </div>
            <div style="order: 3">
              <p><b>Skills</b></p>
              <p>Strength: Lv <span id="Strengthlv">1</span> <span id="StrengthCexp">0</span> / <span id="StrengthMexp">100</span><p/>
              <p>Magic: Lv <span id="Magiclv">1</span> <span
id="MagicCexp">0</span> / <span id="MagicMexp">100</span></p>
              <button onclick="Magicexp()">Click Me!</button>
            </div>
            <div style="order: 2">
              <h1>content</h1>
            </div>
            <!-- You can add more div's here, if you want -->
        </div>
    </div>
</body>
</html>

If you have any questions, go ahead!


问:
How to delete digits-only lines from a text file?
Let's say I have a text file which contains both alphanumerical values and only numerical values of length 10 digits line by line, like the one shown below:

```<code>abcdefgh
0123456789
edf6543jewjew
9876543219
</code>```

I want to delete all the lines which contains only those random 10 digit numbers, i.e. expected output for the above example is the following:

```<code>abcdefgh
edf6543jewjew
</code>```

How can one do this in Python 3.x?

答:
```<code>with open("yourTextFile.txt", "r") as f:
    lines = f.readlines()
with open("yourTextFile.txt", "w") as f:
    for line in lines:
        if not line.strip('\n').isnumeric():
            f.write(line)
        elif len(line.strip('\n')) != 10:
            f.write(line)
</code>```

Body:
Let's say I have a text file which contains both alphanumerical values and only numerical values of length 10 digits line by line, like the one shown below:

abcdefgh
0123456789
edf6543jewjew
9876543219

I want to delete all the lines which contains only those random 10 digit numbers, i.e. expected output for the above example is the following:

abcdefgh
edf6543jewjew

How can one do this in Python 3.x?


答:
The sql is wide open to sql injection in the above code - you ought to consider using prepared statements as, once mastered, will make life much simpler and your code safer.

The below is not tested but essentially works as follows:

The POST request data is filtered - though this is not strictly necessary when using a prepared statement is, IMO, always a good idea.

The sql is prepared for execution and the ? placeholders in the sql are bound to variables.

```<code><?php

    session_start();
    include 'config.php';

    $user=filter_input( INPUT_POST, 'username', FILTER_SANITIZE_STRING );
    $name=filter_input( INPUT_POST, 'friendname', FILTER_SANITIZE_STRING );
    $years=filter_input( INPUT_POST, 'years', FILTER_SANITIZE_NUMBER_INT );
    $nick=filter_input( INPUT_POST, 'nickname', FILTER_SANITIZE_STRING );
    $place=filter_input( INPUT_POST, 'place', FILTER_SANITIZE_STRING );

    $sql='insert into `data` (`username`,`friendname`,`years`,`nickname`,`place`) values (?,?,?,?,?)';
    $stmt=$con->prepare( $sql );

    if( !$stmt )exit('Failed to prepare SQL query');
    $stmt->bind_param('ssiss',$user,$name,$years,$nick,$place);

    $res=$stmt->execute();

    if( $res && $con->affected_rows==1 ){
        $_SESSION['friendname']=$name;
        $_SESSION['username']=$user;
        exit( header('Location: ../form2.php') );
    } else {
        exit('Error');
    }
?>
</code>```

Then your HTML can be modified like this to assign the session variable to a variable - thogh again not strictly necessary to do that

```<code><?php
    session_start();
    $friend = $_SESSION['friendname'];
?>

<html>
    <body>
        <form>
            <p><?php echo $_SESSION['username']; ?></p>
            <h4>Enter some details for your friend <?php echo $friend;?></h4>
        </form>
    </body>
</html>
</code>```

Title: I want to copy the $friendname=$_POST['friendname']; value to the next page when if statement works and echo there

Body:
The sql is wide open to sql injection in the above code - you ought to consider using prepared statements as, once mastered, will make life much simpler and your code safer.

The below is not tested but essentially works as follows:

The POST request data is filtered - though this is not strictly necessary when using a prepared statement is, IMO, always a good idea.

The sql is prepared for execution and the ? placeholders in the sql are bound to variables.

<?php

    session_start();
    include 'config.php';

    $user=filter_input( INPUT_POST, 'username', FILTER_SANITIZE_STRING );
    $name=filter_input( INPUT_POST, 'friendname', FILTER_SANITIZE_STRING );
    $years=filter_input( INPUT_POST, 'years', FILTER_SANITIZE_NUMBER_INT );
    $nick=filter_input( INPUT_POST, 'nickname', FILTER_SANITIZE_STRING );
    $place=filter_input( INPUT_POST, 'place', FILTER_SANITIZE_STRING );

    $sql='insert into `data` (`username`,`friendname`,`years`,`nickname`,`place`) values (?,?,?,?,?)';
    $stmt=$con->prepare( $sql );

    if( !$stmt )exit('Failed to prepare SQL query');
    $stmt->bind_param('ssiss',$user,$name,$years,$nick,$place);

    $res=$stmt->execute();

    if( $res && $con->affected_rows==1 ){
        $_SESSION['friendname']=$name;
        $_SESSION['username']=$user;
        exit( header('Location: ../form2.php') );
    } else {
        exit('Error');
    }
?>

Then your HTML can be modified like this to assign the session variable to a variable - thogh again not strictly necessary to do that

<?php
    session_start();
    $friend = $_SESSION['friendname'];
?>

<html>
    <body>
        <form>
            <p><?php echo $_SESSION['username']; ?></p>
            <h4>Enter some details for your friend <?php echo $friend;?></h4>
        </form>
    </body>
</html>


问:
exact difference between "name" and "value" attribute in input tag
I know that it might be so easy
but I cant understand the exact difference between name and value attributes in an input tag (html).
what do they do?!</p>

答:
Value = The value attribute specifies the value of an  element.

Name = name is only to post form data. The name definies what the name of the attribute will be as soon as the form is submitted. So if you want to read this attribute later you will find it under the "name" in the POST or GET Request. Whereas the id is used to adress a field or element in javascript or css.


问:
Can Loadrunner with Amazon Load Generators test a site that is not publicly accessible?
I'm a web developer and completely new to Loadrunner suite.

Our client has already provided us with some Loadrunner actions, that I need to run them to test a site that is hosted on the company's intranet that I'm currently working.

The computer I'm using can not handle more than 7 vusers, therefore I was requested to use Amazon EC2 for load generators.

Before I request my company to be charged with Amazon services I need to know, would I be able to test our internal page from my computer exactly as I do with the load generator on my localhost, or the page that will be tested needs to be publicly accessible from the internet?

Any feedback will be appreciated. Thanks.

答:
Please read carefully what James wrote. You said you are a web developer so the task that was given to you is roughly equivalent to "write a new DB access layer".

You didn't mention which protocol you are using but I will assume TruClient (based on the 7 vUsers per machine). I will also assume you are using the latest version of LoadRunner or at least something from the 12.6X family.

1) You already have a solution for AWS out of the box in the form of StormRunner (https://www.microfocus.com/en-us/products/stormrunner-load-agile-cloud-testing/overview). If you want to test if the solution works for you please request a couple of execution hours from the sales team and try it. If your company has a valid license for LoadRunner I don't think this will be an issue.

2) You have a simple integration into the controller application for EC2 and alike. In the controller go to Tools->Manage cloud accounts. If you run a small test the cost should not be too great I assume.

3) If you are a developer, we have a new offering called TruWeb which is a transport level protocol which should be more developer friendly. It will be able to run much more users per machine so you will be able to use it to test on EC2 micro machine (free tier). The caveat is that you will have to write some JavaScript code and not be able to reuse the actions given to you. You can download TruWeb from here - https://marketplace.microfocus.com/appdelivery/content/truweb and it comes with the LoadRunner installation out of the box since 12.58. If you need further assistance with TruWeb feel free to email us to - truweb_forum@microfocus.com

I hope this will give you some directions.


问:
How do I specify an absolute path?
I wrote this code, but I couldn't get the html. I don't know why. I want to know why this is when the route is not wrong.</p>

```<code><img id = "navLogo" src = "C:/Bitnami/wampstack-7.1.27-0/apache2/htdocs/TermProject/imgs/navLogo.jpg"></img>
</code>```

答: I believe the source you specify should have path starting from folder where your html is located. So, try something like this "/imgs/navLogo.jpg".

Title: How do I specify an absolute path?


问:
Kafka consumer group does not exist while trying to retrieve detail about group
I'm trying to describe the kafka consumer group via the below command in terminal:

```<code>./kafka-consumer-groups.sh --bootstrap-server $IP:$PORT --describe --group $GROUPID
</code>```

I'm able to get the $GROUPID via this command:

```<code>./kafka-consumer-groups.sh --bootstrap-server $IP:$PORT --list
</code>```

and the response is:

```<code>b'TestProcess'
</code>```

But after trying to get the detail about this group via this command:

```<code>./kafka-consumer-groups.sh --bootstrap-server $IP:$PORT --describe --group TestProcess
</code>```

this result will come up:

```<code>Error: Consumer group 'TestProcess' does not exist.
</code>```

Kafka Version: 2.2.0

答:
It looks like your consumer group is named literally b'TestProcess', so try issuing describe command like this:

```<code>./kafka-consumer-groups.sh --bootstrap-server $IP:$PORT --describe --group "b'TestProcess'"
</code>```

Body:
I'm trying to describe the kafka consumer group via the below command in terminal:

./kafka-consumer-groups.sh --bootstrap-server $IP:$PORT --describe --group $GROUPID

I'm able to get the $GROUPID via this command:

./kafka-consumer-groups.sh --bootstrap-server $IP:$PORT --list

and the response is:

b'TestProcess'

But after trying to get the detail about this group via this command:

./kafka-consumer-groups.sh --bootstrap-server $IP:$PORT --describe --group TestProcess

this result will come up:

Error: Consumer group 'TestProcess' does not exist.

Kafka Version: 2.2.0

Body:
It looks like your consumer group is named literally b'TestProcess', so try issuing describe command like this:

./kafka-consumer-groups.sh --bootstrap-server $IP:$PORT --describe --group "b'TestProcess'"


问:
settings bundle - default value behaviour?
I have created a settings bundle with a single preference value, a text field with a default value.

When my application launches and I retrieve the value it is null. Do I have to manually code the value to use before the user has provided a value?

Also if the user does to the preferences screen and enters the text field then leave it without making any changes the value will not be set ... the user has to actually change the value for it to be saved, is this correct?

答: You can check in your app if you are getting null for key then you can use your own default value.</p>


答:
value is used to get the value of the input in the same page in Javascript

name is used for a reference to the input to pass values to another page, for example when you pass a form with
<input value="some_value" name="input_name"> to a PHP page as GET/POST data, the input is accessed with $_POST['input_name']

Title: exact difference between "name" and "value" attribute in input tag

Body:
I know that it might be so easy
but I cant understand the exact difference between name and value attributes in an input tag (html).
what do they do?!


答:
Here is an example of reformatting the data using code:

First I imported the data into an access table:

Then I looped through the table using vba:

```<code>
Public Sub ReformatData()
'declarations
'Dim rstData2 As DAO.Recordset
'Set rstData2 = CurrentDb.OpenRecordset("tblData2", dbOpenTable)
Dim rstData As DAO.Recordset
Dim currentMeter_Number As Long
Dim counter As Integer
Dim recordstring As String
Set rstData = CurrentDb.OpenRecordset("tblData", dbOpenTable)
'loop through table
If Not rstData.EOF Then
rstData.MoveFirst
Do While Not rstData.EOF
counter = 1
'process first Meter_Number in set
currentMeter_Number = rstData!Meter_Number
recordstring = recordstring & currentMeter_Number & ",#1," & rstData!DateRead & "," & _
Format(rstData!TimeRead, "hh:mm:ss") & "," & rstData!Kwh
rstData.MoveNext
    'process the rest of set
    Do While Not rstData.EOF
    If Not currentMeter_Number = rstData!Meter_Number Then
    Exit Do
    Else
        If Not IsNull(rstData!Meter_Number) Then
        If currentMeter_Number = rstData!Meter_Number Then
        counter = counter + 1
        recordstring = recordstring & ",#" & counter & "," & rstData!DateRead & "," & _
        Format(rstData!TimeRead, "hh:mm:ss") & "," & rstData!Kwh
        rstData.MoveNext
        End If
        End If
        End If
    Loop
recordstring = Left(recordstring, Len(recordstring) - 1) 'remove last comma
Debug.Print recordstring & vbCrLf
'rstData2.AddNew
'rstData2!MeterString = recordstring
'rstData2.Update
recordstring = ""
Loop
End If
End Sub
</code>```

It is unclear where you want to output the data so I demonstrate outputting to debug and to another already existing table.  the table version gives:

Title: Converting column data to row data

Body:
I am very limited in my sql abilities, I have only used simple queries and joins in MS Access. My task is to convert this data:

Meter_Number    Date    Time        Kwh
93112575    23/05/2019  08:00:00    278.334
93112575    23/05/2019  09:00:00    279.254
93112575    23/05/2019  10:00:00    280.012
93112575    23/05/2019  11:00:00    281.315
93112575    23/05/2019  12:00:00    282.256
93112575    23/05/2019  13:00:00    285.852
18794160    22/05/2019  14:00:00    6145.504
18794160    22/05/2019  15:00:00    6147.968
18794160    22/05/2019  16:00:00    6150.855
18794160    22/05/2019  17:00:00    6155.283
18794160    22/05/2019  18:00:00    6161.977
18794160    22/05/2019  19:00:00    6162.854
18794160    22/05/2019  20:00:00    6163.644
18794160    22/05/2019  21:00:00    6165.763
18794160    22/05/2019  22:00:00    6169.031
18794160    22/05/2019  23:00:00    6172.302
18794160    23/05/2019  00:00:00    6175.58
18794160    23/05/2019  01:00:00    6178.863
18794160    23/05/2019  02:00:00    6182.146
18794160    23/05/2019  03:00:00    6185.426
18794160    23/05/2019  04:00:00    6188.709
18794160    23/05/2019  05:00:00    6191.994
18794160    23/05/2019  06:00:00    6195.276
18794160    23/05/2019  07:00:00    6197.547
18794160    23/05/2019  08:00:00    6198.336
18794160    23/05/2019  09:00:00    6199.126
18794160    23/05/2019  10:00:00    6200.301
18794160    23/05/2019  11:00:00    6208.569
15296497    22/05/2019  14:00:00    62.064
15296497    22/05/2019  15:00:00    62.095
15296497    22/05/2019  16:00:00    63.044
15296497    22/05/2019  17:00:00    64.062
15296497    22/05/2019  18:00:00    65.024
15296497    22/05/2019  19:00:00    65.085

into this format:

93112575,#1,23/05/2019,08:00:00,278.334,#2,23/05/2019,09:00:00,279.254,#3,23/05/2019,10:00:00,280.012 ~etc.
18794160,#1,22/05/2019,14:00:00,6145.504,#2,22/05/2019,15:00:00,6147.968,#3,22/05/2019,16:00:00,6150.855,#4,22/05/2019,17:00:00,6155.283 ~etc.
15296497,#1,22/05/2019,14:00:00,62.064,#2,15296497,22/05/2019,15:00:00,62.095,#3,22/05/2019,16:00:00,63.044

This is a similar problem posted on your site:
R Programming Converting data columns to Rows

Any assistance will be be very much appreciated. I do understand that this is not a simple task and will not be offended if no one has time to assist me in this.

I copied some of the code off one of your pages and added it to an event procedure, it populated the table but it placed all the data in one column.

Body:
Here is an example of reformatting the data using code:

First I imported the data into an access table:

Then I looped through the table using vba:

Public Sub ReformatData()
'declarations
'Dim rstData2 As DAO.Recordset
'Set rstData2 = CurrentDb.OpenRecordset("tblData2", dbOpenTable)
Dim rstData As DAO.Recordset
Dim currentMeter_Number As Long
Dim counter As Integer
Dim recordstring As String
Set rstData = CurrentDb.OpenRecordset("tblData", dbOpenTable)
'loop through table
If Not rstData.EOF Then
rstData.MoveFirst
Do While Not rstData.EOF
counter = 1
'process first Meter_Number in set
currentMeter_Number = rstData!Meter_Number
recordstring = recordstring & currentMeter_Number & ",#1," & rstData!DateRead & "," & _
Format(rstData!TimeRead, "hh:mm:ss") & "," & rstData!Kwh
rstData.MoveNext
    'process the rest of set
    Do While Not rstData.EOF
    If Not currentMeter_Number = rstData!Meter_Number Then
    Exit Do
    Else
        If Not IsNull(rstData!Meter_Number) Then
        If currentMeter_Number = rstData!Meter_Number Then
        counter = counter + 1
        recordstring = recordstring & ",#" & counter & "," & rstData!DateRead & "," & _
        Format(rstData!TimeRead, "hh:mm:ss") & "," & rstData!Kwh
        rstData.MoveNext
        End If
        End If
        End If
    Loop
recordstring = Left(recordstring, Len(recordstring) - 1) 'remove last comma
Debug.Print recordstring & vbCrLf
'rstData2.AddNew
'rstData2!MeterString = recordstring
'rstData2.Update
recordstring = ""
Loop
End If
End Sub

It is unclear where you want to output the data so I demonstrate outputting to debug and to another already existing table.  the table version gives:


问:
Use ApplicationHelper in in lib/file.rb
I have a file in lib/thing.rb, and in there I need to call a method defined in ApplicationHelper inside a class method in thing.rb

In other words in Thing.some_method() it calls format_me() in ApplicationHelper

I've tried every conceivable way I can think of to extend ApplicationHelper or extend ActionView::Helpers::ApplicationHelper and it just keeps saying uninitialized constant. Ive also tried Rails.application.helpers but I don't know how to access the method in there...

答:
If you're getting errors about uninitialized constants then you can probably resolve the issue by moving lib/ into app/. Using Ruby 2.6.3 and Rails 5.2.3, given the following files and layout:

```<code># app/helpers/application_helper.rb
module ApplicationHelper
  def baz
    SecureRandom.uuid
  end
end
</code>```

and:

```<code># app/lib/foo.rb
class Foo
  extend ApplicationHelper

  def self.bar
    baz
  end
end
</code>```

Calling Foo.bar returns:

```<code>=> "b6322675-47b2-4ae8-a19a-ffd4af8d6f84"
</code>```

Title: Use ApplicationHelper in in lib/file.rb

Body:
If you're getting errors about uninitialized constants then you can probably resolve the issue by moving lib/ into app/. Using Ruby 2.6.3 and Rails 5.2.3, given the following files and layout:

# app/helpers/application_helper.rb
module ApplicationHelper
  def baz
    SecureRandom.uuid
  end
end

and:

# app/lib/foo.rb
class Foo
  extend ApplicationHelper

  def self.bar
    baz
  end
end

Calling Foo.bar returns:

=> "b6322675-47b2-4ae8-a19a-ffd4af8d6f84"


答:
Use:

```<code>#convert columns to datetimes
df['Date'] = pd.to_datetime(df['Date'], format='%d.%m.%Y')
df1['Date'] = pd.to_datetime(df1['Date'], format='%d.%m.%Y')

#filter expected columns by condition and by columns in list
df2 = df1.loc[df1['Date'] > '2019-02-06', ['Date','X1','X3']]

#match by DatetimeIndex and add values from filtered DataFrame
df = df.set_index('Date').combine_first(df2.set_index('Date')).reset_index()
print (df)
        Date   X1   X2    X3
0 2019-02-04  2.0  2.0  12.0
1 2019-02-05  2.0  2.0   5.0
2 2019-02-06  1.0  2.0   1.0
3 2019-02-07  1.0  NaN   4.0
4 2019-02-08  2.0  NaN   2.0
5 2019-02-09  4.0  NaN   1.0
</code>```

Or if need only append second DataFrame to first:

```<code>df2 = df1.loc[df1['Date'] > '2019-02-06', ['Date','X1','X3']]
df = pd.concat([df, df2], ignore_index=True, sort=True)
print (df)
        Date  X1   X2  X3
0 2019-02-04   2  2.0  12
1 2019-02-05   2  2.0   5
2 2019-02-06   1  2.0   1
3 2019-02-07   1  NaN   4
4 2019-02-08   2  NaN   2
5 2019-02-09   4  NaN   1
</code>```

Title: Union 2 dataframe by condition

Body:
I have 2 table. First in df:

Date       X1   X2  X3
04.02.2019  2   2   12
05.02.2019  2   2   5
06.02.2019  1   2   1

Second in df1:

Date       X1   X2  X3
06.02.2019  1   1   2
07.02.2019  1   1   4
08.02.2019  2   2   2
09.02.2019  4   1   1

And I need to supplement Table 1 with data from Table 2. Data should be taken from the Date, X1, X3 columns and only for rows with the condition Date > 06.02.2019. Result in df:

Date       X1   X2  X3
04.02.2019  2   2   12
05.02.2019  2   2   5
06.02.2019  1   2   1
07.02.2019  1       4
08.02.2019  2       2
09.02.2019  4       1

Body:
Use:

#convert columns to datetimes
df['Date'] = pd.to_datetime(df['Date'], format='%d.%m.%Y')
df1['Date'] = pd.to_datetime(df1['Date'], format='%d.%m.%Y')

#filter expected columns by condition and by columns in list
df2 = df1.loc[df1['Date'] > '2019-02-06', ['Date','X1','X3']]

#match by DatetimeIndex and add values from filtered DataFrame
df = df.set_index('Date').combine_first(df2.set_index('Date')).reset_index()
print (df)
        Date   X1   X2    X3
0 2019-02-04  2.0  2.0  12.0
1 2019-02-05  2.0  2.0   5.0
2 2019-02-06  1.0  2.0   1.0
3 2019-02-07  1.0  NaN   4.0
4 2019-02-08  2.0  NaN   2.0
5 2019-02-09  4.0  NaN   1.0

Or if need only append second DataFrame to first:

df2 = df1.loc[df1['Date'] > '2019-02-06', ['Date','X1','X3']]
df = pd.concat([df, df2], ignore_index=True, sort=True)
print (df)
        Date  X1   X2  X3
0 2019-02-04   2  2.0  12
1 2019-02-05   2  2.0   5
2 2019-02-06   1  2.0   1
3 2019-02-07   1  NaN   4
4 2019-02-08   2  NaN   2
5 2019-02-09   4  NaN   1


问:
how to use d-inline-block
d-inline-block isn't working
I tried with css but still it is not working</p>

```<code><div class="d-inline-block">
    <!--Service Image-->
    <div class="service_img container d-inline-block">
        <img class="responsive" src="/img/service.jpg">
    </div>

    <!--Service Content-->
    <div class="container d-inline-block">
    <p>
        Scroll Up and Down this page to see the parallax scrolling effect.
    This div is just here to enable scrolling.<br>
    Tip: Try to remove the background-attachment property to remove the scrolling effect.

    </p>
    </div>
</div>
</code>```

答:
Instead use inline-block use bootstrap's row/col  (means use flex instead inline-block).

Wrap all in div with class container

Also and use img-fluid class to img

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

        Scroll Up and Down this page to see the parallax scrolling effect.
    This div is just here to enable scrolling.

    Tip: Try to remove the background-attachment property to remove the scrolling effect.

```
</div>
</div>
</p>

<p>IF you want to use <code>d-inline-block</code> use as below:</p>

<p><strong>Set <code>width</code> to each `div</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.w-49{
    width: 49%!important;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

    Scroll Up and Down this page to see the parallax scrolling effect. This div is just here to enable scrolling.
 Tip: Try to remove the background-attachment property to remove the scrolling effect.

```

Title: how to use d-inline-block

Body:
d-inline-block isn't working
I tried with css but still it is not working

        Scroll Up and Down this page to see the parallax scrolling effect.
    This div is just here to enable scrolling.

    Tip: Try to remove the background-attachment property to remove the scrolling effect.

Body:
Instead use inline-block use bootstrap's row/col  (means use flex instead inline-block).

Wrap all in div with class container

Also and use img-fluid class to img

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

<div class="container">
<div class="row">
    <!--Service Image-->
    <div class="service_img col-6">
        <img class="img-fluid" src="https://i.stack.imgur.com/mSXoO.png">
    </div>

    <!--Service Content-->
    <div class="col-6">
    <p>
        Scroll Up and Down this page to see the parallax scrolling effect.
    This div is just here to enable scrolling.<br>
    Tip: Try to remove the background-attachment property to remove the scrolling effect.

    </p>
    </div>
</div>
</div>

IF you want to use d-inline-block use as below:

Set width to each `div

.w-49{
    width: 49%!important;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

<div class="service_img d-inline-block w-49">
  <img class="img-fluid" src="https://i.stack.imgur.com/mSXoO.png">
</div>

<div class="d-inline-block w-49">
  <p>
    Scroll Up and Down this page to see the parallax scrolling effect. This div is just here to enable scrolling.<br> Tip: Try to remove the background-attachment property to remove the scrolling effect.

  </p>
</div>


问:
SQL Error: 1064, SQLState: 42000 while creating new entity
I am working on a Spring mvc web application in which I need to create a town using Hibernate. Following is my town model.

```<code>@Entity
@Table(name="town")
public class TownModel {

    @Id
    @Column(name="townid")
    @GeneratedValue
    private Integer townId;

    @Column(name="name")
    private String townName;

    @Column(name="desc")
    private String townDesc;

    @ManyToOne(optional = true)
    @JoinColumn(name="districtid")
    private DistrictModel districtModel;
}
</code>```

I have another entity named district. Town is a part of district and a district can have multiple towns. Following is my district model:

```<code>@Entity
@Table(name="district")
public class DistrictModel {

    @Id
    @Column(name="districtid")
    @GeneratedValue
    private Integer districtId;

    @Column(name="name")
    private String name;

    @Column(name="desc")
    private String description;

    @OneToMany(mappedBy = "districtModel", fetch = FetchType.EAGER)
    @Fetch(value = FetchMode.SUBSELECT)
    private List<TownModel> townModelList;
}
</code>```

I am using following Hibernate code for saving town:

```<code>Session session = sessionFactory.getCurrentSession();
session.save(townModel);
</code>```

But it shows error:

```<code>21:22:08,104 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http--127.0.0.1-9090-1) SQL Error: 1064, SQLState: 42000
21:22:08,112 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http--127.0.0.1-9090-1) You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc, name) values (2, 'Test town desc.', 'Test town')' at line 1

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc, name) values (2, 'Test town desc.', 'Test town')' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.7.0_45]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) ~[na:1.7.0_45]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.7.0_45]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526) ~[na:1.7.0_45]
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:377) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.Util.getInstance(Util.java:360) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:978) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3887) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3823) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2435) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2582) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2530) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1907) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2141) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2077) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2062) ~[com.mysql.jdbc_5.1.5.jar:na]
    at org.jboss.jca.adapters.jdbc.WrappedPreparedStatement.executeUpdate(WrappedPreparedStatement.java:493) ~[na:na]
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:186) ~[hibernate-core-4.2.16.Final.jar:4.2.16.Final]
    ... 64 common frames omitted
</code>```

答:
I add a table named 'order' in MySQL Workbench, it doesn't give me an error.

But when I execute the query by Spring JPA
It gives out the error.

That's because my table name "order" is a reserved word.

Just make a little change and the error has gone.
change table name from "order" to "orders"

Body:
I am working on a Spring mvc web application in which I need to create a town using Hibernate. Following is my town model.

@Entity
@Table(name="town")
public class TownModel {

    @Id
    @Column(name="townid")
    @GeneratedValue
    private Integer townId;

    @Column(name="name")
    private String townName;

    @Column(name="desc")
    private String townDesc;

    @ManyToOne(optional = true)
    @JoinColumn(name="districtid")
    private DistrictModel districtModel;
}

I have another entity named district. Town is a part of district and a district can have multiple towns. Following is my district model:

@Entity
@Table(name="district")
public class DistrictModel {

    @Id
    @Column(name="districtid")
    @GeneratedValue
    private Integer districtId;

    @Column(name="name")
    private String name;

    @Column(name="desc")
    private String description;

    @OneToMany(mappedBy = "districtModel", fetch = FetchType.EAGER)
    @Fetch(value = FetchMode.SUBSELECT)
    private List<TownModel> townModelList;
}

I am using following Hibernate code for saving town:

Session session = sessionFactory.getCurrentSession();
session.save(townModel);

But it shows error:

21:22:08,104 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http--127.0.0.1-9090-1) SQL Error: 1064, SQLState: 42000
21:22:08,112 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http--127.0.0.1-9090-1) You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc, name) values (2, 'Test town desc.', 'Test town')' at line 1

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc, name) values (2, 'Test town desc.', 'Test town')' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.7.0_45]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) ~[na:1.7.0_45]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.7.0_45]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526) ~[na:1.7.0_45]
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:377) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.Util.getInstance(Util.java:360) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:978) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3887) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3823) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2435) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2582) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2530) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1907) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2141) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2077) ~[com.mysql.jdbc_5.1.5.jar:na]
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2062) ~[com.mysql.jdbc_5.1.5.jar:na]
    at org.jboss.jca.adapters.jdbc.WrappedPreparedStatement.executeUpdate(WrappedPreparedStatement.java:493) ~[na:na]
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:186) ~[hibernate-core-4.2.16.Final.jar:4.2.16.Final]
    ... 64 common frames omitted


问:
How to allow external connections on Docker MySQL image
I am trying to get root access to my Docker MySQL image that I created. I placed environment variables for ROOT_PASSWORD and DATABASE so I'm sure that a password does exist and I am able to access root using the command line. The problem lies in trying to access root with MySQLWorkbench or SequelPro. I have hostname set to localhost, user as root and port as 3307 (I had mapped this port when running the command to create the database). When I attempt to connect I get an error

"Your connection attempt failed for user 'root' to the MySQL server at localhost:3307:
  Host  is not allowed to connect to this MySQL server"

I've tried changing the port number to 3306, changing the IP to 127.0.0.1 as well as  but the error doesn't go away. I checked a GitHub post that suggested that root user should have "%" as host and that could be achieved by changing my bind-address. Problem is I cannot find the mysql.cnf config file...I don't even think one exists on my system

https://i.imgur.com/eeNdg4J.png

答:
A surefire way to get access is to:

```<code>docker inspect mysql_container_name
</code>```

to find the ip address.

Then you can use something like:

```<code>mysql -u root -p -h <docker container ip address>
</code>```

A couple of other notes:

The default mysql port is 3306, so you should also double check that you didn't accidentally map it backward.

The environment variable is called MYSQL_ROOT_PASSWORD not ROOT_PASSWORD

You may need to supply a config that binds and listens on a network interface rather than a socket

The config file is inside the docker container. You can map a volume to use a local file instead:

docker run --name some-mysql -v /my/custom:/etc/mysql/conf.d -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag

See here for more info:
https://docs.docker.com/samples/library/mysql/

Body:
A surefire way to get access is to:

docker inspect mysql_container_name

to find the ip address.

Then you can use something like:

mysql -u root -p -h <docker container ip address>

A couple of other notes:

The default mysql port is 3306, so you should also double check that you didn't accidentally map it backward.

The environment variable is called MYSQL_ROOT_PASSWORD not ROOT_PASSWORD

You may need to supply a config that binds and listens on a network interface rather than a socket

The config file is inside the docker container. You can map a volume to use a local file instead:

docker run --name some-mysql -v /my/custom:/etc/mysql/conf.d -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag

See here for more info:
https://docs.docker.com/samples/library/mysql/


问:
Standard ML permutations
I am working on a function to the permutations for all values in a list.

Here is what I have so far:

```<code>//MY ROTATE FUNCTION

fun rotate e [] = [[e]]
| rotate e (x::xs)= (e::x::xs)::(List.map (fn l => x::l) (rotate e xs));

//MY CURRENT PERMUTATION FUNCTION

fun perm [] = []
| perm (x::xs) = List.concat(List.map (fn l => (rotate x xs)) xs) @ perm xs;
</code>```

OUTPUT:

```<code>- perm [1,2,3];

val it = [[1,2,3],[2,1,3],[2,3,1],[1,2,3],[2,1,3],[2,3,1],[2,3],[3,2]]
</code>```

The output should be something like [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]. As you can see I am missing something here. I believe the issue is my 3 is not being passed to rotate as rotate 3 [1,2] is what I am missing from my code along with two 2 element lists being here for some reason.

How can I correct my perm function to show the output correctly? Any help no matter how big or small would help me a lot.

答:
Here is a simple fix for your attempted solution. You were nearly there.</p>

```<code>fun interleave x [] = [[x]]
| interleave x (h::t) =
    (x::h::t)::(List.map(fn l => h::l) (interleave x t))

fun permute nil = [[]]
| permute (h::t) = List.concat( List.map (fn l => interleave h l) (permute t))
</code>```

ContentLicense: CC BY-SA 2.5

Title: Standard ML permutations

Body:
I am working on a function to the permutations for all values in a list.

Here is what I have so far:

//MY ROTATE FUNCTION

fun rotate e [] = [[e]]
| rotate e (x::xs)= (e::x::xs)::(List.map (fn l => x::l) (rotate e xs));

//MY CURRENT PERMUTATION FUNCTION

fun perm [] = []
| perm (x::xs) = List.concat(List.map (fn l => (rotate x xs)) xs) @ perm xs;

OUTPUT:

- perm [1,2,3];

val it = [[1,2,3],[2,1,3],[2,3,1],[1,2,3],[2,1,3],[2,3,1],[2,3],[3,2]]

The output should be something like [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]. As you can see I am missing something here. I believe the issue is my 3 is not being passed to rotate as rotate 3 [1,2] is what I am missing from my code along with two 2 element lists being here for some reason.

How can I correct my perm function to show the output correctly? Any help no matter how big or small would help me a lot.

LastEditorDisplayName: Roger Pate

Body:
Here is a simple fix for your attempted solution. You were nearly there.

fun interleave x [] = [[x]]
| interleave x (h::t) =
    (x::h::t)::(List.map(fn l => h::l) (interleave x t))

fun permute nil = [[]]
| permute (h::t) = List.concat( List.map (fn l => interleave h l) (permute t))


问:
How can i use telegram lib to auth and send message to my phone number in java?
Im trying to connect my java project to my phone number, i already have the app_id and the hash generated by Telegram.
Im using https://github.com/rubenlagus/TelegramApi this library imported to my pom project, but im not understanding how can i use the app_id, ip and hash that telegram generated for me to authenticate and send a simple "hi" message.

```<code>    AppInfo appInfo = new AppInfo(appId,"devicemodel","systemversion","appversion","langcode");
    TelegramApi api = new TelegramApi(AbsApiState, AppInfo, ApiCallback);
</code>```

I can initialize the variable AppInfo , i have de app_id, do i need to put real data(devicemodel,systemversion,appversion,langcode) to the rest of the required fields?

How can i intialize the Variables AbsApiState and ApiCallback ?

I searched many documentation and examples on the Internet, it is really simple to create a bot to communicate but i want to send message user to user, not bot to user in the future.

Thank you !

答:
The library you have mentioned is for sending messages from bots you own. On the other hand api_id and api_hash are used for client apps for real users. It seems that you want to send a message as user, not a bot. You can't do it with this library.

I suggest using Telethon which is the best library I've ever used for your use case.

Body:
Im trying to connect my java project to my phone number, i already have the app_id and the hash generated by Telegram.
Im using https://github.com/rubenlagus/TelegramApi this library imported to my pom project, but im not understanding how can i use the app_id, ip and hash that telegram generated for me to authenticate and send a simple "hi" message.

    AppInfo appInfo = new AppInfo(appId,"devicemodel","systemversion","appversion","langcode");
    TelegramApi api = new TelegramApi(AbsApiState, AppInfo, ApiCallback);

I can initialize the variable AppInfo , i have de app_id, do i need to put real data(devicemodel,systemversion,appversion,langcode) to the rest of the required fields?

How can i intialize the Variables AbsApiState and ApiCallback ?

I searched many documentation and examples on the Internet, it is really simple to create a bot to communicate but i want to send message user to user, not bot to user in the future.

Thank you !


问:
How to send Http Form with parameters by ktor-client
I've found nearly everywhere in ktor-client documentation and examples they use empty formData to show how the client works

```<code>formParameters: Parameters = Parameters.Empty
</code>```

So what's the kotlin/ktor way to fill it with parameters?

答:
Ktor uses this approach to fill the parameters:</p>

```<code>client.submitForm<HttpResponse>(
        url = "https://foo.com/login",
        formParameters = Parameters.build {
            append("_username", username)
            append("_password", password)
        })
</code>```

Body:
I've found nearly everywhere in ktor-client documentation and examples they use empty formData to show how the client works

formParameters: Parameters = Parameters.Empty

So what's the kotlin/ktor way to fill it with parameters?

Body:
Ktor uses this approach to fill the parameters:

client.submitForm<HttpResponse>(
        url = "https://foo.com/login",
        formParameters = Parameters.build {
            append("_username", username)
            append("_password", password)
        })


问:
Remove a merged line from image OpenCv
I need to identify the text on an image that is merged with 2 pieces. The image has the merged line on it. Is there a way to remove the merge line? to identify the text on it.

this is my image

答: Yeap, it is possible to remove that line but you may have to work a bit harder. The first task is to identify lines. For this, you may use Houge Transformation or RANSAC or any other techniques. This might be helpful for you as well. I would suggest you start with Houge because of lines in your cause has some definite angles which might be easier to detect lines. Then you need to apply some morphological operation like erosion and dilation for smoothing the image. Also, have a look structural analysis and shape descriptors to reduce the false positive and false negative detections. Work on this way and if something not clear, ask again. </p>

Title: Remove a merged line from image OpenCv