问:
Create array from text of selected elements
How do I create an array who's values are the text of selected elements?  For instance, the below HTML should result in array ["test1","test2"].

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Create array</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(function(){
                var matched=$('#tbody td.sel');
                console.log(matched);
                console.log(matched.toArray());
                console.log(matched.text());
                //console.log(matched.toArray().text());
            });
        </script>
    </head>
    <body>
        <table>
            <thead>
                <tr><td>Name</td><td>GUID</td></tr>
            </thead>
            <tbody id="tbody">
                <tr><td>Client1</td><td class='sel'>test1</td></tr>
                <tr><td>Client2</td><td class='sel'>test2</td></tr>
            </tbody>
        </table>
    </body>
</html>
</code>```

答:
If you are casting the jQuery object to an array, you can just use the standard js Array methods, so I am using Array.prototype.map to iterate over the input array and create a new array with the returned values.

$(function() {
  var matched = $('#tbody td.sel')
  console.log(
    matched.toArray().map(function(el) {
      return $(el).text()
    })
  )
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <td>Name</td>
      <td>GUID</td>
    </tr>
  </thead>
  <tbody id="tbody">
    <tr>
      <td>Client1</td>
      <td class='sel'>test1</td>
    </tr>
    <tr>
      <td>Client2</td>
      <td class='sel'>test2</td>
    </tr>
  </tbody>
</table></code>```

Body:
How do I create an array who's values are the text of selected elements?  For instance, the below HTML should result in array ["test1","test2"].

<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Create array</title>

Name	GUID

Client1	test1

Client2	test2

Body:
If you are casting the jQuery object to an array, you can just use the standard js Array methods, so I am using Array.prototype.map to iterate over the input array and create a new array with the returned values.

$(function() {
  var matched = $('#tbody td.sel')
  console.log(
    matched.toArray().map(function(el) {
      return $(el).text()
    })
  )
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <td>Name</td>
      <td>GUID</td>
    </tr>
  </thead>
  <tbody id="tbody">
    <tr>
      <td>Client1</td>
      <td class='sel'>test1</td>
    </tr>
    <tr>
      <td>Client2</td>
      <td class='sel'>test2</td>
    </tr>
  </tbody>
</table>


来源: stackexchange

问:
How can i show left shift operator on my button in android?
I tried using this code but it's showing an error "Tag Name Expected".I don't want to use an image to show that in background of button i wan't to use the symbol ">>" itself.</p>

```<code>XML code:-
 <Button
        android:layout_width="120dp"
        android:layout_height="50dp"
        android:background="@drawable/shape"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="7dp"
        android:text="@string/leftshi"
        android:id="@+id/leftshi"
        android:textSize="35sp"
        android:layout_marginStart="7dp"
        />
String values:
 <resources>
        <string name="leftshi">"<<"</string> //Error is shown here.
 </resources>
</code>```

答:
Strings in resources are written without quotes, also special characters should be either escaped or written in & code:

```<code><string name="leftshi"><<</string>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I tried using this code but it's showing an error "Tag Name Expected".I don't want to use an image to show that in background of button i wan't to use the symbol ">>" itself.

XML code:-
 <Button
        android:layout_width="120dp"
        android:layout_height="50dp"
        android:background="@drawable/shape"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="7dp"
        android:text="@string/leftshi"
        android:id="@+id/leftshi"
        android:textSize="35sp"
        android:layout_marginStart="7dp"
        />
String values:
 <resources>
        <string name="leftshi">"<<"</string> //Error is shown here.
 </resources>

Body:
Strings in resources are written without quotes, also special characters should be either escaped or written in & code:

<string name="leftshi">&lt;&lt;</string>


答:
```<code>var arrText = $("#tbody td.sel").map(function(key, val) {
  return val.textContent
})

console.log(arrText)
</code>```

Title: Create array from text of selected elements


问:
Microsoft Access 2007 & VBA & CSV and ...stuff
I have an assignment for work purpose which isn't really hard to do but I'm not a proficient access user so I, hereby, come to you guys :)

I'm about to write VBA code that is actually a custom CSV files loader. It's going to parse some files and insert their content in the appropriate tables.
My question is: What is the most appropriate way of creating this loader and triggering it?
I guess I have to create a VBA Module in my database project, but then what are the possiblities for the user to invoke the script and load the files ?
Like... is there any file system browser control that I can pop open and ask the user to choose a csv file then load it or whatever else ?

Thank you for your hints guys

Miloud B

答: For the user the easiest will be to use right click on tables, import, select the data, choose the place to import to.</p>

ContentLicense: CC BY-SA 2.5


问:
Force immutability and create instance in the interface declaration
I have an interface that its API are only getter methods thereby ensuring that the class that implements the interface is in that respect immutable.

But if I need to update something that changes the behavior of the interface how would I declare my interface so that it creates a new instance of the concrete class?

Right now I have something like:

```<code>    public interface Generator {
      public int[] values();
      public float[] indications();
      //etc
      public MyEnum type;
    }

    public class ConcreteClass implements Generator {
      private ConcreteClass() {
      }
      public static ConcreteClass createInstance() {

       }
   }
</code>```

I have omitted arguments for clarity.

How would I move the createInstance to the interface?

答:
An interface is not designed to have implementation. With Java 8 you could have default method but it would be a bad idea that interface knows the implementation classes. An interface should stay abstract and not know its subclasses.

If ConcreteClass is immutable, you should document it and ensure that each method with side-effect doesn't apply any modification on the current object but instead create a new instance of ConcreteClass.

For example suppose you want provide method to update the values field, you could provide this method in ConcreteClass :

```<code>public ConcreteClass withValues(int[] values){
   // copy all existing properties from the original to the copy but values
   ConcreteClass copy = new ConcreteClass(values, this.indications, this.type);
   return copy;
}
</code>```

If you want really move out the instance creation from ConcreteClass, you could create a factory that provides this service.

Body:
I have an interface that its API are only getter methods thereby ensuring that the class that implements the interface is in that respect immutable.

But if I need to update something that changes the behavior of the interface how would I declare my interface so that it creates a new instance of the concrete class?

Right now I have something like:

    public interface Generator {
      public int[] values();
      public float[] indications();
      //etc
      public MyEnum type;
    }

    public class ConcreteClass implements Generator {
      private ConcreteClass() {
      }
      public static ConcreteClass createInstance() {

       }
   }

I have omitted arguments for clarity.

How would I move the createInstance to the interface?

Body:
An interface is not designed to have implementation. With Java 8 you could have default method but it would be a bad idea that interface knows the implementation classes. An interface should stay abstract and not know its subclasses.

If ConcreteClass is immutable, you should document it and ensure that each method with side-effect doesn't apply any modification on the current object but instead create a new instance of ConcreteClass.

For example suppose you want provide method to update the values field, you could provide this method in ConcreteClass :

public ConcreteClass withValues(int[] values){
   // copy all existing properties from the original to the copy but values
   ConcreteClass copy = new ConcreteClass(values, this.indications, this.type);
   return copy;
}

If you want really move out the instance creation from ConcreteClass, you could create a factory that provides this service.


问:
Post request from another domain results TokenMismatchException
I'm working with a bank api.

The bank send a post request to my website but does not return there is not a token field is their request and I am faced with TokenMismatchException.

How can I fix this problem?

Here is coresponding codes:

```<code>public function submitPayment()
{
    $api = 'test';
    $amount = '3443354';
    $redirect = URL::to('new-order/after-payment');
    $result = $this->send($api, $amount, $redirect);
    $result = json_decode($result);

    return redirect("https://example.com/$result->transId");
}
</code>```

答:
In short you want to rename the default _token as CSRF token field name of Laravel to something else for that,

You can Override function Illuminate\Foundation\Http\Middleware\VerifyCsrfToken@tokensMatch(); from App\Http\Middleware\VerifyCsrfToken Class and change the CSRF parameter name.

You can add following code in your App\Http\Middleware\VerifyCsrfToken file.

```<code>   /**
     * Determine if the session and input CSRF tokens match.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function tokensMatch($request)
    {
        $sessionToken = $request->session()->token();

        $token = $request->input('_csrf_token') ?: $request->header('X-CSRF-TOKEN');

        if (! $token && $header = $request->header('X-XSRF-TOKEN')) {
            $token = $this->encrypter->decrypt($header);
        }

        if (! is_string($sessionToken) || ! is_string($token)) {
            return false;
        }

        return hash_equals($sessionToken, $token);
    }
</code>```

In above function CSRF field is changed to _csrf_token from _token

Body:
I'm working with a bank api.

The bank send a post request to my website but does not return there is not a token field is their request and I am faced with TokenMismatchException.

How can I fix this problem?

Here is coresponding codes:

public function submitPayment()
{
    $api = 'test';
    $amount = '3443354';
    $redirect = URL::to('new-order/after-payment');
    $result = $this->send($api, $amount, $redirect);
    $result = json_decode($result);

    return redirect("https://example.com/$result->transId");
}

Body:
In short you want to rename the default _token as CSRF token field name of Laravel to something else for that,

You can Override function Illuminate\Foundation\Http\Middleware\VerifyCsrfToken@tokensMatch(); from App\Http\Middleware\VerifyCsrfToken Class and change the CSRF parameter name.

You can add following code in your App\Http\Middleware\VerifyCsrfToken file.

   /**
     * Determine if the session and input CSRF tokens match.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function tokensMatch($request)
    {
        $sessionToken = $request->session()->token();

        $token = $request->input('_csrf_token') ?: $request->header('X-CSRF-TOKEN');

        if (! $token && $header = $request->header('X-XSRF-TOKEN')) {
            $token = $this->encrypter->decrypt($header);
        }

        if (! is_string($sessionToken) || ! is_string($token)) {
            return false;
        }

        return hash_equals($sessionToken, $token);
    }

In above function CSRF field is changed to _csrf_token from _token


问:
Why I obtain this error trying to define a query with parameter in this old PHP application? (Fatal error: Cannot pass parameter 2 by reference in...)
I am pretty new in PHP and I have the following problem trying to define a simple query with parameter on an old PHP application. I have done in this way (mimic the other working query in this application that was made by someone else):

```<code>$result_facility_list = $db->prepare("select name from pm_facility where lang = :id_lang");
$result_hotel_file->bindParam(":id_lang", 2);
</code>```

Then

The problem is that when it try to perform the second line that bind the integer value 2 to the :id_lang parameter I obtain this error message:

```<code>( ! ) Fatal error: Cannot pass parameter 2 by reference in C:\xampp\htdocs\BeTrivius-Panda\templates\default\models\booking.php on line 534
Call Stack
#   Time    Memory  Function    Location
1   0.0326  165272  {main}( )   ..\index.php:0
2   8.2043  835656  include( 'C:\xampp\htdocs\BeTrivius-Panda\templates\default\models\booking.php' )   ..\index.php:146
</code>```

What could be the problem? What am I missing? How can I fix this issue?

答:
If you want to bind the int 2 to :id_lang without it being a variable you can use bindValue():

```<code>$result_hotel_file->bindValue(":id_lang", 2, PDO::PARAM_INT);
</code>```

if you want to use bindParam() (as the name somewhat implies) you will have to use a variable:

```<code>$yourIdVar = 2;
$result_hotel_file->bindParam(":id_lang", $yourIdVar, PDO::PARAM_INT);
</code>```

Body:
I am pretty new in PHP and I have the following problem trying to define a simple query with parameter on an old PHP application. I have done in this way (mimic the other working query in this application that was made by someone else):

$result_facility_list = $db->prepare("select name from pm_facility where lang = :id_lang");
$result_hotel_file->bindParam(":id_lang", 2);

Then

The problem is that when it try to perform the second line that bind the integer value 2 to the :id_lang parameter I obtain this error message:

( ! ) Fatal error: Cannot pass parameter 2 by reference in C:\xampp\htdocs\BeTrivius-Panda\templates\default\models\booking.php on line 534
Call Stack
#   Time    Memory  Function    Location
1   0.0326  165272  {main}( )   ..\index.php:0
2   8.2043  835656  include( 'C:\xampp\htdocs\BeTrivius-Panda\templates\default\models\booking.php' )   ..\index.php:146

What could be the problem? What am I missing? How can I fix this issue?

Body:
If you want to bind the int 2 to :id_lang without it being a variable you can use bindValue():

$result_hotel_file->bindValue(":id_lang", 2, PDO::PARAM_INT);

if you want to use bindParam() (as the name somewhat implies) you will have to use a variable:

$yourIdVar = 2;
$result_hotel_file->bindParam(":id_lang", $yourIdVar, PDO::PARAM_INT);


问:
Why to use throw in the definition of a method?
I am trying to implement a new exception for our code base and I came across this post in SO:

https://stackoverflow.com/a/8152888/654019

but I am not sure why the what method is defined as follow:

```<code>virtual const char* what() const throw (){
    return msg_.c_str();
}
</code>```

What is the meaning of throw in this context?

答:
This is dynamic exception specification, which is deprecated since C++11, and removed from C++17.

throw() is used to specify that the function won't throw any exceptions (directly or indirectly), from C++11 we should use noexcept or noexcept(true) instead.

Body:
I am trying to implement a new exception for our code base and I came across this post in SO:

https://stackoverflow.com/a/8152888/654019

but I am not sure why the what method is defined as follow:

virtual const char* what() const throw (){
    return msg_.c_str();
}

What is the meaning of throw in this context?


问:
how to encode 27 vector3's into a 0-256 value?
I have 27 combinations of 3 values from -1 to 1 of type:

```<code> Vector3(0,0,0);
 Vector3(-1,0,0);
 Vector3(0,-1,0);
 Vector3(0,0,-1);
 Vector3(-1,-1,0);
 ... up to
 Vector3(0,1,1);
 Vector3(1,1,1);
</code>```

I need to convert them to and from a 8-bit sbyte / byte array.

One solution is to say the first digit, of the 256 = X the second digit is Y and the third is Z...

so

```<code>  Vector3(-1,1,1) becomes 022,
  Vector3(1,-1,-1) becomes 200,
  Vector3(1,0,1) becomes 212...
</code>```

I'd prefer to encode it in a more compact way, perhaps using bytes (which I am clueless about), because the above solution uses a lot of multiplications and round functions to decode, do you have some suggestions please? the other option is to write 27 if conditions to write the Vector3 combination to an array, it seems inefficient.

Thanks to Evil Tak for the guidance, i changed the code a bit to add 0-1 values to the first bit, and to adapt it for unity3d:

```<code>function Pack4(x:int,y:int,z:int,w:int):sbyte {
var b: sbyte = 0;

b |= (x + 1) << 6;
b |= (y + 1) << 4;
b |= (z + 1) << 2;
b |= (w + 1);
return b;
}

function unPack4(b:sbyte):Vector4 {
var v : Vector4;
v.x = ((b & 0xC0) >> 6) - 1;      //0xC0 == 1100 0000
v.y = ((b & 0x30) >> 4) - 1;    // 0x30 == 0011 0000
v.z = ((b & 0xC) >> 2) - 1;     // 0xC  == 0000 1100
v.w = (b  & 0x3) - 1;            // 0x3  == 0000 0011
return v;
}
</code>```

答:
One way is to store the component of each vector in every 2 bits of a byte.

Converting a vector component value to and from the 2 bit stored form is as simple as adding and subtracting one, respectively.

```<code>-1 (1111 1111 as a signed byte) <-> 00 (in binary)
 0 (0000 0000 in binary)        <-> 01 (in binary)
 1 (0000 0001 in binary)        <-> 10 (in binary)
</code>```

The packed 2 bit values can be stored in a byte in any order of your preference. I will use the following format: 00XXYYZZ where XX is the converted (packed) value of the X component, and so on. The 0s at the start aren't going to be used.

A vector will then be packed in a byte as follows:

```<code>byte Pack(Vector3<int> vector) {
    byte b = 0;
    b |= (vector.x + 1) << 4;
    b |= (vector.y + 1) << 2;
    b |= (vector.z + 1);
    return b;
}
</code>```

Unpacking a vector from its byte form will be as follows:

```<code>Vector3<int> Unpack(byte b) {
    Vector3<int> v = new Vector<int>();
    v.x = ((b & 0x30) >> 4) - 1;    // 0x30 == 0011 0000
    v.y = ((b & 0xC) >> 2) - 1;     // 0xC == 0000 1100
    v.z = (b & 0x3) - 1;     // 0x3 == 0000 0011
    return v;
}
</code>```

Both the above methods assume that the input is valid, i.e. All components of vector in Pack are either -1, 0 or 1 and that all two-bit sections of b in Unpack have a (binary) value of either 00, 01 or 10.

Since this method uses bitwise operators, it is fast and efficient. If you wish to compress the data further, you could try using the 2 unused bits too, and convert every 3 two-bit elements processed to a vector.

Body:
I have 27 combinations of 3 values from -1 to 1 of type:

 Vector3(0,0,0);
 Vector3(-1,0,0);
 Vector3(0,-1,0);
 Vector3(0,0,-1);
 Vector3(-1,-1,0);
 ... up to
 Vector3(0,1,1);
 Vector3(1,1,1);

I need to convert them to and from a 8-bit sbyte / byte array.

One solution is to say the first digit, of the 256 = X the second digit is Y and the third is Z...

so

  Vector3(-1,1,1) becomes 022,
  Vector3(1,-1,-1) becomes 200,
  Vector3(1,0,1) becomes 212...

I'd prefer to encode it in a more compact way, perhaps using bytes (which I am clueless about), because the above solution uses a lot of multiplications and round functions to decode, do you have some suggestions please? the other option is to write 27 if conditions to write the Vector3 combination to an array, it seems inefficient.

Thanks to Evil Tak for the guidance, i changed the code a bit to add 0-1 values to the first bit, and to adapt it for unity3d:

function Pack4(x:int,y:int,z:int,w:int):sbyte {
var b: sbyte = 0;

b |= (x + 1) << 6;
b |= (y + 1) << 4;
b |= (z + 1) << 2;
b |= (w + 1);
return b;
}

function unPack4(b:sbyte):Vector4 {
var v : Vector4;
v.x = ((b & 0xC0) >> 6) - 1;      //0xC0 == 1100 0000
v.y = ((b & 0x30) >> 4) - 1;    // 0x30 == 0011 0000
v.z = ((b & 0xC) >> 2) - 1;     // 0xC  == 0000 1100
v.w = (b  & 0x3) - 1;            // 0x3  == 0000 0011
return v;
}

Body:
One way is to store the component of each vector in every 2 bits of a byte.

Converting a vector component value to and from the 2 bit stored form is as simple as adding and subtracting one, respectively.

-1 (1111 1111 as a signed byte) <-> 00 (in binary)
 0 (0000 0000 in binary)        <-> 01 (in binary)
 1 (0000 0001 in binary)        <-> 10 (in binary)

The packed 2 bit values can be stored in a byte in any order of your preference. I will use the following format: 00XXYYZZ where XX is the converted (packed) value of the X component, and so on. The 0s at the start aren't going to be used.

A vector will then be packed in a byte as follows:

byte Pack(Vector3<int> vector) {
    byte b = 0;
    b |= (vector.x + 1) << 4;
    b |= (vector.y + 1) << 2;
    b |= (vector.z + 1);
    return b;
}

Unpacking a vector from its byte form will be as follows:

Vector3<int> Unpack(byte b) {
    Vector3<int> v = new Vector<int>();
    v.x = ((b & 0x30) >> 4) - 1;    // 0x30 == 0011 0000
    v.y = ((b & 0xC) >> 2) - 1;     // 0xC == 0000 1100
    v.z = (b & 0x3) - 1;     // 0x3 == 0000 0011
    return v;
}

Both the above methods assume that the input is valid, i.e. All components of vector in Pack are either -1, 0 or 1 and that all two-bit sections of b in Unpack have a (binary) value of either 00, 01 or 10.

Since this method uses bitwise operators, it is fast and efficient. If you wish to compress the data further, you could try using the 2 unused bits too, and convert every 3 two-bit elements processed to a vector.


问:
how i can count the element who have the class "goo"
i want to check how much element have class "goo".

are i can check for specific element or all using jQuery. show me how i can do this task in jQuery

OwnerDisplayName: Steven Spielberg

Body: $(".goo").length


问:
Coursera assignment 3 'Ranking hospitals by outcome in a state'
I'm using WIn7 64x Rstudio Version 3.3.2

The following function is assignment 3 solution in coursera that I have created by looking at other people's solution.
I have 2 qeustions.

```<code>best <- function(state, outcome) {
  data<-read.csv('outcome-of-care-measures.csv',colClasses = 'character')
  frame<-as.data.frame(cbind(data[,2],
                       data[,7],
                       data[,11],
                       data[,17],
                       data[,23]),
                       stringsAsFactors=FALSE)
  colnames(frame)<-c('hospital','state','heart attack','heart failure',
                     'pneumonia')
  if(!state %in% frame[,'state']){
        stop('invalid state')
        }
  else if(!outcome %in% c('hostpital','state','heart attack','heart failure',
                          'pneumonia')){
        stop('invalid outcome')
  }
  else{
        wh<-which(frame[,'state']==state)
        cr<-frame[wh,]
        num<-as.numeric(cr[,outcome])
        minval<-min(num, na.rm=TRUE)
        result<-cr[,'hospital'][which(num==minval)]
        output<-result[order(result)]
  }
  return(output)
  }
</code>```

In this function, First, I don't know the use of "stringAsFactors=FALSE".

```<code> frame<-as.data.frame(cbind(data[,2],
                   data[,7],
                   data[,11],
                   data[,17],
                   data[,23]),
                   **stringsAsFactors=FALSE**)
</code>```

I've the read help document for 'stingAsFactors' via 'read.csv', I don't understand it.

When I remove this('stingAsFactors=FALSE' / functions's name is best2), the return is

best2('SC','heart attack')

```<code>[1] MUSC MEDICAL CENTER
4510 Levels: ABBEVILLE AREA MEDICAL CENTER ABBEVILLE GENERAL HOSPITAL ... ZUNI COMPREHENSIVE COMMUNITY HEALTH CENTER
</code>```

When I don't remove this, the return is

best('SC','heart attack')

```<code>[1] "MUSC MEDICAL CENTER"
Warning message: In best("SC", "heart attack") : NAs introduced by coercion
</code>```

Second question,

```<code>result<-cr[,'hospital'][which(num==minval)]
</code>```

Can the square bracket appear one after the other? In this case, Is the 'cr data' applied to the two square bracket?

I would be really grateful if you could tell about this problem.

答: Ok I'll try to be nice, but you shouldn't really be copying answers, especially if you don't understand it. But to answer your questions: First, stringsAsFactors as you can see sets how R treats strings in the .csv. When set to FALSE it treats them as characters and imports them that way. When set to TRUE (or not set at all), it treats them as factors. And that is why you see it displayed in levels. Second, the code is creating result, which is the hospital column of cr and only the data that fits the given condition of num=minval.

Body:
I'm using WIn7 64x Rstudio Version 3.3.2

The following function is assignment 3 solution in coursera that I have created by looking at other people's solution.
I have 2 qeustions.

best <- function(state, outcome) {
  data<-read.csv('outcome-of-care-measures.csv',colClasses = 'character')
  frame<-as.data.frame(cbind(data[,2],
                       data[,7],
                       data[,11],
                       data[,17],
                       data[,23]),
                       stringsAsFactors=FALSE)
  colnames(frame)<-c('hospital','state','heart attack','heart failure',
                     'pneumonia')
  if(!state %in% frame[,'state']){
        stop('invalid state')
        }
  else if(!outcome %in% c('hostpital','state','heart attack','heart failure',
                          'pneumonia')){
        stop('invalid outcome')
  }
  else{
        wh<-which(frame[,'state']==state)
        cr<-frame[wh,]
        num<-as.numeric(cr[,outcome])
        minval<-min(num, na.rm=TRUE)
        result<-cr[,'hospital'][which(num==minval)]
        output<-result[order(result)]
  }
  return(output)
  }

In this function, First, I don't know the use of "stringAsFactors=FALSE".

 frame<-as.data.frame(cbind(data[,2],
                   data[,7],
                   data[,11],
                   data[,17],
                   data[,23]),
                   **stringsAsFactors=FALSE**)

I've the read help document for 'stingAsFactors' via 'read.csv', I don't understand it.

When I remove this('stingAsFactors=FALSE' / functions's name is best2), the return is

best2('SC','heart attack')

[1] MUSC MEDICAL CENTER
4510 Levels: ABBEVILLE AREA MEDICAL CENTER ABBEVILLE GENERAL HOSPITAL ... ZUNI COMPREHENSIVE COMMUNITY HEALTH CENTER

When I don't remove this, the return is

best('SC','heart attack')

[1] "MUSC MEDICAL CENTER"
Warning message: In best("SC", "heart attack") : NAs introduced by coercion

Second question,

result<-cr[,'hospital'][which(num==minval)]

Can the square bracket appear one after the other? In this case, Is the 'cr data' applied to the two square bracket?

I would be really grateful if you could tell about this problem.


问:
Angular 2 cookie not set
I use the http like this:

```<code>private headers = new Headers({ 'Content-Type': 'application/json' })
login(loginUser: LoginUser): Promise<User> {
        return this.http.post('http://localhost:9009/api/users/login', JSON.stringify(loginUser), { headers: this.headers })
            .toPromise()
            .then(res => res.json())
            .catch(this.handleError)
    }
</code>```

This should set cookie to browser automatically, like this:

But there is no cookie set in browser.

Angular version: 2.4.10

Browser: Chrome 56.0.2924.87 (64-bit) | FireFox 52.0.2 (64-bit)

Language: TypeScript 2.2.1

Node (for AoT issues): node --version = 3.10.10

The response headers:

答:
I solved my problem referring to the following resources:

Understanding and using CORS

How to fix CORS problems

First, this is a problem about Cross-origin.I must set CORS Headers at my java server(in the filter),like this:

```<code>    httpServletResponse.addHeader("Access-Control-Allow-Origin", "http://localhost:4444");
    httpServletResponse.addHeader("Access-Control-Allow-Credentials", "true");
    httpServletResponse.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
    httpServletResponse.addHeader("Access-Control-Max-Age", "3600");
    httpServletResponse.addHeader("Access-Control-Allow-Headers", "Content-Type, Range");
    httpServletResponse.addHeader("Access-Control-Expose-Headers", "Accept-Ranges, Content-Encoding, Content-Length, Content-Range");
</code>```

Second, I set the withCredentials attribution when I make request,like this:

```<code>get(url: string, parmas: any): Observable<any> {
    return this.http.get(url, { search: parmas, headers: this.headers, withCredentials: true })
        .map((res: Response) => res.json())
        .do(data => console.log('server data:', data))  // debug
        .catch(this.handleError);
}
</code>```

Last, thanks @JJJ for helping me detecting of my spell errors.

Title: Angular 2 cookie not set

Body:
I use the http like this:

private headers = new Headers({ 'Content-Type': 'application/json' })
login(loginUser: LoginUser): Promise<User> {
        return this.http.post('http://localhost:9009/api/users/login', JSON.stringify(loginUser), { headers: this.headers })
            .toPromise()
            .then(res => res.json())
            .catch(this.handleError)
    }

This should set cookie to browser automatically, like this:

But there is no cookie set in browser.

Angular version: 2.4.10

Browser: Chrome 56.0.2924.87 (64-bit) | FireFox 52.0.2 (64-bit)

Language: TypeScript 2.2.1

Node (for AoT issues): node --version = 3.10.10

The response headers:

Body:
I solved my problem referring to the following resources:

Understanding and using CORS

How to fix CORS problems

First, this is a problem about Cross-origin.I must set CORS Headers at my java server(in the filter),like this:

    httpServletResponse.addHeader("Access-Control-Allow-Origin", "http://localhost:4444");
    httpServletResponse.addHeader("Access-Control-Allow-Credentials", "true");
    httpServletResponse.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
    httpServletResponse.addHeader("Access-Control-Max-Age", "3600");
    httpServletResponse.addHeader("Access-Control-Allow-Headers", "Content-Type, Range");
    httpServletResponse.addHeader("Access-Control-Expose-Headers", "Accept-Ranges, Content-Encoding, Content-Length, Content-Range");

Second, I set the withCredentials attribution when I make request,like this:

get(url: string, parmas: any): Observable<any> {
    return this.http.get(url, { search: parmas, headers: this.headers, withCredentials: true })
        .map((res: Response) => res.json())
        .do(data => console.log('server data:', data))  // debug
        .catch(this.handleError);
}

Last, thanks @JJJ for helping me detecting of my spell errors.


问:
Invalid configuration object in webpack
I am following Lynda.com - React.js essential training by Eve Porcello. In the video "Building with Webpack", I followed the steps author described exactly, but the "webpack" command failed giving the following error,

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.output.path: The provided value "dist/assets" is not an absolute path!

Following are my webpack.config.js and package.json files.

webpack.config.js

```<code>var webpack = require("webpack");

module.exports = {
  entry: "./src/index.js",
  output: {
    path: "dist/assets",
    filename: "bundle.js",
    publicPath: "assets"
  },
  devServer: {
    inline: true,
    contentBase: "./dist",
    port: 3000
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        loader: "babel-loader",
        query: {
          presets: ["latest", "stage-0", "react"]
        }
      }
    ]
  }
}
</code>```

package.json

```<code>{
  "name": "react-essential",
  "version": "1.0.0",
  "description": "A project focusing on React and related tools",
  "main": "index.js",
  "scripts": {
    "start": "httpster -d ./dist -p 3000"
  },
  "author": "Indu Pillai",
  "license": "MIT",
  "devDependencies": {
    "babel-cli": "^6.18.0",
    "babel-loader": "^6.4.1",
    "babel-preset-latest": "^6.16.0",
    "babel-preset-react": "^6.16.0",
    "babel-preset-stage-0": "^6.16.0",
    "webpack": "^2.3.2",
    "webpack-dev-server": "^2.4.2"
  }
}
</code>```

I repeated the steps again and again, but it's not working. I'm pretty new to this webpack thing, so I'm not able to find out what the problem really is, and what kind of absolute path it requires. I also tried an absolute path suggested by some answer to another (similar) question, but that didn't work.

Thank you!

答:
when you migrate into new version of webpack, this error will occur. For solving this your have to provide absolute path to your directory like this</p>

```<code>module.exports = {
    entry: __dirname + '/src/index.js',
    output: {
        path: __dirname + '/dist',
        filename: 'bundle.js'
    }
};
</code>```

Title: Invalid configuration object in webpack

Body:
I am following Lynda.com - React.js essential training by Eve Porcello. In the video "Building with Webpack", I followed the steps author described exactly, but the "webpack" command failed giving the following error,

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.output.path: The provided value "dist/assets" is not an absolute path!

Following are my webpack.config.js and package.json files.

webpack.config.js

var webpack = require("webpack");

module.exports = {
  entry: "./src/index.js",
  output: {
    path: "dist/assets",
    filename: "bundle.js",
    publicPath: "assets"
  },
  devServer: {
    inline: true,
    contentBase: "./dist",
    port: 3000
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        loader: "babel-loader",
        query: {
          presets: ["latest", "stage-0", "react"]
        }
      }
    ]
  }
}

package.json

{
  "name": "react-essential",
  "version": "1.0.0",
  "description": "A project focusing on React and related tools",
  "main": "index.js",
  "scripts": {
    "start": "httpster -d ./dist -p 3000"
  },
  "author": "Indu Pillai",
  "license": "MIT",
  "devDependencies": {
    "babel-cli": "^6.18.0",
    "babel-loader": "^6.4.1",
    "babel-preset-latest": "^6.16.0",
    "babel-preset-react": "^6.16.0",
    "babel-preset-stage-0": "^6.16.0",
    "webpack": "^2.3.2",
    "webpack-dev-server": "^2.4.2"
  }
}

I repeated the steps again and again, but it's not working. I'm pretty new to this webpack thing, so I'm not able to find out what the problem really is, and what kind of absolute path it requires. I also tried an absolute path suggested by some answer to another (similar) question, but that didn't work.

Thank you!

Body:
when you migrate into new version of webpack, this error will occur. For solving this your have to provide absolute path to your directory like this

module.exports = {
    entry: __dirname + '/src/index.js',
    output: {
        path: __dirname + '/dist',
        filename: 'bundle.js'
    }
};


问:
Using a custom template for actionbar menu item
I am trying to display a menu with text and icon always visible. I have defined my item layout as following

```<code><?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?attr/selectableItemBackground"
    android:clickable="true"
    android:drawableLeft="@drawable/ic_cart"
    android:gravity="center"
    android:orientation="vertical"
    android:text="(0)"
    android:drawablePadding="5dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:textColor="@android:color/white" />
</code>```

And the menu is defined as following

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.taptoscan.taptoscan.MainActivity">

    <item
        android:id="@+id/action_sign"
        android:title="(0)"
        app:showAsAction="always|withText"
        app:actionLayout="@layout/menu_sign" />

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
</menu>
</code>```

I'm having an issue with enabling the ripple effect on the background. It works but the ripple effect is not rounded, lik on a regular menu icon. It's square shaped and looks kinda ugly. What would be the best way to achieve the native ripple effect look on a custom menu item?

EDIT: This is what it looks like

答:
NOTE: Better solution found, check the edit

I figured it out. First I created a background drawable with rounded corners, like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?android:colorControlHighlight">
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">

        <padding
            android:bottom="5dp"
            android:left="5dp"
            android:right="5dp"
            android:top="5dp" />

        <corners android:radius="5dp" />

    </shape>
</ripple>
</code>```

After that, I set the TextView's background as the drawable from above. Ripple effect works as intended and it's all rounded like on default menu items.

EDIT

After further messing around with the custom menu item, I have found out that just by using a TextView without a root element will cause TextView's baseline to be changed after clicking on another menu item and then clicking back on the custom one. The solution is using the following layout

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:background="@drawable/btn_actionbar_icon">

    <TextView
        android:id="@+id/icon_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/ic_cart"
        android:drawablePadding="5dp"
        android:gravity="center_vertical"
        android:padding="10dp"
        android:text="(0)"
        android:textColor="@android:color/white"
        android:textSize="14sp" />

</RelativeLayout>
</code>```

Body:
I am trying to display a menu with text and icon always visible. I have defined my item layout as following

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?attr/selectableItemBackground"
    android:clickable="true"
    android:drawableLeft="@drawable/ic_cart"
    android:gravity="center"
    android:orientation="vertical"
    android:text="(0)"
    android:drawablePadding="5dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:textColor="@android:color/white" />

And the menu is defined as following

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.taptoscan.taptoscan.MainActivity">

    <item
        android:id="@+id/action_sign"
        android:title="(0)"
        app:showAsAction="always|withText"
        app:actionLayout="@layout/menu_sign" />

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
</menu>

I'm having an issue with enabling the ripple effect on the background. It works but the ripple effect is not rounded, lik on a regular menu icon. It's square shaped and looks kinda ugly. What would be the best way to achieve the native ripple effect look on a custom menu item?

EDIT: This is what it looks like

Body:
NOTE: Better solution found, check the edit

I figured it out. First I created a background drawable with rounded corners, like this:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?android:colorControlHighlight">
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">

        <padding
            android:bottom="5dp"
            android:left="5dp"
            android:right="5dp"
            android:top="5dp" />

        <corners android:radius="5dp" />

    </shape>
</ripple>

After that, I set the TextView's background as the drawable from above. Ripple effect works as intended and it's all rounded like on default menu items.

EDIT

After further messing around with the custom menu item, I have found out that just by using a TextView without a root element will cause TextView's baseline to be changed after clicking on another menu item and then clicking back on the custom one. The solution is using the following layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:background="@drawable/btn_actionbar_icon">

    <TextView
        android:id="@+id/icon_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/ic_cart"
        android:drawablePadding="5dp"
        android:gravity="center_vertical"
        android:padding="10dp"
        android:text="(0)"
        android:textColor="@android:color/white"
        android:textSize="14sp" />

</RelativeLayout>


问:
Unity3D update score error
I am following a tutorial by Charger Games on youtube it's about street racer android game and I am seeing this error on the Unity3D's console it says
 NullReferenceException: Object reference not set to an instance of an object UIManager.scoreUpdate ()

This is the code that has line that caused the error

```<code>public Text scoreText;
int score;

void Start () {
    score = 0;
    InvokeRepeating("scoreUpdate", 1.0f, 0.5f);
}
void Update () {
    scoreText.text = "Score: " + score; //this is the line. If I erase this the error will disappear
    }
void scoreUpdate () {
    if (gameOver == false) {
        score += 1;
        }
    }
</code>```

If I remove it, the error will disappear. It's not causing malfunctions or anything, I am just curious cos I am willing to learn. Please help me guys

答:
Difficult to say from this little code. You are trying to access (and set) a property "Text" of some object, but the field scoreText probably does not point to any such object. The same thing would happen if you had for example an array of ints such as int[] myArray = null; and then tried to read its property "Length" like so: myArray.Length which would also resultin null reference error. You need to first make the field reference the object.

In Unity, you probably forgot to drag the GameObject to the field "scoreText" of your script to establish the reference?

Title: Unity3D update score error

Body:
I am following a tutorial by Charger Games on youtube it's about street racer android game and I am seeing this error on the Unity3D's console it says
 NullReferenceException: Object reference not set to an instance of an object UIManager.scoreUpdate ()

This is the code that has line that caused the error

public Text scoreText;
int score;

void Start () {
    score = 0;
    InvokeRepeating("scoreUpdate", 1.0f, 0.5f);
}
void Update () {
    scoreText.text = "Score: " + score; //this is the line. If I erase this the error will disappear
    }
void scoreUpdate () {
    if (gameOver == false) {
        score += 1;
        }
    }

If I remove it, the error will disappear. It's not causing malfunctions or anything, I am just curious cos I am willing to learn. Please help me guys


问:
Developing a python Scraper that opens all links in multiple tabs using Chrome
I am trying to develop a scraper using python that will open links within a webpage in multiple tabs in Chrome.

The code I have managed to put together is

```<code>import urllib2
from datetime import timedelta, date
import selenium.webdriver as webdriver
import selenium.webdriver.support.ui as ui
import time

from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()

i = driver.get("https://investmentinsightindia.wordpress.com/")

driver.find_element_by_partial_link_text(',').click()
driver.get("chrome://newtab/")
</code>```

I have figured out that most individual posts on that site have a ',' (in the date) so I have tried to click on the link that has a , in it's text.

I do realise to make it work on multiple sites, I would eventually need to use something more generic to a link like an href reference from Xpath, I don't know how to do that.

How can I configure it -
1. Opens the homepage (url)
2. Opens the first available link in a new tab
3. Leaves the tab open
4. Opens the second available link in a new tab.....and so on

答:
You can find elements that are links by finding the 'a' elements and then looping over them and clicking one by one.

You can achieve that something like this :

```<code>for elem in driver.find_element_by_xpath('//a') :
    elem.click()
    driver.get("chrome://newtab/")
</code>```

This will open all the urls in the new tab one-by-one.

Body:
I am trying to develop a scraper using python that will open links within a webpage in multiple tabs in Chrome.

The code I have managed to put together is

import urllib2
from datetime import timedelta, date
import selenium.webdriver as webdriver
import selenium.webdriver.support.ui as ui
import time

from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()

i = driver.get("https://investmentinsightindia.wordpress.com/")

driver.find_element_by_partial_link_text(',').click()
driver.get("chrome://newtab/")

I have figured out that most individual posts on that site have a ',' (in the date) so I have tried to click on the link that has a , in it's text.

I do realise to make it work on multiple sites, I would eventually need to use something more generic to a link like an href reference from Xpath, I don't know how to do that.

How can I configure it -
1. Opens the homepage (url)
2. Opens the first available link in a new tab
3. Leaves the tab open
4. Opens the second available link in a new tab.....and so on

Body:
You can find elements that are links by finding the 'a' elements and then looping over them and clicking one by one.

You can achieve that something like this :

for elem in driver.find_element_by_xpath('//a') :
    elem.click()
    driver.get("chrome://newtab/")

This will open all the urls in the new tab one-by-one.


问:
While I am trying to updating a row to my table, I'm getting the following errors:
```<code>mysql> select * from GSLAB;
+--------+--------------+
| empid  | destignation |
+--------+--------------+
| GS101  | Manager      |
| GS102  | ABC          |
| GS-103 | SAS          |
| GS-104 | dsSAS        |
| GS105  | EWSAS        |
| GS106  | EWQAS        |
+--------+--------------+
6 rows in set (0.00 sec)

mysql> update GSLAB set empid= substr(empid,4,15)||substr(empid,1,2)||'-' where empid substr(empid,1,3)<>'-';
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'substr(empid,1,3)<>'-'' at line 1
mysql>
</code>```

答:
I use concat function instead of concat operator '||'

mysql> update GSLAB set empid= concat(substr(empid,1,2),'-',substr(empid,4,15)) where substr(empid,1,3)<>'-';


问:
How to return two values?
I'd like to return a Cartesian coordinate (x, y), as two ints. The only way I see is to create a class and return an instance of it.

How to return two values from a method in Objective C?

答:
I recommend you  to return an NSDictionary, inside Dictionary you can store and send any object type and any number of variables.</p>

```<code>-(NSDictionary*)calculateWith:(id)arg
{
NSDictionary *urDictionary =@{@"key1":value1,@"Key2":value2,.....};
return  urDictionary;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to return two values?

Body:
I recommend you  to return an NSDictionary, inside Dictionary you can store and send any object type and any number of variables.

-(NSDictionary*)calculateWith:(id)arg
{
NSDictionary *urDictionary =@{@"key1":value1,@"Key2":value2,.....};
return  urDictionary;
}


问:
Angular2 timeout in http post request
Is it possible to make a timeout of 3 seconds in a post request ? How ?

My code for the moment

```<code>this.http.post('myUrl',
    MyData, {headers: Myheaders})
        .map(res => res.json())
        .subscribe(
            data => this.ret = data,
            error => console.debug('ERROR', error),
            () => console.log('END')
        );
</code>```

答:
I modified the answer of Thierry to get it working with the latest release. It is necessary to remove the second parameter of the timeout function. According to a discussion regarding an angular-cli issue, the timeout function always throws a TimeoutError now.</p>

```<code>this.http.post('myUrl',
    MyData, {headers: Myheaders})
     .timeout(3000)
     .map(res => res.json())
     .subscribe(
       data => this.ret = data,
       error => console.debug('ERROR', error),
       () => console.log('END')
     );
</code>```

Title: Angular2 timeout in http post request

Body:
Is it possible to make a timeout of 3 seconds in a post request ? How ?

My code for the moment

this.http.post('myUrl',
    MyData, {headers: Myheaders})
        .map(res => res.json())
        .subscribe(
            data => this.ret = data,
            error => console.debug('ERROR', error),
            () => console.log('END')
        );

Body:
I modified the answer of Thierry to get it working with the latest release. It is necessary to remove the second parameter of the timeout function. According to a discussion regarding an angular-cli issue, the timeout function always throws a TimeoutError now.

this.http.post('myUrl',
    MyData, {headers: Myheaders})
     .timeout(3000)
     .map(res => res.json())
     .subscribe(
       data => this.ret = data,
       error => console.debug('ERROR', error),
       () => console.log('END')
     );


问:
What is the best practice to separate presentation logic from app logic in Angular 2?
Is it possible to completely separate the presentation logic (e.g. Toggling UI, Show / hide modal dialog etc.) from component level ? so the component will ONLY handle the data, thus the component won't have UI related functions like hideModal() or  showModal().

答:
You can just move every logic to a service and then bind the view to the service.</p>

```<code>@Injectable()
export ModalService {
  show:bool = false;
  hideModal() { this.show = false; }
  showModal() { this.show = true; }
}

@Component({
   template: '<div>{{modalService.show}}</div><button (click)="modalService.show ? modalService.hide() : modalService.show()">toggle</button>
   providers: [ModalService],
})
class ModalComponent {
  constructor(private:modalService:ModalService){}
}
</code>```

Body:
You can just move every logic to a service and then bind the view to the service.

@Injectable()
export ModalService {
  show:bool = false;
  hideModal() { this.show = false; }
  showModal() { this.show = true; }
}

@Component({
   template: '<div>{{modalService.show}}</div><button (click)="modalService.show ? modalService.hide() : modalService.show()">toggle</button>
   providers: [ModalService],
})
class ModalComponent {
  constructor(private:modalService:ModalService){}
}


问:
Jenkins: Display last console output on project page
When viewing a project in Jenkins, I'd like to see the last console output displayed on the project page.

This satisfies two needs:

I most often just want to see what the output of the build was; clicking through to the last console output seems needlessly cumbersome

Non-technical management can't remember how to / aren't sufficiently motivated to click through to the last console output in cases where the output is relevant to them if only they were to easily see it

I've looked for plugins that support this but can't find any.

What options do I have?

答:
I just created a plugin that displays console output of latest build at the project page.

https://github.com/jenkinsci/display-console-output-plugin

To use this plugin, you have to type mvn hpi:hpi to create a display-console-output.hpi file. Then upload this plugin from http://localhost:8080/pluginManager/advanced.


问:
html, css, javascript - show/hide divs - one is shown than another should be hidden
I want to create show/hide div's.
It is my code: jsfiddle.net/b60b34h1

But it don't works like I want.
I want that when "press button2" pressed than another div's should hidden.
It should show only one div.

Can You help me?
Thanks

答:
So you want to hide the div that is shown...

Then show the div which correspond to the passed id, right?

This can be written just like this:

  function unhide(divID) {
    document.getElementsByClassName('unhidden')[0].className = "hidden";
    document.getElementById(divID).className = "unhidden";
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden { display: none; }
.unhidden { display: block; } </code>```

press button1 press button2 press button3

button1

abc

abc

abc

button2

abc

abc

abc

button3

abc

abc

abc

 ```

Body:
So you want to hide the div that is shown...

Then show the div which correspond to the passed id, right?

This can be written just like this:

  function unhide(divID) {
    document.getElementsByClassName('unhidden')[0].className = "hidden";
    document.getElementById(divID).className = "unhidden";
  }

.hidden { display: none; }
.unhidden { display: block; }

<div>
  <p><a href="javascript:unhide('button1');">press button1</a> <a href="javascript:unhide('button2');">press button2</a> <a href="javascript:unhide('button3');">press button3</a></p>
  <div class="unhidden" id="button1">
    <h3>button1</h3>
    <ul>
      <li>abc</li>
      <li>abc</li>
      <li>abc</li>
    </ul>
  </div>
<div class="hidden" id="button2">
    <h3>button2</h3>
    <ul>
      <li>abc</li>
      <li>abc</li>
      <li>abc</li>
    </ul>
  </div>
<div class="hidden" id="button3">
    <h3>button3</h3>
    <ul>
      <li>abc</li>
      <li>abc</li>
      <li>abc</li>
    </ul>
  </div>
</div>


问:
Install PHP Curl on Windows and Using it on Laravel 5.4
I am using Laravel 5.4 on Windows 10. How to install PHP Curl on Windows and using it on Laravel?</p>

答:
Usually all you need is finding php.ini, find line with curl for example:

```<code>;extension=php_curl.dll
</code>```

remove ; from the beginning of the line so it should look like this:

```<code>extension=php_curl.dll
</code>```

Restart your webserver. Extension should be then available.

Be aware you might have multiple php.ini files (one for command line, one for web server), so make sure you are editing the correct file.

Body:
Usually all you need is finding php.ini, find line with curl for example:

;extension=php_curl.dll

remove ; from the beginning of the line so it should look like this:

extension=php_curl.dll

Restart your webserver. Extension should be then available.

Be aware you might have multiple php.ini files (one for command line, one for web server), so make sure you are editing the correct file.


问:
Couchbase N1QL sub-select combined with GROUP BY
I have the following flight offer data structure given:

```<code>{
  "offerIdentifier": "123",
  "flyFrom": "HAM",
  "flyTo": "LGW",
  "provider": "LH",
  "price": 207,
  "bookingUrl": "https://example.com/",
  "flightCombinationIdentifier": "HAM-LGW-201791570-20179171835"
}
</code>```

The flightCombinationIdentifier property's value can an will appear on multiple offers.

Now I would like to group by flightCombinationIdentifier and find the lowest price available for this combination which should ideally result in a structure like this:

```<code>{
  "offerIdentifier": "456",
  "flightCombinationIdentifier": "HAM-LGW-201791570-20179171835",
  "offer": [
    {
      "bookingUrl": "http://example.com/",
      "price": 97,
      "provider": "LH"
    }
  ]
}
</code>```

So I came up with the following N1QL query:

```<code>select b.flightCombinationIdentifier,
    (
        select b1.price, b1.provider, b1.bookingUrl from bucket b1
        use keys b.offerIdentifier
        where b1.flightCombinationIdentifier = b.flightCombinationIdentifier
        order by b1.price asc
        limit 1
    ) as offer

from bucket b
where b.flyFrom = 'HAM' and b.flyTo = 'LGW'
group by b.flightCombinationIdentifier
</code>```

Unfortunately it dies with the following error:

```<code>[
  {
    "code": 4210,
    "msg": "Expression must be a group key or aggregate: (select (`b1`.`price`), (`b1`.`provider`), (`b1`.`bookingUrl`) from `bucket` as `b1` use keys (`b`.`offerIdentifier`) where ((`b1`.`flightCombinationIdentifier`) = (`b`.`flightCombinationIdentifier`)))  order by (`b1`.`price`) limit 1) as `offer`",
    "query_from_user": "select b.flightCombinationIdentifier,\n    (\n        select b1.price, b1.provider, b1.bookingUrl from bucket b1\n        use keys b.offerIdentifier\n        where b1.flightCombinationIdentifier = b.flightCombinationIdentifier\n        order by b1.price asc\n        limit 1\n    ) as offer\n    \nfrom bucket w\nwhere b.flyFrom = 'HAM' and b.flyTo = 'LGW'\ngroup by b.flightCombinationIdentifier"
  }
]
</code>```

What would be the correct approach to get the subquery's result into the result object?

答:
```<code>SELECT flightCombinationIdentifier, MIN([price, {bookingUrl,price,provider}])[1] AS offer
FROM bucket WHERE flyFrom = 'HAM' AND flyTo = 'LGW'
GROUP BY flightCombinationIdentifier;
</code>```

Body:
I have the following flight offer data structure given:

{
  "offerIdentifier": "123",
  "flyFrom": "HAM",
  "flyTo": "LGW",
  "provider": "LH",
  "price": 207,
  "bookingUrl": "https://example.com/",
  "flightCombinationIdentifier": "HAM-LGW-201791570-20179171835"
}

The flightCombinationIdentifier property's value can an will appear on multiple offers.

Now I would like to group by flightCombinationIdentifier and find the lowest price available for this combination which should ideally result in a structure like this:

{
  "offerIdentifier": "456",
  "flightCombinationIdentifier": "HAM-LGW-201791570-20179171835",
  "offer": [
    {
      "bookingUrl": "http://example.com/",
      "price": 97,
      "provider": "LH"
    }
  ]
}

So I came up with the following N1QL query:

select b.flightCombinationIdentifier,
    (
        select b1.price, b1.provider, b1.bookingUrl from bucket b1
        use keys b.offerIdentifier
        where b1.flightCombinationIdentifier = b.flightCombinationIdentifier
        order by b1.price asc
        limit 1
    ) as offer

from bucket b
where b.flyFrom = 'HAM' and b.flyTo = 'LGW'
group by b.flightCombinationIdentifier

Unfortunately it dies with the following error:

[
  {
    "code": 4210,
    "msg": "Expression must be a group key or aggregate: (select (`b1`.`price`), (`b1`.`provider`), (`b1`.`bookingUrl`) from `bucket` as `b1` use keys (`b`.`offerIdentifier`) where ((`b1`.`flightCombinationIdentifier`) = (`b`.`flightCombinationIdentifier`)))  order by (`b1`.`price`) limit 1) as `offer`",
    "query_from_user": "select b.flightCombinationIdentifier,\n    (\n        select b1.price, b1.provider, b1.bookingUrl from bucket b1\n        use keys b.offerIdentifier\n        where b1.flightCombinationIdentifier = b.flightCombinationIdentifier\n        order by b1.price asc\n        limit 1\n    ) as offer\n    \nfrom bucket w\nwhere b.flyFrom = 'HAM' and b.flyTo = 'LGW'\ngroup by b.flightCombinationIdentifier"
  }
]

What would be the correct approach to get the subquery's result into the result object?


问:
Python Flask website from endless data loop?
I've built some websites using Flask before, including one which used websockets, but this time I'm not sure how to begin.

I currently have an endless loop in Python which gets sensor data from a ZeroMQ socket. It roughly looks like this:

```<code>import zeromq
socket = zeromq.create_socket()
while True:
    data_dict = socket.receive_json()
    print data_dict  # {'temperature': 34.6, 'speed': 12.8, etc.}
</code>```

I now want to create a dashboard showing the incoming sensor data in real time in some nice charts. Since it's in Python and I'm familiar with Flask and websockets I would like to use that.

The websites I built before were basic request/reply based ones though. How on earth would I create a Flask website from a continuous loop?

答:
Basically, what you need is some form of storage two processes can access at the same time.
If you don't want to leave the comfort of a single python executable, you should look into threading:
https://docs.python.org/2/library/thread.html

Otherwise, you could write two different python scripts (one for sensor readout, one for flask), let the one write into a file and the next one reading from it (or use a pipe in Linux, no idea what Windows offers), and run both processes at the same time and let your OS handle the "threading".

The second approach has the advantage of your OS taking care of performance, but you loose a lot of freedom in locking and reading the file. There may be some weird behavior if your server reads in the instant your sensor-script writes, but I did similar things without problems and I dimly recall that an OS should take care of consistent file-states whenever it's read or written to.

Body:
I've built some websites using Flask before, including one which used websockets, but this time I'm not sure how to begin.

I currently have an endless loop in Python which gets sensor data from a ZeroMQ socket. It roughly looks like this:

import zeromq
socket = zeromq.create_socket()
while True:
    data_dict = socket.receive_json()
    print data_dict  # {'temperature': 34.6, 'speed': 12.8, etc.}

I now want to create a dashboard showing the incoming sensor data in real time in some nice charts. Since it's in Python and I'm familiar with Flask and websockets I would like to use that.

The websites I built before were basic request/reply based ones though. How on earth would I create a Flask website from a continuous loop?


问:
Using UNIX_TIMESTAMP in a virtual (calculate) column in MariaDB / MySql
I am trying to create a table with a timestamp column and a virtual (calculated) column that holds a helper key for grouping the rows with timestamps of the same hour. For that I am using the following command in MariaDB / MySql:

```<code>CREATE TABLE mytable(t TIMESTAMP, u INT AS (UNIX_TIMESTAMP(t) DIV 3600);
</code>```

Which returns the following error:

```<code>ERROR 1901 (HY000): Function or expression is not allowed for column 'u'
</code>```

According to the documentation i don't see a reason this should not work. Any ideas?

答:
Replace this...

```<code>(UNIX_TIMESTAMP(t) DIV 3600)
</code>```

...with this...

```<code>(TIMESTAMPDIFF(HOUR,'1970-01-01 00:00:00',t))
</code>```

Verified on MariaDB 10.1.14, this should work in any later version.

Since 1970-01-01 00:00:00 is 0 in UNIX_TIMESTAMP(), and DIV 3600 is integer divide, your expression seems to be equivalent to FLOOR() of the number of hours since 1970-01-01 00:00:00... and TIMESTAMPDIFF() appears to provide the same value.

MariaDB seems to be taking UNIX_TIMESTAMP() to be non-deterministic, which is not correct when arguments are provided.  The MySQL core may lack the ability to consider built-in functions "sometimes deterministic," or this might be a bug.

But I believe you have a viable workaround using TIMESTAMPDIFF().

Note also, you appear to need the PERSISTENT keyword, because otherwise the virtual column can't be indexed, since the value isn't stored.

```<code>ERROR 1901: Key/Index cannot be defined on a non-stored computed column
</code>```

Body:
I am trying to create a table with a timestamp column and a virtual (calculated) column that holds a helper key for grouping the rows with timestamps of the same hour. For that I am using the following command in MariaDB / MySql:

CREATE TABLE mytable(t TIMESTAMP, u INT AS (UNIX_TIMESTAMP(t) DIV 3600);

Which returns the following error:

ERROR 1901 (HY000): Function or expression is not allowed for column 'u'

According to the documentation i don't see a reason this should not work. Any ideas?

Body:
Replace this...

(UNIX_TIMESTAMP(t) DIV 3600)

...with this...

(TIMESTAMPDIFF(HOUR,'1970-01-01 00:00:00',t))

Verified on MariaDB 10.1.14, this should work in any later version.

Since 1970-01-01 00:00:00 is 0 in UNIX_TIMESTAMP(), and DIV 3600 is integer divide, your expression seems to be equivalent to FLOOR() of the number of hours since 1970-01-01 00:00:00... and TIMESTAMPDIFF() appears to provide the same value.

MariaDB seems to be taking UNIX_TIMESTAMP() to be non-deterministic, which is not correct when arguments are provided.  The MySQL core may lack the ability to consider built-in functions "sometimes deterministic," or this might be a bug.

But I believe you have a viable workaround using TIMESTAMPDIFF().

Note also, you appear to need the PERSISTENT keyword, because otherwise the virtual column can't be indexed, since the value isn't stored.

ERROR 1901: Key/Index cannot be defined on a non-stored computed column


问:
Roslyn - Rewrite extension method invocation to full qualified format
How can I rewrite an invocation of an extension method to the full qualified format, that doesn't need a using anymore?

For example.

```<code>list.OrderBy(x => x.Prop)
</code>```

should become

```<code>System.Collections.Generic.Enumerable.OrderBy(list, x => x.Prop)
</code>```

答:
Answering my own question. I use this in a CSharpSyntaxRewriter object.
It would be nice if somebody also could have a look at this.

public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node)
{
    var methodInfo = _model.GetSymbolInfo(node).Symbol as IMethodSymbol;
    if (methodInfo != null)
    {
        var containingType = methodInfo.ContainingType;

        if (methodInfo.IsExtensionMethod)
        {
            // extension method
            var exp = node.Expression as MemberAccessExpressionSyntax;
            if (exp != null)
            {
                // new arguments
                var newArguments = SyntaxFactory.ArgumentList();
                newArguments = newArguments.AddArguments(SyntaxFactory.Argument(exp.Expression));
                newArguments = newArguments.AddArguments(node.ArgumentList.Arguments.ToArray());

                // new expression
                var stack = new Stack<SimpleNameSyntax>();
                stack.Push(exp.Name);
                stack.Push(SyntaxFactory.IdentifierName(containingType.Name));

                for (var s = containingType.ContainingNamespace; s != null; s = s.ContainingNamespace)
                {
                    if (!s.IsGlobalNamespace && s.Name != "")
                        stack.Push(SyntaxFactory.IdentifierName(s.Name));
                }

                // build and return
                if (stack.Count >= 2)
                {
                    var newExp = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, stack.Pop(), stack.Pop());

                    while (stack.Any())
                        newExp = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, newExp, stack.Pop());

                    return node.WithExpression(newExp).WithArgumentList(newArguments);
                }
            }
        }
    }

    return base.VisitInvocationExpression(node);
}
```

Body:
How can I rewrite an invocation of an extension method to the full qualified format, that doesn't need a using anymore?

For example.

list.OrderBy(x => x.Prop)

should become

System.Collections.Generic.Enumerable.OrderBy(list, x => x.Prop)


问:
CSS Transition for Website Issue

.learn-more {
        color: #fff;
        font-size: 20px;
        text-align: center;
        vertical-align: middle;
        text-transform: none;
        max-width: 155px;
        margin: auto;
        background-color: #363636;
        padding: 8px 25px;
        text-decoration: none;
    }

    .learn-more:hover {
        color: #21C8FF;
        transition: .3s ease-in-out;
        -webkit-transition: .3s ease-in-out;
        background-color: #fff;
        text-decoration: none;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Learn More</code>```

So I was working on my Website and I added a CSS transition so when you hover over something it fades into a color red. Very simple. I was just using...

transition: .3s ease-in-out;

-webkit-transition: .3s ease-in-out;

But when I unhover it just cuts out. I want to add a transition so it fades back to its original color. Anyone know how to do that?

Thanks!

TrifleTower

答:
You specified the transition only for the hover state. if you want the transition to persist to multiple states just add it to the .learn-more class. Like this:

.learn-more {
        color: #fff;
        font-size: 20px;
        text-align: center;
        vertical-align: middle;
        text-transform: none;
        max-width: 155px;
        margin: auto;
        background-color: #363636;
        padding: 8px 25px;
        text-decoration: none;
        /* Moved */
        transition: .3s ease-in-out;
        -webkit-transition: .3s ease-in-out;
    }

    .learn-more:hover {
        color: #21C8FF;
        background-color: #fff;
        text-decoration: none;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Learn More</code>```

Title: CSS Transition for Website Issue

Body:
.learn-more {
        color: #fff;
        font-size: 20px;
        text-align: center;
        vertical-align: middle;
        text-transform: none;
        max-width: 155px;
        margin: auto;
        background-color: #363636;
        padding: 8px 25px;
        text-decoration: none;
    }

    .learn-more:hover {
        color: #21C8FF;
        transition: .3s ease-in-out;
        -webkit-transition: .3s ease-in-out;
        background-color: #fff;
        text-decoration: none;
    }

Learn More

So I was working on my Website and I added a CSS transition so when you hover over something it fades into a color red. Very simple. I was just using...

transition: .3s ease-in-out;

-webkit-transition: .3s ease-in-out;

But when I unhover it just cuts out. I want to add a transition so it fades back to its original color. Anyone know how to do that?

Thanks!

TrifleTower

Body:
You specified the transition only for the hover state. if you want the transition to persist to multiple states just add it to the .learn-more class. Like this:

.learn-more {
        color: #fff;
        font-size: 20px;
        text-align: center;
        vertical-align: middle;
        text-transform: none;
        max-width: 155px;
        margin: auto;
        background-color: #363636;
        padding: 8px 25px;
        text-decoration: none;
        /* Moved */
        transition: .3s ease-in-out;
        -webkit-transition: .3s ease-in-out;
    }

    .learn-more:hover {
        color: #21C8FF;
        background-color: #fff;
        text-decoration: none;
    }

<a class="learn-more" href="about.html">Learn More</a>


问:
Using pre rendered html as variable in html file with vueJS
I currently have an issue regarding vueJS.

I have a server side application which renders my html and sends it back in a string.

I want to insert this html into my page to display it.

I have it set up like this currently:

Template:

```<code><div class="section" v-model="html">
   {{ html.body }}
</div>
</code>```

This outputs the html as a string opposed to rendering it to the page.

Any idea on how to solve this ?

Thanks.

答:
You can use the official v-html directive:

```<code><div v-html="rawHtml"></div>
</code>```

See the documentation for more information.

Body:
I currently have an issue regarding vueJS.

I have a server side application which renders my html and sends it back in a string.

I want to insert this html into my page to display it.

I have it set up like this currently:

Template:

   {{ html.body }}

This outputs the html as a string opposed to rendering it to the page.

Any idea on how to solve this ?

Thanks.

Body:
You can use the official v-html directive:

<div v-html="rawHtml"></div>

See the documentation for more information.


问:
Loading data from file using fstream
In the file sequences.txt there are 100 sequences described with two rows. The first one says about the amount of numbers in this sequence while the second one contains of numbers in this sequence(data is sepearated with one space). For example the first four lines are:

5

1 3 6 7 9

5

17 22 27 32 37

Could you tell me how I can load those data using fstream library so that I would be able to do some mathematical operations like calculating the difference in each sequence or their sums? I suppose I have to use two arrays, one for the amount of numbers in each sequnce and the other one for numbers in each sequence. Thanks.

答:
I have code a general solution which will take your file in 2D jagged array. You have now all data in your final Array you can do any task what you want.

File

```<code>5
1 3 6 7 9
5
17 22 27 32 37
6
1 2 3 4 5 6
3
13 45 67
</code>```

Code to get data in 2D Array.

```<code>#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
    string str;
    ifstream in("File.txt");
    int count = 4; //Your number of test cases here as you said 100 or 200
    int *sizes = new int[count]; // all szies for your 1D arrays
    int **Array = new int*[count]; //Main 2D array
    for (int i = 0; i < count; i++)
    {
        in>>sizes[i]; //taking size for 1 row
        Array[i] = new int[sizes[i]]; //Making arrays
        for (int j = 0; j < sizes[i]; j++)
        {
            in >> Array[i][j]; //getting values of row
        }
    }
    for (int i = 0; i < count; i++)
    {
        for (int j = 0; j < sizes[i]; j++)
        {
            cout << Array[i][j] << " "; //Printing Final Array [i,j]
        }
        cout << endl;
    }
    //Now you have your final array in Array which is 2D Jagged Array You Can Do What Ever You Want.
    for (int i = 0; i < count; i++) //memory release
        delete[] Array[i];
    delete[] Array;
    delete[] sizes;
    system("pause");
    return 0;
}
</code>```

Title: Loading data from file using fstream

Body:
I have code a general solution which will take your file in 2D jagged array. You have now all data in your final Array you can do any task what you want.

File

5
1 3 6 7 9
5
17 22 27 32 37
6
1 2 3 4 5 6
3
13 45 67

Code to get data in 2D Array.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
    string str;
    ifstream in("File.txt");
    int count = 4; //Your number of test cases here as you said 100 or 200
    int *sizes = new int[count]; // all szies for your 1D arrays
    int **Array = new int*[count]; //Main 2D array
    for (int i = 0; i < count; i++)
    {
        in>>sizes[i]; //taking size for 1 row
        Array[i] = new int[sizes[i]]; //Making arrays
        for (int j = 0; j < sizes[i]; j++)
        {
            in >> Array[i][j]; //getting values of row
        }
    }
    for (int i = 0; i < count; i++)
    {
        for (int j = 0; j < sizes[i]; j++)
        {
            cout << Array[i][j] << " "; //Printing Final Array [i,j]
        }
        cout << endl;
    }
    //Now you have your final array in Array which is 2D Jagged Array You Can Do What Ever You Want.
    for (int i = 0; i < count; i++) //memory release
        delete[] Array[i];
    delete[] Array;
    delete[] sizes;
    system("pause");
    return 0;
}


问:
Error: can't find symbol GoogleMaps ionic2
I want to use the google maps on ionic2. I have added the cordova-google-maps plugin to my project and in my project i did the following

```<code>import { GoogleMaps } from 'ionic-native'

export class ListPage {
  service = new google.maps.places.AutocompleteService();
  constructor (private googleMaps: GoogleMaps) {}
}
</code>```

I however get two errors.

I get an error that there is no name google and also that there is no symbol GoogleMaps which makes me think why there wont be one in ionic-native. It seems there is only one available if it is @ionic-native/google-maps but i find that weird or is it how it has been set up for ionic2?

Also am i only allowed to do this
service = new google.maps.places.AutocompleteService();
when i add the google maps script  on index.html?
I thought since i have added the google maps plugin from cordova, that i dont need to add the script anymore on index.html or i still have to do both?

Any explanation and help is appreciated.

Thanks

答:
After adding the cordova-google-maps plugin to your app, you need to install the ionic-native wrapper using the below command.

```<code>npm install @ionic-native/google-maps
</code>```

Then import GoogleMaps in your app.module.ts and add it as a provider as well.

Detailed and simple instructions are given here - http://tphangout.com/ionic-2-google-maps/

Hope this helps you. Thanks.

Body:
I want to use the google maps on ionic2. I have added the cordova-google-maps plugin to my project and in my project i did the following

import { GoogleMaps } from 'ionic-native'

export class ListPage {
  service = new google.maps.places.AutocompleteService();
  constructor (private googleMaps: GoogleMaps) {}
}

I however get two errors.

I get an error that there is no name google and also that there is no symbol GoogleMaps which makes me think why there wont be one in ionic-native. It seems there is only one available if it is @ionic-native/google-maps but i find that weird or is it how it has been set up for ionic2?

Also am i only allowed to do this
service = new google.maps.places.AutocompleteService();
when i add the google maps script  on index.html?
I thought since i have added the google maps plugin from cordova, that i dont need to add the script anymore on index.html or i still have to do both?

Any explanation and help is appreciated.

Thanks

Body:
After adding the cordova-google-maps plugin to your app, you need to install the ionic-native wrapper using the below command.

npm install @ionic-native/google-maps

Then import GoogleMaps in your app.module.ts and add it as a provider as well.

Detailed and simple instructions are given here - http://tphangout.com/ionic-2-google-maps/

Hope this helps you. Thanks.


问:
How do I pop the view controller underneath a pushed view controller?
I want to push a view controller onto the stack, then pop the first one that pushed the new one.

```<code>-(void) someMethod {
    MegaSuperAwesomeViewController *tempVC = [[MegaSuperAwesomeViewController alloc] init];
    [self.navigationController pushViewController:tempVC animated:YES];
    [tempVC release];

    // pop this VC, how?
}
</code>```

EDIT: turns out I can pop back 2 view controllers instead once finished with the new VC.  Still not what I wanted exactly, but it works.  The downside is I need to set a flag to indicate that the covered view is completed.

答:
```<code>-(void)popToSelf{

    NSArray *array = [self.navigationController viewControllers];

    for (int i = 0 ; i < array.count ; i++) {
        UIViewController *currentVC = [array objectAtIndex:i];
        if ([currentVC isKindOfClass:[YourViewControllerClass class]]) {
            [self.navigationController popToViewController:[array objectAtIndex:i] animated:YES];
        }
    }
}
</code>```

Body:
I want to push a view controller onto the stack, then pop the first one that pushed the new one.

-(void) someMethod {
    MegaSuperAwesomeViewController *tempVC = [[MegaSuperAwesomeViewController alloc] init];
    [self.navigationController pushViewController:tempVC animated:YES];
    [tempVC release];

    // pop this VC, how?
}

EDIT: turns out I can pop back 2 view controllers instead once finished with the new VC.  Still not what I wanted exactly, but it works.  The downside is I need to set a flag to indicate that the covered view is completed.


问:
Equivalent of shell 'cd' command to change the working directory?
cd is the shell command to change the working directory.

How do I change the current working directory in Python?

答: os.chdir() is the Pythonic version of cd.

OwnerDisplayName: Peter

OwnerDisplayName: PEZ


问:
contact form 7 functions without wordpress
I have a website which is built using bootstrap framework.

I want to implement contact form 7 feature without wordpress. Like this with radio buttons.
I tried using php mail function with bootstrap and it's not working like sending email with data.

Like this Bootstrap with php
Following are the code

"HTML Start here"

```<code><div class="center"><br>
  <button type="button" class="preview btn btn-info btn-lg" data-toggle="modal" data-target="#requestInfo">Free Consultation!</button>
</div>
<!-- The Modal -->
<div id="requestInfo" class="modal">
  <!-- Modal content -->
  <div class="modal-content">
    <div role="form">
      <form method="post" action="modal_form.php" novalidate="novalidate">
        <div class="modal-header">
          <div class="center">
            <button type="button" class="close" data-dismiss="modal">×</button>
            <h4 class="modal-title">Free Consultation!</h4>
          </div>
        </div>

        <div class="modal-body"><br>

          <div class="form-group">
            <input type="text" name="name" id="name" value="" size="40" aria-invalid="false" placeholder="Name with Designation*" required/>
          </div>
          <div class="form-group">
            <input type="text" name="companyname" id="companyname" value="" size="40" aria-invalid="false" placeholder="Company's Name" />
          </div>
          <div class="form-group">
            <input type="email" name="email" id="email" value="" size="40" aria-invalid="false" placeholder="Email*" required />
          </div>
          <div class="form-group">
            <input type="tel" name="mobile" id="mobile" value="" size="40" aria-invalid="false" placeholder="Mobile" />
          </div>
          <div class="form-group">
            <input type="tel" name="state" id="state" value="" size="40" aria-invalid="false" placeholder="Any prefered State in India." />
          </div>

          <p class="lead">Help us to know more about your requirements</p>
          <h4>1. Purpose of Company*</h4>
          <div class="left-align">
            <div class="radio ">
              <label><input type="radio" name="PurposeOfCompany" id="manufacturing" value="Manufacturing Setup">Manufacturing Setup</label>
            </div>
            <div class="radio">
              <label><input type="radio" name="PurposeOfCompany" id="sectors" value="Sectors">Sectors</label>
            </div>
            <div class="radio">
              <label><input type="radio" name="PurposeOfCompany" id="investment" value="Investment">Investment/Finance</label>
            </div>
            <div class="radio">
              <label><input type="radio" name="PurposeOfCompany" id="trading" value="Trading">Trading</label>
            </div>
            <div class="radio">
              <label><input type="radio" name="PurposeOfCompany" id="jv" value="JV">Joint Venture / Mergers and Acquisitions</label>
            </div>
            <div class="radio">
              <label><input type="radio" name="PurposeOfCompany" id="other" value="Other">Others</label>
            </div>
            <div class="form-group" id="other_purpose" style="display: none;">
              <input type="text" name="PurposeOfCompany_Other" id="specify" value="" size="40" aria-invalid="false" placeholder="Specify" />
            </div>

            <div class="form-group">
              <textarea class="form-control" rows="4" id="details" placeholder="Details:"></textarea>
            </div>
            <p>* Mandatory Fields</p>
          </div>
          <div class="modal-footer">
            <div class="center">
              <input class="btn btn-info btn-md" type="submit" value="Submit" />
              <button type="button close" class="btn btn-info btn-sm" data-dismiss="modal">Close</button>
            </div>
          </div>
        </div>
      </form>

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

"HTML Ends here"

"CSS Start here"

```<code><style>
    /* The Modal (background) */
    .modal {
        display: none; /* Hidden by default */
        position: fixed; /* Stay in place */
        padding-top: 100px; /* Location of the box */
        left: 0;
        top: 0;
        width: 100%; /* Full width */
        height: 100%; /* Full height */
        overflow: auto; /* Enable scroll if needed */
        background-color: rgb(0,0,0); /* Fallback color */
        background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
    }

    /* Modal Content */
    .modal-content {
        position: relative;
        background-color: #fefefe;
        margin: auto;
        padding: 10px;
        border: 1px solid #888;
        width: 70%;
        box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
        -webkit-animation-name: animatetop;
        -webkit-animation-duration: 0.4s;
        animation-name: animatetop;
        animation-duration: 0.4s
    }

    /* Add Animation */
    @-webkit-keyframes animatetop {
        from {top:-300px; opacity:0}
        to {top:0; opacity:1}
    }

    @keyframes animatetop {
        from {top:-300px; opacity:0}
        to {top:0; opacity:1}
    }

    /* The Close Button */
    .close {
        float: center;
        font-size: 28px;
        font-weight: bold;
    }

    .close:hover,
    .close:focus {
        color: #000;
        text-decoration: none;
        cursor: pointer;
    }

    .modal-header {
        padding: 0px 5px 5px 0px;
        font-size: 25px;
        font-weight: bold;

    }

    .modal-footer {
        padding: 5px 0px 0px 0px;
        font-size: 25px;
        font-weight: bold;

    }

    .modal-body {padding: 20px 20px;}

    }
</style>
</code>```

"CSS Ends Here"

"JS Start Here"

```<code><script>
    $(document).ready(function(){
        $('input[name=PurposeOfCompany]').change(function(){
            if($(this).val() === 'Other') {
                $('#other_purpose').show();
            } else {
                $('#other_purpose').hide();
            }
        });
    })
</script>
</code>```

"JS Ends Here"

"Php Start Here"

```<code><?php
  $name    = $_POST['name'];
  $cname    = $_POST['cname'];
  $email   = stripslashes($_POST['email']);
  $phone   = stripslashes($_POST['phone']);
  $purpose = $_POST['purpose'];
  $message = $_POST['message'];
  $form_message = "Name: $name \nCompany's Name: $cname \nEmail: $email \nPhone: $phone \nPurpose of Contact: $purpose \nMessage: $message";

  header( "Location: http://www.example.com");

  mail("freeconsultancy@example.com", "Free Consultancy Message!", $form_message, "From: $email" );

?>
</code>```

"Php Ends Here"

When I click submit button php function not sending data.

答: Do not use PHP mail function. Use PHPMailer.</p>

Body:
I have a website which is built using bootstrap framework.

I want to implement contact form 7 feature without wordpress. Like this with radio buttons.
I tried using php mail function with bootstrap and it's not working like sending email with data.

Like this Bootstrap with php
Following are the code

"HTML Start here"

  <button type="button" class="preview btn btn-info btn-lg" data-toggle="modal" data-target="#requestInfo">Free Consultation!</button>

      <form method="post" action="modal_form.php" novalidate="novalidate">

            <button type="button" class="close" data-dismiss="modal">×</button>

Free Consultation!

            <input type="text" name="name" id="name" value="" size="40" aria-invalid="false" placeholder="Name with Designation*" required/>

            <input type="text" name="companyname" id="companyname" value="" size="40" aria-invalid="false" placeholder="Company's Name" />

            <input type="email" name="email" id="email" value="" size="40" aria-invalid="false" placeholder="Email*" required />

            <input type="tel" name="mobile" id="mobile" value="" size="40" aria-invalid="false" placeholder="Mobile" />

            <input type="tel" name="state" id="state" value="" size="40" aria-invalid="false" placeholder="Any prefered State in India." />

Help us to know more about your requirements

1. Purpose of Company*

              <input type="radio" name="PurposeOfCompany" id="manufacturing" value="Manufacturing Setup">Manufacturing Setup

              <input type="radio" name="PurposeOfCompany" id="sectors" value="Sectors">Sectors

              <input type="radio" name="PurposeOfCompany" id="investment" value="Investment">Investment/Finance

              <input type="radio" name="PurposeOfCompany" id="trading" value="Trading">Trading

              <input type="radio" name="PurposeOfCompany" id="jv" value="JV">Joint Venture / Mergers and Acquisitions

              <input type="radio" name="PurposeOfCompany" id="other" value="Other">Others

              <input type="text" name="PurposeOfCompany_Other" id="specify" value="" size="40" aria-invalid="false" placeholder="Specify" />

              <textarea class="form-control" rows="4" id="details" placeholder="Details:"></textarea>

* Mandatory Fields

              <input class="btn btn-info btn-md" type="submit" value="Submit" />
              <button type="button close" class="btn btn-info btn-sm" data-dismiss="modal">Close</button>

      </form>

"HTML Ends here"

"CSS Start here"

"CSS Ends Here"

"JS Start Here"

"JS Ends Here"

"Php Start Here"

<?php
  $name    = $_POST['name'];
  $cname    = $_POST['cname'];
  $email   = stripslashes($_POST['email']);
  $phone   = stripslashes($_POST['phone']);
  $purpose = $_POST['purpose'];
  $message = $_POST['message'];
  $form_message = "Name: $name \nCompany's Name: $cname \nEmail: $email \nPhone: $phone \nPurpose of Contact: $purpose \nMessage: $message";

  header( "Location: http://www.example.com");

  mail("freeconsultancy@example.com", "Free Consultancy Message!", $form_message, "From: $email" );

?>

"Php Ends Here"

When I click submit button php function not sending data.


答:
It's because you are using the transition codes in the :hover state. Use it in the original class instead.

.learn-more {
  color: #fff;
  font-size: 20px;
  text-align: center;
  vertical-align: middle;
  text-transform: none;
  max-width: 155px;
  margin: auto;
  background-color: #363636;
  padding: 8px 25px;
  text-decoration: none;
  transition: .3s ease-in-out;  // here
  -webkit-transition: .3s ease-in-out;  // here
}

.learn-more:hover {
  color: #21C8FF;
  background-color: #fff;
  text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Learn More</code>```

Title: CSS Transition for Website Issue

Body:
It's because you are using the transition codes in the :hover state. Use it in the original class instead.

.learn-more {
  color: #fff;
  font-size: 20px;
  text-align: center;
  vertical-align: middle;
  text-transform: none;
  max-width: 155px;
  margin: auto;
  background-color: #363636;
  padding: 8px 25px;
  text-decoration: none;
  transition: .3s ease-in-out;  // here
  -webkit-transition: .3s ease-in-out;  // here
}

.learn-more:hover {
  color: #21C8FF;
  background-color: #fff;
  text-decoration: none;
}

<a class="learn-more" href="about.html">Learn More</a>


问:
.NET PDF Viewing component to allow searching/highlighting multiple words
I'm looking for a component which allows to highlight specific words inside PDF document. It will be used for searching.

Some components highlight when you perform a search, but they highlight only the text currently being searched. I need more advanced functionality for showing multiple search words.

Eventually, it will look like searching for multiple words simultaneously.

Possible solution would be conversion to plain text and highlighting in RichTextBox, but I need to retain actual document formatting.

Any suggestions?

Thanks!

答:
webSupergoo has a component called ABCpdf.NET that will let you read and modify PDF files, and the professional version will also render/view them directly in your application. It may be possible to use that to add highlighting to the words you're searching for and then display the result.

Note: I've used this component to generate PDFs, but never to modify them or display them, so I can't speak directly to how well this would work.