问:
Asp radio button list each three radio buttons in one row bootstrab
How can i get each 3 radio buttons from asp:RadioButtonList rblbase in one row like below code.

```<code><div class="row">
<div class="col-sm-4">
    Radio1
</div>
<div class="col-sm-4">
    Radio2
</div>

<div class="col-sm-4">
    Radio3
</div>
</code>```

and row below it should be

```<code><div class="row">
<div class="col-sm-4">
    Radio3
</div>
<div class="col-sm-4">
    Radio4
</div>

<div class="col-sm-4">
    Radio5
</div>
</code>```

RadioButtonList

```<code><asp:RadioButtonList ID="rblbase" runat="server"></asp:RadioButtonList>
</code>```

答:
Use RepeatDirection = Horizontal and set margin-left,right in your CSS. For example,

```<code><asp:RadioButtonList ID="rblbase" runat="server"
RepeatDirection="Horizontal" CssClass="myRadioBtn"></asp:RadioButtonList>
</code>```

Then in your css code,

```<code>.myRadioBtn input[type="radio"]
{
  margin-left: 15px;
  margin-right: 15px;
}
</code>```

Orelse you can use CellPadding and CellSpacing, like bellow,

```<code><asp:RadioButtonList ID="rblbase" runat="server"
RepeatDirection="Horizontal" CellPadding="2" CellSpacing="2">
</asp:RadioButtonList> //change the values
</code>```

Hope it helps :)

Body:
How can i get each 3 radio buttons from asp:RadioButtonList rblbase in one row like below code.

    Radio1

    Radio2

    Radio3

and row below it should be

    Radio3

    Radio4

    Radio5

RadioButtonList

<asp:RadioButtonList ID="rblbase" runat="server"></asp:RadioButtonList>

Body:
Use RepeatDirection = Horizontal and set margin-left,right in your CSS. For example,

<asp:RadioButtonList ID="rblbase" runat="server"
RepeatDirection="Horizontal" CssClass="myRadioBtn"></asp:RadioButtonList>

Then in your css code,

.myRadioBtn input[type="radio"]
{
  margin-left: 15px;
  margin-right: 15px;
}

Orelse you can use CellPadding and CellSpacing, like bellow,

<asp:RadioButtonList ID="rblbase" runat="server"
RepeatDirection="Horizontal" CellPadding="2" CellSpacing="2">
</asp:RadioButtonList> //change the values

Hope it helps :)


来源: stackexchange

问:
Using match .. case in scala
I might sound silly but I am new to scala so please bear with me.
I am little confused about using switch case in scala. As per the example of finding the last element of a list

what is the letter 'h' and 'k' is doing ? In short if somebody can explain the below, I will be very grateful.

```<code>def recLast[A](ls: List[A]): A = ls match {
    case h :: Nil => h
    case b :: rest => recLast(rest)
}
</code>```

答:
In Scala, a List[A] is an abstract class implemented using singly linked list, composed of a head element of type A, and a tail of type List[A]. The concrete implementations are Cons (::), which represents which has a head and a tail, and Nil which is the empty list.

What happens in recLast is that the List[A] is decomposed using a feature called Pattern Matching. The case denotes a pattern which we attempt to match on.

The first case:

```<code>case h :: Nil => h
</code>```

Means "In case the List[A] contains a head element h and a tail which is the empty list (called Nil), then return the head element.

The second case

```<code>case b :: rest => recLast(rest)
</code>```

Means "In case the List[A] contains a head element which we bind to b and a tail which we bind to rest, take the tail of the list and recursively call recLast with it.

One way of pattern matching on a List[A] is using the Cons class. By doing head :: tail, which call the ::.apply method in infix notation, it is equivalent to: ::.apply(head, tail)

Appendix

The concrete implementation of the classes:

:: (Cons):

```<code>final case class ::[B](override val head: B,
                       private[scala] var tl: List[B]) extends List[B] {
  override def tail : List[B] = tl
  override def isEmpty: Boolean = false
}
</code>```

Nil:

```<code>case object Nil extends List[Nothing] {
  override def isEmpty = true
  override def head: Nothing =
    throw new NoSuchElementException("head of empty list")
  override def tail: List[Nothing] =
    throw new UnsupportedOperationException("tail of empty list")
  override def equals(that: Any) = that match {
    case that1: scala.collection.GenSeq[_] => that1.isEmpty
    case _ => false
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Using match .. case in scala

Body:
I might sound silly but I am new to scala so please bear with me.
I am little confused about using switch case in scala. As per the example of finding the last element of a list

what is the letter 'h' and 'k' is doing ? In short if somebody can explain the below, I will be very grateful.

def recLast[A](ls: List[A]): A = ls match {
    case h :: Nil => h
    case b :: rest => recLast(rest)
}

Body:
In Scala, a List[A] is an abstract class implemented using singly linked list, composed of a head element of type A, and a tail of type List[A]. The concrete implementations are Cons (::), which represents which has a head and a tail, and Nil which is the empty list.

What happens in recLast is that the List[A] is decomposed using a feature called Pattern Matching. The case denotes a pattern which we attempt to match on.

The first case:

case h :: Nil => h

Means "In case the List[A] contains a head element h and a tail which is the empty list (called Nil), then return the head element.

The second case

case b :: rest => recLast(rest)

Means "In case the List[A] contains a head element which we bind to b and a tail which we bind to rest, take the tail of the list and recursively call recLast with it.

One way of pattern matching on a List[A] is using the Cons class. By doing head :: tail, which call the ::.apply method in infix notation, it is equivalent to: ::.apply(head, tail)

Appendix

The concrete implementation of the classes:

:: (Cons):

final case class ::[B](override val head: B,
                       private[scala] var tl: List[B]) extends List[B] {
  override def tail : List[B] = tl
  override def isEmpty: Boolean = false
}

Nil:

case object Nil extends List[Nothing] {
  override def isEmpty = true
  override def head: Nothing =
    throw new NoSuchElementException("head of empty list")
  override def tail: List[Nothing] =
    throw new UnsupportedOperationException("tail of empty list")
  override def equals(that: Any) = that match {
    case that1: scala.collection.GenSeq[_] => that1.isEmpty
    case _ => false
  }
}


问:
How to make a button that has different parts?
I want to make a button that looks similar to the Club Penguin button you click when you want to join a server.

In this picture you see that the button has three main parts, the emoji, the name, and the amount of people playing.

How can I make a button that is similar to this with multiple parts? Or would a div be better for this? Either way, I want the user to be able to click on it.

This is what I tried but i'm having difficulties.

```<code><div id="container">
  <button id="button">
    <div id="first">
      Emoji
    </div>
    <div id="second">
      Name
    </div>
    <div id="third">
      Player count
    </div>
  </button>
</div>
</code>```

CSS:

```<code>#button {
  width:400px;
}
#first {
  float:left;
}
#second {
  float:center;
}
#third {
  float:right;
}
</code>```

https://jsfiddle.net/rmozk80x/

答:
I wouldn't recommend using the  html element. Instead, you can add JavaScript event listeners to the divs defined containing your clickable content. That content can be styled how you choose. Below is how I interpreted your scenario.

var emojiAction = document.getElementById('first');

emojiAction.addEventListener('click', function() {
    alert('Hello world');
}, false);

var nameAction = document.getElementById('second');

nameAction.addEventListener('click', function() {
    alert('Hello name');
}, false);

var playerCountAction = document.getElementById('third');

playerCountAction.addEventListener('click', function() {
    alert('x Players Online!');
}, false);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#buttonContainer {
  width:100%;
  height:20px;
  background-color:#999;
  text-align:center;
  bottom:0;
  position: fixed;
  margin: 0 auto;
  padding:15px;
}

#first {
  width: calc(33% - 10px);
  height: 20px;
  float: left;
  margin-left: 10px;
}

#second {
  width: calc(33% - 10px);
  height: 20px;
  float: left;
  margin-left: 10px; }

#third {
  width: calc(33% - 10px);
  height: 20px;
  float: left;
  margin-left: 10px;
}</code>```

    Emoji

    Name

    Player Count

```

Body:
I want to make a button that looks similar to the Club Penguin button you click when you want to join a server.

In this picture you see that the button has three main parts, the emoji, the name, and the amount of people playing.

How can I make a button that is similar to this with multiple parts? Or would a div be better for this? Either way, I want the user to be able to click on it.

This is what I tried but i'm having difficulties.

  <button id="button">

      Emoji

      Name

      Player count

  </button>

CSS:

#button {
  width:400px;
}
#first {
  float:left;
}
#second {
  float:center;
}
#third {
  float:right;
}

https://jsfiddle.net/rmozk80x/

Body:
I wouldn't recommend using the  html element. Instead, you can add JavaScript event listeners to the divs defined containing your clickable content. That content can be styled how you choose. Below is how I interpreted your scenario.

var emojiAction = document.getElementById('first');

emojiAction.addEventListener('click', function() {
    alert('Hello world');
}, false);

var nameAction = document.getElementById('second');

nameAction.addEventListener('click', function() {
    alert('Hello name');
}, false);

var playerCountAction = document.getElementById('third');

playerCountAction.addEventListener('click', function() {
    alert('x Players Online!');
}, false);

#buttonContainer {
  width:100%;
  height:20px;
  background-color:#999;
  text-align:center;
  bottom:0;
  position: fixed;
  margin: 0 auto;
  padding:15px;
}

#first {
  width: calc(33% - 10px);
  height: 20px;
  float: left;
  margin-left: 10px;
}

#second {
  width: calc(33% - 10px);
  height: 20px;
  float: left;
  margin-left: 10px; }

#third {
  width: calc(33% - 10px);
  height: 20px;
  float: left;
  margin-left: 10px;
}

<div id="buttonContainer">
  <div id="first">
    Emoji
  </div>
  <div id="second">
    Name
  </div>
  <div id="third">
    Player Count
  </div>
</div>


问:
How can add value to vb variable in js code?
I'm try to add a value to my vb variable in my js code, this is my example

```<code><script>
'<%Dim Myvariable As Integer%>' = 201278
</script>
</code>```

but this doesn't work.
Is there a way to do this?

答:
Declare variable either protected or public:

```<code>Protected  test As Integer = 201278;
</code>```

And in .aspx file:

```<code><script>
    <%=test.toString()%>
</script>
</code>```

edit.

that comment doesn't make any sense @JoséGregorioCalderón the example shows that it IS in script tags. If you mean the file is an external JS file, that is a different problem.

You could solve this in two ways.

1) You serve the JS file as an ASPX file to generate parts of it that are dynamic. you'll need to take care of the headers to serve it is text/javascript

2) You write the variable to your HTML as a data attribute and read it into your JS directly.

i.e.

or...very quick pseudo code.

```<code><body id="myBody" data-variable="<%=MyVariable%>">

var bodyElement = document.getElementById('myBody')
alert(bodyElement.dataset.variable);
</code>```

Body:
I'm try to add a value to my vb variable in my js code, this is my example

but this doesn't work.
Is there a way to do this?

Body:
Declare variable either protected or public:

Protected  test As Integer = 201278;

And in .aspx file:

<script>
    <%=test.toString()%>
</script>

edit.

that comment doesn't make any sense @JoséGregorioCalderón the example shows that it IS in script tags. If you mean the file is an external JS file, that is a different problem.

You could solve this in two ways.

1) You serve the JS file as an ASPX file to generate parts of it that are dynamic. you'll need to take care of the headers to serve it is text/javascript

2) You write the variable to your HTML as a data attribute and read it into your JS directly.

i.e.

or...very quick pseudo code.

<body id="myBody" data-variable="<%=MyVariable%>">

var bodyElement = document.getElementById('myBody')
alert(bodyElement.dataset.variable);


问:
What's the best IPC mechanism for medium-sized data in Perl?
I'm working on designing a multi-tiered app in Perl and I'm wondering about the pros and cons of the various IPC mechnisms available to me.  I'm looking at handling moderately-sized data, typically a few dozen kilobytes but up to a couple of megabytes, and the load is pretty light, at most a couple of hundred requests per minute.

My primary concerns are maintainability and performance (in that order).  I don't think I'll need to scale up to more than one server, or port off of our main platform (RHEL), but I suppose it's something to consider.

I can think of the following options:

Temporary files - Simplistic, probably the worst option in terms of speed and storage requirements

UNIX domain sockets - Not portable, not scalable

Internet Sockets - Portable, scalable

Pipes - Portable, not scalable (?)

Considering that scalability and portability are not my primary concerns, I need to learn more.  What's the best choice, and why?  Please comment if you need additional information.

EDIT: I'll try to give more detail in response to ysth's questions (warning, wall of text follows):

Are readers/writers in a one-to-one relationship, or something more more complicated?

What do you want to happen to the writer if the reader is no longer there or busy?

And vice versa?

What other information do you have about your desired usage?

At this point, I'm contemplating a three-tiered approach, but I'm not sure how many processes I'll have in each tier.  I think I need to have more processes towards the left side and fewer toward the right, but maybe I should have the same number across the board:

```
 .---------.          .----------.        .-------.
 | Request |  ----->  | Business | -----> | Data  |
 | Manager |  <-----  |  Logic   | <----- | Layer |
 `---------'          `----------'        `-------'
```

These names are still generic and probably won't make it into the implementation in these forms.

The request manager is responsible for listening for requests from different interfaces, for example web requests and CLI (where response time is important) and e-mail (where response time is less important).  It performs logging and manages the responses to the requests (which are rendered in a format appropriate to the type of request).

It sends data about the request to the business logic which performs logging, authorization depending on business rules, etc.

The business logic (if it needs to) then requests data from the data layer, which can either talk to (most often) the internal MySQL database or some other data source outside our team's control (e.g., our organization's primary LDAP servers, or our DB2 employee information database, etc.).  This is mostly simply a wrapper which formats the data in a uniform way so that it can be handled more easily in the business logic.

The information then flows back to to the request manager for presentation.

If, when data is flowing to the right, the reader is busy, for the interactive requests I'd like to simply wait a suitable period of time, and return a timeout error if I don't get access in that amount of time (e.g. "Try again later").  For the non-interactive requests (e.g. e-mail), the polling system can simply exit and try again on the next invocation (which will probably be once per 1-3 minutes).

When data is flowing in the other direction, there shouldn't be any waiting situations.   If one of the processes has died when trying to travel back to the left, all I can really do is log and exit.

Anyway, that was pretty verbose, and since I'm still in early design I probably still have some confused ideas in there.  Some of what I've mentioned is probably tangential to the issue of which IPC system to use.  I'm open to other suggestions on the design, but I was trying to keep the question limited in scope (For example, maybe I should consider collapsing down to two tiers, which is a much simpler  for IPC).  What are your thoughts?

答: Temporary files have other problems besides that. I think Internet socks are really the best choice. They are well documented, and as you say, scalable and portable. Even if that is not a core requirement, you get it nearly for free. Sockets are pretty easy to deal with, again there is copious amounts of documentation. You can build out your data sharing mechanism and protocol out in a library and never have to look at it again!</p>

OwnerDisplayName: Adam Bellaire

ContentLicense: CC BY-SA 2.5

Body:
I'm working on designing a multi-tiered app in Perl and I'm wondering about the pros and cons of the various IPC mechnisms available to me.  I'm looking at handling moderately-sized data, typically a few dozen kilobytes but up to a couple of megabytes, and the load is pretty light, at most a couple of hundred requests per minute.

My primary concerns are maintainability and performance (in that order).  I don't think I'll need to scale up to more than one server, or port off of our main platform (RHEL), but I suppose it's something to consider.

I can think of the following options:

Temporary files - Simplistic, probably the worst option in terms of speed and storage requirements

UNIX domain sockets - Not portable, not scalable

Internet Sockets - Portable, scalable

Pipes - Portable, not scalable (?)

Considering that scalability and portability are not my primary concerns, I need to learn more.  What's the best choice, and why?  Please comment if you need additional information.

EDIT: I'll try to give more detail in response to ysth's questions (warning, wall of text follows):

Are readers/writers in a one-to-one relationship, or something more more complicated?

What do you want to happen to the writer if the reader is no longer there or busy?

And vice versa?

What other information do you have about your desired usage?

At this point, I'm contemplating a three-tiered approach, but I'm not sure how many processes I'll have in each tier.  I think I need to have more processes towards the left side and fewer toward the right, but maybe I should have the same number across the board:

 .---------.          .----------.        .-------.
 | Request |  ----->  | Business | -----> | Data  |
 | Manager |  <-----  |  Logic   | <----- | Layer |
 `---------'          `----------'        `-------'

These names are still generic and probably won't make it into the implementation in these forms.

The request manager is responsible for listening for requests from different interfaces, for example web requests and CLI (where response time is important) and e-mail (where response time is less important).  It performs logging and manages the responses to the requests (which are rendered in a format appropriate to the type of request).

It sends data about the request to the business logic which performs logging, authorization depending on business rules, etc.

The business logic (if it needs to) then requests data from the data layer, which can either talk to (most often) the internal MySQL database or some other data source outside our team's control (e.g., our organization's primary LDAP servers, or our DB2 employee information database, etc.).  This is mostly simply a wrapper which formats the data in a uniform way so that it can be handled more easily in the business logic.

The information then flows back to to the request manager for presentation.

If, when data is flowing to the right, the reader is busy, for the interactive requests I'd like to simply wait a suitable period of time, and return a timeout error if I don't get access in that amount of time (e.g. "Try again later").  For the non-interactive requests (e.g. e-mail), the polling system can simply exit and try again on the next invocation (which will probably be once per 1-3 minutes).

When data is flowing in the other direction, there shouldn't be any waiting situations.   If one of the processes has died when trying to travel back to the left, all I can really do is log and exit.

Anyway, that was pretty verbose, and since I'm still in early design I probably still have some confused ideas in there.  Some of what I've mentioned is probably tangential to the issue of which IPC system to use.  I'm open to other suggestions on the design, but I was trying to keep the question limited in scope (For example, maybe I should consider collapsing down to two tiers, which is a much simpler  for IPC).  What are your thoughts?

LastEditorDisplayName: Adam Bellaire

OwnerDisplayName: BobbyShaftoe


问:
Twitter API - how to create new tweets
I would like to post new tweets on my twitter account via API.

How is it possible via Zend Framework Zend_Service_Twitter class?

Or through clean php?

Thanks ;)

答:
From the documentation:

```<code>  $twitter = new Zend_Service_Twitter(array(

      'username' => 'johndoe',

      'accessToken' => $token

  ));

  $response   = $twitter->status->update('My Great Tweet');
</code>```

http://framework.zend.com/manual/en/zend.service.twitter.html

Title: Twitter API - how to create new tweets

Body:
From the documentation:

  $twitter = new Zend_Service_Twitter(array(

      'username' => 'johndoe',

      'accessToken' => $token

  ));

  $response   = $twitter->status->update('My Great Tweet');

http://framework.zend.com/manual/en/zend.service.twitter.html


问:
 does not display local images in WordPress header.php and index.php
I am trying to use a simple <img src= tag to link to a favicon.ico in my header.php file and a .png logo in my index.php file in my WordPress theme, but without any luck. I've tested the link by replacing it with a hyperlink to an image hosted online, which works and proves that the <img src= tag isn't broken, but obviously I would prefer to be able to have the images linked within an internal img folder in the theme. The background image I have used in my site (which is linked in the bootstrap.css and is in the same 'img' folder as the two images I am trying to link to) works perfectly. I've tried copying the formatting of that href link but it doesn't seem to work either.

I've tried many variations of 'img/favicon.ico', '/img/favicon.ico', '../img/favicon.ico' but none of them worked to link to the image files in both cases.

Here is my code for the header.php file:

```<code><?php
/**
 * The header for our theme
 *
 * This is the template that displays all of the <head> section and everything up until <div id="content">
 *
 * @link https://developer.wordpress.org/themes/basics/template-files/#template-partials
 *
 * @package wpbootstrap-sofa
 */

?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="icon" href='../img/favicon.ico'>
<!-- Bootstrap core CSS -->

<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->

<!-- Custom styles for this template -->

<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->

<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
    <?php wp_head(); ?>
</head>

<body>

    <div class="background">

        <nav class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="index.html">home</a>
                </div>
                <div id="navbar" class="collapse navbar-collapse">
                    <ul class="nav navbar-nav">
                        <li class="active"><a href="index.html">home</a>
                        </li>
                        <li><a href="#about">about</a>
                        </li>
                        <li><a href="#blog">blog posts</a>
                        </li>
                        <li><a href="#submit">submit</a>
                        </li>
                        <li><a href="#events">events</a>
                        </li>
                        <li><a href="#mailing">mailing list</a>
                        </li>
                        <li><a href="#contact">contact</a>
                        </li>
                        <li><a href="http://uqsofa.bigcartel.com/" target="_blank">store</a>
                        </li>
                    </ul>
                </div>
                <!--/.collapse navbar-collapse -->
            </div>
        </nav>

        <div class="container">
</code>```

And here is the code for the index.php file:

```<code><?php
/**
 * The main template file
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * E.g., it puts together the home page when no home.php file exists.
 *
 * @link https://codex.wordpress.org/Template_Hierarchy
 *
 * @package wpbootstrap-sofa
 */

get_header(); ?>

<div class="starter-template">
    <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-3 col-lg-3 col-xl-3">
        <div class="center-block">
            <a href="index.html">
                    <img src='../img/sofa-logo.png' class="img-responsive center-block" alt="UQ SoFA logo">
            </a>
        </div>
        <!-- /.center-block -->
    </div>
    </div>
        <div class="row">
                <div class="col-xs-0 col-sm-0 col-md-4 col-lg-4 col-xl-4">
                        <div class="navbar-collapse collapse sidebar-navbar-collapse">
                                <ul class="nav navbar-nav">
                                    <li class="active"><a href="index.html">home</a>
                                    </li>
                                    <li><a href="#about">about</a>
                                    </li>
                                    <li><a href="#blog">blog posts</a>
                                    </li>
                                    <li><a href="#submit">submit</a>
                                    </li>
                                    <li><a href="#events">events</a>
                                    </li>
                                    <li><a href="#mailing">mailing list</a>
                                    </li>
                                    <li><a href="#contact">contact</a>
                                    </li>
                                    <li><a href="http://uqsofa.bigcartel.com/" target="_blank">store</a>
                                    </li>
                                </ul>
                        </div>
                        <!--/.collapse navbar-collapse -->
                    </div>
                    <!-- /.col-xs-0 col-sm-0 col-md-4 col-lg-4 col-xl-4 -->

                <div class="col-xs-12 col-sm-12 col-md-4 col-lg-4 col-xl-4">
                        <div class="panel panel-default">
                                <div class="panel-body">SoFA at Market Day</div>
                        </div>
                        <!-- /.panel panel-default-->
                        <div class="panel panel-default">
                                <div class="panel-body">Cut Thumb ARI</div>
                        </div>
                        <!-- /.panel panel-default-->
                        <div class="panel panel-default">
                                <div class="panel-body">GoMA Talks</div>
                        </div>
                        <!-- /.panel panel-default-->
                </div>
                <!-- /.col-xs-12 col-sm-12 col-md-4 col-lg-4 col-xl-4-->

                <div class="col-xs-12 col-sm-12 col-md-4 col-lg-4 col-xl-4">
                        <div class="panel panel-default">
                                <div class="panel-body">Interview with...</div>
                        </div>
                        <!-- /.panel panel-default-->
                        <div class="panel panel-default">
                                <div class="panel-body">Lecture by...</div>
                        </div>
                        <!-- /.panel panel-default-->
                        <div class="panel panel-default">
                                <div class="panel-body">Post #474</div>
                        </div>
                        <!-- /.panel panel-default-->
                </div>
                <!-- /.col-xs-12 col-sm-12 col-md-4 col-lg-4 col-xl-4-->
        </div>
        <!-- /.row-->
</div>
<!-- /.starter-template-->

</div>
<!-- /.container -->

</div>
<!-- /.background -->

<?php
get_footer();?>
</code>```

Linked here is a screenshot of the configuration of my theme's folders, including the 'img' folder where the images are contained.

Any help that could be provided would be much appreciated.

答: I found the answer by using the method Alexandre suggested and then changing <link rel="icon" to <link rel="shortcut icon"

Title: <img src=...> does not display local images in WordPress header.php and index.php

Body:
I am trying to use a simple <img src= tag to link to a favicon.ico in my header.php file and a .png logo in my index.php file in my WordPress theme, but without any luck. I've tested the link by replacing it with a hyperlink to an image hosted online, which works and proves that the <img src= tag isn't broken, but obviously I would prefer to be able to have the images linked within an internal img folder in the theme. The background image I have used in my site (which is linked in the bootstrap.css and is in the same 'img' folder as the two images I am trying to link to) works perfectly. I've tried copying the formatting of that href link but it doesn't seem to work either.

I've tried many variations of 'img/favicon.ico', '/img/favicon.ico', '../img/favicon.ico' but none of them worked to link to the image files in both cases.

Here is my code for the header.php file:

<?php
/**
 * The header for our theme
 *
 * This is the template that displays all of the  section and everything up until

 *
 * @link https://developer.wordpress.org/themes/basics/template-files/#template-partials
 *
 * @package wpbootstrap-sofa
 */

?><!DOCTYPE html>
<html <?php language_attributes(); ?>>

<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="icon" href='../img/favicon.ico'>

    <?php wp_head(); ?>

                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                        Toggle navigation

                    </button>
                    home

home

about

blog posts

submit

events

mailing list

contact

store

And here is the code for the index.php file:

<?php
/**
 * The main template file
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * E.g., it puts together the home page when no home.php file exists.
 *
 * @link https://codex.wordpress.org/Template_Hierarchy
 *
 * @package wpbootstrap-sofa
 */

get_header(); ?>

home

about

blog posts

submit

events

mailing list

contact

store

SoFA at Market Day

Cut Thumb ARI

GoMA Talks

Interview with...

Lecture by...

Post #474

<?php
get_footer();?>

Linked here is a screenshot of the configuration of my theme's folders, including the 'img' folder where the images are contained.

Any help that could be provided would be much appreciated.


问:
Can not sign in to the rails console for controller integration testing
Right now I am trying to access the rails console in development mood to test integration of controllers.

What I am doing right now is kind of,

```<code>>> ApplicationController.allow_forgery_protection = false
>> app.post('/users/sign_in', {'user'=> {'username' => 'sudo' ,
   'password' => 'sudo'}})
=> 200
>> app.get('/labels')
</code>```

after visiting the authorized link, its showing 401 and redirecting with 302 status.

So, what is wrong I am doing here?

答: I have test it in my rails console, rails 4.2.1. It's working. So i suggest that you can check the app.response.body and app.session after send the sign_in request, check if really success.

Body:
Right now I am trying to access the rails console in development mood to test integration of controllers.

What I am doing right now is kind of,

>> ApplicationController.allow_forgery_protection = false
>> app.post('/users/sign_in', {'user'=> {'username' => 'sudo' ,
   'password' => 'sudo'}})
=> 200
>> app.get('/labels')

after visiting the authorized link, its showing 401 and redirecting with 302 status.

So, what is wrong I am doing here?


问:
Call to undefined function get_stylesheet_directory_uri(); in wp (PHP)
I am using this code to access my css file in my directory but it shows fatal error message "Call to undefined function get_stylesheet_directory_uri();". Please help me to fix it.. Thanx</p>

```<code><link media="all" rel="stylesheet" href="<?php echo get_stylesheet_directory_uri();?>/vendors/material-design-icons/material-icons.css">
</code>```

答:
The function get_stylesheet_directory_uri does exist in WordPress. The reason why  you might be getting an undefined method error:

PHP is not enabled on your server

Make sure your file is a .php file and not .html

If it is a PHP file, then this file is not loading WordPress core. You can achieve this by including wp_load.php at the top of your php script.

$parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
 require_once( $parse_uri[0] . 'wp-load.php' );

If that does not help, post a link of your application or the file hiercharchy of your theme.

Body:
I am using this code to access my css file in my directory but it shows fatal error message "Call to undefined function get_stylesheet_directory_uri();". Please help me to fix it.. Thanx

<link media="all" rel="stylesheet" href="<?php echo get_stylesheet_directory_uri();?>/vendors/material-design-icons/material-icons.css">


问:
Set process variable in JBPM 6
We are using JBPM 6.x and wanted to update process variables once process is in progress.

I have many example to access process variables in java code but nowhere clearly find how to set it in java code?

Just to give more background: We can set variables in process definition as

kcontext.setVariable();

How can we set in java code using API? OR how can get kContext? PLEASE HELP

答:
Try with below approach:</p>

```<code> ProcessInstance processInstance= ksession.startProcess("com.sample.bpmn.hello",params);
    RuleFlowProcessInstance ruleFlowProcessInstance= (RuleFlowProcessInstance) processInstance;
    ruleFlowProcessInstance.setVariable("processVar1","newValue");
</code>```

Title: Set process variable in JBPM 6

Body:
Try with below approach:

 ProcessInstance processInstance= ksession.startProcess("com.sample.bpmn.hello",params);
    RuleFlowProcessInstance ruleFlowProcessInstance= (RuleFlowProcessInstance) processInstance;
    ruleFlowProcessInstance.setVariable("processVar1","newValue");


问:
Python store action/method in block/array
I am beginner in python and I am trying to write something like this in objective-c. In Objective-C, each method can be stored in block and those can be called again later. I have tried to find online but I don't know keyword in python. Can I write like that in python or is there any similar flow ? How shall I do? </p>

```<code>void (^successBlock)() = ^{
    NSLog(@"Test");
};

NSMutableArray *muArr = [NSMutableArray array];
[muArr addObject:successBlock];

for (void (^successBlock)() in muArr) {
    successBlock();
}
</code>```

答:
Functions in Python are first class citizens and so can be stored in variables.

See Assigning a function to a variable

```<code>def successBlock():
    NSLog("Test")

muArr = [successBlock]

for sb in muArr:
    sb()
</code>```

Body:
I am beginner in python and I am trying to write something like this in objective-c. In Objective-C, each method can be stored in block and those can be called again later. I have tried to find online but I don't know keyword in python. Can I write like that in python or is there any similar flow ? How shall I do?

void (^successBlock)() = ^{
    NSLog(@"Test");
};

NSMutableArray *muArr = [NSMutableArray array];
[muArr addObject:successBlock];

for (void (^successBlock)() in muArr) {
    successBlock();
}

Body:
Functions in Python are first class citizens and so can be stored in variables.

See Assigning a function to a variable

def successBlock():
    NSLog("Test")

muArr = [successBlock]

for sb in muArr:
    sb()


问:
devtools::install_github fails with CA cert error
When I try to call install_github, I get the following error (not just for this package, but for all github packages):

```<code>> install_github('ramnathv/slidify')
Downloading github repo ramnathv/slidify@master
Error in curl::curl_fetch_memory(url, handle = handle) :
Problem with the SSL CA cert (path? access rights?)
</code>```

But if I use RCurl directly to access github with ssl, I don't get any problem:

```<code>>  x <- getBinaryURL(
          url='https://github.com/ramnathv/slidify/archive/master.zip',
          followlocation=1L
          )
</code>```

works with no errors, so RCurl can verify the SSL certificate properly and download the archive file.

```<code>> sessionInfo()
R version 3.2.1 (2015-06-18)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Debian GNU/Linux 8 (jessie)

locale:
 [1] LC_CTYPE=en_US.utf8       LC_NUMERIC=C
 [3] LC_TIME=en_US.utf8        LC_COLLATE=en_US.utf8
 [5] LC_MONETARY=en_US.utf8    LC_MESSAGES=en_US.utf8
 [7] LC_PAPER=en_US.utf8       LC_NAME=C
 [9] LC_ADDRESS=C              LC_TELEPHONE=C
 [11] LC_MEASUREMENT=en_US.utf8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] RCurl_1.95-4.7 bitops_1.0-6   devtools_1.8.0

loaded via a namespace (and not attached):
 [1] httr_1.0.0      R6_2.1.0        magrittr_1.5    rversions_1.0.2
 [5] tools_3.2.1     curl_0.9.1      Rcpp_0.12.0     memoise_0.2.1
 [9] xml2_0.1.1      stringi_0.5-5   git2r_0.10.1    stringr_1.0.0
 [13] digest_0.6.8
</code>```

And

```<code>> curlVersion()

$age
[1] 3

$version
[1] "7.38.0"

$vesion_num
[1] 468480

$host
[1] "x86_64-pc-linux-gnu"

$features
   ipv6         ssl        libz        ntlm   asynchdns      spnego
      1           4           8          16         128         256
   largefile         idn tlsauth_srp     ntlm_wb
    512        1024       16384       32768

$ssl_version
[1] "OpenSSL/1.0.1k"

$ssl_version_num
[1] 0

$libz_version
[1] "1.2.8"

$protocols
[1] "dict"   "file"   "ftp"    "ftps"   "gopher" "http"   "https"  "imap"
[9] "imaps"  "ldap"   "ldaps"  "pop3"   "pop3s"  "rtmp"   "rtsp"   "scp"
[17] "sftp"   "smtp"   "smtps"  "telnet" "tftp"

$ares
[1] ""

$ares_num
[1] 0

$libidn
[1] "1.29"
</code>```

If I use httr::set_config( httr::config( ssl_verifypeer = 0L ) ) then I can successfully run install_github but I would prefer to actually check ssl certificates.

Can anyone offer a solution?

答: I removed httr (deleting the whole httr folder directly from my R win-library) and reinstalled it. Then, installation from github worked smoothly

Body:
When I try to call install_github, I get the following error (not just for this package, but for all github packages):

> install_github('ramnathv/slidify')
Downloading github repo ramnathv/slidify@master
Error in curl::curl_fetch_memory(url, handle = handle) :
Problem with the SSL CA cert (path? access rights?)

But if I use RCurl directly to access github with ssl, I don't get any problem:

>  x <- getBinaryURL(
          url='https://github.com/ramnathv/slidify/archive/master.zip',
          followlocation=1L
          )

works with no errors, so RCurl can verify the SSL certificate properly and download the archive file.

> sessionInfo()
R version 3.2.1 (2015-06-18)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Debian GNU/Linux 8 (jessie)

locale:
 [1] LC_CTYPE=en_US.utf8       LC_NUMERIC=C
 [3] LC_TIME=en_US.utf8        LC_COLLATE=en_US.utf8
 [5] LC_MONETARY=en_US.utf8    LC_MESSAGES=en_US.utf8
 [7] LC_PAPER=en_US.utf8       LC_NAME=C
 [9] LC_ADDRESS=C              LC_TELEPHONE=C
 [11] LC_MEASUREMENT=en_US.utf8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] RCurl_1.95-4.7 bitops_1.0-6   devtools_1.8.0

loaded via a namespace (and not attached):
 [1] httr_1.0.0      R6_2.1.0        magrittr_1.5    rversions_1.0.2
 [5] tools_3.2.1     curl_0.9.1      Rcpp_0.12.0     memoise_0.2.1
 [9] xml2_0.1.1      stringi_0.5-5   git2r_0.10.1    stringr_1.0.0
 [13] digest_0.6.8

And

> curlVersion()

$age
[1] 3

$version
[1] "7.38.0"

$vesion_num
[1] 468480

$host
[1] "x86_64-pc-linux-gnu"

$features
   ipv6         ssl        libz        ntlm   asynchdns      spnego
      1           4           8          16         128         256
   largefile         idn tlsauth_srp     ntlm_wb
    512        1024       16384       32768

$ssl_version
[1] "OpenSSL/1.0.1k"

$ssl_version_num
[1] 0

$libz_version
[1] "1.2.8"

$protocols
[1] "dict"   "file"   "ftp"    "ftps"   "gopher" "http"   "https"  "imap"
[9] "imaps"  "ldap"   "ldaps"  "pop3"   "pop3s"  "rtmp"   "rtsp"   "scp"
[17] "sftp"   "smtp"   "smtps"  "telnet" "tftp"

$ares
[1] ""

$ares_num
[1] 0

$libidn
[1] "1.29"

If I use httr::set_config( httr::config( ssl_verifypeer = 0L ) ) then I can successfully run install_github but I would prefer to actually check ssl certificates.

Can anyone offer a solution?


问:
How to make a batch file that writes directory names to a text file
I am trying to write a batch file that scans a directory of folders and outputs the names to a text file.

The folder names are as follows:

```<code>    Folder Name 1 [123abc]
    Folder Name 2 [abc321]
</code>```

I'm needing the the folder names deleted leaving only the brackets and whats in between them listed out to a new.txt

Like this:

```<code>    [123abc]
    [abc321]
</code>```

答:
```<code>for /f "tokens=2delims=[]" %%a in ('dir /b /ad "yourdirectoryname\*[*]*" ') do echo [%%a]>>new.txt
</code>```

(untested - batch line)

Perform a directory list in /b basic form, /ad` of directories only, selecting against the supplied mask in the directory nominated.

Process each line of this list, tokenise using [ and ] ,select the second token and assign to the metavariable %%a. Enclose that metavariable in brackets and output by appending to the file.

If run from the prompt, reduce each %%a to %a.

Body:
I am trying to write a batch file that scans a directory of folders and outputs the names to a text file.

The folder names are as follows:

    Folder Name 1 [123abc]
    Folder Name 2 [abc321]

I'm needing the the folder names deleted leaving only the brackets and whats in between them listed out to a new.txt

Like this:

    [123abc]
    [abc321]

Body:
for /f "tokens=2delims=[]" %%a in ('dir /b /ad "yourdirectoryname\*[*]*" ') do echo [%%a]>>new.txt

(untested - batch line)

Perform a directory list in /b basic form, /ad` of directories only, selecting against the supplied mask in the directory nominated.

Process each line of this list, tokenise using [ and ] ,select the second token and assign to the metavariable %%a. Enclose that metavariable in brackets and output by appending to the file.

If run from the prompt, reduce each %%a to %a.


问:
Which all keys in Bluetooth Keyboard to force Screen-Lock Android and iOS phone
Once I paired by phone with a Bluetooth keyboard which all "keys" (like in windows is Win+L) should be pressed in order to screen-lock my Android and iOS phone.

In fact, I am not using Bluetooth Keyboard, I am implementing a virtual Keyboard in Raspberry Pi.Here, I build a HID profile in Raspberry Pi using Linux Bluetooth stack BlueZ.So my Phone detect as Keyboard and I can send any String like " Hello World " as HID report which will spread in the entire Text box of the phone.Next experiment is to issue an OS interrupt like Screen-Lock to my phone. It will be helpful if anyone state which is Keys to Lock So that in add in my Python script for locking phone programmatically.(I have no Bluetooth keyboard to do try and error test)

答:
So it was quite easy to get the KeyStroke for Android from Android Doc.(https://source.android.com/devices/input/keyboard-devices.html)

But for iOS ,i hadn't got a clue.I seriously doubt whether the HID report structure is different for iOS things.

Update

After sniffing Bluetooth Signal from Bluetooth Keyboard we are able to detect the event data send was a mouse event (Fn + Lock key of keyboard) .The same event structure code in my Rpi and sent to iPhone but never worked. Should i need to do further Handshake ?


问:
inject Image without removing src attribute
is there a way to inject HTML without filtering the src attribute in Dart (no security needed in context), I've tried setInnerHtml, but it doesn't let src pass it...

here's the div I'm adding html in:

```<code><div id="output">
    <!--here goes messages-->

</div>
</code>```

here's my dart code:

```<code>import 'dart:html';
import 'dart:async';

InputElement input = querySelector("#textInput");
var output = querySelector("#output");
var buttonSend = querySelector("#send");
var buttonImg = querySelector("#url");
var buttonVideo = querySelector("#video");

Future<Null> main() async {

  //send custom message
  buttonSend.onClick.listen((MouseEvent event) async{
    addContent(input.value);
  });

  //send img
  buttonImg.onClick.listen((MouseEvent event) async{
    addContent(getPrefabImg(input.value));
  });

  //send video
  buttonVideo.onClick.listen((MouseEvent event) async{
    addContent(getPrefabVideo(input.value));
  });
}

//if user use a prefab img
String getPrefabImg(url) {
  return "<img class='prefabImg' src='" + url + "'>";
}

//if user use a prefab video
String getPrefabVideo(url) {
  return "<iframe class='prefabVideo'' src='" + url + "' frameborder='0' allowfullscreen></iframe>";
}

//reset input and add content
void addContent(value){
  output.setInnerHtml(value + output.innerHtml);
  input.value = null;
 }
</code>```

答:
To create and inject HTML into the DOM without a NodeTreeSanitizer, you will need to switch from using HTML Strings to using Dart's Node objects. Picking a couple of functions from your code as an example, you can change them to something like;

```<code>ImageElement getPrefabImg(String url) {
  return new ImageElement(src: url)..classes.add('prefabImage');
}

void addContent(Node node) {
  output.nodes.insert(0, node);
  input.value = null;
}
</code>```

But with your current code you can easily add a NodeTreeSanitizer like so;

```<code>void addContent(String value) {
  output.insertAdjacentHtml(
      'afterBegin', value, treeSanitizer: NodeTreeSanitizer.trusted);
  input.value = null;
}
</code>```

Body:
is there a way to inject HTML without filtering the src attribute in Dart (no security needed in context), I've tried setInnerHtml, but it doesn't let src pass it...

here's the div I'm adding html in:

here's my dart code:

import 'dart:html';
import 'dart:async';

InputElement input = querySelector("#textInput");
var output = querySelector("#output");
var buttonSend = querySelector("#send");
var buttonImg = querySelector("#url");
var buttonVideo = querySelector("#video");

Future<Null> main() async {

  //send custom message
  buttonSend.onClick.listen((MouseEvent event) async{
    addContent(input.value);
  });

  //send img
  buttonImg.onClick.listen((MouseEvent event) async{
    addContent(getPrefabImg(input.value));
  });

  //send video
  buttonVideo.onClick.listen((MouseEvent event) async{
    addContent(getPrefabVideo(input.value));
  });
}

//if user use a prefab img
String getPrefabImg(url) {
  return "";
}

//if user use a prefab video
String getPrefabVideo(url) {
  return "";
}

//reset input and add content
void addContent(value){
  output.setInnerHtml(value + output.innerHtml);
  input.value = null;
 }

Body:
To create and inject HTML into the DOM without a NodeTreeSanitizer, you will need to switch from using HTML Strings to using Dart's Node objects. Picking a couple of functions from your code as an example, you can change them to something like;

ImageElement getPrefabImg(String url) {
  return new ImageElement(src: url)..classes.add('prefabImage');
}

void addContent(Node node) {
  output.nodes.insert(0, node);
  input.value = null;
}

But with your current code you can easily add a NodeTreeSanitizer like so;

void addContent(String value) {
  output.insertAdjacentHtml(
      'afterBegin', value, treeSanitizer: NodeTreeSanitizer.trusted);
  input.value = null;
}


问:
Convert sub-hourly data to hourly and round up time in R
I have a very big dataframe in R, containing weather data with the following format.

```<code>                 valid temp
    1 17/08/2014 00:20   14
    2 17/08/2014 00:50   14
    3 17/08/2014 01:20   13.5
    4 17/08/2014 01:50   13
    5 17/08/2014 02:20   12
    6 17/08/2014 02:50   10
</code>```

I would like to convert these sub-hourly data to hourly, like the following.

```<code>                    valid tmpc
    1 2014-08-17 00:00:00   14
    2 2014-08-17 01:00:00   13.75
    3 2014-08-17 02:00:00   12.5
</code>```

The class of df$valid is 'factor'. I have tried first converting them to Date through POSIXct, but it gives only NA values. I have also tried changing the system locale and still I get NAs.

答:
Option 1: The lubridate solution using ceiling_date or round_date. It's not clear according to your data frame and results if what you want is to round or ceiling. For instance, in the first row you are rounding and in the third  using ceiling. Anyways here the example:

```<code>library(lubridate)
df <- data.frame(i = 1, valid= "17/08/2014 01:28", temp = 14)
df$valid <- dmy_hm(df$valid)
df$valid_round <- ceiling_date(df$valid , unit="hours")
</code>```

Results:

```<code>  i               valid temp         valid_round
1 1 2014-08-17 01:28:00   14 2014-08-17 02:00:00
</code>```

Option 2: using the base functions. Use:
    df$valid <- as.POSIXct(strptime(df$valid, "%d/%m/%Y %H:%M", tz ="UTC"))
and then round it.

Body:
I have a very big dataframe in R, containing weather data with the following format.

                 valid temp
    1 17/08/2014 00:20   14
    2 17/08/2014 00:50   14
    3 17/08/2014 01:20   13.5
    4 17/08/2014 01:50   13
    5 17/08/2014 02:20   12
    6 17/08/2014 02:50   10

I would like to convert these sub-hourly data to hourly, like the following.

                    valid tmpc
    1 2014-08-17 00:00:00   14
    2 2014-08-17 01:00:00   13.75
    3 2014-08-17 02:00:00   12.5

The class of df$valid is 'factor'. I have tried first converting them to Date through POSIXct, but it gives only NA values. I have also tried changing the system locale and still I get NAs.

Body:
Option 1: The lubridate solution using ceiling_date or round_date. It's not clear according to your data frame and results if what you want is to round or ceiling. For instance, in the first row you are rounding and in the third  using ceiling. Anyways here the example:

library(lubridate)
df <- data.frame(i = 1, valid= "17/08/2014 01:28", temp = 14)
df$valid <- dmy_hm(df$valid)
df$valid_round <- ceiling_date(df$valid , unit="hours")

Results:

  i               valid temp         valid_round
1 1 2014-08-17 01:28:00   14 2014-08-17 02:00:00

Option 2: using the base functions. Use:
    df$valid <- as.POSIXct(strptime(df$valid, "%d/%m/%Y %H:%M", tz ="UTC"))
and then round it.


问:
How to conditionally merge objects from a single Observable stream?
A stream constains the following objects

```<code>const data = [
  { type: 'gps',   id: 1, val: 1 },
  { type: 'gps',   id: 2, val: 2 },
  { type: 'speed', id: 2, val: 3 },
  { type: 'gps',   id: 3, val: 4 },
  { type: 'speed', id: 4, val: 5 },
  { type: 'gps',   id: 4, val: 6 },
  { type: 'gps',   id: 5, val: 7 }
]
</code>```

In case the ids are the same, the objects are merged. If no id matches up, the object is ignored:

```<code>[
   [{type: 'gps', id:2, val:2}, { type: 'speed', id: 2, val: 3 }],
   [{ type: 'speed', id: 4, val: 5 },{ type: 'gps',   id: 4, val: 6 }]
]
</code>```

My idea was to group objects with the same type, ending up with two new streams

```<code>Rx.Observable.from(data)
  .groupBy((x) => x.type)
  .flatMap((g) => ...)
  ....
</code>```

and then to merge/zip them again if the id is equal.

I'm not sure how to specify this in Rx and I'm also not sure if this is a good approach.

答:
There is no need to split the stream and merge it back again. You can use scan to collect the objects and filter out the ones that do not meet to condition

const data = [
  { type: 'gps', id: 1, val: 1 },
  { type: 'gps', id: 2, val: 2 },
  { type: 'speed', id: 2, val: 3 },
  { type: 'gps', id: 3, val: 4 },
  { type: 'speed', id: 4, val: 5 },
  { type: 'gps', id: 4, val: 6 },
  { type: 'gps', id: 5, val: 7 }
]

const generator$ = Rx.Observable.from(data)

generator$
  .scan((acc, x) => {
    if (R.contains(x.id, R.pluck('id', acc))) {
      acc.push(x);
    } else {
      acc = [x]
    }
    return acc
  }, [])
  .filter(x => x.length > 1)
  .subscribe(console.log)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.23.0/ramda.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.1/Rx.min.js"></script></code>```

Body:
A stream constains the following objects

const data = [
  { type: 'gps',   id: 1, val: 1 },
  { type: 'gps',   id: 2, val: 2 },
  { type: 'speed', id: 2, val: 3 },
  { type: 'gps',   id: 3, val: 4 },
  { type: 'speed', id: 4, val: 5 },
  { type: 'gps',   id: 4, val: 6 },
  { type: 'gps',   id: 5, val: 7 }
]

In case the ids are the same, the objects are merged. If no id matches up, the object is ignored:

[
   [{type: 'gps', id:2, val:2}, { type: 'speed', id: 2, val: 3 }],
   [{ type: 'speed', id: 4, val: 5 },{ type: 'gps',   id: 4, val: 6 }]
]

My idea was to group objects with the same type, ending up with two new streams

Rx.Observable.from(data)
  .groupBy((x) => x.type)
  .flatMap((g) => ...)
  ....

and then to merge/zip them again if the id is equal.

I'm not sure how to specify this in Rx and I'm also not sure if this is a good approach.

Body:
There is no need to split the stream and merge it back again. You can use scan to collect the objects and filter out the ones that do not meet to condition

const data = [
  { type: 'gps', id: 1, val: 1 },
  { type: 'gps', id: 2, val: 2 },
  { type: 'speed', id: 2, val: 3 },
  { type: 'gps', id: 3, val: 4 },
  { type: 'speed', id: 4, val: 5 },
  { type: 'gps', id: 4, val: 6 },
  { type: 'gps', id: 5, val: 7 }
]

const generator$ = Rx.Observable.from(data)

generator$
  .scan((acc, x) => {
    if (R.contains(x.id, R.pluck('id', acc))) {
      acc.push(x);
    } else {
      acc = [x]
    }
    return acc
  }, [])
  .filter(x => x.length > 1)
  .subscribe(console.log)

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.23.0/ramda.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.1/Rx.min.js"></script>


问:
Is there a way for a mysqli connection to stay open across files and functions (LAMP)?
I have an index.php and a functions.php.

The index.php does not make connections to the database but uses functions from functions.php that connect all to the same database.

The functions start with

```<code>$mysqli = new mysqli('***', '***', '***', '***');
[...]
$mysqli -> close();
</code>```

As the app grows there are more and more functions which call one other and I'm thinking there must be a better method than constantly opening and closing connections.

答:
Have you tried using classes?

Maybe put the MySQL connection statement in the ctor and using a class member to hold the mysqli handle?

Body:
I have an index.php and a functions.php.

The index.php does not make connections to the database but uses functions from functions.php that connect all to the same database.

The functions start with

$mysqli = new mysqli('***', '***', '***', '***');
[...]
$mysqli -> close();

As the app grows there are more and more functions which call one other and I'm thinking there must be a better method than constantly opening and closing connections.


问:
Dealing with multiple Python versions and PIP?
Is there any way to make pip play well with multiple versions of Python? For example, I want to use pip to explicitly install things to either my site 2.5 installation or my site 2.6 installation.

For example, with easy_install, I use easy_install-2.{5,6}.

And, yes — I know about virtualenv, and no — it's not a solution to this particular problem.

答:
pip is also a python package. So the easiest way to install modules to a specific python version would be below

```<code> python2.7 /usr/bin/pip install foo
</code>```

or

```<code>python2.7 -m pip install foo
</code>```

ContentLicense: CC BY-SA 4.0

Body:
pip is also a python package. So the easiest way to install modules to a specific python version would be below

 python2.7 /usr/bin/pip install foo

or

python2.7 -m pip install foo


问:
While Loop Variable Initialization and Variable Types(C)
I'm relatively new to coding and am currently studying C. I had some trouble regarding a textbook exercise and some help would be much appreciated.

The exercise's main objective is to calculate the total salary that an employee should receive by inputting the hours of work done and the hourly rate. The rate is 100% up to 40 hours, but after 40 hours it goes up to 150%. Here's the code that I wrote:

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

int main (void) {
    int employee, hour, ratenormal, totalrate, counter, rate;
    int salary;

    hour = 1;

    while (hour != -1) {
        printf("Enter # of hours worked (-1 to end): ");
        scanf_s("%d", &hour);
        if (hour == -1) break;

        printf("Enter hourly rate of the work ($00.00): $");
        scanf_s("%d", &rate);

        if (hour <= 40) {
            salary = hour * rate;
        }
        else if (hour > 40) {
            salary = salary + ((hour - 40) * (rate * 1.5));
        }

        printf("Salary is $%d\n\n", salary);
    }

    return 0;
}
</code>```

I had a couple of questions:

1) If I declare the variable "salary" as a float, then the result only prints 0. Why is that?

2) The loop works fine, but only for the first iteration. The problem is that I need to initialize the variable salary again, otherwise it keeps storing some of the value that has been previously used. How could I do this?

Thank you for all the help!

答: end of the line printf("Salary is $%d\n\n", salary); declare salary = 0; Otherwise else condition don't work properly you get previous value also.

Body:
I'm relatively new to coding and am currently studying C. I had some trouble regarding a textbook exercise and some help would be much appreciated.

The exercise's main objective is to calculate the total salary that an employee should receive by inputting the hours of work done and the hourly rate. The rate is 100% up to 40 hours, but after 40 hours it goes up to 150%. Here's the code that I wrote:

#include <stdio.h>

int main (void) {
    int employee, hour, ratenormal, totalrate, counter, rate;
    int salary;

    hour = 1;

    while (hour != -1) {
        printf("Enter # of hours worked (-1 to end): ");
        scanf_s("%d", &hour);
        if (hour == -1) break;

        printf("Enter hourly rate of the work ($00.00): $");
        scanf_s("%d", &rate);

        if (hour <= 40) {
            salary = hour * rate;
        }
        else if (hour > 40) {
            salary = salary + ((hour - 40) * (rate * 1.5));
        }

        printf("Salary is $%d\n\n", salary);
    }

    return 0;
}

I had a couple of questions:

1) If I declare the variable "salary" as a float, then the result only prints 0. Why is that?

2) The loop works fine, but only for the first iteration. The problem is that I need to initialize the variable salary again, otherwise it keeps storing some of the value that has been previously used. How could I do this?

Thank you for all the help!


问:
How to reset a variable in Flume's custom sink class for every batch
I have a flume process that reads data from file on a spooldir & loads the data into MySQL database. There will be multiple types of files that can be processed by the same flume process.

I have created a custom sink java class (extending AbstractSink), that updates a local variable (sInterfaceType) after an initial/first read to decide the data format in the file.
I have to reset it once the file processing completes, so that it has to start with identifying the next batch/interface file.

I tried to do in stop() but it doesn't help. Did anybody do this?

My sink class looks like this:

```<code>public class MyFlumeSink2 extends AbstractSink implements Configurable {

 private String sInterfaceType; //tells file format of current load

 public MyFlumeSink2() {
  //my initialization of variables
 }

 public void configure(Context context) {
  //read context variables
 }

 public void start() {
  //create db connection
 }

 @Override
 public void stop() {
  //destroy connection
  sInterfaceType = ""; //This doesn't help me
  super.stop();
 }

 public Status process() throws EventDeliveryException {
   Channel channel = getChannel();
   Transaction transaction = channel.getTransaction();

   if((sInterfaceType=="" || sInterfaceType==null))
   {
    //Read first line & set sInterfaceType
   }else
     //Insert data in MySQL

   transaction.commit();
 }
}
</code>```

答:
We have to manually decide which event it is, there is no specialized method called for every new file.

I revised my code to read the event line & set InterfaceType based on first element. My code looks like this:

```<code>public Status process() throws EventDeliveryException {
        //....other code...

            sEvtBody = new String(event.getBody());
            sFields = sEvtBody.split(",");

            //check first field to know record type
            enumRec = RecordType.valueOf( checkRecordType(sFields[0].toUpperCase()) );
            switch(enumRec)
            {
                case CUST_ID:
                    sInterfaceType = "T_CUST";
                    bHeader = true;
                    break;
                case TXN_ID:
                    sInterfaceType = "T_CUST_TXNS";
                    bHeader = true;
                    break;
                default:
                    bHeader = false;
            }
            //insert if not header
            if(!bHeader)
            {

                if(sInterfaceType == "T_CUST")
                {
                    if(sFields.length == 14)
                        this.bInsertStatus = daoClass.insertHeader(sFields);
                    else
                        throw new Exception("INCORRECT_COLUMN_COUNT");
                }else if(sInterfaceType == "T_CUST_TXNS")
                {
                    if(sFields.length == 10)
                        this.bInsertStatus = daoClass.insertData(sFields);
                    else
                        throw new Exception("INCORRECT_COLUMN_COUNT");
                }

                //if(!bInsertStatus)
                //  logTransaction(sFields);
            }
            //....Other code....
</code>```

Body:
I have a flume process that reads data from file on a spooldir & loads the data into MySQL database. There will be multiple types of files that can be processed by the same flume process.

I have created a custom sink java class (extending AbstractSink), that updates a local variable (sInterfaceType) after an initial/first read to decide the data format in the file.
I have to reset it once the file processing completes, so that it has to start with identifying the next batch/interface file.

I tried to do in stop() but it doesn't help. Did anybody do this?

My sink class looks like this:

public class MyFlumeSink2 extends AbstractSink implements Configurable {

 private String sInterfaceType; //tells file format of current load

 public MyFlumeSink2() {
  //my initialization of variables
 }

 public void configure(Context context) {
  //read context variables
 }

 public void start() {
  //create db connection
 }

 @Override
 public void stop() {
  //destroy connection
  sInterfaceType = ""; //This doesn't help me
  super.stop();
 }

 public Status process() throws EventDeliveryException {
   Channel channel = getChannel();
   Transaction transaction = channel.getTransaction();

   if((sInterfaceType=="" || sInterfaceType==null))
   {
    //Read first line & set sInterfaceType
   }else
     //Insert data in MySQL

   transaction.commit();
 }
}

Body:
We have to manually decide which event it is, there is no specialized method called for every new file.

I revised my code to read the event line & set InterfaceType based on first element. My code looks like this:

public Status process() throws EventDeliveryException {
        //....other code...

            sEvtBody = new String(event.getBody());
            sFields = sEvtBody.split(",");

            //check first field to know record type
            enumRec = RecordType.valueOf( checkRecordType(sFields[0].toUpperCase()) );
            switch(enumRec)
            {
                case CUST_ID:
                    sInterfaceType = "T_CUST";
                    bHeader = true;
                    break;
                case TXN_ID:
                    sInterfaceType = "T_CUST_TXNS";
                    bHeader = true;
                    break;
                default:
                    bHeader = false;
            }
            //insert if not header
            if(!bHeader)
            {

                if(sInterfaceType == "T_CUST")
                {
                    if(sFields.length == 14)
                        this.bInsertStatus = daoClass.insertHeader(sFields);
                    else
                        throw new Exception("INCORRECT_COLUMN_COUNT");
                }else if(sInterfaceType == "T_CUST_TXNS")
                {
                    if(sFields.length == 10)
                        this.bInsertStatus = daoClass.insertData(sFields);
                    else
                        throw new Exception("INCORRECT_COLUMN_COUNT");
                }

                //if(!bInsertStatus)
                //  logTransaction(sFields);
            }
            //....Other code....


问:
How to use multiprocessing pool.map with multiple arguments
In the Python multiprocessing library, is there a variant of pool.map which supports multiple arguments?

```<code>import multiprocessing

text = "test"

def harvester(text, case):
    X = case[0]
    text + str(X)

if __name__ == '__main__':
    pool = multiprocessing.Pool(processes=6)
    case = RAW_DATASET
    pool.map(harvester(text, case), case, 1)
    pool.close()
    pool.join()
</code>```

答:
In the official documentation states that it supports only one iterable argument. I like to use apply_async in such cases. In your case I would do:</p>

```<code>from multiprocessing import Process, Pool, Manager

text = "test"
def harvester(text, case, q = None):
 X = case[0]
 res = text+ str(X)
 if q:
  q.put(res)
 return res

def block_until(q, results_queue, until_counter=0):
 i = 0
 while i < until_counter:
  results_queue.put(q.get())
  i+=1

if __name__ == '__main__':
 pool = multiprocessing.Pool(processes=6)
 case = RAW_DATASET
 m = Manager()
 q = m.Queue()
 results_queue = m.Queue() # when it completes results will reside in this queue
 blocking_process = Process(block_until, (q, results_queue, len(case)))
 blocking_process.start()
 for c in case:
  try:
   res = pool.apply_async(harvester, (text, case, q = None))
   res.get(timeout=0.1)
  except:
   pass
 blocking_process.join()
</code>```

Body:
In the Python multiprocessing library, is there a variant of pool.map which supports multiple arguments?

import multiprocessing

text = "test"

def harvester(text, case):
    X = case[0]
    text + str(X)

if __name__ == '__main__':
    pool = multiprocessing.Pool(processes=6)
    case = RAW_DATASET
    pool.map(harvester(text, case), case, 1)
    pool.close()
    pool.join()

Body:
In the official documentation states that it supports only one iterable argument. I like to use apply_async in such cases. In your case I would do:

from multiprocessing import Process, Pool, Manager

text = "test"
def harvester(text, case, q = None):
 X = case[0]
 res = text+ str(X)
 if q:
  q.put(res)
 return res

def block_until(q, results_queue, until_counter=0):
 i = 0
 while i < until_counter:
  results_queue.put(q.get())
  i+=1

if __name__ == '__main__':
 pool = multiprocessing.Pool(processes=6)
 case = RAW_DATASET
 m = Manager()
 q = m.Queue()
 results_queue = m.Queue() # when it completes results will reside in this queue
 blocking_process = Process(block_until, (q, results_queue, len(case)))
 blocking_process.start()
 for c in case:
  try:
   res = pool.apply_async(harvester, (text, case, q = None))
   res.get(timeout=0.1)
  except:
   pass
 blocking_process.join()


问:
After using firebase email update API how do I reuse the old email?
UPDATE: it just randomly started working for me now...is there a period of time after updating an email that it is ineligible for new account creation?

I was able to use this API call provided by firebase to change emails for an account, but now I cannot use the other email to create a new count. I cannot reuse the other email at all. It seems like there is still a lock or hold on the old email.
https://firebase.google.com/docs/reference/js/firebase.User#updateEmail

Steps to reproduce error

signup with original@email.com

update account email to  new@email.com (and click verification link sent via email)

cannot create a new account (nor re-update existing account) with original@email.com

I am simply looking to free up the email that is no longer in use. (original@email.com)

Note in image below that 'original@email.com' does not show up

答: This is a security related behavior. The old email is reserved just in case the owner of the email decides to revert to the old account by clicking the email change revocation link which is sent to the old email. This gives the owner of the account the ability to recover their account in case it was hijacked and the attacker tried to change their email. </p>


问:
spring cloud config properties from both local filesystem and git repo
I am using spring cloud config server to host a centralized location for all the property files configurations to be used in the project.
I tried using the config files from a local file system using below and it works fine:

```<code>spring.profiles.active=native
spring.cloud.config.server.native.searchLocations=file://${HOME}/Documents/test-config/cloud-config-properties/
</code>```

I also used the git repo using: spring.cloud.config.server.git.uri=ssh://xxxxxx.com:7999/test/cloud-config-properties.git

I would like to try using a combination of this in my project.
Example - for dev/test profile - i would like to use from local filesystem and for the production - I would like to use Git repository.
I enabled both the git uri and native profiles in my application.properties in config server application. But the properties are always picked up from the local file system. Is this possible?

答:
Not supported out of the box, however there is a workaround for this. You can define the basedir for the configuration server, which is where it saves the files it fetches from the remote server, by setting the property (in the config server):

```<code>spring.cloud.config.server.git.basedir=<your_dir>
</code>```

If you are working with docker, you can map this directory to the host filesystem.

Now whatever file you put in there will be picked up by configuration-server if it matches any of the application/profile in the request. For example you could put a file there called application-dynamic.properties, and have all your clients use dynamic as the last profile, for example

```<code>spring.profiles.active=systesting,dynamic
</code>```

This way everything you will put in application-dynamic.properties will override whatever is defined in your config repo.

One thing to notice though is that you need to add the file only after configuartion server starts, because it deletes this folder during startup.

Needles to say, it's not a good practice doing this in production (for example a restart will cause the file to be deleted), but for test/dev this is the best option.

Body:
I am using spring cloud config server to host a centralized location for all the property files configurations to be used in the project.
I tried using the config files from a local file system using below and it works fine:

spring.profiles.active=native
spring.cloud.config.server.native.searchLocations=file://${HOME}/Documents/test-config/cloud-config-properties/

I also used the git repo using: spring.cloud.config.server.git.uri=ssh://xxxxxx.com:7999/test/cloud-config-properties.git

I would like to try using a combination of this in my project.
Example - for dev/test profile - i would like to use from local filesystem and for the production - I would like to use Git repository.
I enabled both the git uri and native profiles in my application.properties in config server application. But the properties are always picked up from the local file system. Is this possible?

Body:
Not supported out of the box, however there is a workaround for this. You can define the basedir for the configuration server, which is where it saves the files it fetches from the remote server, by setting the property (in the config server):

spring.cloud.config.server.git.basedir=<your_dir>

If you are working with docker, you can map this directory to the host filesystem.

Now whatever file you put in there will be picked up by configuration-server if it matches any of the application/profile in the request. For example you could put a file there called application-dynamic.properties, and have all your clients use dynamic as the last profile, for example

spring.profiles.active=systesting,dynamic

This way everything you will put in application-dynamic.properties will override whatever is defined in your config repo.

One thing to notice though is that you need to add the file only after configuartion server starts, because it deletes this folder during startup.

Needles to say, it's not a good practice doing this in production (for example a restart will cause the file to be deleted), but for test/dev this is the best option.


问:
Error on smack 4.2.0 : IN AAAA yielded an error response NX_DOMAIN
i start openFire and test it with spark everything is ok but when i try to connect with smack 4.2.0 in android studio i got this error:

Ljavax/naming/directory/InitialDirContext;

and my dependencies is this:

compile "org.igniterealtime.smack:smack-java7:4.2.0" compile
  "org.igniterealtime.smack:smack-tcp:4.2.0" compile
  "org.igniterealtime.smack:smack-im:4.2.0" compile
  "org.igniterealtime.smack:smack-extensions:4.2.0" compile
  "org.igniterealtime.smack:smack-android-extensions:4.2.0" compile
  "org.igniterealtime.smack:smack-bosh:4.2.0"

when remove this :
"compile org.igniterealtime.smack:smack-java7:4.2.0"
from dependencies and add this:
compile "org.igniterealtime.smack:smack-android:4.2.0"
my dependencies become like this:

compile 'com.android.support:appcompat-v7:24.0.0' compile
  "org.igniterealtime.smack:smack-android:4.2.0" compile
  "org.igniterealtime.smack:smack-tcp:4.2.0" compile
  "org.igniterealtime.smack:smack-im:4.2.0" compile
  "org.igniterealtime.smack:smack-extensions:4.2.0" compile
  "org.igniterealtime.smack:smack-android-extensions:4.2.0" compile
  "org.igniterealtime.smack:smack-bosh:4.2.0"

I got This Error:

org.jivesoftware.smack.SmackException$ConnectionException: The
  following addresses failed: '192.168.209.2:5222' failed because:
  de.measite.minidns.hla.ResolutionUnsuccessfulException: Asking for
  192.168.209.2. IN A yielded an error response NX_DOMAIN, '192.168.209.2:5222' failed because:
  de.measite.minidns.hla.ResolutionUnsuccessfulException: Asking for
  192.168.209.2. IN AAAA yielded an error response NX_DOMAIN

the part of code that make error when i try to conn.connect() is this:

```<code>XMPPTCPConnectionConfiguration config = null;
            try {
                config = XMPPTCPConnectionConfiguration.builder()
                        .setUsernameAndPassword("admin", "thepass")
                        .setXmppDomain("192.168.1.3")
                        .setHost("192.168.209.2")
                        .setPort(5222)
                        .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
                        .build();
            } catch (Exception e) {
                e.printStackTrace();
            }
                AbstractXMPPConnection conn1 = new XMPPTCPConnection(config);
                conn1.setReplyTimeout(60000);
                conn1.setPacketReplyTimeout(60000);
                conn1.connect();
</code>```

答:
Please check :
https://github.com/igniterealtime/Smack/wiki/Smack-4.2-Readme-and-Upgrade-Guide

In previous versions of Smack, ConnectionConfiguration.setHost(String) could be used to set the XMPP service's host IP address. This is no longer possible due to the added DNSSEC support. You have to use the new connection configuration ConnectionConfiguration.setHostAddress(InetAddress) instead.

You can check this also.

failed because: de.measite.minidns.hla.ResolutionUnsuccessfulException: Asking for xxxx. IN AAAA yielded an error response NX_DOMAIN

Body:
i start openFire and test it with spark everything is ok but when i try to connect with smack 4.2.0 in android studio i got this error:

Ljavax/naming/directory/InitialDirContext;

and my dependencies is this:

compile "org.igniterealtime.smack:smack-java7:4.2.0" compile
  "org.igniterealtime.smack:smack-tcp:4.2.0" compile
  "org.igniterealtime.smack:smack-im:4.2.0" compile
  "org.igniterealtime.smack:smack-extensions:4.2.0" compile
  "org.igniterealtime.smack:smack-android-extensions:4.2.0" compile
  "org.igniterealtime.smack:smack-bosh:4.2.0"

when remove this :
"compile org.igniterealtime.smack:smack-java7:4.2.0"
from dependencies and add this:
compile "org.igniterealtime.smack:smack-android:4.2.0"
my dependencies become like this:

compile 'com.android.support:appcompat-v7:24.0.0' compile
  "org.igniterealtime.smack:smack-android:4.2.0" compile
  "org.igniterealtime.smack:smack-tcp:4.2.0" compile
  "org.igniterealtime.smack:smack-im:4.2.0" compile
  "org.igniterealtime.smack:smack-extensions:4.2.0" compile
  "org.igniterealtime.smack:smack-android-extensions:4.2.0" compile
  "org.igniterealtime.smack:smack-bosh:4.2.0"

I got This Error:

org.jivesoftware.smack.SmackException$ConnectionException: The
  following addresses failed: '192.168.209.2:5222' failed because:
  de.measite.minidns.hla.ResolutionUnsuccessfulException: Asking for
  192.168.209.2. IN A yielded an error response NX_DOMAIN, '192.168.209.2:5222' failed because:
  de.measite.minidns.hla.ResolutionUnsuccessfulException: Asking for
  192.168.209.2. IN AAAA yielded an error response NX_DOMAIN

the part of code that make error when i try to conn.connect() is this:

XMPPTCPConnectionConfiguration config = null;
            try {
                config = XMPPTCPConnectionConfiguration.builder()
                        .setUsernameAndPassword("admin", "thepass")
                        .setXmppDomain("192.168.1.3")
                        .setHost("192.168.209.2")
                        .setPort(5222)
                        .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
                        .build();
            } catch (Exception e) {
                e.printStackTrace();
            }
                AbstractXMPPConnection conn1 = new XMPPTCPConnection(config);
                conn1.setReplyTimeout(60000);
                conn1.setPacketReplyTimeout(60000);
                conn1.connect();


问:
Pod file not being initialized?
When i try to initialize pod file to use cocoapods via terminal, it gives me this error. How to fix it.

```<code>/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/command.rb:128:in `verify_minimum_git_version!': [!] You need at least git version 1.8.5 to use CocoaPods (Pod::Informative)
</code>```

答:
I was having an issue while trying to install packages using cocoapods. I have tried  "sudo xcode-select --switch /Applications/Xcode.app" still getting wrong path error

To fix this

I opened Xcode.

```<code>Preferences
Locations
Selected the Command Lin Tools: Xcode 9.0
</code>```

Now when installing packages with cocoapods I no longer get errors.

Title: Pod file not being initialized?

Body:
When i try to initialize pod file to use cocoapods via terminal, it gives me this error. How to fix it.

/Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.0/lib/cocoapods/command.rb:128:in `verify_minimum_git_version!': [!] You need at least git version 1.8.5 to use CocoaPods (Pod::Informative)

Body:
I was having an issue while trying to install packages using cocoapods. I have tried  "sudo xcode-select --switch /Applications/Xcode.app" still getting wrong path error

To fix this

I opened Xcode.

Preferences
Locations
Selected the Command Lin Tools: Xcode 9.0

Now when installing packages with cocoapods I no longer get errors.


问:
Headless browser that supports HTML 5 video?
I need to automate screenshots of HTML 5 video player pages and their thumbnails, but after looking at some of the more popular headless browsers like PhantomJS they don't support HTML 5 video.

```<code>>phantomjs examples\features.js
Detected features (using Modernizr 2.0.6):

Supported:
  touch
  generatedcontent
  fontface
  flexbox
  canvas
  canvastext
  postmessage
  websqldatabase
  hashchange
  history
  draganddrop
  websockets
  rgba
  hsla
  multiplebgs
  backgroundsize
  borderimage
  borderradius
  boxshadow
  textshadow
  opacity
  cssanimations
  csscolumns
  cssgradients
  cssreflections
  csstransforms
  csstransitions
  localstorage
  sessionstorage
  webworkers
  applicationcache
  svg
  inlinesvg
  smil
  svgclippaths

Not supported:
  csstransforms3d
  webgl
  geolocation
  indexeddb
  video
  audio
</code>```

Note that HTML 5 video is not supported above, what lightweight headless browser DOES support HTML 5 video?

答:
Based on the documentation, SlimerJS can play HTML5 video and audio (and provide screenshots of them):

Since SlimerJS is executed on top of Firefox, it supports all the HTML5 standards recently implemented in Firefox, including things like audio, video, WebGL etc.

The web page rendering in SlimerJS is strictly identical to the rendering in Firefox.

You can go on caniuse.com to see the list of HTML5 features supported by Firefox and you can use in web pages loaded by SlimerJS.

Flash is said to be supported, too, but the Flash content is not available in screenshots:

SlimerJS is able to load Flash content if the Flash plugin is installed (though the plugin's rendering cannot be seen when taking screenshots).

Body:
I need to automate screenshots of HTML 5 video player pages and their thumbnails, but after looking at some of the more popular headless browsers like PhantomJS they don't support HTML 5 video.

>phantomjs examples\features.js
Detected features (using Modernizr 2.0.6):

Supported:
  touch
  generatedcontent
  fontface
  flexbox
  canvas
  canvastext
  postmessage
  websqldatabase
  hashchange
  history
  draganddrop
  websockets
  rgba
  hsla
  multiplebgs
  backgroundsize
  borderimage
  borderradius
  boxshadow
  textshadow
  opacity
  cssanimations
  csscolumns
  cssgradients
  cssreflections
  csstransforms
  csstransitions
  localstorage
  sessionstorage
  webworkers
  applicationcache
  svg
  inlinesvg
  smil
  svgclippaths

Not supported:
  csstransforms3d
  webgl
  geolocation
  indexeddb
  video
  audio

Note that HTML 5 video is not supported above, what lightweight headless browser DOES support HTML 5 video?


问:
Why is bottom-up parsing more common than top-down parsing?
It seems that recursive-descent parsers are not only the simplest to explain, but also the simplest to design and maintain. They aren't limited to LALR(1) grammars, and the code itself can be understood by mere mortals. In contrast, bottom up parsers have limits on the grammars they are able to recognize, and need to be generated by special tools (because the tables that drive them are next-to-impossible to generate by hand).

Why then, is bottom-up (i.e. shift-reduce) parsing more common than top-down (i.e. recursive descent) parsing?

答:
I have two guesses, though I doubt that either fully explains it:

Top-down parsing can be slow.  Recursive-descent parsers may require exponential time to complete their job.  That would put severe limitations on the scalability of a compiler which uses a top-down parser.

Better tools.  If you can express the language in some variant of EBNF, then chances are you can Lex/Yacc your way past a whole lot of tedious code.  There don't seem to be as many tools to help automate the task of putting together a top-down parser.  And let's face it, grinding out parser code just isn't the fun part of toying with languages.


答:
To answer 1). Declare salary as a float and then print it like so

```<code>printf("Salary is $%.2f\n\n", salary);
</code>```

the format %.2f will print the float as with 2 decimals. So if the salary was 550.5 it would print
Salary is $550.50

If I understood question 2) properly I think you want to do this to calculate the salary

```<code>    salary = hour * rate;
    if (hour > 40) {
        salary = salary + ((hour - 40) * (rate * 1.5));
    }
</code>```

With your code, if you enter a number of hours greater than 40 after the first iteration you will reuse the salary value of the previous iteration. In all cases you always want to re calculate the salary value with the standard rate, then IF the number of hours is greater than 40 you add to the salary the number additional hours multiplied by the overtime rate

Title: While Loop Variable Initialization and Variable Types(C)

Body:
To answer 1). Declare salary as a float and then print it like so

printf("Salary is $%.2f\n\n", salary);

the format %.2f will print the float as with 2 decimals. So if the salary was 550.5 it would print
Salary is $550.50

If I understood question 2) properly I think you want to do this to calculate the salary

    salary = hour * rate;
    if (hour > 40) {
        salary = salary + ((hour - 40) * (rate * 1.5));
    }

With your code, if you enter a number of hours greater than 40 after the first iteration you will reuse the salary value of the previous iteration. In all cases you always want to re calculate the salary value with the standard rate, then IF the number of hours is greater than 40 you add to the salary the number additional hours multiplied by the overtime rate


问:
Eclipse error "Could not find or load main class"
I know there are many duplicates of this question, but I have looked at them all, and none of them have solved the issue.

I am trying to run a class that has a main function. I have cleaned the project, checked the classpath for '.', added the bin folder to the classpath under run configurations. I'm not sure what else to try because the class is certainly in the source folder.

Could someone please help me with this issue?

```<code>package testIt;

public class MemoryVisualizerApp extends Application{

public static void main(String[] args) {
    launch(args);
}

//Setup the scene and launch with given properties
@Override
public void start(Stage primaryStage) throws IOException{
    Parent root = FXMLLoader.load(getClass().getResource("/MemoryVisualizer.fxml"));
    Scene scene = new Scene(root, 650, 300);
    //Set whether the screen should be re-sizable (possibly best size = default)
    primaryStage.setResizable(true);
    primaryStage.setMinHeight(300);
    primaryStage.setMinWidth(550);
    primaryStage.setTitle("Memory Usage");
    primaryStage.setScene(scene);
    scene.getStylesheets().add("testIt/MemoryVisualizer.css");
    primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>()
    {
        public void handle(WindowEvent e){
              /*Currently the threads continue running after window is closed. Looking for
              a way to stop the app threads when window closed without stopping the program.*/
        }
    });
    primaryStage.show();
    primaryStage.show();
}

}
</code>```

This code is located within a package, withing the src folder. It utilizes some JavaFX files that arent shown but that shouldnt be an issue.

This is the error:
Error: Could not find or load main class testIt.MemoryVisualizerApp

答: i had same problem but in my case firewall was blocking java directory path, make sure system firewall is allowing java directory path access.</p>

Body:
I know there are many duplicates of this question, but I have looked at them all, and none of them have solved the issue.

I am trying to run a class that has a main function. I have cleaned the project, checked the classpath for '.', added the bin folder to the classpath under run configurations. I'm not sure what else to try because the class is certainly in the source folder.

Could someone please help me with this issue?

package testIt;

public class MemoryVisualizerApp extends Application{

public static void main(String[] args) {
    launch(args);
}

//Setup the scene and launch with given properties
@Override
public void start(Stage primaryStage) throws IOException{
    Parent root = FXMLLoader.load(getClass().getResource("/MemoryVisualizer.fxml"));
    Scene scene = new Scene(root, 650, 300);
    //Set whether the screen should be re-sizable (possibly best size = default)
    primaryStage.setResizable(true);
    primaryStage.setMinHeight(300);
    primaryStage.setMinWidth(550);
    primaryStage.setTitle("Memory Usage");
    primaryStage.setScene(scene);
    scene.getStylesheets().add("testIt/MemoryVisualizer.css");
    primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>()
    {
        public void handle(WindowEvent e){
              /*Currently the threads continue running after window is closed. Looking for
              a way to stop the app threads when window closed without stopping the program.*/
        }
    });
    primaryStage.show();
    primaryStage.show();
}

}

This code is located within a package, withing the src folder. It utilizes some JavaFX files that arent shown but that shouldnt be an issue.

This is the error:
Error: Could not find or load main class testIt.MemoryVisualizerApp


问:
dynamic rendering in express using loop won't work
I have bunch of static file, they are named article1, article2 and so on. So I know it worked when I do

```<code>app.get('/this-is-my-article-routes', (req, res) => {
        res.render('article1');
});
</code>```

but it's too tedious and has lots of repeated code. I tried this but it doesn't work?

```<code>const articleArr = [
    'this-is-my-article-routes'
];

for (i = 0; i<9; i++) {
    app.get(`/${articleArr[i]}`, (req, res) => {
        res.render(`article${i}`);
    });
}
</code>```

Is this even possible? or there's something wrong with my codes?

答:
```<code>how about simple solution using query params
app.get('articleArr/:id', (req, res) => {
        res.render('article/'+req.params.id);
    });
</code>```

Body:
I have bunch of static file, they are named article1, article2 and so on. So I know it worked when I do

app.get('/this-is-my-article-routes', (req, res) => {
        res.render('article1');
});

but it's too tedious and has lots of repeated code. I tried this but it doesn't work?

const articleArr = [
    'this-is-my-article-routes'
];

for (i = 0; i<9; i++) {
    app.get(`/${articleArr[i]}`, (req, res) => {
        res.render(`article${i}`);
    });
}

Is this even possible? or there's something wrong with my codes?