问:
Query work in localhost, but not in live
I need to make iframe url, for example:

```<code>https://url.com/category/{category_name)/t=desktop || /t=mobile.
</code>```

I'm using MAMP to run my local dev env and i got it working like it should be, when query string is equal to desktop it shows 3 posts and when mobile then only one post. Now the issue is following, when sysadmin is updating pre-live env he can see from logs this error:

```<code>[Wed Nov 15 20:09:42.122140 2017] [:error] [pid 7776] [client 10.1.2.66:41696] PHP Parse error: syntax error, unexpected end of file, expecting elseif (T_ELSEIF) or else (T_ELSE) or endif (T_ENDIF) in /var/lib/wordpress/wp-content/themes/wpTheme2/single_iframe.php on line 234
</code>```

single-iframe.php full code: https://pastebin.com/MBC6thDW

When i'm trying to go test url i'm either getting Error 500 or header with query function just printed  out.

I'm using PhpStorm IDE and it doesn't show any errors in my code, what i'm missing here?

答:
Try this code

https://pastebin.com/7ubTY2A4

```<code><?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <meta name="description" content="<?php bloginfo('description'); ?>">
    <?php
    if(get_field('fav_icon', 'option') != ''){
        $favId = get_field('fav_icon', 'option');
        $favDetails = wp_get_attachment_image_src($favId, 'full');
    }
    ?>
    <?php if(!empty($favDetails)): ?>
      <link rel="shortcut icon" href="<?php echo $favDetails[0]; ?>">
    <?php endif;?>

    <title><?php wp_title();?></title>

    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
    <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <?php wp_head(); ?>
    <!--[if (lt IE 9)&(!IEMobile)]>
    <link rel="stylesheet" type="text/css" href="enhanced.css" />
    <link rel="stylesheet" type="text/css" href="iframe.css" />
    <![endif]-->
    <?php
    if(is_front_page()){
        $info = get_bloginfo('description');

        echo '<meta name="og:description" content="'.$info.'">';
        echo '<meta name="og:title" content="Website">';
    }
    ?>
    <style>
        .main-header--frame {
            background-color: #a40057;
            margin-bottom: -40px;
        }
        .main-header--frame .categoryTitle {
            display: inline-block;
            padding-top: 19px;
            padding-left: 10px;
            color: #ffffff;
        }

        .main-header.main-header--frame .container {
            max-width: 1200px;
            background-color: transparent;
        }

    </style>

</head>
<body>
<header class="main-header main-header--frame">
    <nav>
        <div class="container">
            <div class="navbar-header">
                <a href="https://stiil.ee" class="navbar-brand">
                    <img src="logo" alt="logo"
                         class="img-responsive">
                </a>
                <h1 class="categoryTitle">Description</h1>
            </div>
        </div>
    </nav>
</header>
<main class="main-content main-content-inner valitud-content-inner">
    <div class="container">
            <?php
            $queried_object = get_queried_object();
            $taxChilds = get_terms( array(
                    'taxonomy' => 'category',
                    'hide_empty' => true,
                    'child_of' => $queried_object->term_id
            ) ); ?>

            <?php if(isset($_GET) && $_GET['t'] == 'desktop'): ?>
              <div class="category-wrap">
                            <?php
                            $queried_object = get_queried_object();
                            $count =0;
                            foreach($taxChilds as $taxChild): ?>
                                <?php
                                $args = array(
                                        'post_type'=> 'post',
                                        'cat' => $taxChild->slug,
                                        'posts_per_page' => '1',
                                        'orderby' => 'rand',

                                        'tax_query' => array(
                                                array(
                                                        'taxonomy' => 'category',
                                                        'field'    => 'term_id',
                                                        'hide_empty' => false,
                                                        'terms'    =>  $taxChild->term_id,
                                                ),
                                        )
                                );
                                query_posts($args); if(have_posts()):
                                    while(have_posts()): the_post(); ?>
                                        <div class="col-md-4 all itemz <?php echo $taxChild->slug; ?>" data-cat="<?php echo $taxChild->slug; ?>">
                                            <div class="item-wrap">
                                                <a href="<?php the_permalink();?>"><?php the_post_thumbnail('size-370x416');
                                                                                $sponsored = get_field('is_sponsored_content');
                                                                                if($sponsored){
                                                                                echo '<div class="sponsored-text">Ad</div>';
                                                                                };
                                                                                ?></a>
                                                <div class="overlay">
                                                    <div class="notify">
                                                        <a href="<?php the_permalink(); ?>"><img src="<?php echo get_post_cat_img_src();?>" alt=""></a>
                                                    </div>
                                                    <h2  class="categoryTitle"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endwhile;

                                endif; wp_reset_query();?>
                                <?php
                                if ($count == 2) {
                                    break;
                                }
                                ?>
                                <?php $count++; endforeach;?>
              </div>
            <?php endif; ?>

            <?php if(isset($_GET) && $_GET['t'] == 'mobile'): ?>
              <div class="category-wrap">
                            <?php
                            $queried_object = get_queried_object();
                            $count =0;  foreach($taxChilds as $taxChild): ?>
                                <?php
                                $args = array(
                                        'post_type'=> 'post',
                                        'cat' => $taxChild->slug,
                                        'posts_per_page' => '1',
                                        'orderby' => 'rand',

                                        'tax_query' => array(
                                                array(
                                                        'taxonomy' => 'category',
                                                        'field'    => 'term_id',
                                                        'hide_empty' => false,
                                                        'terms'    =>  $taxChild->term_id,
                                                ),
                                        )
                                );
                                query_posts($args);
                                if(have_posts()):
                                    while(have_posts()): the_post(); ?>
                                <div class="col-md-4 all itemz <?php echo $taxChild->slug; ?>" data-cat="<?php echo $taxChild->slug; ?>">
                                    <div class="item-wrap">
                                        <a href="<?php the_permalink();?>"><?php the_post_thumbnail('size-370x416');
                                                                        $sponsored = get_field('is_sponsored_content');
                                                                        if($sponsored){
                                                                            echo '<div class="sponsored-text">SISUTURUNDUS</div>';
                                                                        };
                                                                        ?></a>
                                        <div class="overlay">
                                            <div class="notify">
                                                <a href="<?php the_permalink(); ?>"><img src="<?php echo get_post_cat_img_src();?>" alt=""></a>
                                            </div>
                                            <h2  class="categoryTitle"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
                                        </div>
                                    </div>
                                </div>
                                <?php endwhile;
                                endif; wp_reset_query();?>
                                <?php
                                if ($count == 0) {
                                    break;
                                }
                                ?>
                                <?php $count++; endforeach;?>
              </div>
            <?php endif; ?>

    </div>
</main>
</body>

<!--main-content ends-->
<?php wp_footer(); ?>
</code>```

Body:
I need to make iframe url, for example:

https://url.com/category/{category_name)/t=desktop || /t=mobile.

I'm using MAMP to run my local dev env and i got it working like it should be, when query string is equal to desktop it shows 3 posts and when mobile then only one post. Now the issue is following, when sysadmin is updating pre-live env he can see from logs this error:

[Wed Nov 15 20:09:42.122140 2017] [:error] [pid 7776] [client 10.1.2.66:41696] PHP Parse error: syntax error, unexpected end of file, expecting elseif (T_ELSEIF) or else (T_ELSE) or endif (T_ENDIF) in /var/lib/wordpress/wp-content/themes/wpTheme2/single_iframe.php on line 234

single-iframe.php full code: https://pastebin.com/MBC6thDW

When i'm trying to go test url i'm either getting Error 500 or header with query function just printed  out.

I'm using PhpStorm IDE and it doesn't show any errors in my code, what i'm missing here?

Body:
Try this code

https://pastebin.com/7ubTY2A4

<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <meta name="description" content="<?php bloginfo('description'); ?>">
    <?php
    if(get_field('fav_icon', 'option') != ''){
        $favId = get_field('fav_icon', 'option');
        $favDetails = wp_get_attachment_image_src($favId, 'full');
    }
    ?>
    <?php if(!empty($favDetails)): ?>
      <link rel="shortcut icon" href="<?php echo $favDetails[0]; ?>">
    <?php endif;?>

    <title><?php wp_title();?></title>

    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
    <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <?php wp_head(); ?>
    <!--[if (lt IE 9)&(!IEMobile)]>
    <link rel="stylesheet" type="text/css" href="enhanced.css" />
    <link rel="stylesheet" type="text/css" href="iframe.css" />
    <![endif]-->
    <?php
    if(is_front_page()){
        $info = get_bloginfo('description');

        echo '<meta name="og:description" content="'.$info.'">';
        echo '<meta name="og:title" content="Website">';
    }
    ?>
    <style>
        .main-header--frame {
            background-color: #a40057;
            margin-bottom: -40px;
        }
        .main-header--frame .categoryTitle {
            display: inline-block;
            padding-top: 19px;
            padding-left: 10px;
            color: #ffffff;
        }

        .main-header.main-header--frame .container {
            max-width: 1200px;
            background-color: transparent;
        }

    </style>

</head>
<body>
<header class="main-header main-header--frame">
    <nav>
        <div class="container">
            <div class="navbar-header">
                <a href="https://stiil.ee" class="navbar-brand">
                    <img src="logo" alt="logo"
                         class="img-responsive">
                </a>
                <h1 class="categoryTitle">Description</h1>
            </div>
        </div>
    </nav>
</header>
<main class="main-content main-content-inner valitud-content-inner">
    <div class="container">
            <?php
            $queried_object = get_queried_object();
            $taxChilds = get_terms( array(
                    'taxonomy' => 'category',
                    'hide_empty' => true,
                    'child_of' => $queried_object->term_id
            ) ); ?>

            <?php if(isset($_GET) && $_GET['t'] == 'desktop'): ?>
              <div class="category-wrap">
                            <?php
                            $queried_object = get_queried_object();
                            $count =0;
                            foreach($taxChilds as $taxChild): ?>
                                <?php
                                $args = array(
                                        'post_type'=> 'post',
                                        'cat' => $taxChild->slug,
                                        'posts_per_page' => '1',
                                        'orderby' => 'rand',

                                        'tax_query' => array(
                                                array(
                                                        'taxonomy' => 'category',
                                                        'field'    => 'term_id',
                                                        'hide_empty' => false,
                                                        'terms'    =>  $taxChild->term_id,
                                                ),
                                        )
                                );
                                query_posts($args); if(have_posts()):
                                    while(have_posts()): the_post(); ?>
                                        <div class="col-md-4 all itemz <?php echo $taxChild->slug; ?>" data-cat="<?php echo $taxChild->slug; ?>">
                                            <div class="item-wrap">
                                                <a href="<?php the_permalink();?>"><?php the_post_thumbnail('size-370x416');
                                                                                $sponsored = get_field('is_sponsored_content');
                                                                                if($sponsored){
                                                                                echo '<div class="sponsored-text">Ad</div>';
                                                                                };
                                                                                ?></a>
                                                <div class="overlay">
                                                    <div class="notify">
                                                        <a href="<?php the_permalink(); ?>"><img src="<?php echo get_post_cat_img_src();?>" alt=""></a>
                                                    </div>
                                                    <h2  class="categoryTitle"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endwhile;

                                endif; wp_reset_query();?>
                                <?php
                                if ($count == 2) {
                                    break;
                                }
                                ?>
                                <?php $count++; endforeach;?>
              </div>
            <?php endif; ?>

            <?php if(isset($_GET) && $_GET['t'] == 'mobile'): ?>
              <div class="category-wrap">
                            <?php
                            $queried_object = get_queried_object();
                            $count =0;  foreach($taxChilds as $taxChild): ?>
                                <?php
                                $args = array(
                                        'post_type'=> 'post',
                                        'cat' => $taxChild->slug,
                                        'posts_per_page' => '1',
                                        'orderby' => 'rand',

                                        'tax_query' => array(
                                                array(
                                                        'taxonomy' => 'category',
                                                        'field'    => 'term_id',
                                                        'hide_empty' => false,
                                                        'terms'    =>  $taxChild->term_id,
                                                ),
                                        )
                                );
                                query_posts($args);
                                if(have_posts()):
                                    while(have_posts()): the_post(); ?>
                                <div class="col-md-4 all itemz <?php echo $taxChild->slug; ?>" data-cat="<?php echo $taxChild->slug; ?>">
                                    <div class="item-wrap">
                                        <a href="<?php the_permalink();?>"><?php the_post_thumbnail('size-370x416');
                                                                        $sponsored = get_field('is_sponsored_content');
                                                                        if($sponsored){
                                                                            echo '<div class="sponsored-text">SISUTURUNDUS</div>';
                                                                        };
                                                                        ?></a>
                                        <div class="overlay">
                                            <div class="notify">
                                                <a href="<?php the_permalink(); ?>"><img src="<?php echo get_post_cat_img_src();?>" alt=""></a>
                                            </div>
                                            <h2  class="categoryTitle"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
                                        </div>
                                    </div>
                                </div>
                                <?php endwhile;
                                endif; wp_reset_query();?>
                                <?php
                                if ($count == 0) {
                                    break;
                                }
                                ?>
                                <?php $count++; endforeach;?>
              </div>
            <?php endif; ?>

    </div>
</main>
</body>

<!--main-content ends-->
<?php wp_footer(); ?>


来源: stackexchange

问:
Create new column to identify the first value >0 across different columns
I have the following data frame

```<code>df <- data.frame(col1 = c(0,0,1,1),col2 = c(1,0,0,3),col2 = c(1,0,0,3))
</code>```

How can I identify the the first value of each value which is greater than 0.
The expected output is like this

```<code>df <- data.frame(col1 = c(0,0,1,1),col2 = c(1,0,0,3),col3 = c(1,0,0,3),col4 = c(1,0,1,1))
</code>```

And I have tried the followings

```<code>for (i in 1:3){
  df$col4 <- apply(df[,c(0:i)],1,sum)
  if (df$col4>0)
    break
  }
</code>```

答:
```<code>df$col4 <- apply(df, 1, function(x) x[which(x>0)[1]])
df[is.na(df$col4),'col4'] <- 0
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following data frame

df <- data.frame(col1 = c(0,0,1,1),col2 = c(1,0,0,3),col2 = c(1,0,0,3))

How can I identify the the first value of each value which is greater than 0.
The expected output is like this

df <- data.frame(col1 = c(0,0,1,1),col2 = c(1,0,0,3),col3 = c(1,0,0,3),col4 = c(1,0,1,1))

And I have tried the followings

for (i in 1:3){
  df$col4 <- apply(df[,c(0:i)],1,sum)
  if (df$col4>0)
    break
  }

ContentLicense: CC BY-SA 4.0


问:
String form name to form reference
Basically, I am rewriting some code working for years. Over the time I have many (60+) references to forms - there's a menuitem with OnClick event for each form, where a form reference was created:

```<code>Private Sub SomeForm_Click(sender As Object, e As EventArgs) Handles MenuItemForSomeForm.Click
    NewTab("Some Form", New SomeForm, 0)
End Sub
</code>```

...where first parameter is a name to put in a tabPage.Text where the form is opened, second is a new instance of the (particular) form SomeForm and 0 is a default record to display (0 means no default record).

Now, I created a dynamic menu and stored the form names in a database (due to better access control over the access rights, etc). Now, because the menu is generated at runtime, I can't have the OnClick event with separate instance definition of the form and have to create it at runtime, after the MenuItems are created. The side-effect idea was to cut the code short by using only 1 OnClick event or such with MenuItem.Tag paremeter as FormName. Something like:

```<code>Private Sub clickeventhandler(sender As Object, e As EventArgs)
Dim tsmi As ToolStripMenuItem = CType(sender, ToolStripMenuItem)
Dim newForm As New >>>FormFrom(tsmi.Tag.ToString)<<<  ' only explanation, this won't work
MainW.OpenModuleInTab(new newForm, tsmi.Tag.ToString, 0)
</code>```

However I am failing to find a way to create form (instances) from this string reference. Reference through collection (i.e. List(of) or Dictionary) would be fine too, I believe.

The structure is obviously:

Object → Form → Form1 (class) → MyForm1 (instance)

I know I can create an object like this:

```<code>' Note that you are getting a NEW instance of MyClassA
Dim MyInstance As Object = Activator.CreateInstance(Type.GetType(NameOfMyClass))
</code>```

I can re-type it to a Form type:

```<code>Dim NewForm as Form = CType(MyInstance,Form)
</code>```

... to acccess some of the form properties like Width, TopLevel, etc., but that's about it. I can't do:

```<code>Dim NewForm1 as Form1 = CType(NewForm,Form1)
</code>```

...because obviously, Form1 comes as a string "Form1".

I don't know how to create a Form1 reference from a "Form1" text (then it would be easy to create an instance) or how to create an instance directly (MyForm1).

SOLUTION

As sugested, I used reflection to get the form. The only way working for me I found was this:

```<code>    Dim T As Type = System.Type.GetType(FormName, False)
    If T Is Nothing Then 'if not found prepend default namespace
        Dim Fullname As String = Application.ProductName & "." & FormName
        T = System.Type.GetType(Fullname, True, True)
    End If

    Dim f2 As New Form   ' here I am creating a form and working with it
    f2 = CType(Activator.CreateInstance(T), Form)
    f2.TopLevel = False
    f2.Name = FormName.Replace(" ", "") & Now.ToString("yyyyMMddmmhh")
    f2.FormBorderStyle = FormBorderStyle.None
    f2.Dock = DockStyle.Fill
</code>```

I am using VB.net CallByName to set public variable and same function to run a sub method (every form contains RecordID variable and LoadRecords sub):

```<code>    CallByName(f2, "RecordID", CallType.Set, 111)
    CallByName(f2, "LoadRecords", CallType.Method, Nothing)
</code>```

For testing purposes, I put following into the testing form:

```<code>Public RecordID As Int32
Public Sub LoadRecords()
    MsgBox("Load records!!!!" & vbCrLf & "RecordID = " & RecordID)
End Sub
</code>```

答:
```<code>    Dim AssemblyProduct As String = System.Reflection.Assembly.GetExecutingAssembly().GetName.Name
    Dim FormName As String = "Form1"

    Dim NewForm As Object = Reflection.Assembly.GetExecutingAssembly.CreateInstance(AssemblyProduct & "." & FormName)

    If TypeOf (NewForm) Is Form1 Then
        Dim NewForm1 As Form1 = CType(NewForm, Form1)
        NewForm1.BackColor = Color.AliceBlue
        NewForm1.Show()
    End If
</code>```

Title: String form name to form reference

Body:
Basically, I am rewriting some code working for years. Over the time I have many (60+) references to forms - there's a menuitem with OnClick event for each form, where a form reference was created:

Private Sub SomeForm_Click(sender As Object, e As EventArgs) Handles MenuItemForSomeForm.Click
    NewTab("Some Form", New SomeForm, 0)
End Sub

...where first parameter is a name to put in a tabPage.Text where the form is opened, second is a new instance of the (particular) form SomeForm and 0 is a default record to display (0 means no default record).

Now, I created a dynamic menu and stored the form names in a database (due to better access control over the access rights, etc). Now, because the menu is generated at runtime, I can't have the OnClick event with separate instance definition of the form and have to create it at runtime, after the MenuItems are created. The side-effect idea was to cut the code short by using only 1 OnClick event or such with MenuItem.Tag paremeter as FormName. Something like:

Private Sub clickeventhandler(sender As Object, e As EventArgs)
Dim tsmi As ToolStripMenuItem = CType(sender, ToolStripMenuItem)
Dim newForm As New >>>FormFrom(tsmi.Tag.ToString)<<<  ' only explanation, this won't work
MainW.OpenModuleInTab(new newForm, tsmi.Tag.ToString, 0)

However I am failing to find a way to create form (instances) from this string reference. Reference through collection (i.e. List(of) or Dictionary) would be fine too, I believe.

The structure is obviously:

Object → Form → Form1 (class) → MyForm1 (instance)

I know I can create an object like this:

' Note that you are getting a NEW instance of MyClassA
Dim MyInstance As Object = Activator.CreateInstance(Type.GetType(NameOfMyClass))

I can re-type it to a Form type:

Dim NewForm as Form = CType(MyInstance,Form)

... to acccess some of the form properties like Width, TopLevel, etc., but that's about it. I can't do:

Dim NewForm1 as Form1 = CType(NewForm,Form1)

...because obviously, Form1 comes as a string "Form1".

I don't know how to create a Form1 reference from a "Form1" text (then it would be easy to create an instance) or how to create an instance directly (MyForm1).

SOLUTION

As sugested, I used reflection to get the form. The only way working for me I found was this:

    Dim T As Type = System.Type.GetType(FormName, False)
    If T Is Nothing Then 'if not found prepend default namespace
        Dim Fullname As String = Application.ProductName & "." & FormName
        T = System.Type.GetType(Fullname, True, True)
    End If

    Dim f2 As New Form   ' here I am creating a form and working with it
    f2 = CType(Activator.CreateInstance(T), Form)
    f2.TopLevel = False
    f2.Name = FormName.Replace(" ", "") & Now.ToString("yyyyMMddmmhh")
    f2.FormBorderStyle = FormBorderStyle.None
    f2.Dock = DockStyle.Fill

I am using VB.net CallByName to set public variable and same function to run a sub method (every form contains RecordID variable and LoadRecords sub):

    CallByName(f2, "RecordID", CallType.Set, 111)
    CallByName(f2, "LoadRecords", CallType.Method, Nothing)

For testing purposes, I put following into the testing form:

Public RecordID As Int32
Public Sub LoadRecords()
    MsgBox("Load records!!!!" & vbCrLf & "RecordID = " & RecordID)
End Sub


问:
Check for value definedness in C++
I'm working in C++ and I need to know if a scalar value (for instance a double) is "defined" or not. I also need to be able to "undef" it if needed:

```<code>class Foo {
public:
    double get_bar();

private:
    double bar;
    void calculate_bar() {
        bar = something();
    }
};

double Foo::get_bar() {
    if ( undefined(bar) )
        calculate_bar();
    return bar;
}
</code>```

Is it possible in C++?

Thanks

答:
If you mean at run-time, there is no such thing. If bar is never initialized, it will have whatever random bits happen to be there, depending on how the object is allocated (some allocators will initialize new memory to all-zero).

edit: it's up to the programmer to handle object state in constructors and/or manual initialization methods like init()

OwnerDisplayName: Tunnuz

ContentLicense: CC BY-SA 2.5

Title: Check for value definedness in C++

Body:
I'm working in C++ and I need to know if a scalar value (for instance a double) is "defined" or not. I also need to be able to "undef" it if needed:

class Foo {
public:
    double get_bar();

private:
    double bar;
    void calculate_bar() {
        bar = something();
    }
};

double Foo::get_bar() {
    if ( undefined(bar) )
        calculate_bar();
    return bar;
}

Is it possible in C++?

Thanks

OwnerDisplayName: Jason S


问:
How to write a command line C# program that posts to Twitter
I'd like to write a console program in C# that posts a Tweet to Twitter.  I've never used the Twitter APIs before and don't know anything about how their authentication works.  I found an API library called Twitterizer, but it seems geared towards web applications and wants the user to logon with a web browser.  All the API docs on Twitter's website seems geared around this scenario as well.

Is it possible to access the Twitter APIs using a console app with no web browser access?  I'm perfectly fine hard coding in the name and password for the Twitter user I want to post under as well.  Thanks!

Mike

答:
You'll need to use OAuth for authenticating in twitter.

Then use regular HTTP Request to use the twitter JSON-based API.

Here you can find a good article about OAuth, Twitter and console applications.


问:
forloop for getting object
I have below PHP forloop, $review is object having values of 'avail_1', 'avail_2', 'avail_2' upto avail_40

```<code>$review_array_count = array();

for ($i=1; $i <= 4 ; $i++) {
    if(is_object($review) && $review->avail_.$i == 'yes')
    {
     array_push($review_array_count, '1');
    }
}
echo count($review_array_count);
</code>```

I am counting how many avail_x having value of 'yes', so i am doing forloop upto 40, then pushing 1 to array and counting array.

How can i use object value as avail_.$i? This does not working.

Thanks,

答:
You just want to count how many avail_x having value of "yes" right?

```<code>$count = 0;

foreach (get_object_vars($reviews) as $key => $value) {
    if($value == 'yes'){
        $count++;
    }
}

var_dump($count);
</code>```

Maybe this can help.

Title: forloop for getting object

Body:
I have below PHP forloop, $review is object having values of 'avail_1', 'avail_2', 'avail_2' upto avail_40

$review_array_count = array();

for ($i=1; $i <= 4 ; $i++) {
    if(is_object($review) && $review->avail_.$i == 'yes')
    {
     array_push($review_array_count, '1');
    }
}
echo count($review_array_count);

I am counting how many avail_x having value of 'yes', so i am doing forloop upto 40, then pushing 1 to array and counting array.

How can i use object value as avail_.$i? This does not working.

Thanks,

Body:
You just want to count how many avail_x having value of "yes" right?

$count = 0;

foreach (get_object_vars($reviews) as $key => $value) {
    if($value == 'yes'){
        $count++;
    }
}

var_dump($count);

Maybe this can help.


问:
Tomcat 7 and invalid keystore format
I'm trying to connect to Tomcat through https on a remote server; I've found many answers, but no one has worked for me; I'm using Apache, Tomcat 7 on Ubuntu Server 14.04.

First, I created the certificate keystore writing:

```<code>keytool -genkey -alias tomcat -keyalg RSA
</code>```

after I' ve edited "/etc/tomcat7/server.xml" to use ssl on port 8443:

```<code><Connector port="8443" SSLEnabled="true"
                protocol="org.apache.coyote.http11.Http11Protocol"
                keystoreType="JKS"
               maxThreads="150" scheme="https" secure="true"
                keystoreFile="/usr/lib/jvm/java-7-openjdk-amd64/bin/keytool"
                keystorePass="***********" keyAlias="tomcat"
               clientAuth="false" sslProtocol="TLS"/>
</code>```

where ********** is the password; restarting Tomcat through:

```<code>sudo service tomcat7 restart
</code>```

I'm getting the following error in file "/var/log/tomcat7/catalina.out":

```<code>SEVERE: Failed to initialize connector [Connector[HTTP/1.1-8443]]
org.apache.catalina.LifecycleException: Failed to initialize component [Connector[HTTP/1.1-8443]]
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:106)
    at org.apache.catalina.core.StandardService.initInternal(StandardService.java:559)
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
    at org.apache.catalina.core.StandardServer.initInternal(StandardServer.java:813)
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
    at org.apache.catalina.startup.Catalina.load(Catalina.java:638)
    at org.apache.catalina.startup.Catalina.load(Catalina.java:663)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:280)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:454)
Caused by: org.apache.catalina.LifecycleException: Protocol handler initialization failed
    at org.apache.catalina.connector.Connector.initInternal(Connector.java:980)
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
    ... 12 more
Caused by: java.io.IOException: Invalid keystore format
    at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:650)
    at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:55)
    at java.security.KeyStore.load(KeyStore.java:1214)
    at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getStore(JSSESocketFactory.java:392)
    at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getKeystore(JSSESocketFactory.java:291)
    at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getKeyManagers(JSSESocketFactory.java:549)
    at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getKeyManagers(JSSESocketFactory.java:489)
    at org.apache.tomcat.util.net.jsse.JSSESocketFactory.init(JSSESocketFactory.java:434)
    at org.apache.tomcat.util.net.jsse.JSSESocketFactory.createSocket(JSSESocketFactory.java:181)
    at org.apache.tomcat.util.net.JIoEndpoint.bind(JIoEndpoint.java:397)
    at org.apache.tomcat.util.net.AbstractEndpoint.init(AbstractEndpoint.java:640)
    at org.apache.coyote.AbstractProtocol.init(AbstractProtocol.java:434)
    at org.apache.coyote.http11.AbstractHttp11JsseProtocol.init(AbstractHttp11JsseProtocol.java:119)
    at org.apache.catalina.connector.Connector.initInternal(Connector.java:978)
    ... 13 more
</code>```

The keystore type is JKS, I've verified it through the command:

```<code>$JAVA_HOME/bin/keytool -list
</code>```

which has returned:

```<code>Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

tomcat, 17-Oct-2015, PrivateKeyEntry,
Certificate fingerprint (SHA1): 33:14:32:DD:DA:20:BF:CF:70:32:F5:0E:E9:F1:C1:5B:4E:C3:DB:AB
</code>```

where $JAVA_HOME is "/usr/lib/jvm/java-7-openjdk-amd64";

So when I try to connect to "https://myServerIp:8443/" or to "https://myDomainName:8443/" I get "Unable to connect" error.

答:
just to further support this answer for beginners like me. On Windows OS

First go to C:\Program Files\Java\jdk1.8,
 Press Shift + right-click to open command pront: write this keytool.exe -genkey -alias tomcat -keyalg RSA -keystore /{user.name}/.keystore,
 A sequence of question will then follow after that you will see a new .keytore generated at the specify path

Now you need to go to server.xml and modify this two keystoreFile="${user.home}/.keystore" keystorePass="changeit" with the appropriate one.

Title: Tomcat 7 and invalid keystore format

Body:
I'm trying to connect to Tomcat through https on a remote server; I've found many answers, but no one has worked for me; I'm using Apache, Tomcat 7 on Ubuntu Server 14.04.

First, I created the certificate keystore writing:

keytool -genkey -alias tomcat -keyalg RSA

after I' ve edited "/etc/tomcat7/server.xml" to use ssl on port 8443:

<Connector port="8443" SSLEnabled="true"
                protocol="org.apache.coyote.http11.Http11Protocol"
                keystoreType="JKS"
               maxThreads="150" scheme="https" secure="true"
                keystoreFile="/usr/lib/jvm/java-7-openjdk-amd64/bin/keytool"
                keystorePass="***********" keyAlias="tomcat"
               clientAuth="false" sslProtocol="TLS"/>

where ********** is the password; restarting Tomcat through:

sudo service tomcat7 restart

I'm getting the following error in file "/var/log/tomcat7/catalina.out":

SEVERE: Failed to initialize connector [Connector[HTTP/1.1-8443]]
org.apache.catalina.LifecycleException: Failed to initialize component [Connector[HTTP/1.1-8443]]
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:106)
    at org.apache.catalina.core.StandardService.initInternal(StandardService.java:559)
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
    at org.apache.catalina.core.StandardServer.initInternal(StandardServer.java:813)
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
    at org.apache.catalina.startup.Catalina.load(Catalina.java:638)
    at org.apache.catalina.startup.Catalina.load(Catalina.java:663)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:280)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:454)
Caused by: org.apache.catalina.LifecycleException: Protocol handler initialization failed
    at org.apache.catalina.connector.Connector.initInternal(Connector.java:980)
    at org.apache.catalina.util.LifecycleBase.init(LifecycleBase.java:102)
    ... 12 more
Caused by: java.io.IOException: Invalid keystore format
    at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:650)
    at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:55)
    at java.security.KeyStore.load(KeyStore.java:1214)
    at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getStore(JSSESocketFactory.java:392)
    at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getKeystore(JSSESocketFactory.java:291)
    at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getKeyManagers(JSSESocketFactory.java:549)
    at org.apache.tomcat.util.net.jsse.JSSESocketFactory.getKeyManagers(JSSESocketFactory.java:489)
    at org.apache.tomcat.util.net.jsse.JSSESocketFactory.init(JSSESocketFactory.java:434)
    at org.apache.tomcat.util.net.jsse.JSSESocketFactory.createSocket(JSSESocketFactory.java:181)
    at org.apache.tomcat.util.net.JIoEndpoint.bind(JIoEndpoint.java:397)
    at org.apache.tomcat.util.net.AbstractEndpoint.init(AbstractEndpoint.java:640)
    at org.apache.coyote.AbstractProtocol.init(AbstractProtocol.java:434)
    at org.apache.coyote.http11.AbstractHttp11JsseProtocol.init(AbstractHttp11JsseProtocol.java:119)
    at org.apache.catalina.connector.Connector.initInternal(Connector.java:978)
    ... 13 more

The keystore type is JKS, I've verified it through the command:

$JAVA_HOME/bin/keytool -list

which has returned:

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

tomcat, 17-Oct-2015, PrivateKeyEntry,
Certificate fingerprint (SHA1): 33:14:32:DD:DA:20:BF:CF:70:32:F5:0E:E9:F1:C1:5B:4E:C3:DB:AB

where $JAVA_HOME is "/usr/lib/jvm/java-7-openjdk-amd64";

So when I try to connect to "https://myServerIp:8443/" or to "https://myDomainName:8443/" I get "Unable to connect" error.


问:
Can't install SQL Server 2005 on Win10 x64
I'm trying to install SQL Server 2005 on my Win10 x64.

The problem is I can't even select the Database Services and Reporting services I need cause checkbox is disabled.

I had a bit research on this issue but everyone else seems to have problems after the installation began, whereas, I can't even start the progress.

I tried Run program made for previous versions of windows and extract then install sqlncli.msi from SP4 according to this.

Neither of them enable the checkboxes and I'm running out of ideas.

Should I install sp4 without install SQL Server first? Any suggestion would be appreciated.

答:
I had the Visual Studio subscriptions and turns out you can still download the original version of SQL Server 2005 by downloads search(autocomplete won't show it but the search result will).

And the checkboxes are enabled in this version.

If you face problem during the installation, this works for me.


问:
selectBooleanCheckbox is not set after remoteCommand
I have a remmoteCommand that updates a List, after the items are loaded a repeat render selectBooleanCheckbox. However, the values are not correctly set at the checkbox, all of them are unchecked beside there are some items with selected property (which is Boolean) set to true.

If I just set an Item in the backing bean after the list is loaded it works only for that Item. What could be the problem?

index.xhtml

```<code> <h:form>
        <h:panelGroup id="itemsHolder">
            <h:panelGrid rendered="#{backingBean.items != null}">
                <h:selectBooleanCheckbox value="#{backingBean.item.selected}" disabled="#{backingBean.rendered}" /> #{backingBean.item.name}
                <ui:repeat value="#{backingBean.items.toArray()}" var="option" >
                    <h:selectBooleanCheckbox value="#{option.selected}" disabled="#{backingBean.rendered}" />
                    #{option.name}
                    <br />
                </ui:repeat>
            </h:panelGrid>
        </h:panelGroup>
        <p:remoteCommand rendered="#{backingBean.rendered}"
                         name="initItems"
                         actionListener="#{backingBean.initItems()}"
                         process="@this"
                         update="itemsHolder"/>

    </h:form>

    <ui:fragment rendered="#{backingBean.rendered}">
        <script>
            $(document).ready(function () {
                setTimeout(function () {
                    initItems();
                }, 3000);

            });
        </script>
    </ui:fragment>
</code>```

BackingBean.java

```<code>@Component
@ManagedBean
@Scope("view")
public class BackingBean {

private boolean rendered = true;

private Set<Item> items;

private Item item;

public void initItems() {
    items = new LinkedHashSet<>();
    items.add(new Item("item 1", true, "1"));
    items.add(new Item("item 2", false, "2"));
    items.add(new Item("item 3", true, "3"));

    item = new Item("lonely item", true, "4");
   }

//Getters and setters
}
</code>```

UPDATE:
I created a copy of the real code in a SandBox, I am still not able to reproduce, I think I will have to add more dependencies from real code.

答:
I've recreated your case and it is working just fine with following simple managed bean

```<code>@ManagedBean(name = "bean")
@ViewScoped
public class YourBean implements Serializable {
    List<YourItem> items=new ArrayList<>();
    YourItem anItem=new YourItem();

    @PostConstruct
    public void init() {
        System.out.println("Bean is created");
        //initialize items
        anItem.setSelected(false);
        //add 5 items to list
        for (int i=0;i<5;i++){
            YourItem item=new YourItem();
            item.setSelected(false);
            items.add(item);
        }
    }

    public void onUpdateItems(){
        System.out.println("Items will be updated...");
        anItem.setSelected(true);
        //modify 1st and 3rd item
        items.get(0).setSelected(true);
        items.get(2).setSelected(true);
        //remove 4th item
        items.remove(3);
    }

    public List<YourItem> getItems() {
        return items;
    }

    public void setItems(List<YourItem> items) {
        this.items = items;
    }

    public YourItem getAnItem() {
        return anItem;
    }

    public void setAnItem(YourItem anItem) {
        this.anItem = anItem;
    }
}
</code>```

p:command should be implemented on following way

```<code>          <h:form id="form">
            <h:panelGroup id="itemHolder">
                <h:panelGrid rendered="#{bean.items != null}">
                    <h:selectBooleanCheckbox value="#{bean.anItem.selected}" />
                    <ui:repeat value="#{bean.items}" var="item">
                        <h:selectBooleanCheckbox value="#{item.selected}" />
                        #{item.selected}
                        <br />
                    </ui:repeat>
                </h:panelGrid>
            </h:panelGroup>

            <p:remoteCommand name="startUpdate"
                             actionListener="#{bean.onUpdateItems()}"
                             update=":form:itemHolder"/>
            <p:commandButton value="Update items" onclick="startUpdate();"/>
        </h:form>
</code>```

Compare your code with this example. Very probably there is problem in your managed bean method for updating items List or with the way how you are updating h:panelGroup.

Body:
I have a remmoteCommand that updates a List, after the items are loaded a repeat render selectBooleanCheckbox. However, the values are not correctly set at the checkbox, all of them are unchecked beside there are some items with selected property (which is Boolean) set to true.

If I just set an Item in the backing bean after the list is loaded it works only for that Item. What could be the problem?

index.xhtml

 <h:form>
        <h:panelGroup id="itemsHolder">
            <h:panelGrid rendered="#{backingBean.items != null}">
                <h:selectBooleanCheckbox value="#{backingBean.item.selected}" disabled="#{backingBean.rendered}" /> #{backingBean.item.name}
                <ui:repeat value="#{backingBean.items.toArray()}" var="option" >
                    <h:selectBooleanCheckbox value="#{option.selected}" disabled="#{backingBean.rendered}" />
                    #{option.name}

                </ui:repeat>
            </h:panelGrid>
        </h:panelGroup>

    </h:form>

    <ui:fragment rendered="#{backingBean.rendered}">

    </ui:fragment>

BackingBean.java

@Component
@ManagedBean
@Scope("view")
public class BackingBean {

private boolean rendered = true;

private Set<Item> items;

private Item item;

public void initItems() {
    items = new LinkedHashSet<>();
    items.add(new Item("item 1", true, "1"));
    items.add(new Item("item 2", false, "2"));
    items.add(new Item("item 3", true, "3"));

    item = new Item("lonely item", true, "4");
   }

//Getters and setters
}

UPDATE:
I created a copy of the real code in a SandBox, I am still not able to reproduce, I think I will have to add more dependencies from real code.

Body:
I've recreated your case and it is working just fine with following simple managed bean

@ManagedBean(name = "bean")
@ViewScoped
public class YourBean implements Serializable {
    List<YourItem> items=new ArrayList<>();
    YourItem anItem=new YourItem();

    @PostConstruct
    public void init() {
        System.out.println("Bean is created");
        //initialize items
        anItem.setSelected(false);
        //add 5 items to list
        for (int i=0;i<5;i++){
            YourItem item=new YourItem();
            item.setSelected(false);
            items.add(item);
        }
    }

    public void onUpdateItems(){
        System.out.println("Items will be updated...");
        anItem.setSelected(true);
        //modify 1st and 3rd item
        items.get(0).setSelected(true);
        items.get(2).setSelected(true);
        //remove 4th item
        items.remove(3);
    }

    public List<YourItem> getItems() {
        return items;
    }

    public void setItems(List<YourItem> items) {
        this.items = items;
    }

    public YourItem getAnItem() {
        return anItem;
    }

    public void setAnItem(YourItem anItem) {
        this.anItem = anItem;
    }
}

p:command should be implemented on following way

          <h:form id="form">
            <h:panelGroup id="itemHolder">
                <h:panelGrid rendered="#{bean.items != null}">
                    <h:selectBooleanCheckbox value="#{bean.anItem.selected}" />
                    <ui:repeat value="#{bean.items}" var="item">
                        <h:selectBooleanCheckbox value="#{item.selected}" />
                        #{item.selected}
                        <br />
                    </ui:repeat>
                </h:panelGrid>
            </h:panelGroup>

            <p:remoteCommand name="startUpdate"
                             actionListener="#{bean.onUpdateItems()}"
                             update=":form:itemHolder"/>
            <p:commandButton value="Update items" onclick="startUpdate();"/>
        </h:form>

Compare your code with this example. Very probably there is problem in your managed bean method for updating items List or with the way how you are updating h:panelGroup.


问:
I am getting an issue while running Tensorflow library from python?
Could not load cudart64_80.dll. The GPU version of TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable. Download and install CUDA 8.0 from this URL: https://developer.nvidia.com/cuda-toolkit

答:
I also got the similar issue, and fixed it by downloading CUDA 8.0: https://developer.nvidia.com/cuda-toolkit-archive. I also visited https://developer.nvidia.com/cuda-toolkit and downloaded CUBA 9.0, but it didn't work. Hence, only CUDA 8.0 works.

Ref: https://devtalk.nvidia.com/default/topic/1024550/download-and-install-cuda-8-0-instead-of-cuda-9-0/


问:
SQL Query to add a new column after an existing column in SQL Server 2005
I need a SQL query which add a new column after an existing column, so the column will be added in a specific order.

Please suggest me if any ALTER query which do that.

答:
Microsoft SQL (AFAIK) does not allow you to alter the table and add a column after a specific column. Your best bet is using Sql Server Management Studio, or play around with either dropping and re-adding the table, or creating a new table and moving the data over manually. neither are very graceful.

MySQL does however:

```<code>ALTER TABLE mytable
ADD COLUMN  new_column <type>
AFTER       existing_column
</code>```

Body:
Microsoft SQL (AFAIK) does not allow you to alter the table and add a column after a specific column. Your best bet is using Sql Server Management Studio, or play around with either dropping and re-adding the table, or creating a new table and moving the data over manually. neither are very graceful.

MySQL does however:

ALTER TABLE mytable
ADD COLUMN  new_column <type>
AFTER       existing_column


问:
How to config solr that use Synonym base on KeywordTokenizerFactory
synonym eg: "AAA" => "AVANT AT ALJUNIED"

If i search AAA*BBB

I can get AVANT AT ALJUNIEDBBB.

I was used StandardTokenizerFactory.But it's always breaking field data into lexical units,and then ignore relative position for search words.

On other way,I try to use StandardTokenizerFactory or other filter like WordDelimiterFilterFactory to split word via * . It don't work

答:
You can't - synonyms works with tokens, and KeywordTokenizer keeps the whole string as a single token. So you can't expand just one part of the string when indexing if you're using KT.

In addition the SynonymFilter isn't MultiTermAware, so it's not invoked on query time when doing a wildcard search - so you can't expand synonyms for parts of the string there, regardless of which tokenizer you're using.

This is probably a good case for preprocessing the string and doing the replacements before sending it to Solr, or if the number of replacements are small, having filters to do pattern replacements inside of the strings when indexing to have both versions indexed.


问:
Remove only Horizontal Border from Table
I only want the horizontal line to be removed.

Meaning rows should not have lines and column should have lines.

In my code, there is no line in row as well as column.

I tried:

<!DOCTYPE html>

  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Company
Number

Demo (2)

2017-11-16 12:18:15

        Sr.
        Item
        Qty
        Amount

          1

          Shirt  (DC Dry Clean)

          2

          100

          2

          Saree  (RP ROll Polish)

          2

          100

        Two Hundred Rupees Only
        Total:
        200

```

I only want the horizontal line to be removed after the first row, i.e after Sr, Item and all, and before amount row (the last row).

Body:
I only want the horizontal line to be removed.

Meaning rows should not have lines and column should have lines.

In my code, there is no line in row as well as column.

I tried:

<!DOCTYPE html>

  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Company
Number

Demo (2)

2017-11-16 12:18:15

        Sr.
        Item
        Qty
        Amount

          1

          Shirt  (DC Dry Clean)

          2

          100

          2

          Saree  (RP ROll Polish)

          2

          100

        Two Hundred Rupees Only
        Total:
        200

I only want the horizontal line to be removed after the first row, i.e after Sr, Item and all, and before amount row (the last row).

Body:
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <style>

 #chiru_inv>tbody tr:first-of-type td,
 #chiru_inv>tbody tr:nth-of-type(2) td{
    border: none;
 }

    #chiru_inv>tbody tr td:first-of-type{
    border-left: 1px solid #ddd;
    }

 #chiru_inv>tbody tr td:last-of-type{
    border-right: 1px solid #ddd;
 }

 #chiru_inv>tbody tr td{
  border-left: none;
  border-right: none;
 }

    @media print {
      table {
        border: 0 !important;
      }

   #chiru_inv tr td:first-of-type{
       border-left: 1px solid #ddd !important;
       }

    #chiru_inv tr td:last-of-type{
       border-right: 1px solid #ddd !important;
    }

  #chiru_inv tr:first-of-type td {
          border: 0 !important;
        }
        #chiru_inv tr:nth-of-type(2) td {
          border: 0 !important;
        }
        #chiru_inv tr:nth-of-type(3) td {
          border: 0 !important;
        }

   #chiru_inv>tbody tr td{
     border-left: none!important;
    border-right: none!important;
    }
    }
  </style>
</head>

<body>
  <center>
    <table id="chiru_inv" class="table table-striped table-hover table-bordered table-responsive">
      <tr>
        <td colspan="4" align="center">
          <h1>Company<br /><span style="font-size: 75%;">Number</span></h1>
        </td>
      </tr>
      <tr>
        <td colspan="2">
          <h3><span style="float: left;">Demo&nbsp;(2)</span></h3>
        </td>
        <td colspan="2">
          <h3><span style="float: right;">2017-11-16 12:18:15</span></h3>
        </td>
      </tr>
      <tr>
        <th>Sr.</th>
        <th>Item</th>
        <th>Qty</th>
        <th>Amount</th>
      </tr>

      <tr>
        <td>
          1 </td>
        <td>
          Shirt &nbsp;(DC Dry Clean)
        </td>
        <td>
          2 </td>
        <td>
          100 </td>
      </tr>

      <tr>
        <td>
          2 </td>
        <td>
          Saree &nbsp;(RP ROll Polish)
        </td>
        <td>
          2 </td>
        <td>
          100 </td>
      </tr>

      <tr>
        <td colspan="2"><strong>Two Hundred Rupees Only</strong></td>
        <td><strong>Total:</strong></td>
        <td><strong>200</strong></td>
      </tr>

    </table>
  </center>
</body>

</html>


问:
How to check Application Pool status remotely through SQL server
I am a SQL Database Admin and curious about is it possible to check Application pool site status remotely from DB server?

Is there any way (e.g. SSIS package or SQL script) that I can get the result in table or file?

Thanks in advance

答:
Execute SQL query in SQL server management studio as below :</p>

```<code> SELECT DB_NAME(dbid), COUNT(dbid) AS NoOfConnections, loginame
 FROM sys.sysprocesses
 WHERE dbid > 0
 GROUP BY dbid, loginame
</code>```

Body:
Execute SQL query in SQL server management studio as below :

 SELECT DB_NAME(dbid), COUNT(dbid) AS NoOfConnections, loginame
 FROM sys.sysprocesses
 WHERE dbid > 0
 GROUP BY dbid, loginame


问:
if else condition in shell script to check empty input by user
I am taking input from the user, and wants that if user give empty input , it should display the error message , I am trying below code , please correct me where I am wrong  .

```<code>  #!/bin/bash
    echo "please enter previous version number"
    read prevversion
    echo "please enter new version number"
    read newversion
    echo "please enter environment [DEV2/QAT2/PPE2/PRD]"
    read env

    if[["$env"=" " &&"$prevversion"=" " &&"$newversion"= " "]]
    then
        echo "Please enter the details and try again"

    else

        if [ "$env" = "QAT2" ]
        then
                prevversion="$prevversion"_QAT2
                echo "previous version is $prevversion"
                newversion="$newversion"_QAT2
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "PPE2" ]
        then
                prevversion="$prevversion"
                echo "previous version is $prevversion"
                newversion="$newversion"
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "PRD" ]
        then
                prevversion="$prevversion"
                echo "previous version is $prevversion"
                newversion="$newversion"
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "DEV2" ]
        then
                prevversion="$prevversion"_DEV2
                echo "previous version is $prevversion"
                newversion="$newversion"_DEV2
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        fi

    fi
</code>```

please provide me with correct solution

答:
You need to use ||, not &&. And you should be testing against an empty string, not a string with a single space.

```<code>if [[ "$env" = "" || "$prevversion" = "" || "$newversion" = "" ]]
</code>```

Body:
I am taking input from the user, and wants that if user give empty input , it should display the error message , I am trying below code , please correct me where I am wrong  .

  #!/bin/bash
    echo "please enter previous version number"
    read prevversion
    echo "please enter new version number"
    read newversion
    echo "please enter environment [DEV2/QAT2/PPE2/PRD]"
    read env

    if[["$env"=" " &&"$prevversion"=" " &&"$newversion"= " "]]
    then
        echo "Please enter the details and try again"

    else

        if [ "$env" = "QAT2" ]
        then
                prevversion="$prevversion"_QAT2
                echo "previous version is $prevversion"
                newversion="$newversion"_QAT2
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "PPE2" ]
        then
                prevversion="$prevversion"
                echo "previous version is $prevversion"
                newversion="$newversion"
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "PRD" ]
        then
                prevversion="$prevversion"
                echo "previous version is $prevversion"
                newversion="$newversion"
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "DEV2" ]
        then
                prevversion="$prevversion"_DEV2
                echo "previous version is $prevversion"
                newversion="$newversion"_DEV2
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        fi

    fi

please provide me with correct solution

Body:
You need to use ||, not &&. And you should be testing against an empty string, not a string with a single space.

if [[ "$env" = "" || "$prevversion" = "" || "$newversion" = "" ]]


问:
Azure Create VM with Skus=RS3-PRO using powershell returns error ErrorCode: VMAgentStatusCommunicationError
I have been using Powershell to create Winndows Virtual Machine and so far it has worked pretty well.
My configuration looks like:

```<code>$vmConfig = New-AzureRmVMConfig -VMName $vmName -VMSize Standard_DS2 | `
Set-AzureRmVMOperatingSystem -Windows -ComputerName $vmName -Credential $Credential | `
Set-AzureRmVMSourceImage -PublisherName MicrosoftWindowsDesktop -Offer Windows-10 `
-Skus RS2-PRO -Version latest | Add-AzureRmVMNetworkInterface -Id $nic.Id | `
Set-AzureRmVmBootDiagnostics -Disable
</code>```

Now I have changed the -Skus value to RS3-PRO, I am experiencing long delay at step:

```<code>New-AzureRmVM -ResourceGroupName $vmResourceGroupName -Location $vmLocation -VM $vmConfig
</code>```

It has returned error:

```<code>New-AzureRmVM : Long running operation failed with status 'Failed'. ErrorCode: VMAgentStatusCommunicationError ErrorMessage: VM 'vmname' has not reported status for VM agent or extensions. Please verify the VM has a running VM agent, and can establish outbound connections to Azure storage.
</code>```

StartTime: 2017-11-15 20:59:34 EndTime: 2017-11-15 21:24:48
  OperationID: d1dc18f6-2ac7-4205-b8e6-2fb74fa4cbf9 Status: Failed At
  C:\pathtoscipt.ps1:144
  char:1
  + New-AzureRmVM -ResourceGroupName $vmResourceGroupName -Location $vmLo ...
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : CloseError: (:) [New-AzureRmVM], ComputeCloudException
      + FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.NewAzureVMCommand

The VM is created though and can be reached via RDP too. Sometimes, the operation succeeds too.
I created VM with same image via Azure portal and it got created with no problem. I have following questions:

Does anyone have face similar scenario?

Where should I look for logs about what is happening when the VM is being created.

答:
Your script works for me, I can use it to deploy windows 10 to Azure.

Could you please check your Azure portal to check if there any error logs about this deployment?

Where should I look for logs about what is happening when the VM is
  being created.

Maybe we can check Azure VM agent logs.

Here is the VM agent logs path:C:\WindowsAzure\Logs

Hope this helps.

Body:
I have been using Powershell to create Winndows Virtual Machine and so far it has worked pretty well.
My configuration looks like:

$vmConfig = New-AzureRmVMConfig -VMName $vmName -VMSize Standard_DS2 | `
Set-AzureRmVMOperatingSystem -Windows -ComputerName $vmName -Credential $Credential | `
Set-AzureRmVMSourceImage -PublisherName MicrosoftWindowsDesktop -Offer Windows-10 `
-Skus RS2-PRO -Version latest | Add-AzureRmVMNetworkInterface -Id $nic.Id | `
Set-AzureRmVmBootDiagnostics -Disable

Now I have changed the -Skus value to RS3-PRO, I am experiencing long delay at step:

New-AzureRmVM -ResourceGroupName $vmResourceGroupName -Location $vmLocation -VM $vmConfig

It has returned error:

New-AzureRmVM : Long running operation failed with status 'Failed'. ErrorCode: VMAgentStatusCommunicationError ErrorMessage: VM 'vmname' has not reported status for VM agent or extensions. Please verify the VM has a running VM agent, and can establish outbound connections to Azure storage.

StartTime: 2017-11-15 20:59:34 EndTime: 2017-11-15 21:24:48
  OperationID: d1dc18f6-2ac7-4205-b8e6-2fb74fa4cbf9 Status: Failed At
  C:\pathtoscipt.ps1:144
  char:1
  + New-AzureRmVM -ResourceGroupName $vmResourceGroupName -Location $vmLo ...
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : CloseError: (:) [New-AzureRmVM], ComputeCloudException
      + FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.NewAzureVMCommand

The VM is created though and can be reached via RDP too. Sometimes, the operation succeeds too.
I created VM with same image via Azure portal and it got created with no problem. I have following questions:

Does anyone have face similar scenario?

Where should I look for logs about what is happening when the VM is being created.


问:
Subqueries are not allowed after VALUES?
```<code>INSERT INTO t_MT_User (ID, Badge, Name, Scope, comp_code, dept_code, [status])
VALUES ((SELECT MAX(ID) + 1 FROM t_MT_User), @userBadgeNumber, @userName, @userScope, @companyCode, @departmentCode, 1)
</code>```

This query throws the following error:

Subqueries are not allowed in this context. Only scalar expressions are allowed.

If I change VALUES to SELECT, I get another error instead:

```<code>INSERT INTO t_MT_User (ID, Badge, Name, Scope, comp_code, dept_code, [status])
    SELECT
        ((SELECT MAX(ID) + 1 FROM t_MT_User),
         @userBadgeNumber, @userName, @userScope, @companyCode,
         @departmentCode, 1)
</code>```

Incorrect syntax near ','.

How do I achieve (SELECT MAX(ID) + 1 FROM t_MT_User) in this context?

答:
First thing is first - your code, even if you fix it's syntax, is wrong.
Seems like you try to implement your own auto-increment mechanism. That will fail.

The correct way is to use SQL Server's built-in mechanism for auto-increment, and create the ID columns as an Identity.

Then you don't need to include it in the insert statement at all, and you are safe even in a multi-client or multi-threaded environments (which your current implementation will start giving wrong results).

Body:
INSERT INTO t_MT_User (ID, Badge, Name, Scope, comp_code, dept_code, [status])
VALUES ((SELECT MAX(ID) + 1 FROM t_MT_User), @userBadgeNumber, @userName, @userScope, @companyCode, @departmentCode, 1)

This query throws the following error:

Subqueries are not allowed in this context. Only scalar expressions are allowed.

If I change VALUES to SELECT, I get another error instead:

INSERT INTO t_MT_User (ID, Badge, Name, Scope, comp_code, dept_code, [status])
    SELECT
        ((SELECT MAX(ID) + 1 FROM t_MT_User),
         @userBadgeNumber, @userName, @userScope, @companyCode,
         @departmentCode, 1)

Incorrect syntax near ','.

How do I achieve (SELECT MAX(ID) + 1 FROM t_MT_User) in this context?


问:
Escape exclamation mark in batch file
I got a simple code to connect to remote server.
For some reason, it keep asking for password even when i already gave it in the code.
The password include exclamation mark, tried to escape it with \ / " " ' ' but none of them helped me.

The code:

```<code>@echo off

cmdkey /generic:server /user:user /pass:'Aa123456!'
mstsc.exe /v:server

exit
</code>```

Didn't gave the real server and user of course, but thats the password im using.

Could someone help me?

答:
The below batch log in to remote desktop using the credentials provided.

Save it as RDPLogin.bat (edit credentials as required)

use ^ for escape characters (for example)

```<code>@echo off
::Server Address/IP
set mysrvad=xyz.myrdp.com
::Server User ID
set mysrvid=user
::Server User Password
set mysrvpswd='Aa123456^!'

cmdkey /generic:%mysrvad% /user:%mysrvid% /pass:%mysrvpswd%
cls
mstsc.exe /v:%mysrvad%
exit
</code>```

Title: Escape exclamation mark in batch file

Body:
I got a simple code to connect to remote server.
For some reason, it keep asking for password even when i already gave it in the code.
The password include exclamation mark, tried to escape it with \ / " " ' ' but none of them helped me.

The code:

@echo off

cmdkey /generic:server /user:user /pass:'Aa123456!'
mstsc.exe /v:server

exit

Didn't gave the real server and user of course, but thats the password im using.

Could someone help me?

Body:
The below batch log in to remote desktop using the credentials provided.

Save it as RDPLogin.bat (edit credentials as required)

use ^ for escape characters (for example)

@echo off
::Server Address/IP
set mysrvad=xyz.myrdp.com
::Server User ID
set mysrvid=user
::Server User Password
set mysrvpswd='Aa123456^!'

cmdkey /generic:%mysrvad% /user:%mysrvid% /pass:%mysrvpswd%
cls
mstsc.exe /v:%mysrvad%
exit


问:
Avro Records -> Kafka -> Kafka Connect Sink -> Amazon S3 Storage. Idempotency?
So my employer has Avro messages going through Kafka. We want to archive all messages to Amazon S3. Ideally, they would be stored in S3-like-directories by day and use a path structure something like:

s3://my-bucket/data/day=2016-03-04/data.avro

Is there a reference or best practices for how to do this well?

My one question is idempotency: How do I provide write idempotency, where a record may be sent to my sink writer more than once yet only be stored on S3 once.

Am I correct that I need idempotency? If I implement a simple append (non-idempotent), Kafka Connect may send the same records twice and they may get stored redundantly?

答:
From the description, it looks like what you are looking for is
1) Avro data write to S3

2) Data to be partitioned in S3

3) Exactly-once support while writing.

Qubole StreamX supports rich variety of format conversions, avro being one of them, along with data partition.
And, exactly once is in our pipeline which will be out soon.

Whereas secor is getting deprecated(mentioned in one of their responses on google group) and it also do not support avro.

So you can use qubole streamx to start with.


问:
how to send post requests body in python script
I am sending a post request from Angular-4 and its working perfectly, here how i done it

```<code>demo_service(cate, review) {
  let headers = new Headers();
  headers.append('Content-Type', 'application/json');

  return this.http_obj.post("http://ns519750.ip-158-69-23.net:8100/func/demo/",JSON.stringify( {
    "category": cate,
    "review": review
  }),{headers: headers}).map((response: Response) => response.json());
}
</code>```

Now I am trying to send the same request from python script like that

```<code>userdata = {'category': "laptop2" + '/', 'review':str(reviewData[0].SNR_Review)}
r = requests.post('http://ns519750.ip-158-69-23.net:8100/func/demo/',  data=userdata)
print('rrrr    ', r.content)
print('rrrr    ', r)
</code>```

But it giving me the KeyError, Can anybody tell how does body of post request pass in python script.

Down below is the error log

```<code>File "/home/amad/.local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/home/amad/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
    response = self._get_response(request)
  File "/home/amad/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/amad/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/amad/.local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/amad/.local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 483, in dispatch
    response = self.handle_exception(exc)
  File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 443, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 480, in dispatch
    response = handler(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/rest_framework/decorators.py", line 52, in handler
    return func(*args, **kwargs)
  File "/home/amad/Desktop/djangoshopnroar/userReviews/views.py", line 176, in Calculate_VendorReviewsScore
    r = requests.post('http://ns519750.ip-158-69-23.net:8100/func/demo/',  data=userdata, headers=headers)
  File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 109, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 50, in request
    response = session.request(method=method, url=url, **kwargs)
TypeError: request() got an unexpected keyword argument 'category'
</code>```

答:
First, use the json parameter to request.post() your data as a json instead of a form post, like you do in your JS:

```<code>r = requests.post('http://ns519750.ip-158-69-23.net:8100/func/demo/',  json=userdata)
</code>```

However, I cannot find a relationship between your python code and the exception you posted. Is it the exact same code that gives you an exception ?

Body:
I am sending a post request from Angular-4 and its working perfectly, here how i done it

demo_service(cate, review) {
  let headers = new Headers();
  headers.append('Content-Type', 'application/json');

  return this.http_obj.post("http://ns519750.ip-158-69-23.net:8100/func/demo/",JSON.stringify( {
    "category": cate,
    "review": review
  }),{headers: headers}).map((response: Response) => response.json());
}

Now I am trying to send the same request from python script like that

userdata = {'category': "laptop2" + '/', 'review':str(reviewData[0].SNR_Review)}
r = requests.post('http://ns519750.ip-158-69-23.net:8100/func/demo/',  data=userdata)
print('rrrr    ', r.content)
print('rrrr    ', r)

But it giving me the KeyError, Can anybody tell how does body of post request pass in python script.

Down below is the error log

File "/home/amad/.local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/home/amad/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
    response = self._get_response(request)
  File "/home/amad/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/amad/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/amad/.local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/amad/.local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 483, in dispatch
    response = self.handle_exception(exc)
  File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 443, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 480, in dispatch
    response = handler(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/rest_framework/decorators.py", line 52, in handler
    return func(*args, **kwargs)
  File "/home/amad/Desktop/djangoshopnroar/userReviews/views.py", line 176, in Calculate_VendorReviewsScore
    r = requests.post('http://ns519750.ip-158-69-23.net:8100/func/demo/',  data=userdata, headers=headers)
  File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 109, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 50, in request
    response = session.request(method=method, url=url, **kwargs)
TypeError: request() got an unexpected keyword argument 'category'

Body:
First, use the json parameter to request.post() your data as a json instead of a form post, like you do in your JS:

r = requests.post('http://ns519750.ip-158-69-23.net:8100/func/demo/',  json=userdata)

However, I cannot find a relationship between your python code and the exception you posted. Is it the exact same code that gives you an exception ?


问:
Refresh image URL in ionic 2
I have this HTML syntaks for loop my URL, the URL for get an image from my directory by internet,
but when image changed in my server, the application still showed last image before I update, I was only change image not name.

```<code><ion-card style="margin: auto">
    <ion-card-header class ="head" style="background-color: gray !important">
      <font color="White">{{dt.desc}}</font>
    </ion-card-header>
    <img src= {{dt.name}} >
</ion-card>
</code>```

Whats wrong with this, and how to make image change whenever i change image in server?
In my case the image can replace to new image I've update when I uninstall that apps

答:
You can use this trick to add a random number after the url so the ionic app will refresh the link thinking its a new link.</p>

```<code>this.dt.name = 'www.yourimage.com/image.jpeg?random+\=' + Math.random());
</code>```

Title: Refresh image URL in ionic 2

Body:
I have this HTML syntaks for loop my URL, the URL for get an image from my directory by internet,
but when image changed in my server, the application still showed last image before I update, I was only change image not name.

<ion-card style="margin: auto">
    <ion-card-header class ="head" style="background-color: gray !important">
      {{dt.desc}}
    </ion-card-header>

</ion-card>

Whats wrong with this, and how to make image change whenever i change image in server?
In my case the image can replace to new image I've update when I uninstall that apps

Body:
You can use this trick to add a random number after the url so the ionic app will refresh the link thinking its a new link.

this.dt.name = 'www.yourimage.com/image.jpeg?random+\=' + Math.random());


问:
String form name to form reference
Basically, I am rewriting some code working for years. Over the time I have many (60+) references to forms - there's a menuitem with OnClick event for each form, where a form reference was created:

```<code>Private Sub SomeForm_Click(sender As Object, e As EventArgs) Handles MenuItemForSomeForm.Click
    NewTab("Some Form", New SomeForm, 0)
End Sub
</code>```

...where first parameter is a name to put in a tabPage.Text where the form is opened, second is a new instance of the (particular) form SomeForm and 0 is a default record to display (0 means no default record).

Now, I created a dynamic menu and stored the form names in a database (due to better access control over the access rights, etc). Now, because the menu is generated at runtime, I can't have the OnClick event with separate instance definition of the form and have to create it at runtime, after the MenuItems are created. The side-effect idea was to cut the code short by using only 1 OnClick event or such with MenuItem.Tag paremeter as FormName. Something like:

```<code>Private Sub clickeventhandler(sender As Object, e As EventArgs)
Dim tsmi As ToolStripMenuItem = CType(sender, ToolStripMenuItem)
Dim newForm As New >>>FormFrom(tsmi.Tag.ToString)<<<  ' only explanation, this won't work
MainW.OpenModuleInTab(new newForm, tsmi.Tag.ToString, 0)
</code>```

However I am failing to find a way to create form (instances) from this string reference. Reference through collection (i.e. List(of) or Dictionary) would be fine too, I believe.

The structure is obviously:

Object → Form → Form1 (class) → MyForm1 (instance)

I know I can create an object like this:

```<code>' Note that you are getting a NEW instance of MyClassA
Dim MyInstance As Object = Activator.CreateInstance(Type.GetType(NameOfMyClass))
</code>```

I can re-type it to a Form type:

```<code>Dim NewForm as Form = CType(MyInstance,Form)
</code>```

... to acccess some of the form properties like Width, TopLevel, etc., but that's about it. I can't do:

```<code>Dim NewForm1 as Form1 = CType(NewForm,Form1)
</code>```

...because obviously, Form1 comes as a string "Form1".

I don't know how to create a Form1 reference from a "Form1" text (then it would be easy to create an instance) or how to create an instance directly (MyForm1).

SOLUTION

As sugested, I used reflection to get the form. The only way working for me I found was this:

```<code>    Dim T As Type = System.Type.GetType(FormName, False)
    If T Is Nothing Then 'if not found prepend default namespace
        Dim Fullname As String = Application.ProductName & "." & FormName
        T = System.Type.GetType(Fullname, True, True)
    End If

    Dim f2 As New Form   ' here I am creating a form and working with it
    f2 = CType(Activator.CreateInstance(T), Form)
    f2.TopLevel = False
    f2.Name = FormName.Replace(" ", "") & Now.ToString("yyyyMMddmmhh")
    f2.FormBorderStyle = FormBorderStyle.None
    f2.Dock = DockStyle.Fill
</code>```

I am using VB.net CallByName to set public variable and same function to run a sub method (every form contains RecordID variable and LoadRecords sub):

```<code>    CallByName(f2, "RecordID", CallType.Set, 111)
    CallByName(f2, "LoadRecords", CallType.Method, Nothing)
</code>```

For testing purposes, I put following into the testing form:

```<code>Public RecordID As Int32
Public Sub LoadRecords()
    MsgBox("Load records!!!!" & vbCrLf & "RecordID = " & RecordID)
End Sub
</code>```

答:
```<code>Activator.CreateInstance(TypeFromName("Form1"))
</code>```

TypeFromName Function:

```<code>Dim list As Lazy(Of Type()) = New Lazy(Of Type())(Function() Assembly.GetExecutingAssembly().GetTypes())

Function TypeFromName(name As String) As Type
    Return list.Value.Where(Function(t) t.Name = name).FirstOrDefault()
End Function
</code>```

Title: String form name to form reference

Body:
Basically, I am rewriting some code working for years. Over the time I have many (60+) references to forms - there's a menuitem with OnClick event for each form, where a form reference was created:

Private Sub SomeForm_Click(sender As Object, e As EventArgs) Handles MenuItemForSomeForm.Click
    NewTab("Some Form", New SomeForm, 0)
End Sub

...where first parameter is a name to put in a tabPage.Text where the form is opened, second is a new instance of the (particular) form SomeForm and 0 is a default record to display (0 means no default record).

Now, I created a dynamic menu and stored the form names in a database (due to better access control over the access rights, etc). Now, because the menu is generated at runtime, I can't have the OnClick event with separate instance definition of the form and have to create it at runtime, after the MenuItems are created. The side-effect idea was to cut the code short by using only 1 OnClick event or such with MenuItem.Tag paremeter as FormName. Something like:

Private Sub clickeventhandler(sender As Object, e As EventArgs)
Dim tsmi As ToolStripMenuItem = CType(sender, ToolStripMenuItem)
Dim newForm As New >>>FormFrom(tsmi.Tag.ToString)<<<  ' only explanation, this won't work
MainW.OpenModuleInTab(new newForm, tsmi.Tag.ToString, 0)

However I am failing to find a way to create form (instances) from this string reference. Reference through collection (i.e. List(of) or Dictionary) would be fine too, I believe.

The structure is obviously:

Object → Form → Form1 (class) → MyForm1 (instance)

I know I can create an object like this:

' Note that you are getting a NEW instance of MyClassA
Dim MyInstance As Object = Activator.CreateInstance(Type.GetType(NameOfMyClass))

I can re-type it to a Form type:

Dim NewForm as Form = CType(MyInstance,Form)

... to acccess some of the form properties like Width, TopLevel, etc., but that's about it. I can't do:

Dim NewForm1 as Form1 = CType(NewForm,Form1)

...because obviously, Form1 comes as a string "Form1".

I don't know how to create a Form1 reference from a "Form1" text (then it would be easy to create an instance) or how to create an instance directly (MyForm1).

SOLUTION

As sugested, I used reflection to get the form. The only way working for me I found was this:

    Dim T As Type = System.Type.GetType(FormName, False)
    If T Is Nothing Then 'if not found prepend default namespace
        Dim Fullname As String = Application.ProductName & "." & FormName
        T = System.Type.GetType(Fullname, True, True)
    End If

    Dim f2 As New Form   ' here I am creating a form and working with it
    f2 = CType(Activator.CreateInstance(T), Form)
    f2.TopLevel = False
    f2.Name = FormName.Replace(" ", "") & Now.ToString("yyyyMMddmmhh")
    f2.FormBorderStyle = FormBorderStyle.None
    f2.Dock = DockStyle.Fill

I am using VB.net CallByName to set public variable and same function to run a sub method (every form contains RecordID variable and LoadRecords sub):

    CallByName(f2, "RecordID", CallType.Set, 111)
    CallByName(f2, "LoadRecords", CallType.Method, Nothing)

For testing purposes, I put following into the testing form:

Public RecordID As Int32
Public Sub LoadRecords()
    MsgBox("Load records!!!!" & vbCrLf & "RecordID = " & RecordID)
End Sub

Body:
Activator.CreateInstance(TypeFromName("Form1"))

TypeFromName Function:

Dim list As Lazy(Of Type()) = New Lazy(Of Type())(Function() Assembly.GetExecutingAssembly().GetTypes())

Function TypeFromName(name As String) As Type
    Return list.Value.Where(Function(t) t.Name = name).FirstOrDefault()
End Function


问:
How to add app-logo-image to primeng menubar?
I followed https://www.primefaces.org/primeng/#/menubar which is good to display menu-items that can be passed as a list. My requirement is to add App related logo image to the top-left corner. Plz can someone advise how to make this work.

```<code>ngOnInit() {
        this.items = [
            {label: 'Chart', icon: 'fa-bar-chart', routerLink: 'charts'},
</code>```

and my html looks as below

```<code><p-menubar [model]="items"></p-menubar>
</code>```

As am just passing items as an array, may I know how to display app-logo-image.

答:
What you can do is to add Custom Content :

Custom content can be placed between p-menubar tags.

Insert your logo image :

```<code><p-menubar [model]="items">
    <img id="logo" src="https://www.primefaces.org/wp-content/uploads/fbrfg/favicon-32x32.png"/>
</p-menubar>
</code>```

Then, with a few lines of CSS, add a padding-left to the menu items and position your logo to the left :

```<code>.ui-menubar-root-list {
  padding-left:32px;
}

img#logo {
  position:absolute;
  left:0;
}
</code>```

Demo

Body:
I followed https://www.primefaces.org/primeng/#/menubar which is good to display menu-items that can be passed as a list. My requirement is to add App related logo image to the top-left corner. Plz can someone advise how to make this work.

ngOnInit() {
        this.items = [
            {label: 'Chart', icon: 'fa-bar-chart', routerLink: 'charts'},

and my html looks as below

As am just passing items as an array, may I know how to display app-logo-image.

Body:
What you can do is to add Custom Content :

Custom content can be placed between p-menubar tags.

Insert your logo image :

<p-menubar [model]="items">
    <img id="logo" src="https://www.primefaces.org/wp-content/uploads/fbrfg/favicon-32x32.png"/>
</p-menubar>

Then, with a few lines of CSS, add a padding-left to the menu items and position your logo to the left :

.ui-menubar-root-list {
  padding-left:32px;
}

img#logo {
  position:absolute;
  left:0;
}

Demo


问:
Difference between tables created in SQL DataWarehouse and Database
I know it sounds very silly question but I want to know in what way the tables and their properties would differ if it is created in data warehouse and database.</p>

答:
So data warehouse is an another way to store data but it remains a database.

```<code>DATABASE: Any collection of data organized for storage, accessibility, and retrieval.
DATA WAREHOUSE: A type of database that integrates copies of transaction data from disparate source systems and provisions them for analytical use.
</code>```

The main differences are on high level schema, but at low level they're both databases.

For a more deep explanation: https://www.differencebtw.com/difference-between-database-and-data-warehouse/

Body:
So data warehouse is an another way to store data but it remains a database.

DATABASE: Any collection of data organized for storage, accessibility, and retrieval.
DATA WAREHOUSE: A type of database that integrates copies of transaction data from disparate source systems and provisions them for analytical use.

The main differences are on high level schema, but at low level they're both databases.

For a more deep explanation: https://www.differencebtw.com/difference-between-database-and-data-warehouse/


问:
Building new website on old domain name. How should I redirect the old site?
I recently moved a website to another domain, but I am keeping the original domain for a future website. The recently moved website is permanently moved, but I only want traffic to be redirected temporarily to the other domain.

I have read countless 301 vs 302 posts, articles, etc. and have failed to find any that address this particular situation. And no one answered this similar question:

Moving to a new domain and using the old one for a new website - how to handle 301 redirects?

But the difference with my question is: I don't even know that I should be using a 301 redirect for this. What's the best way to handle this situation in general?

答:
You can use the .htaccess file to redirect with 307 status code (the successor of 302 in HTTP/1.1)</p>

```<code>Redirect 307 / http://other-domain/
</code>```

Body:
You can use the .htaccess file to redirect with 307 status code (the successor of 302 in HTTP/1.1)

Redirect 307 / http://other-domain/


问:
Excel - Finding a name then inserting a specific value
Alright guys, I do not know exactly how to phrase this question but I have a picture and an example of exactly what I am trying to do.

Here is my excel sheet screenshot:

So I have a list of players, their points and a space for their team name.
I have a team already listed in E1:E5, there will be more teams defined in F1:F5 and so on... There are a lot of players in this sheet and the order of them are scrambled.

Instead of manually finding each player and typing in their team name, I wish to just type in the team name and its players into a block and have column A automatically update with the corresponding team name. I tried to fiddle around with VLOOKUP and =Index(match()) to no avail. Is this possible?

Thank you.

答:
This should be doable with Match and Index and Offset and Indirect like this: (assumes unique player names)

in a single column enter your team name and then under the team name

In, say C1 and down from there:

Blue Team
John Smith
Mary Farmer
David Johns

Red Team
Alfred Peterson
Jacob Enders
Joan Summers

Now, to the cells to the right of the names, put their offset from the team: next to John put 1, David, 3, ALfred, 1 etc.

Now the formula, broken into three cells to explain it:

cell 1 - at F1: The reference name - "Jacob Enders"

cell 2 - at F2: =MATCH(F1,C:C,0)

cell 3 - at F3: =INDEX(D:D,F2)

cell 4 - at F4: =OFFSET(INDIRECT("C"&F2,TRUE),-F3,0)

You should be right from there