问:
ASP.NET MVC Intellisense not finding ViewData
I am trying to go through the following tutorial on asp.net.  When I get down to this code:

```<code>    <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MvcApplication1.Views.Home.Index" %>
<%@ Import Namespace="MvcApplication1.Models" %>
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Release Date</th>
</tr>
<% foreach (Movie m in (IEnumerable)ViewData.Model) { %>
<tr>
      <td><%= m.Id %></td>
      <td><%= Html.Encode(m.Title) %></td>
      <td><%= m.DateReleased %></td>
 </tr>
 <% } %>
 </table>
 </asp:Content>
</code>```

When I type in ViewData it doesn't show in intellisense as if I am not including a reference or something.  Also further down Html.Encode Html doesn't show in intellisense. What am I doing wrong?

I am using the latest version of MVC.

答: Try doing a Build on your MVC project. Until the code behind has been compiled for the first time the intellisense won't work.</p>

OwnerDisplayName: RedWolves

Body:
I am trying to go through the following tutorial on asp.net.  When I get down to this code:

    <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MvcApplication1.Views.Home.Index" %>
<%@ Import Namespace="MvcApplication1.Models" %>
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">

Id
Title
Release Date

<% foreach (Movie m in (IEnumerable)ViewData.Model) { %>

      <%= m.Id %>
      <%= Html.Encode(m.Title) %>
      <%= m.DateReleased %>

 <% } %>

 </asp:Content>

When I type in ViewData it doesn't show in intellisense as if I am not including a reference or something.  Also further down Html.Encode Html doesn't show in intellisense. What am I doing wrong?

I am using the latest version of MVC.

OwnerDisplayName: thaBadDawg


来源: stackexchange

问:
How to reload resource bundle in web application?
I have resource bundle as Java class that read values from database. When i update db i need to reload bundle, but i don't know how. Anybody helps ?

```<code>package model.helpers;
public class Messages_en extends ListResourceBundle {
      protected Object[][] getContents() {
            // from DB
            // ...
      }
}
</code>```

In view i use bundle  as below:

```<code><f:loadBundle basename="model.helpers.Messages" var="m" />
</code>```

答:
This is not exactly trivial.

For one just clearing the ResourceBundle via clearCache() doesn't always yield the desired results. Often you need at least also try to clear using the context class loader:

ResourceBundle.clearCache(Thread.currentThread().getContextClassLoader());

This however will still not reload the resource bundle defined in a faces-config.xml file. At least the Mojarra JSF 1.2 implementation privately caches the resource bundle internally. This happens in:

```<code>FacesContext -> Application -> associate (ApplicationAssociate) -> resourceBundles (Map<String, ApplicationResourceBundle>()) -> resources (Map<Locale, ResourceBundle>)
</code>```

It's possible to clear this cache via reflection (at the end of the day, it's just an entry in a Map), or you might wanna replace the Application. Both are not things you normally do lightheartedly.

Purely for development you could use JRebel, which probably already has knowledge of Mojarra and most likely does the reflection trick mentioned above.

After some experimenting, I came to the following code which does the trick on JBoss AS 5/JSF 1.2. It does tie your code to Mojarra (imports sun packages) and can break with any upgrade because of reflective tricks being used. But anyway, this is the code:

```<code>public static void reloadBundle() {

    ResourceBundle.clearCache(Thread.currentThread().getContextClassLoader());

    ApplicationResourceBundle appBundle = ApplicationAssociate.getCurrentInstance().getResourceBundles().get("your_bundle_name");
    Map<Locale, ResourceBundle> resources = getFieldValue(appBundle, "resources");
    resources.clear();
}

@SuppressWarnings("unchecked")
private static <T> T getFieldValue(Object object, String fieldName) {
    try {
        Field field = object.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        return (T) field.get(object);
    } catch (Exception e) {
        return null;
    }
}
</code>```

(replace the getFieldValue helper method with your own favorite reflective util if necessary and sprinkle with exception and null handlers where appropriate)

ContentLicense: CC BY-SA 2.5

Body:
I have resource bundle as Java class that read values from database. When i update db i need to reload bundle, but i don't know how. Anybody helps ?

package model.helpers;
public class Messages_en extends ListResourceBundle {
      protected Object[][] getContents() {
            // from DB
            // ...
      }
}

In view i use bundle  as below:

<f:loadBundle basename="model.helpers.Messages" var="m" />

Body:
This is not exactly trivial.

For one just clearing the ResourceBundle via clearCache() doesn't always yield the desired results. Often you need at least also try to clear using the context class loader:

ResourceBundle.clearCache(Thread.currentThread().getContextClassLoader());

This however will still not reload the resource bundle defined in a faces-config.xml file. At least the Mojarra JSF 1.2 implementation privately caches the resource bundle internally. This happens in:

FacesContext -> Application -> associate (ApplicationAssociate) -> resourceBundles (Map<String, ApplicationResourceBundle>()) -> resources (Map<Locale, ResourceBundle>)

It's possible to clear this cache via reflection (at the end of the day, it's just an entry in a Map), or you might wanna replace the Application. Both are not things you normally do lightheartedly.

Purely for development you could use JRebel, which probably already has knowledge of Mojarra and most likely does the reflection trick mentioned above.

After some experimenting, I came to the following code which does the trick on JBoss AS 5/JSF 1.2. It does tie your code to Mojarra (imports sun packages) and can break with any upgrade because of reflective tricks being used. But anyway, this is the code:

public static void reloadBundle() {

    ResourceBundle.clearCache(Thread.currentThread().getContextClassLoader());

    ApplicationResourceBundle appBundle = ApplicationAssociate.getCurrentInstance().getResourceBundles().get("your_bundle_name");
    Map<Locale, ResourceBundle> resources = getFieldValue(appBundle, "resources");
    resources.clear();
}

@SuppressWarnings("unchecked")
private static <T> T getFieldValue(Object object, String fieldName) {
    try {
        Field field = object.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        return (T) field.get(object);
    } catch (Exception e) {
        return null;
    }
}

(replace the getFieldValue helper method with your own favorite reflective util if necessary and sprinkle with exception and null handlers where appropriate)


问:
Trying to loop advanced custom fields pro functions .php
I am using Advanced Custom Fields with wordpress but I am having an issue getting it to work with creating a short code. I want to drive my team-member post type with a short code that I Can add into visual composer but I am getting an error this is what I have tried.

```<code>function team(){

   // get posts
   $posts = get_posts(array(
    'post_type'         => 'team-member'

   ));

     if( $posts ): ?>
<?php foreach( $posts as $post ):
   setup_postdata( $post );

  $description = get_field('description');
  $name = get_field('name');

  ' i want to loop here to print out every team member

    $cnt='';
    $cnt.='<sction class="row ev-home-4">';
        $cnt.='<div class="col-sm-12 owl-carousel owl-theme" id="teams">';
            $cnt.=' <div class="item ev-home-4-block">
                        <div class="col-sm-12 ev-home-4-block-1">
                            <img src="'.get_site_url().'/wp-content/uploads/2017/11/test-1.png" class="img-responsive">
                            <div class="row row2 ev-home-4-block-2">
                                <h2>'.$name.'</h2>
                                <small>'.$description.'</small>
                            </div>
                        </div>
                    </div>';

        $cnt.='</div>';
    $cnt.='</sction>';

    <?php endif; ?>
<?php endforeach; ?>
    return $cnt;
}
add_shortcode('team','team');
</code>```

But I am getting the following error

https://preview.ibb.co/iJsi5G/chrome_2017_12_07_22_37_54.png

答:
Maybe something like : </p>

```<code>function team() {
$args = array('post_type' => 'team-member');
$return_string ="";
$the_query = new WP_Query( $args );
    while ( $the_query->have_posts() ) : $the_query->the_post();
        $return_string .= 'Your html/images etc here here';
    endwhile;
wp_reset_postdata();
return $return_string;
}

add_shortcode( 'yourShortCodeNameHere', 'team' );
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using Advanced Custom Fields with wordpress but I am having an issue getting it to work with creating a short code. I want to drive my team-member post type with a short code that I Can add into visual composer but I am getting an error this is what I have tried.

function team(){

   // get posts
   $posts = get_posts(array(
    'post_type'         => 'team-member'

   ));

     if( $posts ): ?>
<?php foreach( $posts as $post ):
   setup_postdata( $post );

  $description = get_field('description');
  $name = get_field('name');

  ' i want to loop here to print out every team member

    $cnt='';
    $cnt.='<sction class="row ev-home-4">';
        $cnt.='
';
            $cnt.='

'.$name.'

                                '.$description.'

';

        $cnt.='
';
    $cnt.='</sction>';

    <?php endif; ?>
<?php endforeach; ?>
    return $cnt;
}
add_shortcode('team','team');

But I am getting the following error

https://preview.ibb.co/iJsi5G/chrome_2017_12_07_22_37_54.png

Body:
Maybe something like :

function team() {
$args = array('post_type' => 'team-member');
$return_string ="";
$the_query = new WP_Query( $args );
    while ( $the_query->have_posts() ) : $the_query->the_post();
        $return_string .= 'Your html/images etc here here';
    endwhile;
wp_reset_postdata();
return $return_string;
}

add_shortcode( 'yourShortCodeNameHere', 'team' );


问:
Can any one explain me how does the string and number comparison work in javascript?
I have compared some strings and numbers to see the result as true and false

```<code>"dfdf" > 1
false
"dfdf" > 99
false
"dfdf" > 9999
false
"dfdf" > 99999
false
1> ''
true
1> '545'
false
1> '545d'
false
1> '555'
false
1> 'ddfdf'
false
9999 > 'dfsdfadf'
false
</code>```

I have tried few different combinations in the code as you can see but got the mixed result and want to know how exactly the comparison works in javascript.

another addition which is even more confusing

```<code>"dasfads" > "dasfdsf"
false
"abc" > "a"
true
"abc" > "agf"
false
"abcf" > "agf"
false
</code>```

答:
String Vs String

The comparison is done character by character when you are comparing strings. First different character found in both string will be compared using their char codes. (Note: Chars after that will be ignored.)

```<code>>> "a".charCodeAt(0)
97
>> "}".charCodeAt(0)
125
>> "}" > "a"
true
>> "-}" > "a"
false
</code>```

String Vs Number

Any time a string is compared with a number the string is converted into an integer and then both are compared. If the string can't be converted into a number, then it returns false. (Note: NaN, Nothing can be compared against NaN. Any comparison with NaN will return false)

```<code>>> 'dfsdfadf' > 999999 // Can't be converted to integer, hence false
false
>> 'd' > 9999999999 // Can't be converted to integer, hence false
false
>> '' == false // '' is empty string which is 0 or false
true
>> 1 > '' // '' is false,0 explained in prev case
true
</code>```

Body:
I have compared some strings and numbers to see the result as true and false

"dfdf" > 1
false
"dfdf" > 99
false
"dfdf" > 9999
false
"dfdf" > 99999
false
1> ''
true
1> '545'
false
1> '545d'
false
1> '555'
false
1> 'ddfdf'
false
9999 > 'dfsdfadf'
false

I have tried few different combinations in the code as you can see but got the mixed result and want to know how exactly the comparison works in javascript.

another addition which is even more confusing

"dasfads" > "dasfdsf"
false
"abc" > "a"
true
"abc" > "agf"
false
"abcf" > "agf"
false

Body:
String Vs String

The comparison is done character by character when you are comparing strings. First different character found in both string will be compared using their char codes. (Note: Chars after that will be ignored.)

>> "a".charCodeAt(0)
97
>> "}".charCodeAt(0)
125
>> "}" > "a"
true
>> "-}" > "a"
false

String Vs Number

Any time a string is compared with a number the string is converted into an integer and then both are compared. If the string can't be converted into a number, then it returns false. (Note: NaN, Nothing can be compared against NaN. Any comparison with NaN will return false)

>> 'dfsdfadf' > 999999 // Can't be converted to integer, hence false
false
>> 'd' > 9999999999 // Can't be converted to integer, hence false
false
>> '' == false // '' is empty string which is 0 or false
true
>> 1 > '' // '' is false,0 explained in prev case
true

ContentLicense: CC BY-SA 4.0


问:
Checkable ImageView
Does anybody know if it possible to make ImageView checkable. I try to use State-list drawable resource in my project where I define pictures for my ImageView check states, but there is no property to make ImageView checkable, only clickable.

Maybe anybody knows a way to solve this problem?

答:
If you want change check state while clicking on ImageView, change "extend ImageView" to CompoundButton.</p>

```<code>public class CheckableImageView extends CompoundButton {

    public CheckableImageView(Context context) {
        super(context);
    }

    public CheckableImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    private static final int[] CheckedStateSet = {android.R.attr.state_checked};

    public void setChecked(boolean b) {
        boolean oldState = isChecked();
        super.setChecked(b);
        if (b != oldState) {
            refreshDrawableState();
        }
    }

    @Override
    public int[] onCreateDrawableState(int extraSpace) {
        final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
        if (isChecked()) {
            mergeDrawableStates(drawableState, CheckedStateSet);
        }
        return drawableState;
    }

    @Override
    protected void drawableStateChanged() {
        super.drawableStateChanged();
        invalidate();
    }

}
</code>```

Title: Checkable ImageView

Body:
If you want change check state while clicking on ImageView, change "extend ImageView" to CompoundButton.

public class CheckableImageView extends CompoundButton {

    public CheckableImageView(Context context) {
        super(context);
    }

    public CheckableImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    private static final int[] CheckedStateSet = {android.R.attr.state_checked};

    public void setChecked(boolean b) {
        boolean oldState = isChecked();
        super.setChecked(b);
        if (b != oldState) {
            refreshDrawableState();
        }
    }

    @Override
    public int[] onCreateDrawableState(int extraSpace) {
        final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
        if (isChecked()) {
            mergeDrawableStates(drawableState, CheckedStateSet);
        }
        return drawableState;
    }

    @Override
    protected void drawableStateChanged() {
        super.drawableStateChanged();
        invalidate();
    }

}


问:
How to add value to column using dplyr lag() based on prior row value in same column
I am trying to modify a column with test values (1 or 0) based on the prior row of the same column and the value in another column. It is not a problem for one or two rows, but I need to "lead" the value for up to 50 rows which is cumbersome to code.

```<code>df <- data.frame(matrix(nrow = 10, ncol = 3))
names(df) <- c("letter", "color", "test")
df[, 1] <- c("a", "a", "b", "b", "b", "b", "b", "c", "c", "c")
df[1:2, 2] <- c("blue")
df[8:10, 2] <- c("green")
df[, 3] <- c(0, 0, 1, 0, 0, 0, 0, 0, 0, 0)
</code>```

df:

```<code>   letter color test
1       a  blue    0
2       a  blue    0
3       b  <NA>    1
4       b  <NA>    0
5       b  <NA>    0
6       b  <NA>    0
7       b  <NA>    0
8       c green    0
9       c green    0
10      c green    0
</code>```

My actual data is rather hard to recreate for this question, but this df is where I'm at after the first bit of coding - I've identified that the "1" in the test column (df[3, 3]) is where my problem starts. I now need to "lead" the 1 in the test column until the "color" is not NA and the "letter" is not "b".

Code such as the following will not suffice (even though my example makes it look like it will):

```<code>... mutate(test = ifelse(letter == "b" & is.na(color), 1, test)
</code>```

For my purposes, I need to use the following code to "lead" the 1:

```<code>df <- df %>%
  mutate(test = ifelse(lag(test) == 1 & is.na(color), 1, test))
</code>```

However, running this code will only populate the single next row:

```<code>   letter color test
1       a  blue    0
2       a  blue    0
3       b  <NA>    1
4       b  <NA>    1
5       b  <NA>    0
6       b  <NA>    0
7       b  <NA>    0
8       c green    0
9       c green    0
10      c green    0
</code>```

To accomplish this, I have been writing the same mutate command like 50 times (running over the same column). For example:

```<code>df <- df %>%
  mutate(test = ifelse(lag(test) == 1 & is.na(color), 1, test),
         test = ifelse(lag(test) == 1 & is.na(color), 1, test),
         test = ifelse(lag(test) == 1 & is.na(color), 1, test),
         test = ifelse(lag(test) == 1 & is.na(color), 1, test),
         test = ifelse(lag(test) == 1 & is.na(color), 1, test))
</code>```

This returns the desired result:

```<code>  letter color test
1       a  blue    0
2       a  blue    0
3       b  <NA>    1
4       b  <NA>    1
5       b  <NA>    1
6       b  <NA>    1
7       b  <NA>    1
8       c green    0
9       c green    0
10      c green    0
</code>```

But this is quite clumsy and potentially leaves the possibility open that I did not write enough duplicate mutate commands.

Is there a way to use dplyr (or another method) to accomplish this? A for loop could probably get the job done, but I'm not sure it's necessary. Additionally, I am still learning R and have not really been able to figure out the apply family of functions. Could an apply variant be used in this situation?

答:
If I understood you correctly then considering your example you can achieve the end result using

```<code>library(dplyr)
df %>% group_by(letter, color) %>%
  mutate(test = first(test))
</code>```

```<code>#sample data
> dput(df)
structure(list(letter = structure(c(1L, 1L, 2L, 2L, 2L, 2L, 2L,
3L, 3L, 3L), .Label = c("a", "b", "c"), class = "factor"), color = structure(c(2L,
2L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L), .Label = c("<NA>", "blue",
"green"), class = "factor"), test = c(0L, 0L, 1L, 0L, 0L, 0L,
0L, 0L, 0L, 0L)), .Names = c("letter", "color", "test"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10"))
</code>```

Body:
I am trying to modify a column with test values (1 or 0) based on the prior row of the same column and the value in another column. It is not a problem for one or two rows, but I need to "lead" the value for up to 50 rows which is cumbersome to code.

df <- data.frame(matrix(nrow = 10, ncol = 3))
names(df) <- c("letter", "color", "test")
df[, 1] <- c("a", "a", "b", "b", "b", "b", "b", "c", "c", "c")
df[1:2, 2] <- c("blue")
df[8:10, 2] <- c("green")
df[, 3] <- c(0, 0, 1, 0, 0, 0, 0, 0, 0, 0)

df:

   letter color test
1       a  blue    0
2       a  blue    0
3       b  <NA>    1
4       b  <NA>    0
5       b  <NA>    0
6       b  <NA>    0
7       b  <NA>    0
8       c green    0
9       c green    0
10      c green    0

My actual data is rather hard to recreate for this question, but this df is where I'm at after the first bit of coding - I've identified that the "1" in the test column (df[3, 3]) is where my problem starts. I now need to "lead" the 1 in the test column until the "color" is not NA and the "letter" is not "b".

Code such as the following will not suffice (even though my example makes it look like it will):

... mutate(test = ifelse(letter == "b" & is.na(color), 1, test)

For my purposes, I need to use the following code to "lead" the 1:

df <- df %>%
  mutate(test = ifelse(lag(test) == 1 & is.na(color), 1, test))

However, running this code will only populate the single next row:

   letter color test
1       a  blue    0
2       a  blue    0
3       b  <NA>    1
4       b  <NA>    1
5       b  <NA>    0
6       b  <NA>    0
7       b  <NA>    0
8       c green    0
9       c green    0
10      c green    0

To accomplish this, I have been writing the same mutate command like 50 times (running over the same column). For example:

df <- df %>%
  mutate(test = ifelse(lag(test) == 1 & is.na(color), 1, test),
         test = ifelse(lag(test) == 1 & is.na(color), 1, test),
         test = ifelse(lag(test) == 1 & is.na(color), 1, test),
         test = ifelse(lag(test) == 1 & is.na(color), 1, test),
         test = ifelse(lag(test) == 1 & is.na(color), 1, test))

This returns the desired result:

  letter color test
1       a  blue    0
2       a  blue    0
3       b  <NA>    1
4       b  <NA>    1
5       b  <NA>    1
6       b  <NA>    1
7       b  <NA>    1
8       c green    0
9       c green    0
10      c green    0

But this is quite clumsy and potentially leaves the possibility open that I did not write enough duplicate mutate commands.

Is there a way to use dplyr (or another method) to accomplish this? A for loop could probably get the job done, but I'm not sure it's necessary. Additionally, I am still learning R and have not really been able to figure out the apply family of functions. Could an apply variant be used in this situation?

Body:
If I understood you correctly then considering your example you can achieve the end result using

library(dplyr)
df %>% group_by(letter, color) %>%
  mutate(test = first(test))

#sample data
> dput(df)
structure(list(letter = structure(c(1L, 1L, 2L, 2L, 2L, 2L, 2L,
3L, 3L, 3L), .Label = c("a", "b", "c"), class = "factor"), color = structure(c(2L,
2L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L), .Label = c("<NA>", "blue",
"green"), class = "factor"), test = c(0L, 0L, 1L, 0L, 0L, 0L,
0L, 0L, 0L, 0L)), .Names = c("letter", "color", "test"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10"))


答:
You might be over complicating everything with lag. It seems that  by grouping by letter you can simply fill all the rest of the positions (after 1) where your color is NA.

```<code>library(tidyverse)

df %>%
 group_by(letter) %>%
 mutate(test = replace(test, is.na(color) & test != 1, NA)) %>%
 fill(test)
</code>```

which gives,

```<code># A tibble: 10 x 3
# Groups:   letter [3]
   letter color  test
    <chr> <chr> <dbl>
 1      a  blue     0
 2      a  blue     0
 3      b  <NA>     1
 4      b  <NA>     1
 5      b  <NA>     1
 6      b  <NA>     1
 7      b  <NA>     1
 8      c green     0
 9      c green     0
10      c green     0
</code>```

Title: How to add value to column using dplyr lag() based on prior row value in same column

Body:
You might be over complicating everything with lag. It seems that  by grouping by letter you can simply fill all the rest of the positions (after 1) where your color is NA.

library(tidyverse)

df %>%
 group_by(letter) %>%
 mutate(test = replace(test, is.na(color) & test != 1, NA)) %>%
 fill(test)

which gives,

# A tibble: 10 x 3
# Groups:   letter [3]
   letter color  test
    <chr> <chr> <dbl>
 1      a  blue     0
 2      a  blue     0
 3      b  <NA>     1
 4      b  <NA>     1
 5      b  <NA>     1
 6      b  <NA>     1
 7      b  <NA>     1
 8      c green     0
 9      c green     0
10      c green     0


问:
Redirect and 'field' keyword issues when retriving objects from database
I have 3 models Account,Company, and Products.

Company can have multiple products, Account can have multiple Companies.

```<code>class Product(Meta):
    company = models.ForeignKey(Company, related_name='products', on_delete=models.CASCADE)

class Company(Meta):
    account = models.ForeignKey(Account, related_name='account', on_delete=models.CASCADE)
</code>```

I'm using Django 2.0 new url patterns, and I defined the urls:

```<code> path('dashboard/', include('accounts.urls',  namespace='accounts')),
</code>```

in accounts urls.py

```<code> path('companies/<int:pk>/', AccountCompanyDetailView.as_view(), name='detail_company'),
</code>```

In a CBV I'm trying to get a Product instance, if the Product doesn't exist, check if Company doesn't exist and base on the above results do a redirect.

I overwrite the def get_object(self):

```<code>class AccountCProduct(DetailView):
 model = Product
    template_name_suffix = '_account_detail'

    def get_object(self):

        company_pk = self.kwargs.get('pk1')
        product_pk = self.kwargs.get('pk2')

        account = self.request.user.account
        if not account:
            raise Http404
        try:
            product = Product.objects.get(company__account=account, company__pk=company_pk, pk=product_pk)
        except Product.DoesNotExist:
            try:
                company = Company.objects.get(account=account, pk=company_pk)
                print(company)
            except Company.DoesNotExist:
                return redirect('accounts')
            print('redirect 1')
            return redirect('accounts:detail_company', pk=company_pk)

        return product
</code>```

If I use it as above (with Company code commented) when a product is wrong there is no error but redirect doesn't happen.

If I un-comment the company part, I receive field error:

```<code>Cannot resolve keyword 'company' into field.
</code>```

company is the ForeignKey on the Product Model to the Company Model.

I'm doing the Company lookup after, and not before, Product lookup not to do two lookup(s) if is not necessary.

What I want to achieve, example:

Account has 2 Companies with ids 1 and 2 and Company 1 has Product with id 1

```<code>http://127.0.0.1:8000/dashboard/companies/1/products/1/
</code>```

will go to the product of Company 1

```<code>http://127.0.0.1:8000/dashboard/companies/1/products/2/
</code>```

will fail because company 1 doesn't have a Product with id 2 and redirect to company 1 detail page

```<code>http://127.0.0.1:8000/dashboard/companies/3/products/2/
</code>```

will fail because first doesn't found the product and then doesn't found a Company with id 3 in the account and returns to account dashboard

答:
You cannot do a redirect from inside the get_object() method. That method must return a model object - you cannot return responses from there.

You need to do this logic in the get() method instead. I think it's easiest just to replace the whole method:

```<code>def get(self, request, *args, **kwargs):
    company_pk = kwargs.get('pk1')
    product_pk = kwargs.get('pk2')

    account = request.user.account
    if not account:
        raise Http404()
    try:
        self.object = Product.objects.get(company__account=account, company__pk=company_pk, pk=product_pk)
    except Product.DoesNotExist:
        try:
            company = Company.objects.get(account=account, pk=company_pk)
        except Company.DoesNotExist:
            return redirect('accounts')

        return redirect('accounts:detail_company', pk=company_pk)

    context = self.get_context_data(object=self.object)
    return self.render_to_response(context)
</code>```

Note that you are setting self.object directly here, and no longer using get_object() at all.

Body:
I have 3 models Account,Company, and Products.

Company can have multiple products, Account can have multiple Companies.

class Product(Meta):
    company = models.ForeignKey(Company, related_name='products', on_delete=models.CASCADE)

class Company(Meta):
    account = models.ForeignKey(Account, related_name='account', on_delete=models.CASCADE)

I'm using Django 2.0 new url patterns, and I defined the urls:

 path('dashboard/', include('accounts.urls',  namespace='accounts')),

in accounts urls.py

 path('companies/<int:pk>/', AccountCompanyDetailView.as_view(), name='detail_company'),

In a CBV I'm trying to get a Product instance, if the Product doesn't exist, check if Company doesn't exist and base on the above results do a redirect.

I overwrite the def get_object(self):

class AccountCProduct(DetailView):
 model = Product
    template_name_suffix = '_account_detail'

    def get_object(self):

        company_pk = self.kwargs.get('pk1')
        product_pk = self.kwargs.get('pk2')

        account = self.request.user.account
        if not account:
            raise Http404
        try:
            product = Product.objects.get(company__account=account, company__pk=company_pk, pk=product_pk)
        except Product.DoesNotExist:
            try:
                company = Company.objects.get(account=account, pk=company_pk)
                print(company)
            except Company.DoesNotExist:
                return redirect('accounts')
            print('redirect 1')
            return redirect('accounts:detail_company', pk=company_pk)

        return product

If I use it as above (with Company code commented) when a product is wrong there is no error but redirect doesn't happen.

If I un-comment the company part, I receive field error:

Cannot resolve keyword 'company' into field.

company is the ForeignKey on the Product Model to the Company Model.

I'm doing the Company lookup after, and not before, Product lookup not to do two lookup(s) if is not necessary.

What I want to achieve, example:

Account has 2 Companies with ids 1 and 2 and Company 1 has Product with id 1

http://127.0.0.1:8000/dashboard/companies/1/products/1/

will go to the product of Company 1

http://127.0.0.1:8000/dashboard/companies/1/products/2/

will fail because company 1 doesn't have a Product with id 2 and redirect to company 1 detail page

http://127.0.0.1:8000/dashboard/companies/3/products/2/

will fail because first doesn't found the product and then doesn't found a Company with id 3 in the account and returns to account dashboard

Body:
You cannot do a redirect from inside the get_object() method. That method must return a model object - you cannot return responses from there.

You need to do this logic in the get() method instead. I think it's easiest just to replace the whole method:

def get(self, request, *args, **kwargs):
    company_pk = kwargs.get('pk1')
    product_pk = kwargs.get('pk2')

    account = request.user.account
    if not account:
        raise Http404()
    try:
        self.object = Product.objects.get(company__account=account, company__pk=company_pk, pk=product_pk)
    except Product.DoesNotExist:
        try:
            company = Company.objects.get(account=account, pk=company_pk)
        except Company.DoesNotExist:
            return redirect('accounts')

        return redirect('accounts:detail_company', pk=company_pk)

    context = self.get_context_data(object=self.object)
    return self.render_to_response(context)

Note that you are setting self.object directly here, and no longer using get_object() at all.


问:
How to convert QVariant to QJsonValue?
How to convert QVariant to QJsonValue?
I know QVariant provide the toJsonValue function, but it did not perform as expected.

For example:

```<code>qDebug()<<QVariant(1.0).toJsonValue();
qDebug()<<QVariant("test").toJsonValue();
</code>```

Both return:

```<code>QJsonValue(null)
QJsonValue(null)
</code>```

Expect output:

```<code>QJsonValue(double, 1)
QJsonValue(string, "test")
</code>```

答:
You might do the following:

```<code>QVariant dblVariant(1.0);
QVariant strVariant("test");

QJsonValue dblJs(dblVariant.toDouble());
QJsonValue strJs(strVariant.toString());
</code>```

Your approach doesn't work because variant object should have user type QJsonValue, but it doesn't. Therefore it returns default constructed QJsonValue object.

Title: How to convert QVariant to QJsonValue?

Body:
How to convert QVariant to QJsonValue?
I know QVariant provide the toJsonValue function, but it did not perform as expected.

For example:

qDebug()<<QVariant(1.0).toJsonValue();
qDebug()<<QVariant("test").toJsonValue();

Both return:

QJsonValue(null)
QJsonValue(null)

Expect output:

QJsonValue(double, 1)
QJsonValue(string, "test")

Body:
You might do the following:

QVariant dblVariant(1.0);
QVariant strVariant("test");

QJsonValue dblJs(dblVariant.toDouble());
QJsonValue strJs(strVariant.toString());

Your approach doesn't work because variant object should have user type QJsonValue, but it doesn't. Therefore it returns default constructed QJsonValue object.


问:
Is it possible to have multiple STDIN streams?
I'm hoping to connect two USB barcode scanners to a single computer, allowing two people to scan ticket barcodes simultaneously.  If both people scan at the same time, however, the input from STDIN will get messy.

Is there a way to set up different STDIN streams, each tied to a specific USB port?  The console script is in Ruby, though pointers in any language would be much appreciated.

答:
Try connecting 2 USB barcode scanners first and test if what you are afraid of happens. I suspect all barcode digits are sent in a single burst while interrupts from other keyboard-like devices are on hold - so you won't get two barcodes "interlaced" together.

It's impossible to have more than one stdin, not literally. Other options will depend based on the OS you are on - on linux maybe the drivers provide you different character devices for different scanners. On Windows i believe you will have to learn talking the USB HID protocol... best if you don't have to do any of that.


问:
How do I set the default value Point(0,0) for center and radius = 1?
Please help me modify this class Circle, (1) setting a default instance.

The circle class uses a Point object as the center. Use center and radius keywords, with the center as the first parameter. Use repr and str . When assigning point object and radius value to a circle,
the output should look like this for assigned values

this is what I am getting

Defaults for a circle with no inputs are: center at a default instance of a
    Point object, and radius of 1.

This is how the output should look like for default values

This is what I am getting for defaults

If I am to change the following

```<code>def __repr__(self):
     return "Circle(center=Point({0}, {1}), radius={2})"
                .format(self.center.x,self.center.y,self.radius)
</code>```

to this:

```<code>def __repr__(self):
      return "Circle(center=Point({0}, {1}), radius {2})"
                 .format(self.center[0],self.center[1],self.radius)
</code>```

This will create an error, because point object for assigned center Point(2, 3) does not support indexing.

```<code> import math
class Point:
    def __init__(self,x=0,y=0):
        self.x = x
        self.y = y
    def __iter__(self):
        yield self.x
        yield self.y
    def __add__(self,other):
        return Point(self.x+other.x,self.y+other.y)
    def __mul__(self,n):
        return Point(self.x*n,self.y*n)
    def __rmul__(self,n):
        return Point(n*self.x,n*self.y)
    @classmethod
    def from_tuple (cls, self=(0,0)):
        return cls(*self)
    def loc_from_tuple(self,t=(0,0)):
        self.x=t[0]
        self.y=t[1]
    def __str__(self):
        return "Point at ({0}, {1})".format(self.x,self.y)
    def __repr__(self):
        return"Point(x={0}, y={1})".format(self.x,self.y)
    @property
    def magnitude(self):
        return math.sqrt(self.x**2+self.y**2)
    def distance (self, other):
        return math.sqrt((self.x-other.x)**2+(self.y-other.y)**2)
    def shift(p1, p2):
        mx = p1.x+p2.x
        my = p1.y+p2.y
        return Point(mx,my)
class Circle(Point):
    def __init__(self, center=(0,0), radius=1):
        Point.__init__(self,center)
        self.center=center
        self.radius=radius
    def __str__(self):
        return "Circle with center at ({0}, {1}) and radius {2}"
        .format(self.center.x, self.center.y, self.radius)
    def __repr__(self):
        return "Circle(center=Point({0}, {1}), radius={2})"
        .format(self.center.x,self.center.y,self.radius)
    def __add__(self,other):
        return Circle(
        Point(self.center.x+other.center.x,
        self.center.y+other.center.y),
        self.radius+other.radius)
    @classmethod
    def from_tuple(cls, center,radius):
        return cls(center, radius)
    @property
    def radius(self):
        return self._radius
    @radius.setter
    def radius(self, radius):
        if radius<0:
            raise ValueError('The radius cannot be negative')
        self._radius=radius
    @property
    def diameter(self):
        return self._radius*2
    @diameter.setter
    def diameter(self, diameter):
        if diameter<0:
            raise ValueError('The radius cannot be negative')
        self._radius = diameter/2
    @property
    def area(self):
        return math.pi*self.radius**2
</code>```

答:
Center is a tuple, so it does not have an attribute x. Here you define center:

```<code>class Circle(Point):
    def __init__(self, center=(0,0), radius=1):
        Point.__init__(self,center)
        self.center=center
</code>```

And here you call center.x

```<code>def __repr__(self):
    return "Circle(center=Point({0}, {1}), radius={2})"
    .format(self.center.x,self.center.y,self.radius)
</code>```

A quick workaround would be to change __repr__ to something like:

```<code>def __repr__(self):
    return "Circle(center=Point({0}, {1}), radius={2})"
    .format(self.center[0],self.center[1],self.radius)
</code>```

That way you will be indexing the tuple. Another approach will be to make center a dictionary like center = {'x':0, 'y'0}. Then __repr__ will work as is although you will have to go through the rest of your program to ensure consistency.

Body:
Please help me modify this class Circle, (1) setting a default instance.

The circle class uses a Point object as the center. Use center and radius keywords, with the center as the first parameter. Use repr and str . When assigning point object and radius value to a circle,
the output should look like this for assigned values

this is what I am getting

Defaults for a circle with no inputs are: center at a default instance of a
    Point object, and radius of 1.

This is how the output should look like for default values

This is what I am getting for defaults

If I am to change the following

def __repr__(self):
     return "Circle(center=Point({0}, {1}), radius={2})"
                .format(self.center.x,self.center.y,self.radius)

to this:

def __repr__(self):
      return "Circle(center=Point({0}, {1}), radius {2})"
                 .format(self.center[0],self.center[1],self.radius)

This will create an error, because point object for assigned center Point(2, 3) does not support indexing.

 import math
class Point:
    def __init__(self,x=0,y=0):
        self.x = x
        self.y = y
    def __iter__(self):
        yield self.x
        yield self.y
    def __add__(self,other):
        return Point(self.x+other.x,self.y+other.y)
    def __mul__(self,n):
        return Point(self.x*n,self.y*n)
    def __rmul__(self,n):
        return Point(n*self.x,n*self.y)
    @classmethod
    def from_tuple (cls, self=(0,0)):
        return cls(*self)
    def loc_from_tuple(self,t=(0,0)):
        self.x=t[0]
        self.y=t[1]
    def __str__(self):
        return "Point at ({0}, {1})".format(self.x,self.y)
    def __repr__(self):
        return"Point(x={0}, y={1})".format(self.x,self.y)
    @property
    def magnitude(self):
        return math.sqrt(self.x**2+self.y**2)
    def distance (self, other):
        return math.sqrt((self.x-other.x)**2+(self.y-other.y)**2)
    def shift(p1, p2):
        mx = p1.x+p2.x
        my = p1.y+p2.y
        return Point(mx,my)
class Circle(Point):
    def __init__(self, center=(0,0), radius=1):
        Point.__init__(self,center)
        self.center=center
        self.radius=radius
    def __str__(self):
        return "Circle with center at ({0}, {1}) and radius {2}"
        .format(self.center.x, self.center.y, self.radius)
    def __repr__(self):
        return "Circle(center=Point({0}, {1}), radius={2})"
        .format(self.center.x,self.center.y,self.radius)
    def __add__(self,other):
        return Circle(
        Point(self.center.x+other.center.x,
        self.center.y+other.center.y),
        self.radius+other.radius)
    @classmethod
    def from_tuple(cls, center,radius):
        return cls(center, radius)
    @property
    def radius(self):
        return self._radius
    @radius.setter
    def radius(self, radius):
        if radius<0:
            raise ValueError('The radius cannot be negative')
        self._radius=radius
    @property
    def diameter(self):
        return self._radius*2
    @diameter.setter
    def diameter(self, diameter):
        if diameter<0:
            raise ValueError('The radius cannot be negative')
        self._radius = diameter/2
    @property
    def area(self):
        return math.pi*self.radius**2

Body:
Center is a tuple, so it does not have an attribute x. Here you define center:

class Circle(Point):
    def __init__(self, center=(0,0), radius=1):
        Point.__init__(self,center)
        self.center=center

And here you call center.x

def __repr__(self):
    return "Circle(center=Point({0}, {1}), radius={2})"
    .format(self.center.x,self.center.y,self.radius)

A quick workaround would be to change __repr__ to something like:

def __repr__(self):
    return "Circle(center=Point({0}, {1}), radius={2})"
    .format(self.center[0],self.center[1],self.radius)

That way you will be indexing the tuple. Another approach will be to make center a dictionary like center = {'x':0, 'y'0}. Then __repr__ will work as is although you will have to go through the rest of your program to ensure consistency.


答:
The error message tells you everything you need to know:
    AttributeError: 'tuple' object has no attribute 'x'

The offending line is this one:

```<code>return "Circle(center=Point({0}, {1}), radius={2})"
.format(self.center.x,self.center.y,self.radius)
</code>```

The object center is a tuple, meaning its variables are accessed with indices, not attribute names. Try instead:

```<code>return "Circle(center=Point({0}, {1}), radius={2})"
.format(self.center[0],self.center[1],self.radius)
</code>```

What would be even better is to actually make use of the inheritance Circle has from Point and access x and y directly - there is no reason to keep the center as an instance variable if you have all you need already there:

```<code>return "Circle(center=Point({0}, {1}), radius={2})"
.format(self.x,self.y,self.radius)
</code>```

Title: How do I set the default value Point(0,0) for center and radius = 1?

Body:
The error message tells you everything you need to know:
    AttributeError: 'tuple' object has no attribute 'x'

The offending line is this one:

return "Circle(center=Point({0}, {1}), radius={2})"
.format(self.center.x,self.center.y,self.radius)

The object center is a tuple, meaning its variables are accessed with indices, not attribute names. Try instead:

return "Circle(center=Point({0}, {1}), radius={2})"
.format(self.center[0],self.center[1],self.radius)

What would be even better is to actually make use of the inheritance Circle has from Point and access x and y directly - there is no reason to keep the center as an instance variable if you have all you need already there:

return "Circle(center=Point({0}, {1}), radius={2})"
.format(self.x,self.y,self.radius)


问:
How can I make this css animation smooth
In the below example you can see the boxes jumping a little bit, How can I make that transition smooth?

.container {
  text-align: center;
  margin-top: 30px;
}

.box {
  background: rgba(0, 10, 103, 0.5);
  height: 50px;
  width: 50px;
  border: 3px solid rgba(0, 10, 103, 0.9);
  margin: 10px;
  display: inline-block;
  animation: updn 1s infinite ease-out;
}

.box:nth-child(2) {
  animation-delay: 1.2s;
}

.box:nth-child(3) {
  animation-delay: 1.4s;
}

@keyframes updn {
  0% {
    transform: translateY(-10px) translateX(10px);
  }
  50% {
    transform: translateY(0px);
  }
  75% {
    transform: translateY(10px);
  }
  100% {
    transform: translateY(0px) translateX(0px);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div></code>```

答:
It looks like the jump between the start and end of the animation is too big and that's causing a jump.

This CSS should improve the smoothness:

```<code>@keyframes updn {
      0% {
        transform: translateY(0px);
      }
      25% {
        transform: translateY(-5px) translateX(5px);
      }
      50% {
        transform: translateY(-10px) translateX(10px);
      }
      75% {
        transform: translateY(-5px) translateX(5px);
      }
      100% {
        transform: translateY(0px);
      }
    }
</code>```

This is how it looks:

.container {
  text-align: center;
  margin-top: 30px;
}

.box {
  background: rgba(0, 10, 103, 0.5);
  height: 50px;
  width: 50px;
  border: 3px solid rgba(0, 10, 103, 0.9);
  margin: 10px;
  display: inline-block;
  animation: updn 1s infinite ease-out;
}

.box:nth-child(2) {
  animation-delay: 1.2s;
}

.box:nth-child(3) {
  animation-delay: 1.4s;
}

@keyframes updn {
  0% {
    transform: translateY(0px);
  }
  25% {
    transform: translateY(-5px) translateX(5px);
  }
  50% {
    transform: translateY(-10px) translateX(10px);
  }
  75% {
    transform: translateY(-5px) translateX(5px);
  }
  100% {
    transform: translateY(0px);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div></code>```

Body:
It looks like the jump between the start and end of the animation is too big and that's causing a jump.

This CSS should improve the smoothness:

@keyframes updn {
      0% {
        transform: translateY(0px);
      }
      25% {
        transform: translateY(-5px) translateX(5px);
      }
      50% {
        transform: translateY(-10px) translateX(10px);
      }
      75% {
        transform: translateY(-5px) translateX(5px);
      }
      100% {
        transform: translateY(0px);
      }
    }

This is how it looks:

.container {
  text-align: center;
  margin-top: 30px;
}

.box {
  background: rgba(0, 10, 103, 0.5);
  height: 50px;
  width: 50px;
  border: 3px solid rgba(0, 10, 103, 0.9);
  margin: 10px;
  display: inline-block;
  animation: updn 1s infinite ease-out;
}

.box:nth-child(2) {
  animation-delay: 1.2s;
}

.box:nth-child(3) {
  animation-delay: 1.4s;
}

@keyframes updn {
  0% {
    transform: translateY(0px);
  }
  25% {
    transform: translateY(-5px) translateX(5px);
  }
  50% {
    transform: translateY(-10px) translateX(10px);
  }
  75% {
    transform: translateY(-5px) translateX(5px);
  }
  100% {
    transform: translateY(0px);
  }
}

<div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>


问:
How to set an active tab
i did a tabbed menu on bootstrap. But i can't figure out active tab

How to style active tab, When i  define active class, it only effects first tab.

screenshot

heres my code below

```<code>    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
      <script>
   jQuery(function($){
       $(".circle").children("circle").click(function(){
           $(".active").removeClass("active");
       });
   });
</script>
  </head>
  <body>

<!-- Nav tabs --><div class="d-none d-sm-block girintile">
<ul class="nav nav-justified" role="tablist">
  <li class="nav-item">
      <a class="nav-link active" data-toggle="tab" href="#section-1" role="tab"> <div class="team-box"> <img src="kisi.png" class="img-fluid rounded-circle circle active"> <h4 class="no-a">Yunus Melih Gözütok</h4><p>CEO</p> </div></a>
  </li>
  <li class="nav-item">
    <a class="nav-link" data-toggle="tab" href="#section-2" role="tab"><div class="team-box"> <img src="kisi.png" class="img-fluid rounded-circle circle"> <h4 class="no-a">Yunus Melih Gözütok</h4><p>CEO</p> </div></a>
  </li>
  <li class="nav-item">
    <a class="nav-link" data-toggle="tab" href="#section-3" role="tab"><div class="team-box"> <img src="kisi.png" class="img-fluid rounded-circle circle"> <h4 class="no-a">Yunus Melih Gözütok</h4><p>CEO</p> </div></a>
  </li>
  <li class="nav-item">
    <a class="nav-link" data-toggle="tab" href="#section-4" role="tab"><div class="team-box"> <img src="kisi.png" class="img-fluid rounded-circle circle"> <h4 class="no-a">Yunus Melih Gözütok</h4><p>CEO</p> </div></a>
  </li>
    <li class="nav-item">
    <a class="nav-link" data-toggle="tab" href="#section-5" role="tab"><div class="team-box"> <img src="kisi.png" class="img-fluid rounded-circle circle"> <h4 class="no-a">Yunus Melih Gözütok</h4><p>CEO</p> </div></a>
  </li>
</ul></div>

<!-- Tab panes -->
<div class="tab-content girintile "><br>
  <div class="tab-pane box active" id="section-1" role="tabpanel"><h4 class="bg-grey">Yunus Melih Gözütok</h4><p class="text-justified girintile"> yunus</p></div>
  <div class="tab-pane box" id="section-2" role="tabpanel"><h4 class="bg-grey">Yunus Melih Gözütok1</h4><p class="text-justified girintile"> melih</p></div>
  <div class="tab-pane box" id="section-3" role="tabpanel"><h4 class="bg-grey">Yunus Melih Gözütok2</h4><p class="text-justified girintile"> gözütok</p></div>
  <div class="tab-pane box" id="section-4" role="tabpanel"><h4 class="bg-grey">Yunus Melih Gözütok3</h4><p class="text-justified girintile"> lipsum</p></div>
  <div class="tab-pane box" id="section-5" role="tabpanel"><h4 class="bg-grey">Yunus Melih Gözütok4</h4><p class="text-justified girintile"> lipsum</p></div>
</div>
</code>```

答:
Just use this code will do </p>

```<code>$(".nav-item .nav-link").click(function(e){
  e.preventDefault();
  $(this).addClass("active");
  $(".nav-item .nav-link").not($(this)).removeClass("active");
})
</code>```

Title: How to set an active tab

Body:
i did a tabbed menu on bootstrap. But i can't figure out active tab

How to style active tab, When i  define active class, it only effects first tab.

screenshot

heres my code below

Yunus Melih Gözütok

CEO

Yunus Melih Gözütok

CEO

Yunus Melih Gözütok

CEO

Yunus Melih Gözütok

CEO

Yunus Melih Gözütok

CEO

Yunus Melih Gözütok

 yunus

Yunus Melih Gözütok1

 melih

Yunus Melih Gözütok2

 gözütok

Yunus Melih Gözütok3

 lipsum

Yunus Melih Gözütok4

 lipsum

Body:
Just use this code will do

$(".nav-item .nav-link").click(function(e){
  e.preventDefault();
  $(this).addClass("active");
  $(".nav-item .nav-link").not($(this)).removeClass("active");
})


问:
PHP Query won't work with DELETE
I have connection, and I wan't delete one record by choosing ID (option have value of row ID in db)

```<code><form class="form">
      <?php
      require "connect.php";
      $select = $_POST['del_zaint'];
      if(isset($_POST['Del'])){
        $$que = "DELETE FROM `zainteresowania` WHERE `zainteresowania`.`id` = '".$select."'";
        mysqli_query($db, $que);
      }
      mysqli_close($db);
      ?>

      <span class="main-page__info">Usuń rekord zainteresowań.</span>
      <select name="del_zaint">
        <option disabled selected>Wybierz rekord do usunięcia</option>
        <?php
        require "connect.php";
        $que = "SELECT * from zainteresowania";
        $wynik = mysqli_query($db, $que);
        while($row = mysqli_fetch_array($wynik)){
          echo "<option value=".$row['id'].">"."[".$row['id']."] ".$row['zainteresowanie']."</option>";
        }
        mysqli_close($db);
        ?>
      </select>
      <input name="Del" type="submit" value="Usuń">
    </form>
</code>```

Nothing is done by this :/ I choose option and after clicking submit with name = Del, it won't work, just reset to normal position. (Adding informations to db and showing from it works well)

答:
Please change this to:

```<code>require "connect.php";
$select = $_POST['del_zaint'];
if(isset($_POST['Del'])){
  $que = "DELETE FROM `zainteresowania` WHERE `zainteresowania`.`id` = $select";
  mysqli_query($db, $que);
}
mysqli_close($db);
</code>```

I have had cases where PHP only notices variables if they are included directly in double quotes and but not single quotes. The other option is to use string concatenation so that PHP knows where the variable is.

```<code>require "connect.php";
    $select = $_POST['del_zaint'];
    if(isset($_POST['Del'])){
      $que = "DELETE FROM `zainteresowania` WHERE `zainteresowania`.`id` = '".$select."'";
      mysqli_query($db, $que);
    }
    mysqli_close($db);
</code>```

Title: PHP Query won't work with DELETE

Body:
I have connection, and I wan't delete one record by choosing ID (option have value of row ID in db)

<form class="form">
      <?php
      require "connect.php";
      $select = $_POST['del_zaint'];
      if(isset($_POST['Del'])){
        $$que = "DELETE FROM `zainteresowania` WHERE `zainteresowania`.`id` = '".$select."'";
        mysqli_query($db, $que);
      }
      mysqli_close($db);
      ?>

      Usuń rekord zainteresowań.
      <select name="del_zaint">
        <option disabled selected>Wybierz rekord do usunięcia</option>
        <?php
        require "connect.php";
        $que = "SELECT * from zainteresowania";
        $wynik = mysqli_query($db, $que);
        while($row = mysqli_fetch_array($wynik)){
          echo "<option value=".$row['id'].">"."[".$row['id']."] ".$row['zainteresowanie']."</option>";
        }
        mysqli_close($db);
        ?>
      </select>
      <input name="Del" type="submit" value="Usuń">
    </form>

Nothing is done by this :/ I choose option and after clicking submit with name = Del, it won't work, just reset to normal position. (Adding informations to db and showing from it works well)

Body:
Please change this to:

require "connect.php";
$select = $_POST['del_zaint'];
if(isset($_POST['Del'])){
  $que = "DELETE FROM `zainteresowania` WHERE `zainteresowania`.`id` = $select";
  mysqli_query($db, $que);
}
mysqli_close($db);

I have had cases where PHP only notices variables if they are included directly in double quotes and but not single quotes. The other option is to use string concatenation so that PHP knows where the variable is.

require "connect.php";
    $select = $_POST['del_zaint'];
    if(isset($_POST['Del'])){
      $que = "DELETE FROM `zainteresowania` WHERE `zainteresowania`.`id` = '".$select."'";
      mysqli_query($db, $que);
    }
    mysqli_close($db);


问:
Mongo db project a field not in the group
I'm wondering if I can project field is not exist in the group.
For example I have the below collections and I want the name of students who has highest soccer across all students

```<code>{ "_id" : 1, "Snmae" : Alex, "score" : 97}
{ "_id" : 2, "Snmae" : Sara, "socre" : 97 }
{ "_id" : 3, "Snmae" : Sam, "socre" : 93 }
{ "_id" : 4, "Snmae" : Dan, "socre" : 77 }

db.stuudent.aggregate(
{$project:{_id:0,sname:1,score:1}},
{ $group : { _id : "", High_Score: { $max: "$score" }}}
 );
</code>```

The desire output is

Sname: Alex  ,  score: 97

Sname: Sara  ,  score: 97

答:
Data:

```<code>{ "_id" : 1.0, "Sname" : "Alex", "score" : 97.0 },
{ "_id" : 2.0, "Sname" : "Sara", "score" : 97.0 },
{ "_id" : 3.0, "Sname" : "Sam", "score" : 93.0 },
{ "_id" : 4.0, "Sname" : "Dan", "score" : 77.0 }
</code>```

Query:

```<code>db.collection.aggregate([
    {
        $group: {
            _id: "$score",
            "names": { $push: "$Sname" }
        }
    },
    { $sort: { "_id": -1 } },
    { $limit: 1},
    { $unwind: "$names" },
    {
        $project: {
            "Sname": "$names",
            "score": "$_id",
            "_id": 0
        }
    }
])
</code>```

Explanation:

$group - groups the students by score.

$sort - sorts the documents by score in the descending direction.

$limit - takes only first document (document with highest score value).

$unwind - splits "names" array into separated documents.

$project - generates the final results (documents with defined shape).

Body:
I'm wondering if I can project field is not exist in the group.
For example I have the below collections and I want the name of students who has highest soccer across all students

{ "_id" : 1, "Snmae" : Alex, "score" : 97}
{ "_id" : 2, "Snmae" : Sara, "socre" : 97 }
{ "_id" : 3, "Snmae" : Sam, "socre" : 93 }
{ "_id" : 4, "Snmae" : Dan, "socre" : 77 }

db.stuudent.aggregate(
{$project:{_id:0,sname:1,score:1}},
{ $group : { _id : "", High_Score: { $max: "$score" }}}
 );

The desire output is

Sname: Alex  ,  score: 97

Sname: Sara  ,  score: 97

Body:
Data:

{ "_id" : 1.0, "Sname" : "Alex", "score" : 97.0 },
{ "_id" : 2.0, "Sname" : "Sara", "score" : 97.0 },
{ "_id" : 3.0, "Sname" : "Sam", "score" : 93.0 },
{ "_id" : 4.0, "Sname" : "Dan", "score" : 77.0 }

Query:

db.collection.aggregate([
    {
        $group: {
            _id: "$score",
            "names": { $push: "$Sname" }
        }
    },
    { $sort: { "_id": -1 } },
    { $limit: 1},
    { $unwind: "$names" },
    {
        $project: {
            "Sname": "$names",
            "score": "$_id",
            "_id": 0
        }
    }
])

Explanation:

$group - groups the students by score.

$sort - sorts the documents by score in the descending direction.

$limit - takes only first document (document with highest score value).

$unwind - splits "names" array into separated documents.

$project - generates the final results (documents with defined shape).


问:
sqlite wrapper in vc++?
I'm going to use a wrapper for opening .sqlite files and exploring their contents. here is the wrapper which I'm going to use:
SQLite C++ Wrapper

But I don't know how to use it! can anyone help me please?
Can you introduce me a library with a better documentation?

thanks so much

答:
On this page you have both an updated source and documentation in pdf for sqlite3x.

http://www.wanderinghorse.net/computing/sqlite/

Title: sqlite wrapper in vc++?


问:
How to continue recording even after pressing the home button?
I'm programming an Android application (I'm using Android Studio).

I start the recording with the following code (this is just a fragment):

```<code>public void start() {
    int minBufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNELS, AUDIO_ENCODING);
    audioRecord = new AudioRecord(
            MediaRecorder.AudioSource.MIC,
            SAMPLE_RATE, CHANNELS, AUDIO_ENCODING,
            minBufferSize
    );
    audioRecord.startRecording();
    recordingThread = new Thread(new Runnable() {
        public void run() {
            readAudioData();
        }
    }, "AudioRecorder Thread");
    recordingThread.start();
}
</code>```

I want, when I press the home button, the application continues recording. Right now, when I press the home button, the recording stops.

Any idea on how to do this?

答:
You can to create a service and you can start the service when you want to record audio it works even you press home button.

You can start service by

```<code>startService(new Intent(YourActivity,Service.class));
</code>```

and can call that method onStartCommand()
and can stop service by this

```<code>stopService(new Intent(YourActivity,Service.class));
</code>```

or by stopself();

Body:
I'm programming an Android application (I'm using Android Studio).

I start the recording with the following code (this is just a fragment):

public void start() {
    int minBufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNELS, AUDIO_ENCODING);
    audioRecord = new AudioRecord(
            MediaRecorder.AudioSource.MIC,
            SAMPLE_RATE, CHANNELS, AUDIO_ENCODING,
            minBufferSize
    );
    audioRecord.startRecording();
    recordingThread = new Thread(new Runnable() {
        public void run() {
            readAudioData();
        }
    }, "AudioRecorder Thread");
    recordingThread.start();
}

I want, when I press the home button, the application continues recording. Right now, when I press the home button, the recording stops.

Any idea on how to do this?

Body:
You can to create a service and you can start the service when you want to record audio it works even you press home button.

You can start service by

startService(new Intent(YourActivity,Service.class));

and can call that method onStartCommand()
and can stop service by this

stopService(new Intent(YourActivity,Service.class));

or by stopself();


答:
The main issue is you have not set method="post" with your form tag. So set it there and give it a try.

A suggestion:

Chage your query like this:

```<code>$que = "DELETE FROM `zainteresowania` WHERE `zainteresowania`.`id` = '".$select."'";  // Check the changes I made around $select.
</code>```

Title: PHP Query won't work with DELETE

Body:
The main issue is you have not set method="post" with your form tag. So set it there and give it a try.

A suggestion:

Chage your query like this:

$que = "DELETE FROM `zainteresowania` WHERE `zainteresowania`.`id` = '".$select."'";  // Check the changes I made around $select.


问:
Get the non-zero minimum of a column and its index
I want to find the minimum value of a column of a matrix of non-negative integers, excluding 0. I know the matrix is square and only has zeros on every element of its main diagonal (i.e. a(i,i)=0 for all i).

I have tried this:

```<code>[best_cost,index] = min(star_costs([1:i-1,i+1:nbr],i));
</code>```

Where nbr is the size of my matrix.

However, the index that is returned is the index excluding the zero, not taking into account the ith element. For example, my first column is:

```<code>[0 9 11 5 18 13 14]'
</code>```

so the code returns best_cost=5and index=3 because the 0 element is excluded. However, I would like to get index=4 as anyone would expect.

Of course just adding 1 does not have sense, as it could happen for any column and, except for the case of this first column, the minimum of the column could be above or below the diagonal.

答:
Replace zeros with inf and then use min.

```<code>A(1:size(A,1)+1:end) = inf;    %If the diagonal is to be excluded
%if all zeros are to be excluded including non-diagonal elements, use this instead:
%A(A==0) = inf;                %Use tolerance if you have floating point numbers
[best_cost, index] = min(A);
</code>```

Body:
I want to find the minimum value of a column of a matrix of non-negative integers, excluding 0. I know the matrix is square and only has zeros on every element of its main diagonal (i.e. a(i,i)=0 for all i).

I have tried this:

[best_cost,index] = min(star_costs([1:i-1,i+1:nbr],i));

Where nbr is the size of my matrix.

However, the index that is returned is the index excluding the zero, not taking into account the ith element. For example, my first column is:

[0 9 11 5 18 13 14]'

so the code returns best_cost=5and index=3 because the 0 element is excluded. However, I would like to get index=4 as anyone would expect.

Of course just adding 1 does not have sense, as it could happen for any column and, except for the case of this first column, the minimum of the column could be above or below the diagonal.

Body:
Replace zeros with inf and then use min.

A(1:size(A,1)+1:end) = inf;    %If the diagonal is to be excluded
%if all zeros are to be excluded including non-diagonal elements, use this instead:
%A(A==0) = inf;                %Use tolerance if you have floating point numbers
[best_cost, index] = min(A);


问:
Powershell: TextBlock in Runspace – Add Inline with fontstyles
I have a problem with powershell and styling a part of Text in a TextBlock.

I use a function to push text to a runspace window and a TextBlock in it, which works fine.

```<code>Function Update-Log {
    Param (
        $Content,
        $type = "Black"
    )
    $syncHash.Window.Dispatcher.invoke(
        [action]{$syncHash.log_txt.Foreground = $type; $syncHash.log_txt.Inlines.Add($Content); },
        "Normal"
    )
}
</code>```

Even the change of color works without problems. But now I would like to mark individual words bold. I have tried a pragmatic approach:

```<code>Update-Log "Here is some <bold>bold</bold> text."
</code>```

Unfortunately this did not work. Can you help me to find a solution for this problem?

答:
I found a solution:</p>

```<code>   $syncHash.TextBlockName.Dispatcher.invoke(
        [action]{
            $Run = New-Object System.Windows.Documents.Run
            $Run.Text = $Content
            $Run.FontWeight = $weight
            $Run.TextDecorations = $decorations
            $Run.FontStyle = $atyle
            $syncHash.TextBlockName.Inlines.Add($Run)
            },
        "Normal"
    )
}
</code>```

Body:
I have a problem with powershell and styling a part of Text in a TextBlock.

I use a function to push text to a runspace window and a TextBlock in it, which works fine.

Function Update-Log {
    Param (
        $Content,
        $type = "Black"
    )
    $syncHash.Window.Dispatcher.invoke(
        [action]{$syncHash.log_txt.Foreground = $type; $syncHash.log_txt.Inlines.Add($Content); },
        "Normal"
    )
}

Even the change of color works without problems. But now I would like to mark individual words bold. I have tried a pragmatic approach:

Update-Log "Here is some <bold>bold</bold> text."

Unfortunately this did not work. Can you help me to find a solution for this problem?

Body:
I found a solution:

   $syncHash.TextBlockName.Dispatcher.invoke(
        [action]{
            $Run = New-Object System.Windows.Documents.Run
            $Run.Text = $Content
            $Run.FontWeight = $weight
            $Run.TextDecorations = $decorations
            $Run.FontStyle = $atyle
            $syncHash.TextBlockName.Inlines.Add($Run)
            },
        "Normal"
    )
}


问:
'await' expression is only allowed within an async function
I have an async method like below. It shows an error [ts] 'await' expression is only allowed within an async function. here await userProfile.set({. Can you tell me how to sort out it?

Note: Maybe it is due to I have tried to call promise inside the observable. Any clue?

 async loginWithGoogle(): Promise<void> {
    const result = await this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
    const userId: string = result.uid;
    const userProfile: AngularFirestoreDocument<UserProfile> = this.fireStore.doc(`userProfile/${userId}`);
    const userProfiles: AngularFirestoreCollection<UserProfile> = this.fireStore.collection('userProfile/', ref => ref.where('email', '==', result.email));
    const userProfiles$: Observable<UserProfile[]> = userProfiles.valueChanges();
    userProfiles$.subscribe(res => {
      if (res == null) {
        await userProfile.set({ //here it shows error
          id: userId,
          email: result.email,
          creationTime: moment().format(),
          lastSignInTime: moment().format()
        });
      }
    });
  }
```

答:
Your main function is async but you’re using await in an arrow function which isn’t declared as async

```<code>userProfiles$.subscribe(async res => {
  if (res == null) {
    await userProfile.set({
...
</code>```

Body:
Your main function is async but you’re using await in an arrow function which isn’t declared as async

userProfiles$.subscribe(async res => {
  if (res == null) {
    await userProfile.set({
...


问:
How can i use the variable in the path for source directory and destination using groovy
git1 repository have a folder named sports which further have subfolders and files inside it.I want to copy the file given by the output of git diff given by command2.

```<code>def command2 = "git diff --stat @{12.hours.ago}"
Process process = command2.execute(null, new File('C:/git1'))
def b=process.text
println b
</code>```

Output of Groovy Console is Sports/Cricket/Players/Virat.txt.

Now i want to use this file path in sourceDir as shown below.

```<code>def sourceDir = "C:/git1/$b"
def destinationDir = "D:/git1/$b"
(new AntBuilder()).copy(file: sourceDir, tofile: destinationDir)
</code>```

This is giving error as Warning: Could not find file C:\git1\Sports\Cricket\Players\Virat.txt
 to copy.

答:
As you can see in your comment with the byte array, the last character of the string is a newline character (10). This of course makes the path invalid but is not easily recognizable in the error message. Add a .trim() after the .text and it should work with both, AntBuilder and Files and on both, Windows and Linux. If you would have done it on Windows there would be a 13 additionally before the 10.

Another maybe even better approach would be not to use git diff as you do, as it is a porcelain command. Porcelain command as their name suggests are not stable and their arguments and output can change any time. They are meant for human usage, not for scripts. Scripts should use plumbing commands which are much more stable in input and output. With the respective plumbing command you might not have had your problem.

Body:
git1 repository have a folder named sports which further have subfolders and files inside it.I want to copy the file given by the output of git diff given by command2.

def command2 = "git diff --stat @{12.hours.ago}"
Process process = command2.execute(null, new File('C:/git1'))
def b=process.text
println b

Output of Groovy Console is Sports/Cricket/Players/Virat.txt.

Now i want to use this file path in sourceDir as shown below.

def sourceDir = "C:/git1/$b"
def destinationDir = "D:/git1/$b"
(new AntBuilder()).copy(file: sourceDir, tofile: destinationDir)

This is giving error as Warning: Could not find file C:\git1\Sports\Cricket\Players\Virat.txt
 to copy.


问:
Meteo HTTP call: can't access data
I'm experiencing a strange problem with meteor. I'm trying to make HTTP call an use the data in a React-Component. But I can't access the returned data.
on the server:

```<code>'get': function get() {

    try {
      const data = Meteor.http.get('url', {
        params: {
            "api_key": "key",
            "attribute": "attribute"
        }
      }
      return data.data;

    } catch (exception) {
      throw new Meteor.Error('500', exception);
    }
},
</code>```

on the client: i've set up a container using withTracker() so that i can access the http response as props in my react component.

```<code>export default withTracker(() => {
    var data = [];
    Meteor.call('get', function(error, success) {
        if (error) {
            console.log('error', error.reason);
        }
        if (success) {
            data.push(success);
            console.log('success', success);
        }
    });

    return {
        data,
    };
})(Component);
</code>```

I've tried all possible combination. Using arrays and objects, but none of them worked out. When using console.log(data), I get some data on the client. But using console.log(data[0]) return undefined.

I've also tried returning an object from the server 'get' method. An using js Object.assign. But when calling console.log(data.name) for example, I get undefined on the client.

Maybe I'm not solving it the right way, but I don't understand why this is always returning undefined when I tried to access the object's data.

答: Solved by calling putting Meteor.call in a component method, and passing another component method in the callback because Meteor.call does not support promises or async / await. reference

Title: Meteo HTTP call: can't access data

Body:
I'm experiencing a strange problem with meteor. I'm trying to make HTTP call an use the data in a React-Component. But I can't access the returned data.
on the server:

'get': function get() {

    try {
      const data = Meteor.http.get('url', {
        params: {
            "api_key": "key",
            "attribute": "attribute"
        }
      }
      return data.data;

    } catch (exception) {
      throw new Meteor.Error('500', exception);
    }
},

on the client: i've set up a container using withTracker() so that i can access the http response as props in my react component.

export default withTracker(() => {
    var data = [];
    Meteor.call('get', function(error, success) {
        if (error) {
            console.log('error', error.reason);
        }
        if (success) {
            data.push(success);
            console.log('success', success);
        }
    });

    return {
        data,
    };
})(Component);

I've tried all possible combination. Using arrays and objects, but none of them worked out. When using console.log(data), I get some data on the client. But using console.log(data[0]) return undefined.

I've also tried returning an object from the server 'get' method. An using js Object.assign. But when calling console.log(data.name) for example, I get undefined on the client.

Maybe I'm not solving it the right way, but I don't understand why this is always returning undefined when I tried to access the object's data.


问:
Clear table before reloding the data in a table
I am trying to bind data from the database. what is happening is that it binds every 5 seconds. Now its binding properly but it does not clear the earlier data. it keeps pilling up. So if there is 3 rows .. it needs to show only 3 rows. now what is happening is it is adding 3 rows every 5 seconds and keeps pilling 6-9-12 every 5 seconds.
I need to clear the data and then load every 5 seconds.</p>

```<code><script type="text/javascript">
        $(document).ready(function () {
            Get();
            setInterval(function () {
                Get() // this will run after every 5 seconds
            }, 5000);
        });

    function Get() {
        $.ajax({
            type: "POST",
            url: "../adminpage/noti.ashx",
            data: {},
            dataType: "json",
            success: function (response) {
                $.each(response, function (index, itemData) {
                    var tr = "<tr>" +
                                  "<td>" + itemData.msg + "</td>" +
                                  "<td>" + itemData.dt + "</td>" +
                                  "</tr>";

                    $("#testTable").find("tbody").append(tr);
                });

                BindTable();
            }
        });
    }
    function BindTable() {

        try {
            $('#testTable thead th').each(function (i) {
                var title = $('#testTable thead th').eq($(this).index()).text();

                if (title != "") {
                    $(this).html('<div style="width:40%;text-align:center;white-space:nowrap">' + title + '</div>');
                }
            });

        }
        catch (e) { }
    }
</script>

<table id="testTable" class="display" cellspacing="0" width="100%">
                                        <thead>
                                            <tr>
                                                <th class="m-list-timeline__text" style="width:70%">msg</th>
                                                <th class="m-list-timeline__time" style="width:30%">dt</th>
                                            </tr>
                                        </thead>
                                          <tbody></tbody>
                                    </table>
</code>```

答:
```<code>$('#myTable').empty()
</code>```

<p>try to remove the content of the table before the ajax call
then fill the data </p>

Body:
I am trying to bind data from the database. what is happening is that it binds every 5 seconds. Now its binding properly but it does not clear the earlier data. it keeps pilling up. So if there is 3 rows .. it needs to show only 3 rows. now what is happening is it is adding 3 rows every 5 seconds and keeps pilling 6-9-12 every 5 seconds.
I need to clear the data and then load every 5 seconds.

                                                msg
                                                dt

Body:
$('#myTable').empty()

try to remove the content of the table before the ajax call
then fill the data


问:
Any benefits from scaling up Deployment's Pods on same Node in Kuberenets
Consider a Deployment that runs 1 Pod containing a NodeJS container with no specified resource limits. My Kubernetes Cluster consists of 3 Nodes and is running different applications, 2 of the Nodes that are running other applications than NodeJS are experiencing a steady high load (i.e. CPU utilization > 80%), deeming scheduling new Pods into those Nodes ineffective.

```<code>|  Pod:A |   |  Pod:A |  |  Pod:NodeJS   |
|  Pod:B |   |  Pod:B |  |               |
|--------|   |--------|  |---------------|
|CPU 85% |   |CPU 85% |  |    CPU 60%    |
|Mem:80% |   |Mem:85% |  |    Mem:70%    |
  Node 1       Node 2          Node 3
</code>```

In the case where NodeJS application experiences high loads, would there be any benefits if I scale up the Deployment that an extra Pod would also run on Node 3, considering no resource limits defined?

```<code>|  Pod:NodeJS   |
|  Pod:NodeJS   |
|---------------|
|    CPU 60%    |
|    Mem:70%    |
     Node 3
</code>```

答:
As you know, Pods are an ephemeral entity in kubernetes. They get killed without prior notice.
In your example you have a single pod for your nodeJS application, thus if you pod gets rescheduled for whatever reason you'll end up with a downtime in your service.
For this reason it makes sense IMHO to scale up your pod in order to have multiple instances of it running simultaneously.
Obviously, if all instances are run on the same node, a failure in that node will still cause you a downtime, but this should happen much less frequently than a pod reschedule.</p>

Body:
Consider a Deployment that runs 1 Pod containing a NodeJS container with no specified resource limits. My Kubernetes Cluster consists of 3 Nodes and is running different applications, 2 of the Nodes that are running other applications than NodeJS are experiencing a steady high load (i.e. CPU utilization > 80%), deeming scheduling new Pods into those Nodes ineffective.

|  Pod:A |   |  Pod:A |  |  Pod:NodeJS   |
|  Pod:B |   |  Pod:B |  |               |
|--------|   |--------|  |---------------|
|CPU 85% |   |CPU 85% |  |    CPU 60%    |
|Mem:80% |   |Mem:85% |  |    Mem:70%    |
  Node 1       Node 2          Node 3

In the case where NodeJS application experiences high loads, would there be any benefits if I scale up the Deployment that an extra Pod would also run on Node 3, considering no resource limits defined?

|  Pod:NodeJS   |
|  Pod:NodeJS   |
|---------------|
|    CPU 60%    |
|    Mem:70%    |
     Node 3


问:
Unable to pass json row in dynamically created table using angular JS
I'm creating a table dynamically using Angular JS. In my table, I have to pass JSON row. But when it renders it's showing error !

Error: [$parse:syntax] Syntax Error: Token 'Object' is unexpected, expecting []] at column 9 of the expression [[object Object] | QcDetailsManualAuto] starting at [Object] | QcDetailsManualAuto].

CODE :

```<code>var jData = JSON.parse(response.data);
             var vQCTableData = jData.ResultData;
            var vQCTable = '';
            vQCTable += "<table class=\"table table-striped table-bordered table-hover\" id=\"qctable\">";
            vQCTable += "<thead>";
            vQCTable += "<tr>";
            vQCTable += "<th>SOM</th>";
            vQCTable += "<th>EOM</th>";
            vQCTable += "<th>Type of Error</th>";
            vQCTable += "<th>QC Type</th>";
            vQCTable += "<th>Remarks</th>";
            vQCTable += "<th>Action</th>";
            vQCTable += "</tr>";
            vQCTable += "</thead>";
            for(var td in vQCTableData)
            {
                vQCTable += "<tbody>";
                vQCTable += "<tr class=\"wer1\" ng-if=\"" + vQCTableData[td] + " | QcDetailsManualAuto\">";
                vQCTable += "<td>" +vQCTableData[td].SOM+ "</td>";
                vQCTable += "<td>" +vQCTableData[td].EOM+ "</td>";
                vQCTable += "<td>" +vQCTableData[td].Parameter+ "</td>";
                vQCTable += "<td>" +vQCTableData[td].QCType+ "</td>";
                vQCTable += "<td>" +vQCTableData[td].Remarks+ "</td>";
                vQCTable += "<td class=\"MediaDataListPointer\">";
                vQCTable += "<span ng-click=\"QCParameterEdit(" + vQCTableData[td] + ")\" title=\"Edit\" class=\"glyphicon glyphicon-pencil QualityCheckIcons\"></span>";
                vQCTable += "<span ng-click=\"DeleteMQC(" + vQCTableData[td] + ")\" title=\"Delete\" class=\"glyphicon glyphicon-trash QualityCheckIcons\"></span>";
                vQCTable += "</td>";
                vQCTable += "</tr>";
                vQCTable += " </tbody>";
            }
            vQCTable += "</table>";

            var mediadiv = angular.element(document.querySelector('#mediadiv'));
            mediadiv.html($compile(vQCTable)($scope));
</code>```

In [response] I m getting data after calling URL.

QCParameterEdit function require json row for its functionality

```<code>    $scope.QCParameterEdit = function (data) {
    $("#GenerateMarksModal").modal();
    $scope.QCPDRButton = "Update";
    $scope.somModel = data.SOM;
    $scope.eomModel = data.EOM;
    $scope.qCParameterModel = data.QcParamUID;
    $scope.typeOfErrorModel = data.Type;
    $scope.typeModel = data.Type;
    $scope.remarksModel = data.Remarks;
    $scope.UID = data.UID;
    $scope.QcParameterIUDSuccess = false;
    $scope.QcParameterIUDFailure = false;
    $scope.QcParameterIUDSMessage = '';
    $scope.QcParameterIUDFMessage = '';
};
</code>```

QcDetailsManualAuto is angular custom filter [Can not change it because it being used at multiple places]

```<code>app.filter('QcDetailsManualAuto', function () {
return function (value) {
    var result = false;
    if (value.QCType == 'Auto' || value.QCType == 'Manual') { result = true; }
    return result;
};
});
</code>```

Thanks in Advance!

答:
Do like this :

```<code>var vQCT ='';
vQCT +="<table >";
                            vQCT +="<thead>";
                                vQCT +="<tr >";
                                    vQCT +="<th>SOM</th>";
                                    vQCT +="<th>EOM</th>";
                                    vQCT +="<th>Type of Error</th>";
                                    vQCT +="<th>QC Type</th>";
                                    vQCT +="<th>Remarks</th>";
                                    vQCT +="<th>Action</th>";
                                vQCT +="</tr>";
                            vQCT +="</thead>";
vQCT +="<tbody>";
                                vQCT +="<tr ng-repeat=\"QCTD in vQCTableData\" ng-if=\"QCTD | QcDetailsManualAuto\">";
                                        vQCT +="<td>{{QCTD.SOM}}</td>";
                                        vQCT +="<td>{{QCTD.EOM}}</td>";
                                        vQCT +="<td>{{QCTD.Parameter}}</td>";
                                        vQCT +="<td>{{QCTD.QCType}}</td>";
                                        vQCT +="<td>{{QCTD.Remarks}}</td>";
                                        vQCT +="<td>";
                                        vQCT +="<span ng-click=\"QCParameterEdit(QCTD)\" title=\"Edit\" class=\"glyphicon glyphicon-pencil QualityCheckIcons\"></span>";
                                        vQCT +="<span ng-click=\"DeleteMQC(QCTD.UID)\" class=\"glyphicon glyphicon-trash QualityCheckIcons deleteQC\"></span>";
                                        vQCT +="</td>";
                                vQCT +="</tr>";
                            vQCT +="</tbody>";
                        vQCT +="</table>";

var mediadiv = angular.element(document.querySelector('#mediadiv'));
        mediadiv.html($compile(vQCT)($scope));

var jData = JSON.parse(response.data);
         $scope.vQCTableData= jData.ResultData;
</code>```

in your response section

Body:
I'm creating a table dynamically using Angular JS. In my table, I have to pass JSON row. But when it renders it's showing error !

Error: [$parse:syntax] Syntax Error: Token 'Object' is unexpected, expecting []] at column 9 of the expression [[object Object] | QcDetailsManualAuto] starting at [Object] | QcDetailsManualAuto].

CODE :

var jData = JSON.parse(response.data);
             var vQCTableData = jData.ResultData;
            var vQCTable = '';
            vQCTable += "
";
            vQCTable += "
";
            vQCTable += "
";
            vQCTable += "SOM	";
            vQCTable += "EOM	";
            vQCTable += "Type of Error	";
            vQCTable += "QC Type	";
            vQCTable += "Remarks	";
            vQCTable += "Action	";
            vQCTable += "
";
            vQCTable += "
";
            for(var td in vQCTableData)
            {
                vQCTable += "
";
                vQCTable += "
";
                vQCTable += "" +vQCTableData[td].SOM+ "	";
                vQCTable += "" +vQCTableData[td].EOM+ "	";
                vQCTable += "" +vQCTableData[td].Parameter+ "	";
                vQCTable += "" +vQCTableData[td].QCType+ "	";
                vQCTable += "" +vQCTableData[td].Remarks+ "	";
                vQCTable += "";
                vQCTable += "";
                vQCTable += "";
                vQCTable += "	";
                vQCTable += "
";
                vQCTable += "
";
            }
            vQCTable += "
";

            var mediadiv = angular.element(document.querySelector('#mediadiv'));
            mediadiv.html($compile(vQCTable)($scope));

In [response] I m getting data after calling URL.

QCParameterEdit function require json row for its functionality

    $scope.QCParameterEdit = function (data) {
    $("#GenerateMarksModal").modal();
    $scope.QCPDRButton = "Update";
    $scope.somModel = data.SOM;
    $scope.eomModel = data.EOM;
    $scope.qCParameterModel = data.QcParamUID;
    $scope.typeOfErrorModel = data.Type;
    $scope.typeModel = data.Type;
    $scope.remarksModel = data.Remarks;
    $scope.UID = data.UID;
    $scope.QcParameterIUDSuccess = false;
    $scope.QcParameterIUDFailure = false;
    $scope.QcParameterIUDSMessage = '';
    $scope.QcParameterIUDFMessage = '';
};

QcDetailsManualAuto is angular custom filter [Can not change it because it being used at multiple places]

app.filter('QcDetailsManualAuto', function () {
return function (value) {
    var result = false;
    if (value.QCType == 'Auto' || value.QCType == 'Manual') { result = true; }
    return result;
};
});

Thanks in Advance!

Body:
Do like this :

var vQCT ='';
vQCT +="<table >";
                            vQCT +="<thead>";
                                vQCT +="<tr >";
                                    vQCT +="<th>SOM</th>";
                                    vQCT +="<th>EOM</th>";
                                    vQCT +="<th>Type of Error</th>";
                                    vQCT +="<th>QC Type</th>";
                                    vQCT +="<th>Remarks</th>";
                                    vQCT +="<th>Action</th>";
                                vQCT +="</tr>";
                            vQCT +="</thead>";
vQCT +="<tbody>";
                                vQCT +="<tr ng-repeat=\"QCTD in vQCTableData\" ng-if=\"QCTD | QcDetailsManualAuto\">";
                                        vQCT +="<td>{{QCTD.SOM}}</td>";
                                        vQCT +="<td>{{QCTD.EOM}}</td>";
                                        vQCT +="<td>{{QCTD.Parameter}}</td>";
                                        vQCT +="<td>{{QCTD.QCType}}</td>";
                                        vQCT +="<td>{{QCTD.Remarks}}</td>";
                                        vQCT +="<td>";
                                        vQCT +="<span ng-click=\"QCParameterEdit(QCTD)\" title=\"Edit\" class=\"glyphicon glyphicon-pencil QualityCheckIcons\"></span>";
                                        vQCT +="<span ng-click=\"DeleteMQC(QCTD.UID)\" class=\"glyphicon glyphicon-trash QualityCheckIcons deleteQC\"></span>";
                                        vQCT +="</td>";
                                vQCT +="</tr>";
                            vQCT +="</tbody>";
                        vQCT +="</table>";

var mediadiv = angular.element(document.querySelector('#mediadiv'));
        mediadiv.html($compile(vQCT)($scope));

var jData = JSON.parse(response.data);
         $scope.vQCTableData= jData.ResultData;

in your response section


问:
How to push message from different class? (EE7 Websocket)
I have implemented a websocket endpoint using the API provided with Java EE 7 for a game using HTML5 websockets. I can successfully send messages using a timer task in order to update the ball position, bricks, etc. but I would like to be able to send messages from within my Game class to the correct player, and send a message when the game is lost, when the score is updated, ...

The only way this would be possible for me right now is to send the score, amountOfLives, ... at every single update but I feel like this is not the way to go. Is it possible to send messages to a client from different classes, in this case my Game class?

Game class (See comment what I would like to achieve)

```<code>public class Game implements Runnable {

    private void loseLife() {
        if (lives != 0) {
            lives -= 1;
            ball.reset(paddle);
        } else {
            lose();
        }
    }

    private void lose() {
        gameRunning = false;

        // What I would like to achieve
        sendMessage("Game is lost");
    }
}
</code>```

Socket endpoint:

```<code>@ServerEndpoint("/singleplayer")
public class SingleplayerSocket {

    private static final Set<Session> PLAYERS = Collections.synchronizedSet(new HashSet<Session>());

    private Session session;
    private Gson gson;
    private Game game;

    private void sendMessage(String message) {
        try {
            for (Session player : PLAYERS) {
                if (player == session) {
                    player.getBasicRemote().sendText(message);
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;

        PLAYERS.add(session);
        sendMessage("Connection established");
    }

    @OnMessage
    public void onMessage(String message) {
        if (session != null && session.isOpen()) {
            gson = new Gson();

            String messageType = gson.fromJson(message, MessageType.class).getMessage();

            switch (messageType) {

                case "gameSetup":
                    String jsonData = getJsonData(message);
                    GameSetupRequest request = gson.fromJson(jsonData, GameSetupRequest.class);

                    int canvasWidth = request.getCanvasWidth();
                    int canvasHeight = request.getCanvasHeight();
                    String difficultyName = request.getDifficulty();

                    sendMessage(gameSetup(canvasWidth, canvasHeight, difficultyName));
                    break;

                case "gameStart":
                    Thread gameLoop = new Thread(game);
                    gameLoop.start();

                    Timer timer = new Timer();
                    timer.schedule(new UpdateTask(), 0, 1000 / 60);

                    sendMessage("Game started");
                    break;
        }
    }

    @OnClose
    public void onClose(Session session) {
        PLAYERS.remove(session);
        this.session = null;
    }

    class UpdateTask extends TimerTask {

        @Override
        public void run() {
            if (game.isGameRunning()) {
                sendMessage(gameUpdate());
            }
        }
    }
</code>```

答:
Solved it by adding the session to my constructor

```<code>private Session session;

public Game(Session session, int width, int height) {
    this.session = session;
    this.WIDTH = width;
    this.HEIGHT = height;
}

private void sendMessage(String text) {
    try {
        session.getBasicRemote().sendText(text);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

and then generating a new game like this:

```<code>game = new Game(session, setupRequest.getCanvasWidth(), setupRequest.getCanvasHeight());
</code>```

Body:
I have implemented a websocket endpoint using the API provided with Java EE 7 for a game using HTML5 websockets. I can successfully send messages using a timer task in order to update the ball position, bricks, etc. but I would like to be able to send messages from within my Game class to the correct player, and send a message when the game is lost, when the score is updated, ...

The only way this would be possible for me right now is to send the score, amountOfLives, ... at every single update but I feel like this is not the way to go. Is it possible to send messages to a client from different classes, in this case my Game class?

Game class (See comment what I would like to achieve)

public class Game implements Runnable {

    private void loseLife() {
        if (lives != 0) {
            lives -= 1;
            ball.reset(paddle);
        } else {
            lose();
        }
    }

    private void lose() {
        gameRunning = false;

        // What I would like to achieve
        sendMessage("Game is lost");
    }
}

Socket endpoint:

@ServerEndpoint("/singleplayer")
public class SingleplayerSocket {

    private static final Set<Session> PLAYERS = Collections.synchronizedSet(new HashSet<Session>());

    private Session session;
    private Gson gson;
    private Game game;

    private void sendMessage(String message) {
        try {
            for (Session player : PLAYERS) {
                if (player == session) {
                    player.getBasicRemote().sendText(message);
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;

        PLAYERS.add(session);
        sendMessage("Connection established");
    }

    @OnMessage
    public void onMessage(String message) {
        if (session != null && session.isOpen()) {
            gson = new Gson();

            String messageType = gson.fromJson(message, MessageType.class).getMessage();

            switch (messageType) {

                case "gameSetup":
                    String jsonData = getJsonData(message);
                    GameSetupRequest request = gson.fromJson(jsonData, GameSetupRequest.class);

                    int canvasWidth = request.getCanvasWidth();
                    int canvasHeight = request.getCanvasHeight();
                    String difficultyName = request.getDifficulty();

                    sendMessage(gameSetup(canvasWidth, canvasHeight, difficultyName));
                    break;

                case "gameStart":
                    Thread gameLoop = new Thread(game);
                    gameLoop.start();

                    Timer timer = new Timer();
                    timer.schedule(new UpdateTask(), 0, 1000 / 60);

                    sendMessage("Game started");
                    break;
        }
    }

    @OnClose
    public void onClose(Session session) {
        PLAYERS.remove(session);
        this.session = null;
    }

    class UpdateTask extends TimerTask {

        @Override
        public void run() {
            if (game.isGameRunning()) {
                sendMessage(gameUpdate());
            }
        }
    }

Body:
Solved it by adding the session to my constructor

private Session session;

public Game(Session session, int width, int height) {
    this.session = session;
    this.WIDTH = width;
    this.HEIGHT = height;
}

private void sendMessage(String text) {
    try {
        session.getBasicRemote().sendText(text);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

and then generating a new game like this:

game = new Game(session, setupRequest.getCanvasWidth(), setupRequest.getCanvasHeight());


问:
Save a file interactively?
Using tk_choose.files or file.choose I am able to select a file interactively. Is there an analogous function wherein I can allow a user to interactively decide where to save the output of a write.table?

答:
On Windows 7 and working through the RGUI, I can specify something like:

```<code>write.table(x = iris, file = file.choose())
</code>```

which pops open a Windows Explorer dialogue. I can then navigate to any existing file, create a new file by right clicking, or simply by typing the name of a new file where it will ask to create a new file.

I guess this may not be platform independent...can others with the appropriate OS's verify?

Title: Save a file interactively?

Body:
On Windows 7 and working through the RGUI, I can specify something like:

write.table(x = iris, file = file.choose())

which pops open a Windows Explorer dialogue. I can then navigate to any existing file, create a new file by right clicking, or simply by typing the name of a new file where it will ask to create a new file.

I guess this may not be platform independent...can others with the appropriate OS's verify?