问:
Lodash with typescript find not working with overload
I am trying to use _.find on typescript on a Object to return a value f this object.
It originally looked like this:

  const iconDict = {
    dashboard: <DataVisualizer />,
    settings: <SettingsApp />,
    'company-manager': <CompanyManager />,
    'tenant-administrator': <TenantAdministrator />,
    glob
  const icon =
    _.find(iconDict, (icon, key) => {
      const url = window.location.href
      if (url.indexOf(key) !== -1) {
        return icon
      }
    }) || iconDict['global']
```

<p>The code above gives me the error:</p>

```
No overload matches this call.
  The last overload gave the following error.
    Argument of type '(icon: Element, key: string) => Element | undefined' is not assignable to parameter of type 'string | number | symbol | [string | number | symbol, any] | ObjectIterator | PartialShallow | undefined'.
      Type '(icon: Element, key: string) => Element | undefined' is not assignable to type 'ObjectIterator'.
        Type 'Element | undefined' is not assignable to type 'boolean'.
          Type 'undefined' is not assignable to type 'boolean'
```

<p>Probably because it is falling on this overload</p>

<p>I tried to add the typing of the object like this</p>

<pre class="lang-js prettyprint-override"><code>  const icon =
    _.find<typeof iconDict, JSX.Element>(iconDict, (icon, key) => {
      const url = window.location.href
      if (url.indexOf(key) !== -1) {
        return icon
      }
</code>```

And I then get:

```
Argument of type '(icon: Element, key: string) => Element | undefined' is not assignable to parameter of type 'ObjectIteratorTypeGuard'.
  Signature '(icon: Element, key: string): Element | undefined' must be a type predicate.ts(2345)
```

Because it falls on this definition

And now I am not sure how to proceed.
How to make the typescript knows that I will return either a type of a value of the object or undefined?

Thanks

答:
I am not sure if you are using @types/lodash, but it is a first step here, to give TS some signatures of find.

There is this override of find:

find<T>(
  collection: List<T> | null | undefined,
  predicate?: ListIterateeCustom<T, boolean>,
  fromIndex?: number
): T|undefined;
```

<p>That should work if you change your predicate to </p>

<pre class="lang-js prettyprint-override"><code>(icon, key) => {
  const url = window.location.href
  return url.indexOf(key) !== -1 ? icon : false
}
</code>```

So it will return boolean in not-found case.

Body:
I am trying to use _.find on typescript on a Object to return a value f this object.
It originally looked like this:

  const iconDict = {
    dashboard: <DataVisualizer />,
    settings: <SettingsApp />,
    'company-manager': <CompanyManager />,
    'tenant-administrator': <TenantAdministrator />,
    glob
  const icon =
    _.find(iconDict, (icon, key) => {
      const url = window.location.href
      if (url.indexOf(key) !== -1) {
        return icon
      }
    }) || iconDict['global']

The code above gives me the error:

No overload matches this call.
  The last overload gave the following error.
    Argument of type '(icon: Element, key: string) => Element | undefined' is not assignable to parameter of type 'string | number | symbol | [string | number | symbol, any] | ObjectIterator | PartialShallow | undefined'.
      Type '(icon: Element, key: string) => Element | undefined' is not assignable to type 'ObjectIterator'.
        Type 'Element | undefined' is not assignable to type 'boolean'.
          Type 'undefined' is not assignable to type 'boolean'

Probably because it is falling on this overload

I tried to add the typing of the object like this

  const icon =
    _.find<typeof iconDict, JSX.Element>(iconDict, (icon, key) => {
      const url = window.location.href
      if (url.indexOf(key) !== -1) {
        return icon
      }

And I then get:

Argument of type '(icon: Element, key: string) => Element | undefined' is not assignable to parameter of type 'ObjectIteratorTypeGuard'.
  Signature '(icon: Element, key: string): Element | undefined' must be a type predicate.ts(2345)

Because it falls on this definition

And now I am not sure how to proceed.
How to make the typescript knows that I will return either a type of a value of the object or undefined?

Thanks

Body:
I am not sure if you are using @types/lodash, but it is a first step here, to give TS some signatures of find.

There is this override of find:

find<T>(
  collection: List<T> | null | undefined,
  predicate?: ListIterateeCustom<T, boolean>,
  fromIndex?: number
): T|undefined;

That should work if you change your predicate to

(icon, key) => {
  const url = window.location.href
  return url.indexOf(key) !== -1 ? icon : false
}

So it will return boolean in not-found case.


来源: stackexchange

问:
cannot output session variable in json response
This is probably really simple but it isn't obvious to me right now why this isn't working.

I am setting a session variable on the index.php file, putting the value into a hidden field within a form and then submitting the form via jQuery and ajax. All the other form data is there and the hidden input value is there. But if I just try to echo the actual session variable out I get nothing eg:

```<code>$response['message'] = $_SESSION['csrf_token']; // no output

$response['message'] = $_POST['token']; // outputs the session variable value stored in the hidden field
</code>```

On index.php

```<code><?php
session_start();
$_SESSION['csrf_token'] = uniqid('', true);
?>

 <input type="hidden" name="token" value="<?php echo $_SESSION['csrf_token']; ?>">
</code>```

jQuery:

```<code>var form = $('#testForm').serialize();
            $.ajax({
                url: 'test',
                type: 'POST',
                dataType: 'json',
                data: form,
                beforeSend: function() {

                    // loading spinner etc.
                }
            })
</code>```

答:
You just need to make sure the session has started on each script.</p>

```<code>session_start();
$response['message'] = $_SESSION['csrf_token'];
$response['message'] = $_POST['token'];
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is probably really simple but it isn't obvious to me right now why this isn't working.

I am setting a session variable on the index.php file, putting the value into a hidden field within a form and then submitting the form via jQuery and ajax. All the other form data is there and the hidden input value is there. But if I just try to echo the actual session variable out I get nothing eg:

$response['message'] = $_SESSION['csrf_token']; // no output

$response['message'] = $_POST['token']; // outputs the session variable value stored in the hidden field

On index.php

<?php
session_start();
$_SESSION['csrf_token'] = uniqid('', true);
?>

 <input type="hidden" name="token" value="<?php echo $_SESSION['csrf_token']; ?>">

jQuery:

var form = $('#testForm').serialize();
            $.ajax({
                url: 'test',
                type: 'POST',
                dataType: 'json',
                data: form,
                beforeSend: function() {

                    // loading spinner etc.
                }
            })

Body:
You just need to make sure the session has started on each script.

session_start();
$response['message'] = $_SESSION['csrf_token'];
$response['message'] = $_POST['token'];


问:
Build Electron for different environments
Ahoy,

I have an electron app where I currently manually edit an URL in one of my files, depending on which environment (dev, prod, test) I wish to build for. However I would rather like to define that in my script so I don't have to rewrite the URL every time (e.g. electron-builder -w --x64 --ia32 --test or something like that).

As far as I can tell it is possible to have different build files (https://github.com/electron-userland/electron-builder/issues/1109), but I can't quite figure how the setup should be, and furthermore I can't figure how to get the attributes from the build files (e.g. build/publish/url). It seems possible to get icon and name (https://github.com/electron-userland/electron-builder/issues/639), but not url?

```<code>package.json

    {... ,
      "build":{
        ... ,
        "publish":[{
          ... ,
          "url": "https://my.website.url" <--- Change on build and fetchable in code?
        }],
      }
    }

</code>```

I'm sorry if I have missed anything - I consider writing an explicit tutorial somewhere once I've got a hang of this.

Thanks in advance

答:
I found a (albeit a bit hack'ish imo) solution which I will use for now.

I simply added "--c.extraMetadata.productName=dev-" (and test instead of dev for the test build) to the build script, and then in my code i would check which environment that had been prepended to the build, and switch the URL accordingly. The good thing about this approach is that now I can also see which environment the .exe file is pointing at!

I'm still convinced that the "correct" way is having multiple YAML files, like Rhayene suggests, but the approach above just seems much easier and more directly controlled.

Body:
Ahoy,

I have an electron app where I currently manually edit an URL in one of my files, depending on which environment (dev, prod, test) I wish to build for. However I would rather like to define that in my script so I don't have to rewrite the URL every time (e.g. electron-builder -w --x64 --ia32 --test or something like that).

As far as I can tell it is possible to have different build files (https://github.com/electron-userland/electron-builder/issues/1109), but I can't quite figure how the setup should be, and furthermore I can't figure how to get the attributes from the build files (e.g. build/publish/url). It seems possible to get icon and name (https://github.com/electron-userland/electron-builder/issues/639), but not url?

package.json

    {... ,
      "build":{
        ... ,
        "publish":[{
          ... ,
          "url": "https://my.website.url" <--- Change on build and fetchable in code?
        }],
      }
    }

I'm sorry if I have missed anything - I consider writing an explicit tutorial somewhere once I've got a hang of this.

Thanks in advance


问:
getattr(): attribute name must be string
```<code>Very beginner here i am not getting whats the error here
#Models.py file

`from django.db import models

    class User(models.Model):
        name = models.CharField(max_length=20)
        email = models.CharField(max_length=100)
        date_created = models.DateTimeField(auto_now_add=True)

        def __str__(self):
            return self.name

    class Recipe(models.Model):
        name = models.CharField(max_length=50,null=True)
        steps = models.CharField(max_length=2000,null=True)
        image = models.ImageField(height_field=200,width_field=200,null = True, blank = True)
        ingredients = models.CharField(max_length=100, null=True)
        description = models.CharField(max_length=1000,null=True)
        user = models.ForeignKey(User, on_delete=models.CASCADE)`

#Form file

    `from django import forms
from django.forms import ModelForm
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Recipe

class SignupForm(UserCreationForm):
    username = forms.CharField(max_length=30)
    email = forms.EmailField(max_length=200)

    class Meta:
        model = User
        fields = ['username','email','password1','password2']

class RecipeForm(ModelForm):
    class Meta:
        model = Recipe
        fields = ['name','steps','image','ingredients','description']`
#views.py file

    `from django.shortcuts import render, redirect
from .forms import SignupForm,RecipeForm
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages

# views here
 @login_required(login_url='blog-login')
    def recipes(request):
        form = RecipeForm()
        if request.method == "POST":
            form = RecipeForm(request.POST)
            if form.is_valid():
                form.save()
                return redirect('blog-home')
        context = {'form':form}
        return render(request,'food_app/Add_recipe.html',context)`
</code>```

答:
The Recipe models ImageField's height_field and width_field are both supposed to be the names of fields that you can store the value in, not an integer value.

Either remove these properties or add a couple fields to hold the values.


问:
First value of my PHP Array is returned as 'null' when it has a value
I'd really like some help with the following MySQL / PHP problem (maybe bug?)

I'm trying to retrieve and display an array of data from my database using MySQL / PHP, but when I echo out the array, it returns the first value as 'null'.

So, even though the database has the following info:

```<code>"Example 1", "Example 2", "Example 3"...
</code>```

The php echos out:

```<code>"null", "Example 2, "Example 3"
</code>```

I would imagine this would be a common problem, but I haven't managed to find the required information elsewhere on the internet, so I'm hoping you kind folks can help.

My PHP

```<code>/* If connection to database, run sql statement. */
if ($conn) {
    $fetch = mysql_query("SELECT column FROM table WHERE approved = '1' ");

    // declare empty array to fill later
    $result = array();

    // make sure the MySQL pointer is looking at the first row
    mysql_data_seek($fetch, 0);

    while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {

        foreach ($row as $value) {

            $row_array = $value;

            // push info into new array with just the value
            array_push($result, $row_array);
        }
    }
}
/* Free connection resources. */
mysql_close($conn);

/* Toss back results as json encoded array. */
echo json_encode($result);
</code>```

UPDATE

New code courtesy of Mark B:

```<code>if ($conn)
{
$sql = "SELECT column_name FROM table WHERE comment_approved = '1' ";
$query = mysql_query($sql) or die(mysql_error());

$result = array();
while ($row = mysql_fetch_assoc($query)) {
    $result[] = $row['column_name'];

}

}

/* Free connection resources. */
mysql_close($conn);

/* Toss back results as json encoded array. */
echo json_encode($result);
</code>```

NOTE:

The 'null' problem still occurs with or without the:

```<code> mysql_data_seek($fetch, 0);
</code>```

as that appears to do nothing.

Any help would be great!

SOLVED

Thanks to Mark B who pointed out that the problem was probably in the database rather than the PHP, it turned out there was the character ` lurking where there should have been a '. This caused the information to appear 'null'.

答: Try removing the call to mysql_data_seek. I see no reason why the MySQL pointer wouldn't already point to the first row at the first call to mysql_fetch_array.

ContentLicense: CC BY-SA 3.0

Body:
I'd really like some help with the following MySQL / PHP problem (maybe bug?)

I'm trying to retrieve and display an array of data from my database using MySQL / PHP, but when I echo out the array, it returns the first value as 'null'.

So, even though the database has the following info:

"Example 1", "Example 2", "Example 3"...

The php echos out:

"null", "Example 2, "Example 3"

I would imagine this would be a common problem, but I haven't managed to find the required information elsewhere on the internet, so I'm hoping you kind folks can help.

My PHP

/* If connection to database, run sql statement. */
if ($conn) {
    $fetch = mysql_query("SELECT column FROM table WHERE approved = '1' ");

    // declare empty array to fill later
    $result = array();

    // make sure the MySQL pointer is looking at the first row
    mysql_data_seek($fetch, 0);

    while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {

        foreach ($row as $value) {

            $row_array = $value;

            // push info into new array with just the value
            array_push($result, $row_array);
        }
    }
}
/* Free connection resources. */
mysql_close($conn);

/* Toss back results as json encoded array. */
echo json_encode($result);

UPDATE

New code courtesy of Mark B:

if ($conn)
{
$sql = "SELECT column_name FROM table WHERE comment_approved = '1' ";
$query = mysql_query($sql) or die(mysql_error());

$result = array();
while ($row = mysql_fetch_assoc($query)) {
    $result[] = $row['column_name'];

}

}

/* Free connection resources. */
mysql_close($conn);

/* Toss back results as json encoded array. */
echo json_encode($result);

NOTE:

The 'null' problem still occurs with or without the:

 mysql_data_seek($fetch, 0);

as that appears to do nothing.

Any help would be great!

SOLVED

Thanks to Mark B who pointed out that the problem was probably in the database rather than the PHP, it turned out there was the character ` lurking where there should have been a '. This caused the information to appear 'null'.


问:
AUTOCAD SPECIFY LOCATION OF A POINT RELATIVE TO AN EXISTING LINE

I have a line (3d) with defined chainage (km relative to a reference location). There are a list of fixed objects around the line, wherein the X-Y-Z coordinates of the objects are given. The line and the objects have the same origin and same coordinate system. I need to extract the location of the objects relative to the line, that is, the relative chainage and the distance to the line. Anyone knows how to extract the list of relative locations for those objects?

ps. I showed an example of a line and some objects around it. The objects are plot out based on their coordinates. Now I need to find the km-info of these points relative to the line and the distance to the line (in practice the line can containe lots of curves, just imaging it's the centre line of a road).

Thanks in advance!

答:
I don't have ready solution but algorithm would be:

select those objects, in LISP You may use (ssget )

get the basepoint for each of object center of circle for example: (setq center(vlax-get-property Object 'Center)).

Project center point to curve - axis (setq projection(vlax-curve-getClosestPointTo axis  center )).

Read length of curve from it's begining to projection: ( setq dist ( vlax-curve-getDistAtPoint axis projection ) ).

Recalculate distance based on fixed distance of line.


问:
Stop a youtube video with jquery?
I have a jquery slider that I have built, basically just three pannels that slide by applying negative left CSS values. Works great, but I have a youtube video in one slide that wont stop when I slide. I've tried display:none and Visibility:hidden which works in all but IE, the audio keeps going in IE.

Is there an easy way to kill a video with jquery?

答:
This works for me

stopIframeVideo = () => {
  let iframe = $('.video-iframe')
  iframe.each((index) => {
    iframe[index].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');
  })
};

$('.close').click(() => {
    stopIframeVideo()
});```

ContentLicense: CC BY-SA 2.5

Title: Stop a youtube video with jquery?


问:
How to connect 2 queries SQL
How to connect these 2 queries to receive one that gives such a response:

```<code>user_name  room_name_reserved    room_name_biggest_time

user_1       room_1                  room_2
</code>```

room_name_reserved - most often reserved room by user

room_name_biggest_time  - room when user spent the most time

1 query:

```<code> SELECT
        us.name as user_name
        ,ro.name as room_name_reserved
    FROM reservation re
    INNER JOIN user us on us.id = re.userid
    INNER JOIN room ro on ro.id = re.roomid
    GROUP BY us.name, ro.name
    HAVING COUNT(room_name_reser) = (SELECT COUNT(*) FROM reservation re1
        WHERE re1.userid = re.userid
        GROUP BY re1.roomid
        ORDER BY COUNT(*) DESC
        LIMIT 1
        )
</code>```

2 query :

```<code>SELECT
    us.name as user_name
    ,ro.name as room_name_biggest_time
from Reservation re
INNER JOIN user us on us.id = re.userid
INNER JOIN room ro on ro.id = re.roomid
WHERE (strftime('%s', re.EndsAt) - strftime('%s', re.StartsAt)) = (SELECT MAX((strftime('%s', re1.EndsAt) - strftime('%s', re1.StartsAt))) as time FROM Reservation re1 where re1.UserId = re.userid
</code>```

ORDER BY time DESC
LIMIT 1 )

答:
Assuming you are using MySql, here's a little hack that can work:

```<code>SELECT
    user_name,
    SUBSTRING_INDEX(group_concat(room_name ORDER BY n_reservations DESC), ',', 1) as room_name_reserved,
    SUBSTRING_INDEX(group_concat(room_name ORDER BY total_stay DESC), ',', 1) as room_name_biggest_time
FROM (
    SELECT
      us.name as user_name,
      ro.name as room_name,
      count(*) as n_reservations,
      sum(strftime('%s', re.EndsAt) - strftime('%s', re.StartsAt)) as total_stay
    FROM user u
    JOIN reservation re on us.id = re.userid
    JOIN room ro on ro.id = re.roomid
    GROUP BY us.name, ro.name
    ) t
GROUP BY user_name
</code>```

Explanation:

With the subquery, aliased as t, we extract the total number of reservations (count(*)) and the total staying time (sum(...)) for each user/room, producing an intermediate output as follows:

```<code>user  room  n_reservations  total_stay
--------------------------------------
user1 room1 1               6000
user1 room2 2               3000
user1 room3 1               4000
user2 room2 1               9000
user2 room4 5               4000
</code>```

With the outer query we GROUP BY user, and for each user we first group concat the room name using a sorting based on counts and sums made before (biggest value first), producing an intermediate output as follow:

```<code>user  group_concat#1     group_concat#2
---------------------------------------
user1 room2,room1,room3  room1,room3,room2
user2 room4,room2        room2,room4
</code>```

Last step, we split by comma the output of the two group_concat mantaining only the first value, so final result will be:

```<code>user  room_name_reserved  room_name_biggest_time
-----------------------------------------------
user1 room2               room1
user2 room4               room2
</code>```

Title: How to connect 2 queries SQL

Body:
How to connect these 2 queries to receive one that gives such a response:

user_name  room_name_reserved    room_name_biggest_time

user_1       room_1                  room_2

room_name_reserved - most often reserved room by user

room_name_biggest_time  - room when user spent the most time

1 query:

 SELECT
        us.name as user_name
        ,ro.name as room_name_reserved
    FROM reservation re
    INNER JOIN user us on us.id = re.userid
    INNER JOIN room ro on ro.id = re.roomid
    GROUP BY us.name, ro.name
    HAVING COUNT(room_name_reser) = (SELECT COUNT(*) FROM reservation re1
        WHERE re1.userid = re.userid
        GROUP BY re1.roomid
        ORDER BY COUNT(*) DESC
        LIMIT 1
        )

2 query :

SELECT
    us.name as user_name
    ,ro.name as room_name_biggest_time
from Reservation re
INNER JOIN user us on us.id = re.userid
INNER JOIN room ro on ro.id = re.roomid
WHERE (strftime('%s', re.EndsAt) - strftime('%s', re.StartsAt)) = (SELECT MAX((strftime('%s', re1.EndsAt) - strftime('%s', re1.StartsAt))) as time FROM Reservation re1 where re1.UserId = re.userid

ORDER BY time DESC
LIMIT 1 )

Body:
Assuming you are using MySql, here's a little hack that can work:

SELECT
    user_name,
    SUBSTRING_INDEX(group_concat(room_name ORDER BY n_reservations DESC), ',', 1) as room_name_reserved,
    SUBSTRING_INDEX(group_concat(room_name ORDER BY total_stay DESC), ',', 1) as room_name_biggest_time
FROM (
    SELECT
      us.name as user_name,
      ro.name as room_name,
      count(*) as n_reservations,
      sum(strftime('%s', re.EndsAt) - strftime('%s', re.StartsAt)) as total_stay
    FROM user u
    JOIN reservation re on us.id = re.userid
    JOIN room ro on ro.id = re.roomid
    GROUP BY us.name, ro.name
    ) t
GROUP BY user_name

Explanation:

With the subquery, aliased as t, we extract the total number of reservations (count(*)) and the total staying time (sum(...)) for each user/room, producing an intermediate output as follows:

user  room  n_reservations  total_stay
--------------------------------------
user1 room1 1               6000
user1 room2 2               3000
user1 room3 1               4000
user2 room2 1               9000
user2 room4 5               4000

With the outer query we GROUP BY user, and for each user we first group concat the room name using a sorting based on counts and sums made before (biggest value first), producing an intermediate output as follow:

user  group_concat#1     group_concat#2
---------------------------------------
user1 room2,room1,room3  room1,room3,room2
user2 room4,room2        room2,room4

Last step, we split by comma the output of the two group_concat mantaining only the first value, so final result will be:

user  room_name_reserved  room_name_biggest_time
-----------------------------------------------
user1 room2               room1
user2 room4               room2


问:
How to create dataframeSource in R? Unable to create a corpus that fits my needs
A beginner here.
I have a dataset of 4 columns, basically news articles, containing columns with names: date, author, title and body (which contains text).
I want to create a corpus, but I don't understand how to create DataframeSource, basically the arguments I am passing. I understand the VectorSource.
Thereafter my aim is to do some basic text analysis. Thank you!

答:
The help of ?DataframeSource, specifies that you need 2 columns named "doc_id" and "text". Otherwise it will fail.

So you need to create a data.frame exactly like this before continuing. If your case the data looks like this:

```<code>my_data <- data.frame(date = c(Sys.Date() - 1, Sys.Date()) ,
                      author = c("author1", "author2"),
                      title = c("title_1", "title_2"),
                   body = c("This is text1.", "This is text2."),
                   stringsAsFactors = FALSE)
</code>```

You should now get an error like below when using DataframeSource(mydata):

Error in DataframeSource(my_data) :    all(!is.na(match(c("doc_id",
  "text"), names(x)))) is not TRUE

To solve this, you need to rename the columns title and body. For example like this:

```<code>index <- match(c("title", "body"), colnames(my_data))
colnames(my_data)[index] <- c("doc_id", "text")

# DataframeSource now works
ds <- DataframeSource(my_data)
</code>```

Body:
The help of ?DataframeSource, specifies that you need 2 columns named "doc_id" and "text". Otherwise it will fail.

So you need to create a data.frame exactly like this before continuing. If your case the data looks like this:

my_data <- data.frame(date = c(Sys.Date() - 1, Sys.Date()) ,
                      author = c("author1", "author2"),
                      title = c("title_1", "title_2"),
                   body = c("This is text1.", "This is text2."),
                   stringsAsFactors = FALSE)

You should now get an error like below when using DataframeSource(mydata):

Error in DataframeSource(my_data) :    all(!is.na(match(c("doc_id",
  "text"), names(x)))) is not TRUE

To solve this, you need to rename the columns title and body. For example like this:

index <- match(c("title", "body"), colnames(my_data))
colnames(my_data)[index] <- c("doc_id", "text")

# DataframeSource now works
ds <- DataframeSource(my_data)


问:
How to force external URLs inserted in the wagtail Draftail editor to open on the new tab?
Basically I need that the target="_blank" attribute would be added to all the external URLs inserted in the wagtail Draftail richtext editor:

```<code>In [2]: wagtail.__version__
Out[2]: '2.0.1'
</code>```

EDIT-1: This is not a duplicate. wagtail version 2 uses completely different richtext editor.

The proposed answer suggests $('a[href^="http://"]').attr('target', '_blank') which would add the appropriate attribute to the all links on the page which contain http://. It's very suboptimal solution, as there may be many more links on the page which do not require such a treatment. Obviously there must be more adequate fix, especially because wagtail already differentiate Internal and External links on the editor UI (see attached image).

EDIT-2:

It seems that in the wagtail.core.rich_text.feature_registry.FeatureRegistry class there is a method, which to my best understanding assign different handler to the different URL type, however I don't see what these these handlers are, how they get called or how to modify them?

```<code>def register_link_type(self, link_type, handler):
    self.link_types[link_type] = handler
</code>```

答:
Create file wagtail_hooks.py and add the following lines:</p>

```<code>class NewWindowExternalLinkHandler(LinkHandler):
    identifier = 'external'

    @classmethod
    def expand_db_attributes(cls, attrs):
        href = attrs["href"]
        return '<a href="%s" target="_blank" rel="noopener noreferrer">' % escape(href)

@hooks.register('register_rich_text_features')
def register_rich_text_handlers(features):
    features.register_link_type(NewWindowExternalLinkHandler)
</code>```

Body:
Basically I need that the target="_blank" attribute would be added to all the external URLs inserted in the wagtail Draftail richtext editor:

In [2]: wagtail.__version__
Out[2]: '2.0.1'

EDIT-1: This is not a duplicate. wagtail version 2 uses completely different richtext editor.

The proposed answer suggests $('a[href^="http://"]').attr('target', '_blank') which would add the appropriate attribute to the all links on the page which contain http://. It's very suboptimal solution, as there may be many more links on the page which do not require such a treatment. Obviously there must be more adequate fix, especially because wagtail already differentiate Internal and External links on the editor UI (see attached image).

EDIT-2:

It seems that in the wagtail.core.rich_text.feature_registry.FeatureRegistry class there is a method, which to my best understanding assign different handler to the different URL type, however I don't see what these these handlers are, how they get called or how to modify them?

def register_link_type(self, link_type, handler):
    self.link_types[link_type] = handler

Body:
Create file wagtail_hooks.py and add the following lines:

class NewWindowExternalLinkHandler(LinkHandler):
    identifier = 'external'

    @classmethod
    def expand_db_attributes(cls, attrs):
        href = attrs["href"]
        return '<a href="%s" target="_blank" rel="noopener noreferrer">' % escape(href)

@hooks.register('register_rich_text_features')
def register_rich_text_handlers(features):
    features.register_link_type(NewWindowExternalLinkHandler)


问:
Spark: Unsupported class version error
I am trying to run a java spark job, using spark-submit, on a cluster where all nodes have java 1.7 installed.

The job fails with a java.lang.UnsupportedClassVersionError: com/windlogics/dmf/wether/MyClass: Unsupported major.minor version 51.0.

This error seems to be caused by compiling with an lower version of java and running with a higher version. However, I have verified that the code is being compiled with 1.7.

Also, the job works fine when the master is set to local. How can I go about debugging and fixing this error?

A part of the error log is below.

15/01/21 15:14:57 WARN scheduler.TaskSetManager: Lost task 0.0 in stage 0.0 (TID 0, sphddp07.zzz.local): java.lang.UnsupportedClassVersionError: com/zzz/dmf/wether/MyClass: Unsupported major.minor version 51.0
          java.lang.ClassLoader.defineClass1(Native Method)
          java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
          java.lang.ClassLoader.defineClass(ClassLoader.java:615)
          java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
          java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
          java.net.URLClassLoader.access$000(URLClassLoader.java:58)
          java.net.URLClassLoader$1.run(URLClassLoader.java:197)
          java.security.AccessController.doPrivileged(Native Method)
          java.net.URLClassLoader.findClass(URLClassLoader.java:190)
          java.lang.ClassLoader.loadClass(ClassLoader.java:306)
          java.lang.ClassLoader.loadClass(ClassLoader.java:247)
          java.lang.Class.forName0(Native Method)
          java.lang.Class.forName(Class.java:247)
          org.apache.spark.serializer.JavaDeserializationStream$$anon$1.resolveClass(JavaSerializer.scala:59)
          java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1574)
          java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1495)
          java.io.ObjectInputStream.readClass(ObjectInputStream.java:1461)
          java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1311)
          java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1946)
          java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1870)
          java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1752)
          java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328)
          java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1946)
          java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1870)
          java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1752)
          java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328)
          java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
          scala.collection.immutable.$colon$colon.readObject(List.scala:362)
          sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
          sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
          java.lang.reflect.Method.invoke(Method.java:597)
          java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:969)
          java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1848)
          java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1752)
          java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328)
          java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1946)
          java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1870)
          java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1752)
          java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328)
          java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1946)
          java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1870)
          java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1752)
          java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328)
          java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
          scala.collection.immutable.$colon$colon.readObject(List.scala:362)
          sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
          sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
          java.lang.reflect.Method.invoke(Method.java:597)
          java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:969)
          java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1848)
          java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1752)
          java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328)
          java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1946)
          java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1870)
          java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1752)
          java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328)
          java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1946)
          java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1870)
          java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1752)
          java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328)
          java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
          org.apache.spark.serializer.JavaDeserializationStream.readObject(JavaSerializer.scala:62)
          org.apache.spark.serializer.JavaSerializerInstance.deserialize(JavaSerializer.scala:87)
          org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:57)
          org.apache.spark.scheduler.Task.run(Task.scala:54)
          org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:177)
          java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
          java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)

答:
Please look at the Spark version and corresponding JDK requirements from Spark Documentation page https://spark.apache.org/docs/latest/.

For example, Spark 2.4.5 runs on Java 8 and I had Java 13 on my system. Resolved the issue by moving my system to the required JDK.

Title: Spark: Unsupported class version error


问:
Python "list order"
I have 2 troubles with my data, can anyone help me:

How can I get from this:

1.

```<code>k=[['1','7', 'U1'],
 ['1.5', '8', 'U1'],
 ['2', '5.5', 'U1']]
</code>```

get this

```<code>1,7,U1
1.5,8,U1
2,5.5,U1
</code>```

EDIT 2   I MAKE SOME CHANGE ON  second case:, still searching solution for this one:

2. And how to get, from this

```<code>l=array([[[ 4.24231542], 'U1'],
       [[ 3.41424819], 'U1'],
       [[ 2.17214734], 'U1'],], dtype=object)
</code>```

get

```<code>4.24231542,U1
3.41424819,U1
2.17214734,U1
</code>```

Thanks

答:
```<code>for a in k: print ",".join (a)
</code>```

Title: Python "list order"

Body:
I have 2 troubles with my data, can anyone help me:

How can I get from this:

1.

k=[['1','7', 'U1'],
 ['1.5', '8', 'U1'],
 ['2', '5.5', 'U1']]

get this

1,7,U1
1.5,8,U1
2,5.5,U1

EDIT 2   I MAKE SOME CHANGE ON  second case:, still searching solution for this one:

2. And how to get, from this

l=array([[[ 4.24231542], 'U1'],
       [[ 3.41424819], 'U1'],
       [[ 2.17214734], 'U1'],], dtype=object)

get

4.24231542,U1
3.41424819,U1
2.17214734,U1

Thanks

Body: for a in k: print ",".join (a)


问:
AutoCloseable-ish method but runs only on catch

I would like to two have two different methods running in catch and final blocks. I have found AutoCloseable interface, but I need something to fire in case of exception only.

Like:

```<code>SomeService service = CreateService().andOpenTransaction()

try {
    service.doSomeMessyThingsInsideDB();
} catch (Exception e) {
    service.rollbackTransaction();
    throw e;
} finally {
    service.closeConnection();
}
</code>```

Is there any way to make it simpler? As I said I am familiar with AutoCloseable, but it helps me only with finally block. I still cannot use it inside the catch.

答:
You said you are familiar with AutoCloseable, but you don't use it.
Have you considered using try-with-resources statement?

Your code can be simplified to:

```<code>try (SomeService service = CreateService().andOpenTransaction()) {
    service.doSomeMessyThingsInsideDB();
} catch(exception e){
    service.rollbackTransaction();
    throw e;
}
</code>```

Oracle has great doc for that, including examples.

Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

Answering your question, this is as simple as it can get.
If your class doesn't implement Closeable then you can either implement it or use finally.

Body:
I would like to two have two different methods running in catch and final blocks. I have found AutoCloseable interface, but I need something to fire in case of exception only.

Like:

SomeService service = CreateService().andOpenTransaction()

try {
    service.doSomeMessyThingsInsideDB();
} catch (Exception e) {
    service.rollbackTransaction();
    throw e;
} finally {
    service.closeConnection();
}

Is there any way to make it simpler? As I said I am familiar with AutoCloseable, but it helps me only with finally block. I still cannot use it inside the catch.

Body:
You said you are familiar with AutoCloseable, but you don't use it.
Have you considered using try-with-resources statement?

Your code can be simplified to:

try (SomeService service = CreateService().andOpenTransaction()) {
    service.doSomeMessyThingsInsideDB();
} catch(exception e){
    service.rollbackTransaction();
    throw e;
}

Oracle has great doc for that, including examples.

Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

Answering your question, this is as simple as it can get.
If your class doesn't implement Closeable then you can either implement it or use finally.


问:
Keras module not found
I had installed TensorFlow using pip install --upgrade tensorflow.
but when I tried importing tensorflow.keras, it throws the following error. can anyone help me with this?enter image description here

答:
Please use from tensorflow import keras

or for your case, you will have to do from tensorflow.keras.models import Sequential to import Sequential model.

Title: Keras module not found


问:
How do I edit a file after I shell to a Docker container?
I successfully shelled to a Docker container using:

```<code>docker exec -i -t 69f1711a205e bash
</code>```

Now I need to edit file and I don't have any editors inside:

```<code>root@69f1711a205e:/# nano
bash: nano: command not found
root@69f1711a205e:/# pico
bash: pico: command not found
root@69f1711a205e:/# vi
bash: vi: command not found
root@69f1711a205e:/# vim
bash: vim: command not found
root@69f1711a205e:/# emacs
bash: emacs: command not found
root@69f1711a205e:/#
</code>```

How do I edit files?

答:
You can use cat if installed, with the > caracter.
Here is the manipulation :

```<code>cat > file_to_edit
#1 Write or Paste you text
#2 don't forget to leave a blank line at the end of file
#3 Ctrl + C to apply configuration
</code>```

Now you can see the result with the command

```<code>cat file
</code>```

Body:
I successfully shelled to a Docker container using:

docker exec -i -t 69f1711a205e bash

Now I need to edit file and I don't have any editors inside:

root@69f1711a205e:/# nano
bash: nano: command not found
root@69f1711a205e:/# pico
bash: pico: command not found
root@69f1711a205e:/# vi
bash: vi: command not found
root@69f1711a205e:/# vim
bash: vim: command not found
root@69f1711a205e:/# emacs
bash: emacs: command not found
root@69f1711a205e:/#

How do I edit files?

Body:
You can use cat if installed, with the > caracter.
Here is the manipulation :

cat > file_to_edit
#1 Write or Paste you text
#2 don't forget to leave a blank line at the end of file
#3 Ctrl + C to apply configuration

Now you can see the result with the command

cat file


问:
React: How can i access a attribute within a  tag
in my code, i am trying to pass some data from my onClick() function

```<code><TableCell value={i} align="center" onClick={e => this.deleteUser(e)}><DeleteIcon /></TableCell>
</code>```

My table cell is created in a for loop, and it is assigned the value i when it is first created. When the delete user icon is clicked, i want the value i to be passed along as well. in my onClick function, the even is passed along

```<code>deleteUser(e) {
        console.log(e.currentTarget).
    }
</code>```

this is my delete user function. When i test the function with console.log(). This is printed

```<code><td class="MuiTableCell-root MuiTableCell-alignCenter" value="0"> ... </td>
</code>```

How can i get value from within the td tag? I cant access it with event.currentTarget.value

答:
You can use the getAttribute property of the currentTarget.
https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute

function handleclick(e) {
var val = e.getAttribute("value");
console.log("test " + val);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
<tr><td value="55" onclick="handleclick(this)">test</td></tr>
</table></code>```

Since it's React you might want to provide the i value in the onClick directly.

```<code><TableCell align="center" onClick={e => this.deleteUser(i)}><DeleteIcon /></TableCell>
</code>```

Title: React: How can i access a attribute within a <td> tag

Body:
in my code, i am trying to pass some data from my onClick() function

<TableCell value={i} align="center" onClick={e => this.deleteUser(e)}><DeleteIcon /></TableCell>

My table cell is created in a for loop, and it is assigned the value i when it is first created. When the delete user icon is clicked, i want the value i to be passed along as well. in my onClick function, the even is passed along

deleteUser(e) {
        console.log(e.currentTarget).
    }

this is my delete user function. When i test the function with console.log(). This is printed

 ...

How can i get value from within the td tag? I cant access it with event.currentTarget.value

Body:
You can use the getAttribute property of the currentTarget.
https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute

function handleclick(e) {
var val = e.getAttribute("value");
console.log("test " + val);
}

<table>
<tr><td value="55" onclick="handleclick(this)">test</td></tr>
</table>

Since it's React you might want to provide the i value in the onClick directly.

<TableCell align="center" onClick={e => this.deleteUser(i)}><DeleteIcon /></TableCell>


问:
Trying to make a program that checks if a password contains uppercase letter and a number in c
I am trying to make a program that checks whether the password created contains an uppercase letter and a number. Both the for loops execute fine if only one of them is written without the other (one loop works fine if I comment out the other loop), but if I type them both together only the second for loop (that's associated with checking if there is a number or not) works and the other doesn't work.

So with the written code below, if I type a password that does not contain an uppercase letter nor a number I get the "Please make sure that your password contains a number and try again." message only.

Note :

I tried using the assigning the integer i to zero after the first loop and using it in the second loop instead of x but I get the same result.

I am using code::blocks compiler.

Could anyone point out where did I go wrong?

Sorry if the question isn't clear enough this is my first question here in stackoverflow, and thanks in advance.

The code :

```<code>#include <stdio.h>
#include <ctype.h>

int main()

{

    char password[25];

    int i;

    int x;

    printf("Create a strong password (must contain an uppercase letter and a number, and must be at least 8 characters) :\n");
    scanf(" %s", password);

    for (i = 0; i <= 25; i++)
    {

        if ( isupper(password[i]) == 1 )
        {
            break;
        }

        if (i == 25)
        {
            printf("\nPlease make sure that your password contains an uppercase letter and try again.\n");
        }

    }

      for (x = 0; x <= 25; x++)
    {

        if (isdigit(password[x]) == 1)
        {
            break;
        }

        if ( x == 25 )
        {
             printf("\nPlease make sure that your password contains a number and try again.\n");
        }

    }

    return 0;
}
</code>```

答:
There are a number of issues in your code, which I shall attempt to address here.

First, as mentioned in the comments, your two for loops will (most likely) go "out of bounds" as array indexes in C start at zero and end at "n - 1" (where "n" is the size of the array).

Second, the isupper() and isdigit() functions do not (necessarily) return "1" for a 'positive result' - the specification states only that they return non-zero. So, we can just test the return value as a 'Boolean' value (zero will equate to 'false' and any non-zero will equate to 'true').

Lastly, rather than run your for loops for the entire password buffer, you need only run until the terminating nul character is found - at which point you will know that a required uppercase letter or digit  is not including in the string.

Here's a 'working' version of your code, with comments added where I've made changes:

int main()
{
    char password[25];
    int i;
    int x;
    printf("Create a strong password (must contain an uppercase letter and a number, and must be at least 8 characters) :\n");
    scanf(" %s", password);
    for (i = 0; i < 25; i++) { // password[24] is the last possible element - NOT password[25].
        if (isupper(password[i])) { // "isupper()" will return NON-ZERO (but not necessarily 1!)
            break;
        }
        else if (password[i] == '\0') { // we've reached the end of the string and not found an uppercase...
            printf("\nPlease make sure that your password contains an uppercase letter and try again.\n");
            break;
        }
    }
    for (x = 0; x < 25; x++) { // as before, use "x < 25" rather than "x <= 25"
        if (isdigit(password[x])) { // "isdigit()" will return NON-ZERO (but not necessarily 1!)
            break;
        }
        else if (password[x] == '\0') { // we've reached the end of the string and not found a digit...
            printf("\nPlease make sure that your password contains a number and try again.\n");
            break;
        }
    }
    return 0;
}
```

Body:
I am trying to make a program that checks whether the password created contains an uppercase letter and a number. Both the for loops execute fine if only one of them is written without the other (one loop works fine if I comment out the other loop), but if I type them both together only the second for loop (that's associated with checking if there is a number or not) works and the other doesn't work.

So with the written code below, if I type a password that does not contain an uppercase letter nor a number I get the "Please make sure that your password contains a number and try again." message only.

Note :

I tried using the assigning the integer i to zero after the first loop and using it in the second loop instead of x but I get the same result.

I am using code::blocks compiler.

Could anyone point out where did I go wrong?

Sorry if the question isn't clear enough this is my first question here in stackoverflow, and thanks in advance.

The code :

#include <stdio.h>
#include <ctype.h>

int main()

{

    char password[25];

    int i;

    int x;

    printf("Create a strong password (must contain an uppercase letter and a number, and must be at least 8 characters) :\n");
    scanf(" %s", password);

    for (i = 0; i <= 25; i++)
    {

        if ( isupper(password[i]) == 1 )
        {
            break;
        }

        if (i == 25)
        {
            printf("\nPlease make sure that your password contains an uppercase letter and try again.\n");
        }

    }

      for (x = 0; x <= 25; x++)
    {

        if (isdigit(password[x]) == 1)
        {
            break;
        }

        if ( x == 25 )
        {
             printf("\nPlease make sure that your password contains a number and try again.\n");
        }

    }

    return 0;
}


问:
My program will not show a navigationBar after rightaccessoryview has been clicked. It only shows the view but not the navigationalBar
```<code>   - (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:    (UIControl *)control{
        NSLog(@"Disclosure button pressed");
        DetailView *tmpView = [[DetailView alloc]initWithNibName:@"DetailView" bundle:nil];
        self.detailViewController = tmpView;

        [self.navigationController pushViewController:self.detailViewController animated:YES];
        //[self.view addSubview:detailViewController.view];
        [tmpView release];
    }
</code>```

答: Are you sure the navigation controller exists in current view controller from where you click on the map annotation? Make sure self.navigationController is not nil.</p>


问:
Add row to top of table after headers
I want to add new data to a table with a form. I have it adding data at the bottom of the sheet.

I want the new info at the top.

With my code, it sends the data to two sheets, the "home" sheet and the sheet that is selected in the first combo box.

```<code>Private Sub CommandButton1_Click()
TargetSheet = ComboBox1.Value
If TargetSheet = "" Then
    Exit Sub
End If
Worksheets(TargetSheet).Activate
lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
ActiveSheet.Cells(lastrow + 1, 1).Value = TextBox1.Value
ActiveSheet.Cells(lastrow + 1, 2).Value = TextBox2.Value
ActiveSheet.Cells(lastrow + 1, 3).Value = TextBox3.Value
ActiveSheet.Cells(lastrow + 1, 4).Value = TextBox4.Value
ActiveSheet.Cells(lastrow + 1, 5).Value = TextBox5.Value
ActiveSheet.Cells(lastrow + 1, 6).Value = TextBox6.Value
ActiveSheet.Cells(lastrow + 1, 7).Value = TextBox7.Value
ActiveSheet.Cells(lastrow + 1, 8).Value = TextBox8.Value

Worksheets("Home").Activate
lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
ActiveSheet.Cells(lastrow + 1, 1).Value = ComboBox1.Value
ActiveSheet.Cells(lastrow + 1, 2).Value = TextBox1.Value
ActiveSheet.Cells(lastrow + 1, 3).Value = TextBox2.Value
ActiveSheet.Cells(lastrow + 1, 4).Value = TextBox3.Value
ActiveSheet.Cells(lastrow + 1, 5).Value = TextBox4.Value
ActiveSheet.Cells(lastrow + 1, 6).Value = TextBox5.Value
ActiveSheet.Cells(lastrow + 1, 7).Value = TextBox6.Value
ActiveSheet.Cells(lastrow + 1, 8).Value = TextBox7.Value
ActiveSheet.Cells(lastrow + 1, 9).Value = TextBox8.Value
ActiveSheet.Cells(lastrow + 1, 10).Value = Date
ActiveSheet.Cells(lastrow + 1, 11).Value = TimeValue(Now)
ActiveSheet.Cells(lastrow + 1, 12).Value = TextBox9.Value

MsgBox ("Item Added Successfully.")
TextBox1.Value = ""
TextBox2.Value = ""
TextBox3.Value = ""
TextBox4.Value = ""
Worksheets("Home").Activate
Worksheets("Home").Cells(1, 1).Select
End Sub
</code>```

How do I put the new data in the second row since I have headers on the sheet?

答:
There are a lot of stuff to improve <s>your</s> my code, but I want to keep it simple

Some things to begin:

Use option explicit so you don't have unexpected behavior with undefined variables

Always indent your code (see www.rubberduckvba.com a free tool that helps you with that)

Try to separate your logic defining variables and the reusing them

Name your forms' controls

Check a great article about UserForms (when you feel you're ready to advance)

Check the code's comments, and adapt it to fit your needs

EDIT: No need for the EntireRow qualifier as we are already selecting the whole row, and added the copy format from below

Code:

```<code>Private Sub CommandButton1_Click()

    ' Define object variables
    Dim targetSheet As Worksheet
    Dim homeSheet As Worksheet

    Dim targetSheetName As String
    Dim homeSheetName As String

    Dim targetSheetTopRow As Long
    Dim homeSheetTopRow As Long

    Dim textBox1Value As Variant
    Dim textBox2Value As Variant
    Dim textBox3Value As Variant
    Dim textBox4Value As Variant
    Dim textBox5Value As Variant
    Dim textBox6Value As Variant
    Dim textBox7Value As Variant
    Dim textBox8Value As Variant
    Dim textBox9Value As Variant

    ' Define parameters
    targetSheetTopRow = 2
    homeSheetTopRow = 2
    homeSheetName = "Home"

    ' Validate if combobox has any value
    If Me.ComboBox1.Value = vbNullString Then Exit Sub

    ' Get target sheet name
    targetSheetName = Me.ComboBox1.Value

    ' Add a reference to sheets
    Set targetSheet = ThisWorkbook.Worksheets(targetSheetName)
    Set homeSheet = ThisWorkbook.Worksheets(homeSheetName)

    ' Store current controls values
    textBox1Value = Me.TextBox1.Value
    textBox2Value = Me.TextBox2.Value
    textBox3Value = Me.TextBox3.Value
    textBox4Value = Me.TextBox4.Value
    textBox5Value = Me.TextBox5.Value
    textBox6Value = Me.TextBox6.Value
    textBox7Value = Me.TextBox7.Value
    textBox8Value = Me.TextBox8.Value

    ' No need to activate stuff
    With targetSheet
        ' Insert a row after row 2
        .Range(targetSheetTopRow & ":" & targetSheetTopRow).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrBelow

        ' Add cells values
        .Cells(targetSheetTopRow, 1).Value = textBox1Value
        .Cells(targetSheetTopRow, 2).Value = textBox2Value
        .Cells(targetSheetTopRow, 3).Value = textBox3Value
        .Cells(targetSheetTopRow, 4).Value = textBox4Value
        .Cells(targetSheetTopRow, 5).Value = textBox5Value
        .Cells(targetSheetTopRow, 6).Value = textBox6Value
        .Cells(targetSheetTopRow, 7).Value = textBox7Value
        .Cells(targetSheetTopRow, 8).Value = textBox8Value
    End With

    With homeSheet
        ' Insert a row after row 2
        .Range(homeSheetTopRow & ":" & homeSheetTopRow).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrBelow

        ' Add cells values
        .Cells(homeSheetTopRow, 1).Value = textBox1Value
        .Cells(homeSheetTopRow, 2).Value = textBox2Value
        .Cells(homeSheetTopRow, 3).Value = textBox3Value
        .Cells(homeSheetTopRow, 4).Value = textBox4Value
        .Cells(homeSheetTopRow, 5).Value = textBox5Value
        .Cells(homeSheetTopRow, 6).Value = textBox6Value
        .Cells(homeSheetTopRow, 7).Value = textBox7Value
        .Cells(homeSheetTopRow, 8).Value = textBox8Value
        .Cells(homeSheetTopRow, 9).Value = Date
        .Cells(homeSheetTopRow, 10).Value = TimeValue(Now)
        .Cells(homeSheetTopRow, 11).Value = textBox9Value
    End With

    ' Clear control's values
    Me.TextBox1.Value = vbNullString
    Me.TextBox2.Value = vbNullString
    Me.TextBox3.Value = vbNullString
    Me.TextBox4.Value = vbNullString

    ' Alert user
    MsgBox ("Item Added Successfully.")

    ' Goto...
    homeSheet.Activate
    homeSheet.Cells(1, 1).Select

End Sub
</code>```

Let me know if it works or you need more help

Title: Add row to top of table after headers

Body:
I want to add new data to a table with a form. I have it adding data at the bottom of the sheet.

I want the new info at the top.

With my code, it sends the data to two sheets, the "home" sheet and the sheet that is selected in the first combo box.

Private Sub CommandButton1_Click()
TargetSheet = ComboBox1.Value
If TargetSheet = "" Then
    Exit Sub
End If
Worksheets(TargetSheet).Activate
lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
ActiveSheet.Cells(lastrow + 1, 1).Value = TextBox1.Value
ActiveSheet.Cells(lastrow + 1, 2).Value = TextBox2.Value
ActiveSheet.Cells(lastrow + 1, 3).Value = TextBox3.Value
ActiveSheet.Cells(lastrow + 1, 4).Value = TextBox4.Value
ActiveSheet.Cells(lastrow + 1, 5).Value = TextBox5.Value
ActiveSheet.Cells(lastrow + 1, 6).Value = TextBox6.Value
ActiveSheet.Cells(lastrow + 1, 7).Value = TextBox7.Value
ActiveSheet.Cells(lastrow + 1, 8).Value = TextBox8.Value

Worksheets("Home").Activate
lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
ActiveSheet.Cells(lastrow + 1, 1).Value = ComboBox1.Value
ActiveSheet.Cells(lastrow + 1, 2).Value = TextBox1.Value
ActiveSheet.Cells(lastrow + 1, 3).Value = TextBox2.Value
ActiveSheet.Cells(lastrow + 1, 4).Value = TextBox3.Value
ActiveSheet.Cells(lastrow + 1, 5).Value = TextBox4.Value
ActiveSheet.Cells(lastrow + 1, 6).Value = TextBox5.Value
ActiveSheet.Cells(lastrow + 1, 7).Value = TextBox6.Value
ActiveSheet.Cells(lastrow + 1, 8).Value = TextBox7.Value
ActiveSheet.Cells(lastrow + 1, 9).Value = TextBox8.Value
ActiveSheet.Cells(lastrow + 1, 10).Value = Date
ActiveSheet.Cells(lastrow + 1, 11).Value = TimeValue(Now)
ActiveSheet.Cells(lastrow + 1, 12).Value = TextBox9.Value

MsgBox ("Item Added Successfully.")
TextBox1.Value = ""
TextBox2.Value = ""
TextBox3.Value = ""
TextBox4.Value = ""
Worksheets("Home").Activate
Worksheets("Home").Cells(1, 1).Select
End Sub

How do I put the new data in the second row since I have headers on the sheet?

Body:
There are a lot of stuff to improve <s>your</s> my code, but I want to keep it simple

Some things to begin:

Use option explicit so you don't have unexpected behavior with undefined variables

Always indent your code (see www.rubberduckvba.com a free tool that helps you with that)

Try to separate your logic defining variables and the reusing them

Name your forms' controls

Check a great article about UserForms (when you feel you're ready to advance)

Check the code's comments, and adapt it to fit your needs

EDIT: No need for the EntireRow qualifier as we are already selecting the whole row, and added the copy format from below

Code:

Private Sub CommandButton1_Click()

    ' Define object variables
    Dim targetSheet As Worksheet
    Dim homeSheet As Worksheet

    Dim targetSheetName As String
    Dim homeSheetName As String

    Dim targetSheetTopRow As Long
    Dim homeSheetTopRow As Long

    Dim textBox1Value As Variant
    Dim textBox2Value As Variant
    Dim textBox3Value As Variant
    Dim textBox4Value As Variant
    Dim textBox5Value As Variant
    Dim textBox6Value As Variant
    Dim textBox7Value As Variant
    Dim textBox8Value As Variant
    Dim textBox9Value As Variant

    ' Define parameters
    targetSheetTopRow = 2
    homeSheetTopRow = 2
    homeSheetName = "Home"

    ' Validate if combobox has any value
    If Me.ComboBox1.Value = vbNullString Then Exit Sub

    ' Get target sheet name
    targetSheetName = Me.ComboBox1.Value

    ' Add a reference to sheets
    Set targetSheet = ThisWorkbook.Worksheets(targetSheetName)
    Set homeSheet = ThisWorkbook.Worksheets(homeSheetName)

    ' Store current controls values
    textBox1Value = Me.TextBox1.Value
    textBox2Value = Me.TextBox2.Value
    textBox3Value = Me.TextBox3.Value
    textBox4Value = Me.TextBox4.Value
    textBox5Value = Me.TextBox5.Value
    textBox6Value = Me.TextBox6.Value
    textBox7Value = Me.TextBox7.Value
    textBox8Value = Me.TextBox8.Value

    ' No need to activate stuff
    With targetSheet
        ' Insert a row after row 2
        .Range(targetSheetTopRow & ":" & targetSheetTopRow).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrBelow

        ' Add cells values
        .Cells(targetSheetTopRow, 1).Value = textBox1Value
        .Cells(targetSheetTopRow, 2).Value = textBox2Value
        .Cells(targetSheetTopRow, 3).Value = textBox3Value
        .Cells(targetSheetTopRow, 4).Value = textBox4Value
        .Cells(targetSheetTopRow, 5).Value = textBox5Value
        .Cells(targetSheetTopRow, 6).Value = textBox6Value
        .Cells(targetSheetTopRow, 7).Value = textBox7Value
        .Cells(targetSheetTopRow, 8).Value = textBox8Value
    End With

    With homeSheet
        ' Insert a row after row 2
        .Range(homeSheetTopRow & ":" & homeSheetTopRow).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrBelow

        ' Add cells values
        .Cells(homeSheetTopRow, 1).Value = textBox1Value
        .Cells(homeSheetTopRow, 2).Value = textBox2Value
        .Cells(homeSheetTopRow, 3).Value = textBox3Value
        .Cells(homeSheetTopRow, 4).Value = textBox4Value
        .Cells(homeSheetTopRow, 5).Value = textBox5Value
        .Cells(homeSheetTopRow, 6).Value = textBox6Value
        .Cells(homeSheetTopRow, 7).Value = textBox7Value
        .Cells(homeSheetTopRow, 8).Value = textBox8Value
        .Cells(homeSheetTopRow, 9).Value = Date
        .Cells(homeSheetTopRow, 10).Value = TimeValue(Now)
        .Cells(homeSheetTopRow, 11).Value = textBox9Value
    End With

    ' Clear control's values
    Me.TextBox1.Value = vbNullString
    Me.TextBox2.Value = vbNullString
    Me.TextBox3.Value = vbNullString
    Me.TextBox4.Value = vbNullString

    ' Alert user
    MsgBox ("Item Added Successfully.")

    ' Goto...
    homeSheet.Activate
    homeSheet.Cells(1, 1).Select

End Sub

Let me know if it works or you need more help


问:
How to overrwite directory using kubectl cp
I am copying a local directory into Kubernetes pod using kubectl cp command

```<code>kubectl cp test $POD:/tmp
</code>```

It copies the test directory into Kubernetes pod /tmp directory.

Now I want to overwrite the test directory in the pod.  I did not find any option to overwrite directory while copying using kubectl cp command.

Currently, I am deleting the test directory from the pod and then copy the directory.

```<code>kubectl exec $POD -- sh -c 'rm -rf /tmp/test'
kubectl cp test $POD:/tmp
</code>```

This is working fine, but in case any error comes while copying, existing directory from pod will also be deleted.

How can I overwrite the pod directory with a local directory without deleting the pod directory first?

Thanks in advance.

答: Instead of doing "kubectl cp" everytime for your directory, mount your local directory to your pod using "volume mounts". </p>

Body:
I am copying a local directory into Kubernetes pod using kubectl cp command

kubectl cp test $POD:/tmp

It copies the test directory into Kubernetes pod /tmp directory.

Now I want to overwrite the test directory in the pod.  I did not find any option to overwrite directory while copying using kubectl cp command.

Currently, I am deleting the test directory from the pod and then copy the directory.

kubectl exec $POD -- sh -c 'rm -rf /tmp/test'
kubectl cp test $POD:/tmp

This is working fine, but in case any error comes while copying, existing directory from pod will also be deleted.

How can I overwrite the pod directory with a local directory without deleting the pod directory first?

Thanks in advance.


问:
How do I put an href link in an IOS App (OpenGL)
My App is written in OpenGL and C++, I do not use XIB file for presentation. So how can I create an href link that the user clicks and takes them someone in the browser?</p>

答: OpenGL only draws things to the screen. There's no concept of geometric objects. So you'll have to detect a click on the link text and call the appropriate iOS API invoking the URL.</p>


问:
Select the latest record for an Id per day - Oracle pl sql
How can I write a sql statement which returns the latest record per day, per an Id. Eg. with the data as below.

```<code>Id   Name        Comment         Value    DateTime
1    Tim         Test            100      02/06/2020 15:05:12
2    Sue         House           200      03/06/2020 08:25:01
1    Tim         Test            150      02/06/2020 18:05:12
3    Doug        Cars            680      10/05/2019 04:45:10
2    Sue         Tennis          200      03/06/2020 10:35:15
</code>```

I'd get :

```<code>Id   Name        Comment         Value    DateTime
1    Tim         Test            150      02/06/2020 18:05:12
3    Doug        Cars            680      10/05/2019 04:45:10
2    Sue         Tennis          200      03/06/2020 10:35:15
</code>```

Would I need a sub-select query which groups by the max date time?

答:
By using FIRST/LAST you don't need even a sub-query:</p>

```<code>WITH t(ID, NAME, COMMENT_, VALUE, DateTime) AS (
    SELECT 1,'Tim','Test', 100, TO_DATE('02/06/2020 15:05:12', 'dd/mm/yyyy hh24:mi:ss') FROM dual
    UNION ALL SELECT 2,'Sue','House', 200, TO_DATE('03/06/2020 08:25:01', 'dd/mm/yyyy hh24:mi:ss') FROM dual
    UNION ALL SELECT 1,'Tim','Test', 150, TO_DATE('02/06/2020 18:05:12', 'dd/mm/yyyy hh24:mi:ss') FROM dual
    UNION ALL SELECT 3,'Doug','Cars', 680, TO_DATE('10/05/2019 04:45:10', 'dd/mm/yyyy hh24:mi:ss') FROM dual
    UNION ALL SELECT 2,'Sue','Tennis', 300, TO_DATE('03/06/2020 10:35:15', 'dd/mm/yyyy hh24:mi:ss') FROM dual
    UNION ALL SELECT 2,'Sue','Steets', 400, TO_DATE('10/10/2020 10:35:15', 'dd/mm/yyyy hh24:mi:ss') FROM dual)
SELECT ID,
    MAX(NAME) KEEP (DENSE_RANK LAST ORDER BY DateTime) AS NAME,
    MAX(COMMENT_) KEEP (DENSE_RANK LAST ORDER BY DateTime) AS COMMENT_,
    MAX(VALUE) KEEP (DENSE_RANK LAST ORDER BY DateTime) AS VALUE,
    MAX(DateTime) KEEP (DENSE_RANK LAST ORDER BY DateTime) AS DateTime
FROM t
GROUP BY ID, TRUNC(DateTime);

+------------------------------------------+
|ID|NAME|COMMENT_|VALUE|DATETIME           |
+------------------------------------------+
|1 |Tim |Test    |150  |02.06.2020 18:05:12|
|2 |Sue |Tennis  |300  |03.06.2020 10:35:15|
|2 |Sue |Steets  |400  |10.10.2020 10:35:15|
|3 |Doug|Cars    |680  |10.05.2019 04:45:10|
+------------------------------------------+
</code>```

Body:
How can I write a sql statement which returns the latest record per day, per an Id. Eg. with the data as below.

Id   Name        Comment         Value    DateTime
1    Tim         Test            100      02/06/2020 15:05:12
2    Sue         House           200      03/06/2020 08:25:01
1    Tim         Test            150      02/06/2020 18:05:12
3    Doug        Cars            680      10/05/2019 04:45:10
2    Sue         Tennis          200      03/06/2020 10:35:15

I'd get :

Id   Name        Comment         Value    DateTime
1    Tim         Test            150      02/06/2020 18:05:12
3    Doug        Cars            680      10/05/2019 04:45:10
2    Sue         Tennis          200      03/06/2020 10:35:15

Would I need a sub-select query which groups by the max date time?

Body:
By using FIRST/LAST you don't need even a sub-query:

WITH t(ID, NAME, COMMENT_, VALUE, DateTime) AS (
    SELECT 1,'Tim','Test', 100, TO_DATE('02/06/2020 15:05:12', 'dd/mm/yyyy hh24:mi:ss') FROM dual
    UNION ALL SELECT 2,'Sue','House', 200, TO_DATE('03/06/2020 08:25:01', 'dd/mm/yyyy hh24:mi:ss') FROM dual
    UNION ALL SELECT 1,'Tim','Test', 150, TO_DATE('02/06/2020 18:05:12', 'dd/mm/yyyy hh24:mi:ss') FROM dual
    UNION ALL SELECT 3,'Doug','Cars', 680, TO_DATE('10/05/2019 04:45:10', 'dd/mm/yyyy hh24:mi:ss') FROM dual
    UNION ALL SELECT 2,'Sue','Tennis', 300, TO_DATE('03/06/2020 10:35:15', 'dd/mm/yyyy hh24:mi:ss') FROM dual
    UNION ALL SELECT 2,'Sue','Steets', 400, TO_DATE('10/10/2020 10:35:15', 'dd/mm/yyyy hh24:mi:ss') FROM dual)
SELECT ID,
    MAX(NAME) KEEP (DENSE_RANK LAST ORDER BY DateTime) AS NAME,
    MAX(COMMENT_) KEEP (DENSE_RANK LAST ORDER BY DateTime) AS COMMENT_,
    MAX(VALUE) KEEP (DENSE_RANK LAST ORDER BY DateTime) AS VALUE,
    MAX(DateTime) KEEP (DENSE_RANK LAST ORDER BY DateTime) AS DateTime
FROM t
GROUP BY ID, TRUNC(DateTime);

+------------------------------------------+
|ID|NAME|COMMENT_|VALUE|DATETIME           |
+------------------------------------------+
|1 |Tim |Test    |150  |02.06.2020 18:05:12|
|2 |Sue |Tennis  |300  |03.06.2020 10:35:15|
|2 |Sue |Steets  |400  |10.10.2020 10:35:15|
|3 |Doug|Cars    |680  |10.05.2019 04:45:10|
+------------------------------------------+


问:
Artisan, creating tables in database
I am trying to create mysql tables in Laravel 5. I created a file in /project/database/migrations called users.php:

```<code>[...]
public function up()
{
    Schema::create('users', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('username');
        $table->string('fullname');
        $table->int('number');
        $table->string('email')->unique();
        $table->string('password', 60);
        $table->rememberToken();
        $table->timestamps();
    });
}
[...]
</code>```

I then tried running these commands in the project-folder:

```<code>$ php artisan migrate
$ php artisan migrate:install
$ php artisan migrate --pretend
</code>```

None of them return any output and no tables are created. The database to be populated exists.

答:
In order to give a value in the table, we need to give a command:

```<code>php artisan make:migration create_users_table
</code>```

and after then this command line

```<code>php artisan migrate
</code>```

......

Title: Artisan, creating tables in database

Body:
I am trying to create mysql tables in Laravel 5. I created a file in /project/database/migrations called users.php:

[...]
public function up()
{
    Schema::create('users', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('username');
        $table->string('fullname');
        $table->int('number');
        $table->string('email')->unique();
        $table->string('password', 60);
        $table->rememberToken();
        $table->timestamps();
    });
}
[...]

I then tried running these commands in the project-folder:

$ php artisan migrate
$ php artisan migrate:install
$ php artisan migrate --pretend

None of them return any output and no tables are created. The database to be populated exists.

Body:
In order to give a value in the table, we need to give a command:

php artisan make:migration create_users_table

and after then this command line

php artisan migrate

......


问:
Produce messages to IBM MQ using REST API. Apache Camel
I have to send messages to IBM MQ by hitting a rest service. Below is the code I came up with, using Camel XML DSL.

```<code><rest path="/basePath">
    <post uri="/path" consumes="application/xml" produces="application/xml">
        <to uri="ibmmq:QUEUE.NAME"/>
    </post>
</rest>
</code>```

When I try to post the message, I get the following exception

```<code>org.apache.camel.RuntimeExchangeException: Failed to resolve replyTo destination on the exchange
</code>```

Is the post method expecting response back from QUEUE, so that it can respond back to rest client?
I only need the post service to reply with 200, if the message is successfully produced to QUEUE, 500 otherwise.
How to solve this problem?

答:
Pattern of your exchange is InOut so this is default behavior for your jms producer. Try change it for specific endpoint like this:</p>

```<code><to uri="ibmmq:QUEUE.NAME" pattern="InOnly"/>
</code>```

Body:
I have to send messages to IBM MQ by hitting a rest service. Below is the code I came up with, using Camel XML DSL.

<rest path="/basePath">
    <post uri="/path" consumes="application/xml" produces="application/xml">
        <to uri="ibmmq:QUEUE.NAME"/>
    </post>
</rest>

When I try to post the message, I get the following exception

org.apache.camel.RuntimeExchangeException: Failed to resolve replyTo destination on the exchange

Is the post method expecting response back from QUEUE, so that it can respond back to rest client?
I only need the post service to reply with 200, if the message is successfully produced to QUEUE, 500 otherwise.
How to solve this problem?

Body:
Pattern of your exchange is InOut so this is default behavior for your jms producer. Try change it for specific endpoint like this:

<to uri="ibmmq:QUEUE.NAME" pattern="InOnly"/>


问:
CSS menu bar to span page width
I'd like the main menu from this page http://www2.gardencomedyclub.co.uk to use the entire width of the page. I've tried using margin: 0 auto; in varying places in the #menu css tags but it keeps being left justified. I'd just like the margin between the li elements to expand to fill the full width of the #mainmenu div.
Thanks for any help!

答: From your #menu li remove float:left and instead use display:inline-block. This will however push the last li in a new row. To solve that, You will have to change the margin and padding for "a" as margin: 0 1px and padding: 0 1px. This works in IE9, FF4.01, GG11, AF5.0.5 and Opera 11.</p>

Title: CSS menu bar to span page width


问:
How to pass the model ID across the pages in Asp.Net
I want to pass the Model.Game ID from Details page to another view page which is Cart.
The way I do is inserting the @Html.DisplayFor(model => model.Game.ID) in the app-route-id. Is that appropriate to do so?

Details.cshtml

```<code>@page "{id:int}"
@model GameSanctuary.Pages.Games.DetailsModel

@{
    ViewData["Title"] = "Details";
}

<h2>Details</h2>

<div>
    <h4>Game</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Game.G_Description)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.Game.G_Description)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.Game.G_Genre)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.Game.G_Genre)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.Game.G_Price)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.Game.G_Price)
        </dd>
    </dl>
</div>
<div>
    <a asp-page="./Index">Back to List</a>
    <a asp-page="./Cart" asp-page-handler="buynow" class="btn" asp-route-id="@Html.DisplayFor(model => model.Game.ID)">Add to Cart</a>
</div>
</code>```

Cart.cshtml.cs

```<code> public async Task<IActionResult> OnGetBuyNow(int id)
        {
            cart = SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart");
            if (cart == null)
            {
                cart = new List<Item>();
                cart.Add(new Item
                {
                    Game = await _context.Game.FirstOrDefaultAsync(m => m.ID == id)
                });
                SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
            }
            return RedirectToPage("Cart");
        }
</code>```

The id value that I retrieved in OnGetBuyNow is 0 but the expected value should be 1 based on the model.Game.ID in Details.cshtml. Is that something missing in between?

答:
no, it's not appropriate.

Html.DisplayFor() renders the display template which matches whatever type you use it on. That's not what you want. What you want is a simple number surely which can be injected directly like this:

```<code>asp-route-id="@Model.Game.ID"
</code>```

I would start there and see if that gives you what you want

Body:
I want to pass the Model.Game ID from Details page to another view page which is Cart.
The way I do is inserting the @Html.DisplayFor(model => model.Game.ID) in the app-route-id. Is that appropriate to do so?

Details.cshtml

@page "{id:int}"
@model GameSanctuary.Pages.Games.DetailsModel

@{
    ViewData["Title"] = "Details";
}

Details

Game

            @Html.DisplayNameFor(model => model.Game.G_Description)

            @Html.DisplayFor(model => model.Game.G_Description)

            @Html.DisplayNameFor(model => model.Game.G_Genre)

            @Html.DisplayFor(model => model.Game.G_Genre)

            @Html.DisplayNameFor(model => model.Game.G_Price)

            @Html.DisplayFor(model => model.Game.G_Price)

    Back to List
     model.Game.ID)">Add to Cart

Cart.cshtml.cs

 public async Task<IActionResult> OnGetBuyNow(int id)
        {
            cart = SessionHelper.GetObjectFromJson<List<Item>>(HttpContext.Session, "cart");
            if (cart == null)
            {
                cart = new List<Item>();
                cart.Add(new Item
                {
                    Game = await _context.Game.FirstOrDefaultAsync(m => m.ID == id)
                });
                SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);
            }
            return RedirectToPage("Cart");
        }

The id value that I retrieved in OnGetBuyNow is 0 but the expected value should be 1 based on the model.Game.ID in Details.cshtml. Is that something missing in between?

Body:
no, it's not appropriate.

Html.DisplayFor() renders the display template which matches whatever type you use it on. That's not what you want. What you want is a simple number surely which can be injected directly like this:

asp-route-id="@Model.Game.ID"

I would start there and see if that gives you what you want


问:
How does TensorFlow calculate the gradients of an FFT layer?
If I insert the function, e.g., tf.fft(input, name=None), into a neural network, how does TensorFlow calculate the gradients in backpropagation?

I didn't find any documentation about this.

I am using TensorFlow 1.0.

答: If you're just inserting the tf.fft(...) function in the middle of a model I'm not certain tensorflow will even be able to handle a forward pass. If you read the docs on tf.signal.fft (https://www.tensorflow.org/api_docs/python/tf/signal/fft) or even just read the tf.fft function header, they both require inputs with dtype=tf.complex64 or dtype=tf.complex128. Perhaps tensorflow will cast float32 inputs to complex and then back again, allowing you to complete a forward pass, I'm not sure, but from what I can gather from reading tensorflow gradient documents casting values causes a disconnect between error gradient and Model parameters, meaning a backward pass won't work. You could try implementing a custom fft function which doesn't cast values and see if that works? It's not so easy though.</p>


问:
How to get multiple elements by class name that are changing?
Can anyone help me?
I am trying to select multiple elements by class name.
Everything is good until somewhere in the middle of page comments text is not available, just reviewers name and product that has been reviewed.
How to set it to skip the element and move to the next row if it is not present for that particular row?

edited:
  So after suggestions, I tried using the below code but Console is saying

-forEach is not a function. I am running this on the following page:
https://www.etsy.com/shop/FamilyshirtsCo/reviews

```<code>var productRows = document.getElementsByClassName("div.flag-body pb-xs-0");
productRows.forEach(function(productRow){
var name = productRow.querySelector(".p.shop2-review-attribution");
var comments = productRow.querySelector(".p.prose break-word m-xs-0");
var product = productRow.querySelector(".flag-body hide-xs hide-sm");
var final = product[i].innerText +" | "+ price[i].innerText +" | "+
quantity[i].innerText;
console.log(final);
});
</code>```

答:
Must be for loop not forEach. It is HTMLCollection not simple array.

var productRows = document.getElementsByClassName("product-row");

for ( var x = 0; x < productRows.lenght; x++) {
 var product = productRows[x].querySelector(".product");
 var price = productRows[x].querySelector(".price");
 var quantity = productRows[x].querySelector(".quantity");
 var order = product[i].innerText + " | " +
   price[i].innerText + " | " +
   quantity[i].innerText;

 console.log(order);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="product-row">
        <div class="product">
            some product
        </div>
        <div class="price">
            some price
        </div>
        <div class="quantity">
            some quantity
        </div>
    </div></code>```

Body:
Can anyone help me?
I am trying to select multiple elements by class name.
Everything is good until somewhere in the middle of page comments text is not available, just reviewers name and product that has been reviewed.
How to set it to skip the element and move to the next row if it is not present for that particular row?

edited:
  So after suggestions, I tried using the below code but Console is saying

-forEach is not a function. I am running this on the following page:
https://www.etsy.com/shop/FamilyshirtsCo/reviews

var productRows = document.getElementsByClassName("div.flag-body pb-xs-0");
productRows.forEach(function(productRow){
var name = productRow.querySelector(".p.shop2-review-attribution");
var comments = productRow.querySelector(".p.prose break-word m-xs-0");
var product = productRow.querySelector(".flag-body hide-xs hide-sm");
var final = product[i].innerText +" | "+ price[i].innerText +" | "+
quantity[i].innerText;
console.log(final);
});

Body:
Must be for loop not forEach. It is HTMLCollection not simple array.

var productRows = document.getElementsByClassName("product-row");

for ( var x = 0; x < productRows.lenght; x++) {
 var product = productRows[x].querySelector(".product");
 var price = productRows[x].querySelector(".price");
 var quantity = productRows[x].querySelector(".quantity");
 var order = product[i].innerText + " | " +
   price[i].innerText + " | " +
   quantity[i].innerText;

 console.log(order);
};

 <div class="product-row">
        <div class="product">
            some product
        </div>
        <div class="price">
            some price
        </div>
        <div class="quantity">
            some quantity
        </div>
    </div>


问:
How to run the program while it is away from the database file?
I'm trying to run my program it is away from the SQLite database file BUT there is an exception raised that says

Data Source cannot be empty.  Use :memory: to open an in-memory database

Here is my code

static string path;
static SQLiteConnection cnn = new SQLiteConnection($"Data Source={path};Pooling=true;FailIfMissing=false;Version=3");

private void Form_Load(object sender, EventArgs e) {
    OpenFileDialog ofd = new OpenFileDialog();
    if (ofd.ShowDialog() == DialogResult.OK) path = ofd.FileName;
    OpenDB();
}
```

答:
Please try to create connection object when you have path value assigned.

SQLiteConnection cnn; // requires not to be accessed until assigned
// hosting connection in the form is not the best idea so you may try to create data access object (additional class) with DB access implemented in this new class

void OpenDB(string filename)
{
 // you may want to add existing connection check and disposing code here
 cnn = new SQLiteConnection(@"Data Source=" + filename + ";Pooling=true;FailIfMissing=false;Version=3");
}

```

<p>it should be used like </p>

<pre class="lang-cs prettyprint-override"><code>        if (ofd.ShowDialog() == DialogResult.OK)
        {
            path = ofd.FileName;
            OpenDB(path);
        }
</code>```

Body:
Please try to create connection object when you have path value assigned.

SQLiteConnection cnn; // requires not to be accessed until assigned
// hosting connection in the form is not the best idea so you may try to create data access object (additional class) with DB access implemented in this new class

void OpenDB(string filename)
{
 // you may want to add existing connection check and disposing code here
 cnn = new SQLiteConnection(@"Data Source=" + filename + ";Pooling=true;FailIfMissing=false;Version=3");
}

it should be used like

        if (ofd.ShowDialog() == DialogResult.OK)
        {
            path = ofd.FileName;
            OpenDB(path);
        }


问:
SQL Error OLE.INTEROP
I'm getting an error whenever I load Management Studio or open a folder in the server explorer, etc. Additionally, If I try to create a new database it constantly is updating and does not finish. I have attached a screenshot of the error. Please let me know what I can do to fix this because it's really aggravating.

Error Screen http://frickinsweet.com/databaseError.gif

答: From MSDN forum http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=120476&SiteID=1</p>

OwnerDisplayName: Ryan Lanciaux

Title: SQL Error OLE.INTEROP

LastEditorDisplayName: Oli

OwnerDisplayName: Gulzar


答:
For margin:0 auto; to work, you need to set a width.

Use width:730px; on #menu and it should work.

Title: CSS menu bar to span page width

Body:
I'd like the main menu from this page http://www2.gardencomedyclub.co.uk to use the entire width of the page. I've tried using margin: 0 auto; in varying places in the #menu css tags but it keeps being left justified. I'd just like the margin between the li elements to expand to fill the full width of the #mainmenu div.
Thanks for any help!


问:
Pass activity result to correct fragment
I have several fragments in view pager. Some of them can trigger the method to attach some file or take a photo. Currently from the fragment I am calling method from activity to get a file (file picker intent) or taking photo (camera intent), process it in onActivityResult and would like to deliver this file to the proper fragment but sometimes it shows like the visible fragment is different than should be. I wanted to have it in one place instead of onActivityResult in each fragment that's why i wanted to put it to the activity. Is that a correct way or how can I do that correctly?

To clarify I want to pass new Object created inside the onActivityResult to show something in the fragment recycler view.

I am using below code to check the visible fragment:

```<code>private Fragment getVisibleFragment() {
        FragmentManager fragmentManager = MyActivity.this.getSupportFragmentManager();
        List<Fragment> fragments = fragmentManager.getFragments();
        for (Fragment fragment : fragments) {
            if (fragment != null && fragment.isVisible())
                return fragment;
        }
        return null;
    }
</code>```

答:
It works for me; in my app I upload multiple photos to the server,
 selecting photos from gallery in fragment and pass result activity to
 fragment.</p>

```<code> GallaryFragment mFragment = new GallaryFragment();

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == YOUR_FRAGMENT_CODE) {
        try {
            //Your Selected Data From Gallery
            mFragment.onActivityResult(requestCode, resultCode, data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    super.onActivityResult(requestCode, resultCode, data);
 }
</code>```

Body:
I have several fragments in view pager. Some of them can trigger the method to attach some file or take a photo. Currently from the fragment I am calling method from activity to get a file (file picker intent) or taking photo (camera intent), process it in onActivityResult and would like to deliver this file to the proper fragment but sometimes it shows like the visible fragment is different than should be. I wanted to have it in one place instead of onActivityResult in each fragment that's why i wanted to put it to the activity. Is that a correct way or how can I do that correctly?

To clarify I want to pass new Object created inside the onActivityResult to show something in the fragment recycler view.

I am using below code to check the visible fragment:

private Fragment getVisibleFragment() {
        FragmentManager fragmentManager = MyActivity.this.getSupportFragmentManager();
        List<Fragment> fragments = fragmentManager.getFragments();
        for (Fragment fragment : fragments) {
            if (fragment != null && fragment.isVisible())
                return fragment;
        }
        return null;
    }

Body:
It works for me; in my app I upload multiple photos to the server,
 selecting photos from gallery in fragment and pass result activity to
 fragment.

 GallaryFragment mFragment = new GallaryFragment();

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == YOUR_FRAGMENT_CODE) {
        try {
            //Your Selected Data From Gallery
            mFragment.onActivityResult(requestCode, resultCode, data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    super.onActivityResult(requestCode, resultCode, data);
 }


问:
How can you insert into an array field in a MongoDB schema in a MERN application using GraphQL?
I am learning how to develop using MongoDB, express, react, node and GraphQL. I have researched a lot and am having issues grasping one concept. My application is basically a recipe app where users are able to CRUD recipes and have an online cookbook collection of them.

With this in mind I created this schema:

```<code>const CookbookProfileSchema = mongoose.Schema({
    fName: String,
    lName: String,
    email: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'], index: true},
    password: String,
    cookbook: [{
      recipe: {
        rTitle: String,
        rDescription: String,
        rCookTime: String,
        rIngredients: [{
          iName: String,
          iMeasurement: String,
        }],
        rInstructions: [{
          text: String
        }]
    }
  }]
});
</code>```

I have only used SQL databases until now, and I have found tutorials showing me how to create 2 different schemas with a relationship but at that point wouldn't I just be better off with a relational database?

These are my type definitions:

```<code>const typeDefs = `
  type Query {
    userProfiles: [UserProfile]
    userLookup(id: ID!): [UserProfile]
    userLogin(email: String, password: String): [UserProfile]
  }
  type UserProfile{
    id: ID!
    fName: String
    lName: String
    email: String
    password: String
    cookbook: [Recipe]
  }

  type Recipe{
    rTitle: String
    rDescription: String
    rCookTime: String
    rIngredients: [Ingredient]
    rInstrctions: [Instruction]
  }

  type Ingredient{
    iname: String
    iMeasurement: String
  }

  type Instruction{
    text: String
  }

  type Mutation {
    createUser(fName: String, lName: String, email: String, password: String): UserProfile
    removeUser(id: ID!): Boolean
    updateUser(id: ID!, fName: String, lName: String): Boolean
    updatePassword(id: ID!, password: String): Boolean
  }
`
</code>```

And these are my resolvers so far:

```<code>const resolvers = {
  Query: {
    userProfiles: () => UserProfile.find(),
    //userLogin: async (_, {id}) => await UserProfile.findById(new ObjectID({id}))
    userLookup: (_, {id}) => UserProfile.find(ObjectId(id)),
    userLogin: (_, email, password) => UserProfile.find(email, password)
  },
  Mutation: {
    //User CRUD Mutations
    createUser: async (_, {fName, lName, email, password }) => {
      const user = new UserProfile({ fName, lName, email, password, cookbook: null});
      await user.save();
      return user;
    },
    removeUser: async (_, {id}) => {
      await UserProfile.findByIdAndRemove(id);
      return true;
    },
    updateUser: async (_,{id, fName, lName}) => {
      //Code in front end to check if the fname or lname is null
      await UserProfile.findByIdAndUpdate(id, {fName , lName });
      return true;
    },
    updatePassword: async (_, {id, password}) => {
      await UserProfile.findByIdAndUpdate(id, { password });
      return true;
    },

  }
}

const server = new GraphQLServer({ typeDefs, resolvers })
mongoose.connection.once('open', function() {
  server.start(() => console.log('Server is running on localhost:4000'))
});
</code>```

I am intending for a user to have many recipes, a recipe can have many ingredients and many instructions so I can display it in a list type format that they can check off for just that session or state. In a relational database I would have a table for recipes and have them relate the user. Instructions and ingredients would be related to the recipe. Then for the view I would simply query all the recipes belonging to that user to make the cookbook. How could I do something similar here or should I just go the relational route? I really want to experience how to use mongodb to it's fullest though.

Any help or advice would be greatly appreciated!

答:
I guess you already found out you don't have the hasMany, belongTo e.t.c relationship methods in MongoDB. However, it is possible for you to model the relational-type relationships with MongoDB. Check here.

Although, I should stress that "having as many tables as possible to represent the different data entities(data normalization)" like we do for SQL databases might not be a good schema design for NoSQL databases like MongoDB. Most times, you are better off having documents that are related to each other together.

Body:
I am learning how to develop using MongoDB, express, react, node and GraphQL. I have researched a lot and am having issues grasping one concept. My application is basically a recipe app where users are able to CRUD recipes and have an online cookbook collection of them.

With this in mind I created this schema:

const CookbookProfileSchema = mongoose.Schema({
    fName: String,
    lName: String,
    email: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'], index: true},
    password: String,
    cookbook: [{
      recipe: {
        rTitle: String,
        rDescription: String,
        rCookTime: String,
        rIngredients: [{
          iName: String,
          iMeasurement: String,
        }],
        rInstructions: [{
          text: String
        }]
    }
  }]
});

I have only used SQL databases until now, and I have found tutorials showing me how to create 2 different schemas with a relationship but at that point wouldn't I just be better off with a relational database?

These are my type definitions:

const typeDefs = `
  type Query {
    userProfiles: [UserProfile]
    userLookup(id: ID!): [UserProfile]
    userLogin(email: String, password: String): [UserProfile]
  }
  type UserProfile{
    id: ID!
    fName: String
    lName: String
    email: String
    password: String
    cookbook: [Recipe]
  }

  type Recipe{
    rTitle: String
    rDescription: String
    rCookTime: String
    rIngredients: [Ingredient]
    rInstrctions: [Instruction]
  }

  type Ingredient{
    iname: String
    iMeasurement: String
  }

  type Instruction{
    text: String
  }

  type Mutation {
    createUser(fName: String, lName: String, email: String, password: String): UserProfile
    removeUser(id: ID!): Boolean
    updateUser(id: ID!, fName: String, lName: String): Boolean
    updatePassword(id: ID!, password: String): Boolean
  }
`

And these are my resolvers so far:

const resolvers = {
  Query: {
    userProfiles: () => UserProfile.find(),
    //userLogin: async (_, {id}) => await UserProfile.findById(new ObjectID({id}))
    userLookup: (_, {id}) => UserProfile.find(ObjectId(id)),
    userLogin: (_, email, password) => UserProfile.find(email, password)
  },
  Mutation: {
    //User CRUD Mutations
    createUser: async (_, {fName, lName, email, password }) => {
      const user = new UserProfile({ fName, lName, email, password, cookbook: null});
      await user.save();
      return user;
    },
    removeUser: async (_, {id}) => {
      await UserProfile.findByIdAndRemove(id);
      return true;
    },
    updateUser: async (_,{id, fName, lName}) => {
      //Code in front end to check if the fname or lname is null
      await UserProfile.findByIdAndUpdate(id, {fName , lName });
      return true;
    },
    updatePassword: async (_, {id, password}) => {
      await UserProfile.findByIdAndUpdate(id, { password });
      return true;
    },

  }
}

const server = new GraphQLServer({ typeDefs, resolvers })
mongoose.connection.once('open', function() {
  server.start(() => console.log('Server is running on localhost:4000'))
});

I am intending for a user to have many recipes, a recipe can have many ingredients and many instructions so I can display it in a list type format that they can check off for just that session or state. In a relational database I would have a table for recipes and have them relate the user. Instructions and ingredients would be related to the recipe. Then for the view I would simply query all the recipes belonging to that user to make the cookbook. How could I do something similar here or should I just go the relational route? I really want to experience how to use mongodb to it's fullest though.

Any help or advice would be greatly appreciated!