问:
PHPMailer 6 Composer Not Working
How do I setup PHPMailer properly to get it to work on the server.

I have set it up like in the example provided.

One I upload a file the upload.php file is ran but all I get back is a 500 Internal Server Error.

=============== EDIT ===============

Problem seems to be PHP version 5.3.3

This setup works on PHP version ^7

.

server setup

```<code>/ root
- uploads.php
- form.html
- vendor (dir)
  - composer (dir)
  - phpmailer (dir)
  - autoload.php
</code>```

.

form.html

```<code><!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <form action="upload.php" method="POST" enctype="multipart/form-data">
      <input type="file" name="file">
      <button type="submit" name="submit">Upload</button>
    </form>
  </body>
</html>
</code>```

.

upload.php

```<code><?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require './vendor/autoload.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

  $mail = new PHPMailer; // <-- error on this line
  echo "after phpmailer"; // <-- does not run

  // phpmailer code here ...

}
</code>```

答: PHPMailer 6.0 and up requires PHP 5.5 as a minimum. You should be using at least PHP 7.0 anyway - but even that reaches end of life in December 2017.</p>

Title: PHPMailer 6 Composer Not Working

Body:
How do I setup PHPMailer properly to get it to work on the server.

I have set it up like in the example provided.

One I upload a file the upload.php file is ran but all I get back is a 500 Internal Server Error.

=============== EDIT ===============

Problem seems to be PHP version 5.3.3

This setup works on PHP version ^7

.

server setup

/ root
- uploads.php
- form.html
- vendor (dir)
  - composer (dir)
  - phpmailer (dir)
  - autoload.php

.

form.html

<!DOCTYPE html>

    <form action="upload.php" method="POST" enctype="multipart/form-data">
      <input type="file" name="file">
      <button type="submit" name="submit">Upload</button>
    </form>

.

upload.php

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require './vendor/autoload.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

  $mail = new PHPMailer; // <-- error on this line
  echo "after phpmailer"; // <-- does not run

  // phpmailer code here ...

}


来源: stackexchange

问:
Can i set different color for different category
Can i set color for button header and other element form page to another color with different  category?

exam.

in my homepage my page color is red ,
when i change category to shirt color is change to blue,
and change to shoe color is change to pink.

how can i do for set this in admin panel?

答:
You can manage color of category from Admin > Manage categories -> Custom Layout -> Custom Layout Update and paste below given code:

```<code><reference name="head">
    <action method="addCss">
        <stylesheet>css/custom_category_1.css</stylesheet>
        <params>media="all"</params>
    </action>
</reference>
</code>```

Define the custom background in the css. Override the default styling by adding !important

ContentLicense: CC BY-SA 3.0

Body:
You can manage color of category from Admin > Manage categories -> Custom Layout -> Custom Layout Update and paste below given code:

<reference name="head">
    <action method="addCss">
        <stylesheet>css/custom_category_1.css</stylesheet>
        <params>media="all"</params>
    </action>
</reference>

Define the custom background in the css. Override the default styling by adding !important


问:
Convert recursive function into a for loop and while loop
I need to convert

```<code>def aRecursive(n):
    if n is 1:
        return 3
    else:
        return 2 * aRecursive(n-1) + 5
</code>```

into a for loop and a while loop. I can't seem to wrap my mind around the process. The original function for these loops are:

```<code>a(1) = 3
a(n) = 2 * a(n-1) + 5
</code>```

An answer and explanation would help out immensely.

答:
I am going to offer a solution based on how functions are called. This solution is generic, in that you can use the same approach to convert any recursive function to an iterative one. It is theoretically possible but it seems no one talks about how. Since your function is easy, it is not hard to come up with a iterative one. But how about non-recursive post-order traversal of a binary tree? You can only do it on a case by case basis if you don't have a generic approach that I am going to present.

Here we go. First we need to write down your recursive version with a slight change to facilitate the conversion:

```<code>def f(N):
    n = N        # N is the top level parameter passed to this function
    res = None   # res is the result returned by this function
[start]:         # here we create a label; not python, only for converting
    if n == 1:
        return 3
    else:
        return 2 * f(n-1) + 5
</code>```

Next we are going to convert two things: the function call and the return statements. The function call is basically 2 steps: push parameters and return address to stack and jump to the actual code. The return is basically pop parameters and jump to the saved address. So here we go:

```<code>def f(N):
    n = N        # N is the top level parameter passed to this function
    res = None   # res is the result returned by this function
[start]:         # here we create a label; not python, only for converting
    if n == 1:
        return 3
    else:
        push(n)       # push current parameter; since there is only one recursive function call in the body, we know where to return and there is no need to push the return address
        n = n-1       # the next level actual parameter is now n-1
        goto [start]  # we go to the code of the function which is the start of this same function
        return 2 * f(n-1) + 5  # we will never reach here... this line is where we need to return when any `return` statements is met
</code>```

Next we will change the first return statements (the return 3):

```<code>def f(N):
    n = N        # N is the top level parameter passed to this function
    res = None   # res is the result returned by this function
[start]:         # here we create a label; not python, only for converting
    if n == 1:
        res = 3
        # for `return` we need to see if this is the top level or a inner recursive call
        if stack is empty: # we are in top level
            return res
        # hey we are in a recursive call, and we need to return to the code after `goto`, why not move these code here?
        else:
            n = pop()      # we pop the parameter saved
            # this line is where we need to return when any `return` statements is met
            return 2 * f(n-1) + 5
    else:
        push(n)       # push current parameter; since there is only one recursive function call in the body, we know where to return and there is no need to push the return address
        n = n-1       # the next level actual parameter is now n-1
        goto [start]  # we go to the code of the function which is the start of this same function
</code>```

Then we will convert the return 2*f(n-1)+5:

```<code>def f(N):
    n = N        # N is the top level parameter passed to this function
    res = None   # res is the result returned by this function
[start]:         # here we create a label; not python, only for converting
    if n == 1:
        res = 3
        if stack is empty:
            return res
        else:
            [loop]:
            n = pop()      # we pop the parameter saved
            # begin conversion of return
            res = 2*res+5
            if stack is empty:
                return res;
            else:
                # we need to pop stack and jump to the same return, so we just jump to [loop]
                goto [loop]
    else:
        push(n)       # push current parameter; since there is only one recursive function call in the body, we know where to return and there is no need to push the return address
        n = n-1       # the next level actual parameter is now n-1
        goto [start]  # we go to the code of the function which is the start of this same function
</code>```

Now the conversion is done, and we need to simplify this mess. First we should consider if a stack is really need. For this particular problem, every push just make n=n-1 and every pop makes n=n+1. So the stack is not really needed.

```<code>def f(N):
    n = N        # N is the top level parameter passed to this function
    res = None   # res is the result returned by this function
[start]:         # here we create a label; not python, only for converting
    if n == 1:
        res = 3
        if n == N:         # SAME as stack is empty
            return res     # really return
        else:
            [loop]:
            n = n+1       # WE JUST INCREASE N INSTEAD OF POP
            res = 2*res+5
            if n==N:      # SAME as stack is empty
                return res;
            else:
                goto [loop]
    else:
        # NO PUSH NEEDED
        n = n-1       # the next level actual parameter is now n-1
        goto [start]
</code>```

The stack is eliminated, and we need to make these goto statements disappear. Notice the [start] label and goto [start] makes a loop, we just need to make them a 'while' loop:

```<code>def f(N):
    n = N        # N is the top level parameter passed to this function
    res = None   # res is the result returned by this function
    # we reverse the if n==1 and make it a condition in while
    while n != 1:
        # NO PUSH NEEDED
        n = n-1       # the next level actual parameter is now n-1
    # you soon noticed the above calculation is not needed at all, it just sets n = 1

    res = 3
    if n == N:
        return res
    else:
        [loop]:
        n = n+1
        res = 2*res+5
        if n==N:
            return res;
        else:
            goto [loop]
</code>```

We optimized the first loop and replace them with n=1. And we need to make the second loop labeled by [loop] and goto [loop] disappear:

```<code>def f(N):
    n = N        # N is the top level parameter passed to this function
    res = None   # res is the result returned by this function
    n = 1        # the result of the first while loop

    res = 3
    if n == N:
        return res
    else:
        do:              # Python does not have do while, but it is straight forward to do this convert
            n = n+1
            res = 2*res+5
        while n!=N
        return res
</code>```

We will soon notice that the first 4 statements can be combined and we remove all comments:

```<code>def f(N):
    n = 1
    res = 3
    if n == N:
        return res
    else:
        do:
            n = n+1
            res = 2*res+5
        while n!=N
        return res
</code>```

We will reverse the if n==N statement:

```<code>def f(N):
    n = 1
    res = 3
    if n != N:
        do:
            n = n+1
            res = 2*res+5
        while n!=N
        return res
    else:
        return res
</code>```

It is obvious that return res can be put on top level and the if n!=N and do/while loop can be combined to a single while loop:

```<code>def f(N):
    n = 1
    res = 3
    while n != N:
        n = n+1
        res = 2*res+5
    return res
</code>```

This is the equivalent version of the original recursive function. Notice that I do not dig into this specific problem to come up with this version, I only deal with function call conversions. I suggest you go through the whole process on your own in your favorite text editor and it is kind of fun. You will find it is very mechanical and the only thing that requires some thought is the stack usage. Other techniques like "reverse if conditions" or "convert goto to structural loops" are quite easy.

It is also interesting to see that the iterative version is more efficient than the recursive one based only on the conversion process alone because: 1. we eliminate the use of the stack; 2. we eliminate a loop that decrease n to 1. We at least save some CPU cycles and stack storage.

Body:
I need to convert

def aRecursive(n):
    if n is 1:
        return 3
    else:
        return 2 * aRecursive(n-1) + 5

into a for loop and a while loop. I can't seem to wrap my mind around the process. The original function for these loops are:

a(1) = 3
a(n) = 2 * a(n-1) + 5

An answer and explanation would help out immensely.

Body:
I am going to offer a solution based on how functions are called. This solution is generic, in that you can use the same approach to convert any recursive function to an iterative one. It is theoretically possible but it seems no one talks about how. Since your function is easy, it is not hard to come up with a iterative one. But how about non-recursive post-order traversal of a binary tree? You can only do it on a case by case basis if you don't have a generic approach that I am going to present.

Here we go. First we need to write down your recursive version with a slight change to facilitate the conversion:

def f(N):
    n = N        # N is the top level parameter passed to this function
    res = None   # res is the result returned by this function
[start]:         # here we create a label; not python, only for converting
    if n == 1:
        return 3
    else:
        return 2 * f(n-1) + 5

Next we are going to convert two things: the function call and the return statements. The function call is basically 2 steps: push parameters and return address to stack and jump to the actual code. The return is basically pop parameters and jump to the saved address. So here we go:

def f(N):
    n = N        # N is the top level parameter passed to this function
    res = None   # res is the result returned by this function
[start]:         # here we create a label; not python, only for converting
    if n == 1:
        return 3
    else:
        push(n)       # push current parameter; since there is only one recursive function call in the body, we know where to return and there is no need to push the return address
        n = n-1       # the next level actual parameter is now n-1
        goto [start]  # we go to the code of the function which is the start of this same function
        return 2 * f(n-1) + 5  # we will never reach here... this line is where we need to return when any `return` statements is met

Next we will change the first return statements (the return 3):

def f(N):
    n = N        # N is the top level parameter passed to this function
    res = None   # res is the result returned by this function
[start]:         # here we create a label; not python, only for converting
    if n == 1:
        res = 3
        # for `return` we need to see if this is the top level or a inner recursive call
        if stack is empty: # we are in top level
            return res
        # hey we are in a recursive call, and we need to return to the code after `goto`, why not move these code here?
        else:
            n = pop()      # we pop the parameter saved
            # this line is where we need to return when any `return` statements is met
            return 2 * f(n-1) + 5
    else:
        push(n)       # push current parameter; since there is only one recursive function call in the body, we know where to return and there is no need to push the return address
        n = n-1       # the next level actual parameter is now n-1
        goto [start]  # we go to the code of the function which is the start of this same function

Then we will convert the return 2*f(n-1)+5:

def f(N):
    n = N        # N is the top level parameter passed to this function
    res = None   # res is the result returned by this function
[start]:         # here we create a label; not python, only for converting
    if n == 1:
        res = 3
        if stack is empty:
            return res
        else:
            [loop]:
            n = pop()      # we pop the parameter saved
            # begin conversion of return
            res = 2*res+5
            if stack is empty:
                return res;
            else:
                # we need to pop stack and jump to the same return, so we just jump to [loop]
                goto [loop]
    else:
        push(n)       # push current parameter; since there is only one recursive function call in the body, we know where to return and there is no need to push the return address
        n = n-1       # the next level actual parameter is now n-1
        goto [start]  # we go to the code of the function which is the start of this same function

Now the conversion is done, and we need to simplify this mess. First we should consider if a stack is really need. For this particular problem, every push just make n=n-1 and every pop makes n=n+1. So the stack is not really needed.

def f(N):
    n = N        # N is the top level parameter passed to this function
    res = None   # res is the result returned by this function
[start]:         # here we create a label; not python, only for converting
    if n == 1:
        res = 3
        if n == N:         # SAME as stack is empty
            return res     # really return
        else:
            [loop]:
            n = n+1       # WE JUST INCREASE N INSTEAD OF POP
            res = 2*res+5
            if n==N:      # SAME as stack is empty
                return res;
            else:
                goto [loop]
    else:
        # NO PUSH NEEDED
        n = n-1       # the next level actual parameter is now n-1
        goto [start]

The stack is eliminated, and we need to make these goto statements disappear. Notice the [start] label and goto [start] makes a loop, we just need to make them a 'while' loop:

def f(N):
    n = N        # N is the top level parameter passed to this function
    res = None   # res is the result returned by this function
    # we reverse the if n==1 and make it a condition in while
    while n != 1:
        # NO PUSH NEEDED
        n = n-1       # the next level actual parameter is now n-1
    # you soon noticed the above calculation is not needed at all, it just sets n = 1

    res = 3
    if n == N:
        return res
    else:
        [loop]:
        n = n+1
        res = 2*res+5
        if n==N:
            return res;
        else:
            goto [loop]

We optimized the first loop and replace them with n=1. And we need to make the second loop labeled by [loop] and goto [loop] disappear:

def f(N):
    n = N        # N is the top level parameter passed to this function
    res = None   # res is the result returned by this function
    n = 1        # the result of the first while loop

    res = 3
    if n == N:
        return res
    else:
        do:              # Python does not have do while, but it is straight forward to do this convert
            n = n+1
            res = 2*res+5
        while n!=N
        return res

We will soon notice that the first 4 statements can be combined and we remove all comments:

def f(N):
    n = 1
    res = 3
    if n == N:
        return res
    else:
        do:
            n = n+1
            res = 2*res+5
        while n!=N
        return res

We will reverse the if n==N statement:

def f(N):
    n = 1
    res = 3
    if n != N:
        do:
            n = n+1
            res = 2*res+5
        while n!=N
        return res
    else:
        return res

It is obvious that return res can be put on top level and the if n!=N and do/while loop can be combined to a single while loop:

def f(N):
    n = 1
    res = 3
    while n != N:
        n = n+1
        res = 2*res+5
    return res

This is the equivalent version of the original recursive function. Notice that I do not dig into this specific problem to come up with this version, I only deal with function call conversions. I suggest you go through the whole process on your own in your favorite text editor and it is kind of fun. You will find it is very mechanical and the only thing that requires some thought is the stack usage. Other techniques like "reverse if conditions" or "convert goto to structural loops" are quite easy.

It is also interesting to see that the iterative version is more efficient than the recursive one based only on the conversion process alone because: 1. we eliminate the use of the stack; 2. we eliminate a loop that decrease n to 1. We at least save some CPU cycles and stack storage.


问:
unable to view new table data after concat - Ionic 3 Angular 4
I'm using ionic's events to pass data from page to page. In this instance I'm passing an array to another page, let's say with two objects. The data I'm wanting to add to is called dataOne and I'm using a life cycle function so that when the user enters the page they will be automatically tested from this function whether or not there is an event to be concatenated onto dataOne. The issue is, the data isn't being added. I'm able to retrieve the data but nothing happens to the table, as I'm still getting the same result.

ts

```<code>ionViewWillEnter(){
    this.events.subscribe('market', (dataTwo) => {
            return this.dataOne = this.dataOne.concat(dataTwo)
          })
}
</code>```

答:
What is 'Market' ? dataOne is array? In my opinion, </p>

```<code>dataOne: any[]=[];
...
this.events.subscribe((dataTwo) =>{
 this.dataOne.push(dataTwo.market); // if market you want to catch data
}
</code>```

Body:
I'm using ionic's events to pass data from page to page. In this instance I'm passing an array to another page, let's say with two objects. The data I'm wanting to add to is called dataOne and I'm using a life cycle function so that when the user enters the page they will be automatically tested from this function whether or not there is an event to be concatenated onto dataOne. The issue is, the data isn't being added. I'm able to retrieve the data but nothing happens to the table, as I'm still getting the same result.

ts

ionViewWillEnter(){
    this.events.subscribe('market', (dataTwo) => {
            return this.dataOne = this.dataOne.concat(dataTwo)
          })
}

Body:
What is 'Market' ? dataOne is array? In my opinion,

dataOne: any[]=[];
...
this.events.subscribe((dataTwo) =>{
 this.dataOne.push(dataTwo.market); // if market you want to catch data
}


问:
Javascript local variable technique
I have a simple question related to one-line programming. First an example:

```<code>function test(a)
{
   var b=a.toString();
   return b.replace("a","b");
}
</code>```

It's very simple (this function is, of course, useless), but the question here is little more complicated: What if I was to do this in one line? I have my thoughts, but tell me does this work properly with respect to memory cleanup:

```<code>function test(a)
{
   return (arguments[1]=a.toString()).doSomething().doSomethingMore(arguments[1]);
}
</code>```

This is, of course, an example, but the idea is simple: use arguments as a container for local variables - I'm not sure, but from what I know, when a function is over, arguments are deleted also? Or does create new elements in arguments makes this element defined globally? From my tests, it seems that I'm correct, but I'm curious to see if anyone has tried this? Is this a safe and clean solution?:) Thanks for any comments.

Here are a more real problem with One-Line script problem:

```<code>function (number,limiter)
{
return ((arguments[2] = number.toString().replace(
         new RegExp("(\\d+)(\\d{3})($|"+limiter+")"),
         '$1'+limiter+'$2$3')) == number) ?
            arguments[2] :
            arguments.callee(arguments[2],limiter);
}
</code>```

This one line function do things with given string and return it or parse it recursively to the same function. (on other thread I show how this could be done without recursion, but this is not a case of a problem).

答:
Why are you trying to avoid creating a variable locally?  Doing so makes code that's a lot easier to read/understand, and I don't think you're really gaining anything.

The variables are basically just references to the objects you're creating.  Whether you assign them to a normal variable or put them in an array the cleanup is going to be the same.  Both the arguments array and the local variable will be out of scope once the method returns so I don't think you're going to see any difference in behavior.  (the arguments array's scope might be different if the method was called via an apply() command, but I haven't tested that to be sure).

ContentLicense: CC BY-SA 4.0

Title: Javascript local variable technique

Body:
I have a simple question related to one-line programming. First an example:

function test(a)
{
   var b=a.toString();
   return b.replace("a","b");
}

It's very simple (this function is, of course, useless), but the question here is little more complicated: What if I was to do this in one line? I have my thoughts, but tell me does this work properly with respect to memory cleanup:

function test(a)
{
   return (arguments[1]=a.toString()).doSomething().doSomethingMore(arguments[1]);
}

This is, of course, an example, but the idea is simple: use arguments as a container for local variables - I'm not sure, but from what I know, when a function is over, arguments are deleted also? Or does create new elements in arguments makes this element defined globally? From my tests, it seems that I'm correct, but I'm curious to see if anyone has tried this? Is this a safe and clean solution?:) Thanks for any comments.

Here are a more real problem with One-Line script problem:

function (number,limiter)
{
return ((arguments[2] = number.toString().replace(
         new RegExp("(\\d+)(\\d{3})($|"+limiter+")"),
         '$1'+limiter+'$2$3')) == number) ?
            arguments[2] :
            arguments.callee(arguments[2],limiter);
}

This one line function do things with given string and return it or parse it recursively to the same function. (on other thread I show how this could be done without recursion, but this is not a case of a problem).

OwnerDisplayName: Herms

ContentLicense: CC BY-SA 2.5


问:
Excel API cell.insert taking a very long time to run
I am trying to insert some rows within or below a used range from sheet.

Although my code here shows a hard-coded array, the data actually comes from a server application. I determine the order of inserts after scanning the server response.  My code works somewhat like below:

Excel.run(function (ctx) {
    var rowIdsArray = [1, 2, 3, 4, 5, 6, 7, 8, 9]; //data that might have come from server
    var sht = ctx.workbook.worksheets.getItem("Sheet1");
    for (var i = 50; i > 3; i--) {
        //I might want these rows to be inserted before rows
        //3 to 50. So 9 rows inserted 48 times
        for (var counter1 = 0; counter1 < rowIdsArray.length; counter1++) {
            var cell = sht.getUsedRange().getRow(parseInt(i)).getOffsetRange(1, 0);
            cell.insert();
        }
    }
    return ctx.sync().then(function () {
        console.log("rows inserted");
    });
}).catch(function (e) {
    console.log("Error Message is -> " + e.message);
});
```

I have rowIdsArray as array of rows with the id that I want to insert. The loop iterating explains at which index (in my project this array has random number) I want to add these rows into the sheet.

So I am basically inserting number of rows into the sheet (400-450 rows), but its taking way too much time. I can see Excel inserting rows very slowly, one by one.

Does office.js API provides any other way to achieve the same with very less time?

答:
You could set all the values at once:

```<code>Excel.run(function (ctx) {
  var sheetName = "Sheet1";
  var rangeAddress = "A3";
  //values is:
  // [1, 2, 3, 4, 5, 6, 7, 8, 9]
  // [2, 3, 4, 5, 6, 7, 8, 9, 10]
  //...
  // [50, 51, 52, 53, 54, 55, 56, 57, 58]
  var values = (function(values){
    var i = -1;
    var rows = rows;
    ret = [];
    while(++i<rows){
      ret.push(
        values.map(
          function(value){
            return value+i;
          }
        )
      );
    }
  })([1,2,3,4,5,6,7,8,9]);
  var range = ctx.workbook
    .worksheets.getItem(sheetName)
    .getRange(rangeAddress)
    .getRowsBelow(rows)
    .getColumnsAfter(9);
  range.insert("Down");
  range.values = values;
  range.load('text');
  return ctx.sync().then(function() {
    console.log(range.text);
  });
}).catch(function(error) {
  console.log("Error: " + error);
  if (error instanceof OfficeExtension.Error) {
    console.log("Debug info: " + JSON.stringify(error.debugInfo));
  }
});
</code>```

I don't have excel so can't test it but that should do it.

Body:
I am trying to insert some rows within or below a used range from sheet.

Although my code here shows a hard-coded array, the data actually comes from a server application. I determine the order of inserts after scanning the server response.  My code works somewhat like below:

Excel.run(function (ctx) {
    var rowIdsArray = [1, 2, 3, 4, 5, 6, 7, 8, 9]; //data that might have come from server
    var sht = ctx.workbook.worksheets.getItem("Sheet1");
    for (var i = 50; i > 3; i--) {
        //I might want these rows to be inserted before rows
        //3 to 50. So 9 rows inserted 48 times
        for (var counter1 = 0; counter1 < rowIdsArray.length; counter1++) {
            var cell = sht.getUsedRange().getRow(parseInt(i)).getOffsetRange(1, 0);
            cell.insert();
        }
    }
    return ctx.sync().then(function () {
        console.log("rows inserted");
    });
}).catch(function (e) {
    console.log("Error Message is -> " + e.message);
});

I have rowIdsArray as array of rows with the id that I want to insert. The loop iterating explains at which index (in my project this array has random number) I want to add these rows into the sheet.

So I am basically inserting number of rows into the sheet (400-450 rows), but its taking way too much time. I can see Excel inserting rows very slowly, one by one.

Does office.js API provides any other way to achieve the same with very less time?

Body:
You could set all the values at once:

Excel.run(function (ctx) {
  var sheetName = "Sheet1";
  var rangeAddress = "A3";
  //values is:
  // [1, 2, 3, 4, 5, 6, 7, 8, 9]
  // [2, 3, 4, 5, 6, 7, 8, 9, 10]
  //...
  // [50, 51, 52, 53, 54, 55, 56, 57, 58]
  var values = (function(values){
    var i = -1;
    var rows = rows;
    ret = [];
    while(++i<rows){
      ret.push(
        values.map(
          function(value){
            return value+i;
          }
        )
      );
    }
  })([1,2,3,4,5,6,7,8,9]);
  var range = ctx.workbook
    .worksheets.getItem(sheetName)
    .getRange(rangeAddress)
    .getRowsBelow(rows)
    .getColumnsAfter(9);
  range.insert("Down");
  range.values = values;
  range.load('text');
  return ctx.sync().then(function() {
    console.log(range.text);
  });
}).catch(function(error) {
  console.log("Error: " + error);
  if (error instanceof OfficeExtension.Error) {
    console.log("Debug info: " + JSON.stringify(error.debugInfo));
  }
});

I don't have excel so can't test it but that should do it.


问:
How to define click event on click and href event when user opens a new tab
This is very specific requirement but was wondering if this is possible.

I have a header menu, "Create Report". I had defined "click" event for this. On clicking this menu, it opens a new modal, without changing the route.. and once user feeds some data there and clicks submit, it changes the route to "/reports" and shows the data.

But problem with this approach is, when user want to open this link (header menu Create report) in new tab (right click and open in new tab), it doesn't open anything.. may be new tab could not understand this.

One solution is to replace click with href, so instead I can do, href="/report". But this way, as soon as user clicks this link, it changes the route, to "/report", which I do not want. I want to change the route when user submits the report.

I can not use ng-click/ ng-href due to some techinal limitation with my current project.

I hope my question is clear, please let me know if you know of a solution or you want any more information.

答:
I'm not sure if understand You correctly but You can achieve this effect by replacing in modal window your submit button with link and nested button. Like this:</p>

```<code><a href="/report" target="_parent">
    <button onclick="form.submit()">Submit</button>
</a>
</code>```

Body:
I'm not sure if understand You correctly but You can achieve this effect by replacing in modal window your submit button with link and nested button. Like this:

<a href="/report" target="_parent">
    <button onclick="form.submit()">Submit</button>
</a>


问:
find a string in an array with pointers
I have a problem, I need to test if a string is present in an other array in C using pointer. I tried this, but it doesn't work, if anyone has any suggestion... here is the code I tried, thank you in advance... </p>

```<code>/* Like the strstr() function. It returns a pointer to the first occurrence of the string aiguille in the string meule_de_foin.
 * @param meule_de_foin the string to search in
 * @param aiguille the string to find
 * @return a pointer to the first occurrence of the string aiguille in the string meule_de_foin if aiguille is in meule_de_foin, NULL otherwise
 */

const char * IMPLEMENT(indexOfString)(const char *meule_de_foin, const char *aiguille) {
    int isFound; isFound=0;
    int first; first=meule_de_foin;

    while(isFound==0){
        if(*aiguille=='\0' && *meule_de_foin=='\0'){
            isFound=1;
        } else if (*aiguille == *meule_de_foin){
            aiguille=aiguille+1;
            meule_de_foin=meule_de_foin+1;
        }else{
            isFound=2;
        }
    }

    if(isFound==1){
        return (first);
    }else{
        return(NULL);
    }
}

if(isFound==1){
    return (first);
}else{
    return(NULL);
}
</code>```

答:
You're only testing if two strings are completely equal.

You need to stop checking when you reach the end of the search string, even if you're not at the end of the string to search.

And if it's not found, you need to check again starting at the next character, and keep repeating this until you reach the end of the string. So you need another loop around the loop that searches.

```<code>int isFound = 0;
const char *first;
for (first = meule_de_foin; *first != '\0' && isFound != 1; first++) {
    isFound = 0;
    const char *search = aiguille;
    const char *cur = first;
    while (!isFound) {
        if (*search == '\0') { // End of search string
            isFound = 1;
        } else if (*search != *cur) { // Non-matching character, stop matching
            isFound = 2;
        } else { // Keep matching
            search++;
            cur++;
        }
    }
}

if (isFound == 1) {
    return first;
else {
    return NULL;
}
</code>```

Title: find a string in an array with pointers

Body:
I have a problem, I need to test if a string is present in an other array in C using pointer. I tried this, but it doesn't work, if anyone has any suggestion... here is the code I tried, thank you in advance...

/* Like the strstr() function. It returns a pointer to the first occurrence of the string aiguille in the string meule_de_foin.
 * @param meule_de_foin the string to search in
 * @param aiguille the string to find
 * @return a pointer to the first occurrence of the string aiguille in the string meule_de_foin if aiguille is in meule_de_foin, NULL otherwise
 */

const char * IMPLEMENT(indexOfString)(const char *meule_de_foin, const char *aiguille) {
    int isFound; isFound=0;
    int first; first=meule_de_foin;

    while(isFound==0){
        if(*aiguille=='\0' && *meule_de_foin=='\0'){
            isFound=1;
        } else if (*aiguille == *meule_de_foin){
            aiguille=aiguille+1;
            meule_de_foin=meule_de_foin+1;
        }else{
            isFound=2;
        }
    }

    if(isFound==1){
        return (first);
    }else{
        return(NULL);
    }
}

if(isFound==1){
    return (first);
}else{
    return(NULL);
}

Body:
You're only testing if two strings are completely equal.

You need to stop checking when you reach the end of the search string, even if you're not at the end of the string to search.

And if it's not found, you need to check again starting at the next character, and keep repeating this until you reach the end of the string. So you need another loop around the loop that searches.

int isFound = 0;
const char *first;
for (first = meule_de_foin; *first != '\0' && isFound != 1; first++) {
    isFound = 0;
    const char *search = aiguille;
    const char *cur = first;
    while (!isFound) {
        if (*search == '\0') { // End of search string
            isFound = 1;
        } else if (*search != *cur) { // Non-matching character, stop matching
            isFound = 2;
        } else { // Keep matching
            search++;
            cur++;
        }
    }
}

if (isFound == 1) {
    return first;
else {
    return NULL;
}


问:
Error while trying to join peer to channel in fabric
I am trying to build a fabric network with two channels. One peer is able to join the channel but while trying to join  the second peer to channel getting following error:

Error: genesis block file not found open mychannel.block: no such file or directory

this is my code used for channel creation and joining peers:

Creating channel:

```<code>docker exec -e "CORE_PEER_LOCALMSPID=Org2MSP" -e "CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/msp/users/Admin@org2.example.com/msp" peer0.org2.example.com peer channel create -o orderer.example.com:7050 -c mychannel -f /etc/hyperledger/configtx/channel.tx
</code>```

Joining peers:

```<code>docker exec -e "CORE_PEER_LOCALMSPID=Org2MSP" -e "CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/msp/users/Admin@org2.example.com/msp" peer0.org2.example.com peer channel join -b mychannel.block

docker exec -e "CORE_PEER_LOCALMSPID=Org1MSP" -e "CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/msp/users/Admin@org1.example.com/msp" peer0.org1.example.com peer channel join -b mychannel.block
</code>```

Please correct if something is wrong.

答:
The issue is that mychannel.block is only available within the peer0.org2.example.com container (since that is the container where you ran the channel create command).  The peer0.org1.example.com container does not have access to mychannel.block and that's why you get the error.

What you will need to do is to actually have to do is mount a shared volume for both containers and make sure that you when you run channel create that mychannel.block is output in the shared volume

Body:
I am trying to build a fabric network with two channels. One peer is able to join the channel but while trying to join  the second peer to channel getting following error:

Error: genesis block file not found open mychannel.block: no such file or directory

this is my code used for channel creation and joining peers:

Creating channel:

docker exec -e "CORE_PEER_LOCALMSPID=Org2MSP" -e "CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/msp/users/Admin@org2.example.com/msp" peer0.org2.example.com peer channel create -o orderer.example.com:7050 -c mychannel -f /etc/hyperledger/configtx/channel.tx

Joining peers:

docker exec -e "CORE_PEER_LOCALMSPID=Org2MSP" -e "CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/msp/users/Admin@org2.example.com/msp" peer0.org2.example.com peer channel join -b mychannel.block

docker exec -e "CORE_PEER_LOCALMSPID=Org1MSP" -e "CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/msp/users/Admin@org1.example.com/msp" peer0.org1.example.com peer channel join -b mychannel.block

Please correct if something is wrong.


问:
dc.js LineChart Aggregated by Month/Year
I trying to plot a lineChart and I want to aggregate data by Month. I am using dataset from crossfilter documentation with slight modification in date.

This is how my dataset looks like:

```<code>var data = [
  {date: "2011-11-14T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab"},
  {date: "2011-07-10T16:28:54Z", quantity: 1, total: 300, tip: 200, type: "visa"},
  {date: "2011-07-15T16:28:54Z", quantity: 1, total: 300, tip: 200, type: "visa"},
  {date: "2011-06-14T16:30:43Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-06-14T16:48:46Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-05-14T16:53:41Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-07-17T16:14:06Z", quantity: 1, total: 100, tip: 0, type: "cash"},
  {date: "2011-05-14T16:58:03Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-12-14T17:07:21Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-11-14T17:22:59Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-11-14T17:25:45Z", quantity: 2, total: 200, tip: 0, type: "cash"},
  {date: "2011-11-14T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "visa"}
];
</code>```

I want to group total by Month-Year. My Data Group is returning total based on date instead of Month.

In my graph, July 10, 15 and 17 are plotted as different point. I want to combine them all into July-2017 points. How do I acheive that ? Any pointers?
Thanks All!

here is a fiddle:
https://jsfiddle.net/usingh2buffaloedu/8u0etnwd/

答:
I've had issues with time rendering in dc.js, but in your example the key is to get the month values in your dimension.

```<code>var dateDimension = facts.dimension(function (d) {return d3.time.month(d.newDate); });
</code>```

See the updated fiddle (https://jsfiddle.net/ury1k1bs/1/)

I think the .round() chart method is only useful for brushing, not for rendering.

For more see the time interval example provided by dc.js...
http://dc-js.github.io/dc.js/examples/switching-time-intervals.html

Body:
I trying to plot a lineChart and I want to aggregate data by Month. I am using dataset from crossfilter documentation with slight modification in date.

This is how my dataset looks like:

var data = [
  {date: "2011-11-14T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab"},
  {date: "2011-07-10T16:28:54Z", quantity: 1, total: 300, tip: 200, type: "visa"},
  {date: "2011-07-15T16:28:54Z", quantity: 1, total: 300, tip: 200, type: "visa"},
  {date: "2011-06-14T16:30:43Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-06-14T16:48:46Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-05-14T16:53:41Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-07-17T16:14:06Z", quantity: 1, total: 100, tip: 0, type: "cash"},
  {date: "2011-05-14T16:58:03Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-12-14T17:07:21Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-11-14T17:22:59Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-11-14T17:25:45Z", quantity: 2, total: 200, tip: 0, type: "cash"},
  {date: "2011-11-14T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "visa"}
];

I want to group total by Month-Year. My Data Group is returning total based on date instead of Month.

In my graph, July 10, 15 and 17 are plotted as different point. I want to combine them all into July-2017 points. How do I acheive that ? Any pointers?
Thanks All!

here is a fiddle:
https://jsfiddle.net/usingh2buffaloedu/8u0etnwd/

Body:
I've had issues with time rendering in dc.js, but in your example the key is to get the month values in your dimension.

var dateDimension = facts.dimension(function (d) {return d3.time.month(d.newDate); });

See the updated fiddle (https://jsfiddle.net/ury1k1bs/1/)

I think the .round() chart method is only useful for brushing, not for rendering.

For more see the time interval example provided by dc.js...
http://dc-js.github.io/dc.js/examples/switching-time-intervals.html


问:
Trouble in scraping specific element having same classname using beautifulsoup python
How can I extract text with status information Semi-Furnished,
Available immediately for Family on,Semi-Furnished.

As the div class="proDetailsRowElm" has detail and status information i am ending up getting  detail an status information in my list.

Could you please help me to get only status information?

HTML CODE

Details:

3 Bathroom
3 Balcony

Status:
Semi-Furnished,
Available immediately for Family

```
</div>
</div>
</p>

<p><strong>Python code</strong> </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>property_status_list=soup.find_all('div',class_='proDetailsRowElm')
for property_status in property_status_list:
    for element in property_status_list:
        print(element.text)</code>```

Above code Output

Details:
3 Bathroom
3 Balcony

Status:
Furnished,
Available immediately for Family

Required Output

Status:
Furnished,
Available immediately for Family

答:
I'm by no means a BeautifulSoup expert but you might be able to use next_sibling:

```<code>property_status_list=soup.find_all('div',class_='proDetailsRowElm')
for property_status in property_status_list:
    try:
        k = property_status.find('label', text='Status:').next_sibling
        print(repr(k))
    except:
        pass
</code>```

Returns:

```<code>'\nSemi-Furnished,\nAvailable immediately for Family\n'
</code>```

Body:
How can I extract text with status information Semi-Furnished,
Available immediately for Family on,Semi-Furnished.

As the div class="proDetailsRowElm" has detail and status information i am ending up getting  detail an status information in my list.

Could you please help me to get only status information?

HTML CODE

Details:

3 Bathroom
3 Balcony

  <a class='stop-propagation underline font-type-4 view-details-link' href="javascript:void(0);" onclick="stopPage=true;window.open('/propertyDetails/3-BHK-1800-Sq-ft-Multistorey-Apartment-FOR-Rent-Kadubeesanahalli-in-Bangalore&id=4d423330363332363633', '_blank');callDetailPropertData('30632663');addViewedPropertyToCookie('30632663',1);detailViewTrack('30632663');clicktrack('1', 'propertyId=30632663,'+'2', 'div'+',sessionId='+sessionId  ,'Rent','Kadubeesanahalli','Agent','91','Bangalore' ,'','', 'N','35,000','','3','Multistorey Apartment','','','8','','',false,'','',''); trackPropertyPosition('1', '2', '30632663', 'div')">

Status:
Semi-Furnished,
Available immediately for Family

Python code

property_status_list=soup.find_all('div',class_='proDetailsRowElm')
for property_status in property_status_list:
    for element in property_status_list:
        print(element.text)

Above code Output

Details:
3 Bathroom
3 Balcony

Status:
Furnished,
Available immediately for Family

Required Output

Status:
Furnished,
Available immediately for Family

Body:
I'm by no means a BeautifulSoup expert but you might be able to use next_sibling:

property_status_list=soup.find_all('div',class_='proDetailsRowElm')
for property_status in property_status_list:
    try:
        k = property_status.find('label', text='Status:').next_sibling
        print(repr(k))
    except:
        pass

Returns:

'\nSemi-Furnished,\nAvailable immediately for Family\n'


问:
A business scenario that could involve integration of a number of IT systems using JMS?
Can anyone give me some suggestions of a business scenarios where I can implement Java Messaging Services (JMS). The message can be sent either by queue(point-to-point) or topic (regular/durable subscription).

I will be using JMS (enabled through TIBCO Enterprise Messaging Services).

The business scenarios must involve atleast 3 IT systems/applications.

答:
Here are some of the scenarios where we (food retailer) use messaging:

-connection systems between remote locations, in our case POS and inventory management systems in stores, and central ERP and forecast systems: master data changes are sent as XML messages from the central ERP system to the store systems. the store systems send changes in inventory, orders and sales to the central systems. This is completely PTP based, as the master data is unique for each store.

-usage as a central messaging backbone, either directly for systems that are capable to do messaging, or via some adapter functionality for databases, files, SAP systems or HTTP. Here the messaging system builds the base for our ESB.


问:
Android App is logged in even app is re-installed
I have an Android app where I have at the start of the app.

There is one weird thing happening with my app.

Even I delete app and re-install, the app takes last logged in data and show me that I am already logged in.

Below are the steps.

Login to app as testuser

Delete app

Install app again

Actually it should ask me for login, however it shows that I am already logged in with testuser.

OS that I have on Android is 7.0 on S6 Edge phone.

Note : I check on S4 and all is fine. It ask me to login on each re-install.

答:
Apps that target Android 6.0 (API level 23) or higher automatically participate in Auto Backup. This is because the android:allowBackup attribute, which enables/disables backup, defaults to true if omitted. To avoid confusion, we recommend you explicitly set the attribute in the <application> element of your AndroidManifest.xml.

```<code><application ...
    android:allowBackup="false">
</application>
</code>```

Files that are backed up

By default, Auto Backup includes files in most of the directories that are assigned to your app by the system:

Shared preferences files.

Files in the directory returned by getFilesDir().

Files in the directory returned by getDatabasePath(String), which also includes files created with the SQLiteOpenHelper class.

Files in directories created with getDir(String, int).

Files on external storage in the directory returned by getExternalFilesDir(String).

for more information read Auto Backup for Apps

or when you logout Try to delete in manually like this

```<code>File preferenceFile = new File("/data/data/"+ getPackageName()+ "/shared_prefs/");
File[] listFiles = preferenceFile.listFiles();
for (File file : listFiles) {
    file.delete();
}
</code>```

Body:
Apps that target Android 6.0 (API level 23) or higher automatically participate in Auto Backup. This is because the android:allowBackup attribute, which enables/disables backup, defaults to true if omitted. To avoid confusion, we recommend you explicitly set the attribute in the <application> element of your AndroidManifest.xml.

<application ...
    android:allowBackup="false">
</application>

Files that are backed up

By default, Auto Backup includes files in most of the directories that are assigned to your app by the system:

Shared preferences files.

Files in the directory returned by getFilesDir().

Files in the directory returned by getDatabasePath(String), which also includes files created with the SQLiteOpenHelper class.

Files in directories created with getDir(String, int).

Files on external storage in the directory returned by getExternalFilesDir(String).

for more information read Auto Backup for Apps

or when you logout Try to delete in manually like this

File preferenceFile = new File("/data/data/"+ getPackageName()+ "/shared_prefs/");
File[] listFiles = preferenceFile.listFiles();
for (File file : listFiles) {
    file.delete();
}


问:
Making sticky javascript
I have a javascript form where I am using innerHTML to set some text.

When the form submits that information is lost.Is there anyway I can make it "sticky".I was thinking a cookie but that's about all I know.

Thanks

```<code><form "action="" name="myform">
<input type="text" name='name">
<div id="theName"></div>
</form>
</code>```

Quick example I am capturing the name and need the div to show the name after the form submits.

答:
This should be happening server-side. Javascript is for enhancing a page, it's not to be depended on for data manipulation.

Your script, converted to PHP, would look like

```<code><form action="" method="post" name="myform">
  <input type="text" name='name">
  <div id="theName"><?php
    if(isset($_POST['name'])) { echo $_POST['name']; }
  ?></div>
</form>
</code>```

...and it would work every time, without having to call any JS.

You'll have to handle the form data somehow anyway - how were you intending to retrieve the data without a server-side script?

Title: Making sticky javascript

Body:
I have a javascript form where I am using innerHTML to set some text.

When the form submits that information is lost.Is there anyway I can make it "sticky".I was thinking a cookie but that's about all I know.

Thanks

<form "action="" name="myform">
<input type="text" name='name">

</form>

Quick example I am capturing the name and need the div to show the name after the form submits.

Body:
This should be happening server-side. Javascript is for enhancing a page, it's not to be depended on for data manipulation.

Your script, converted to PHP, would look like

<form action="" method="post" name="myform">
  <input type="text" name='name">
  <div id="theName"><?php
    if(isset($_POST['name'])) { echo $_POST['name']; }
  ?></div>
</form>

...and it would work every time, without having to call any JS.

You'll have to handle the form data somehow anyway - how were you intending to retrieve the data without a server-side script?


问:
Define dynamic actions/slugs with Routers in PhalconPHP
I have a website made in PHP Phalcon, and it has several controllers.

Now I need this website to receive words in the URL (example.com/WORD) and check if they exist in the database, but I must continue to support other controllers like example.com/aboutme.

After few hours of trying different methods and searching online I cannot find a way to accomplish this task. The closer intent was creating a Route to redirect non-existing actions to a new controller, but I cannot make this solution work.

Can you think on a solution that may work and share the code/idea? I am not adding any code because I could not get to do anything useful.

答:
This should not be a problem at all. Here are sample routes:</p>

```<code>// Default - This serves as multipurpose route definition
// I can use it to create non pretty urls if I don't want to define them.
// Example: profiles/login, profiles/register - Don't need those pretty :)
$router->add('/:controller/:action/:params', ['controller' => 1, 'action' => 2, 'params' => 3]);
$router->add('/:controller/:action', ['controller' => 1, 'action' => 2]);
$router->add('/:controller', ['controller' => 1]);

// Product page - www.example.com/product-slug-here
$router->add('/{slug}', 'Products::view')->setName('product');

// Blog
$router->add('/blog/{slug}', 'Blog::view')->setName('blog');
$router->add('/blog', 'Blog::index')->setName('blog-short');

// Contacts - Pretty urls in native website language
$router->add('/kontakti', 'Blabla::contacts')->setName('contats');
</code>```

Body:
This should not be a problem at all. Here are sample routes:

// Default - This serves as multipurpose route definition
// I can use it to create non pretty urls if I don't want to define them.
// Example: profiles/login, profiles/register - Don't need those pretty :)
$router->add('/:controller/:action/:params', ['controller' => 1, 'action' => 2, 'params' => 3]);
$router->add('/:controller/:action', ['controller' => 1, 'action' => 2]);
$router->add('/:controller', ['controller' => 1]);

// Product page - www.example.com/product-slug-here
$router->add('/{slug}', 'Products::view')->setName('product');

// Blog
$router->add('/blog/{slug}', 'Blog::view')->setName('blog');
$router->add('/blog', 'Blog::index')->setName('blog-short');

// Contacts - Pretty urls in native website language
$router->add('/kontakti', 'Blabla::contacts')->setName('contats');


问:
Is there a way to record the phone screen using ARCore SDK?
I want to record phone screen in a video format.

Is there a way to record my screen using ARcore android SDK??

答: Do you want the recording functionality to be built into your app? If not, just use something like the DU Recorder App. Worked well for me for recording Google Tango Apps. Haven't tested it with ARCore, but should work as well.</p>


问:
Where to put Mako filters
I have written a Mako filter that adds HTML linebreaks:

```<code><%!
    def makelinebreaks(text):
        return text.replace("\r", "<br/>")
%>
</code>```

It works if I put it in the template file. But if I want to use it in several templates then I must redeclare it. Is there any file where I could put the code so that the filter is in scope of all my templates instead of putting as a script in every template it is used?

答:
Suppose that you have defined this filter in a template called filters.mako.  Then in templates that wish to use the filter, simply import filters.mako using a <%namespace> tag

```<code><%namespace file="filters.mako" import="*"/>
</code>```

This is equivalent to a from filters import * construct in Python.  You could also import just the names you want with

```<code><%namespace file="filters.mako" import="makelinebreaks"/>
</code>```

Or, for something equivalent to import filters use:

```<code><%namespace file="filters.mako" name="filters"/>
</code>```

Now you can use your filter as filters. makelinebreaks

```<code>${something | filters.makelinebreaks}
</code>```

Title: Where to put Mako filters

Body:
I have written a Mako filter that adds HTML linebreaks:

<%!
    def makelinebreaks(text):
        return text.replace("\r", "
")
%>

It works if I put it in the template file. But if I want to use it in several templates then I must redeclare it. Is there any file where I could put the code so that the filter is in scope of all my templates instead of putting as a script in every template it is used?

Body:
Suppose that you have defined this filter in a template called filters.mako.  Then in templates that wish to use the filter, simply import filters.mako using a <%namespace> tag

<%namespace file="filters.mako" import="*"/>

This is equivalent to a from filters import * construct in Python.  You could also import just the names you want with

<%namespace file="filters.mako" import="makelinebreaks"/>

Or, for something equivalent to import filters use:

<%namespace file="filters.mako" name="filters"/>

Now you can use your filter as filters. makelinebreaks

${something | filters.makelinebreaks}


问:
copy linked files in visual studio to a location
I have a project set up in my visual studio solution that contains a number of linked files. These are content files.

When I build the project I would like to copy the linked files to another location. Is this possible and how can I achieve it?

答:
It seems that simply adding

```<code><CopyToOutputDirectory>Always</CopyToOutputDirectory>
</code>```

to the linked file item in a Visual Studio 2017 csproj project file will cause the linked file to be copied to the output directory on build, whether you have declared the build action as None or Content.

For example these both work...

```<code><None Include="..\configuration\Shared.OctopusDeploy.config">
  <Link>Shared.OctopusDeploy.config</Link>
  <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>

<Content Include="..\configuration\Shared.OctopusDeploy.config">
  <Link>Shared.OctopusDeploy.config</Link>
  <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</code>```

Body:
It seems that simply adding

<CopyToOutputDirectory>Always</CopyToOutputDirectory>

to the linked file item in a Visual Studio 2017 csproj project file will cause the linked file to be copied to the output directory on build, whether you have declared the build action as None or Content.

For example these both work...

<None Include="..\configuration\Shared.OctopusDeploy.config">
  <Link>Shared.OctopusDeploy.config</Link>
  <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>

<Content Include="..\configuration\Shared.OctopusDeploy.config">
  <Link>Shared.OctopusDeploy.config</Link>
  <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>


问:
How can I make a function treat a whole sentence like one parameter?
How should I pass a sentence to function and make it behave like one parameter.

Example:

```<code>function Test ()
{
  echo $1
}
body="This the test"
Test $body
</code>```

I want output like this=> "This the test"  because of spaces it will print me Test only. What specific characters should i put to make whole sentence like one parameter. Thanks in advance.

答:
Quoting the arguments as you do in your question will work.

```<code>$ function ztest () { echo $1; }
$ ztest "This is a test"
This is a test
</code>```

So, there's nothing else you need to do.

Edit: from comments, you have a logger function and want to pass it two arguments, a string and a "mode".  You would do this as follows:

```<code>logger "This is a test" 0
</code>```

or, if the log message is in a variable,

```<code>logger "$logmessage" 0
</code>```

Putting your variables inside " is rarely a bad idea in shell scripts.

Body:
How should I pass a sentence to function and make it behave like one parameter.

Example:

function Test ()
{
  echo $1
}
body="This the test"
Test $body

I want output like this=> "This the test"  because of spaces it will print me Test only. What specific characters should i put to make whole sentence like one parameter. Thanks in advance.

Body:
Quoting the arguments as you do in your question will work.

$ function ztest () { echo $1; }
$ ztest "This is a test"
This is a test

So, there's nothing else you need to do.

Edit: from comments, you have a logger function and want to pass it two arguments, a string and a "mode".  You would do this as follows:

logger "This is a test" 0

or, if the log message is in a variable,

logger "$logmessage" 0

Putting your variables inside " is rarely a bad idea in shell scripts.


问:
getting file path from command line argument in python
Can anyone guide me how can I  get file path if we pass file from command line argument and extract file also. In case we also need to check if the file exist into particular directory

```<code>python.py /home/abhishek/test.txt
</code>```

get file path and check test.txt exist into abhishek folder.

I know it may be very easy but I am bit new to pytho

答:
I think the most elegant way is to use the ArgumentParser This way you even get the -h option that helps the user to figure out how to pass the arguments. I have also included an optional argument (--outputDirectory).

Now you can simply execute with python3 test.py /home/test.txt --outputDirectory /home/testDir/

```<code>import argparse
import sys
import os

def create_arg_parser():
    # Creates and returns the ArgumentParser object

    parser = argparse.ArgumentParser(description='Description of your app.')
    parser.add_argument('inputDirectory',
                    help='Path to the input directory.')
    parser.add_argument('--outputDirectory',
                    help='Path to the output that contains the resumes.')
    return parser

if __name__ == "__main__":
    arg_parser = create_arg_parser()
    parsed_args = arg_parser.parse_args(sys.argv[1:])
    if os.path.exists(parsed_args.inputDirectory):
       print("File exist")
</code>```

Body:
Can anyone guide me how can I  get file path if we pass file from command line argument and extract file also. In case we also need to check if the file exist into particular directory

python.py /home/abhishek/test.txt

get file path and check test.txt exist into abhishek folder.

I know it may be very easy but I am bit new to pytho

Body:
I think the most elegant way is to use the ArgumentParser This way you even get the -h option that helps the user to figure out how to pass the arguments. I have also included an optional argument (--outputDirectory).

Now you can simply execute with python3 test.py /home/test.txt --outputDirectory /home/testDir/

import argparse
import sys
import os

def create_arg_parser():
    # Creates and returns the ArgumentParser object

    parser = argparse.ArgumentParser(description='Description of your app.')
    parser.add_argument('inputDirectory',
                    help='Path to the input directory.')
    parser.add_argument('--outputDirectory',
                    help='Path to the output that contains the resumes.')
    return parser

if __name__ == "__main__":
    arg_parser = create_arg_parser()
    parsed_args = arg_parser.parse_args(sys.argv[1:])
    if os.path.exists(parsed_args.inputDirectory):
       print("File exist")


问:
Get list of top ordered products
im tring to get the top products that are ordered and the quantity, but i notice that is giving me the sold products and not the ordered products that should be more, what is wrong with this code? Why is not showing the right results?</p>

```<code>set_time_limit(0);
ini_set('memory_limit', '8000M');

require '../app/Mage.php';
umask(0);
Mage::app();
Mage::register('isSecureArea', 1);
function getBestsellingProducts()
{
    // number of products to display
    $productCount = 400;

    // store ID
    $storeId    = Mage::app()->getStore()->getId();

    // get today and last 30 days time
    $today = time();
    $last = $today - (60*60*24*30);

    $from = date("Y-m-d", $last);
    $to = date("Y-m-d", $today);

    // get most view ed products for current category
    $products = Mage::getResourceModel('reports/product_collection')
                    ->addAttributeToSelect('*')
                    ->addOrderedQty($from, $to)
                    //->setStoreId($storeId)
                    //->addStoreFilter($storeId)
                    ->setOrder('ordered_qty', 'desc')
                    ->setPageSize($productCount);

    Mage::getSingleton('catalog/product_status')
            ->addVisibleFilterToCollection($products);
    Mage::getSingleton('catalog/product_visibility')
            ->addVisibleInCatalogFilterToCollection($products);

    return $products;
}

$products = getBestsellingProducts();

foreach ($products as $key => $value) {

    $pro = Mage::getModel('catalog/product')->load($value->getId());
    echo $pro->getName() ." - ". $pro->getSku() . " - " . $value->ordered_qty . "<br>";
}
</code>```

答:
Follow the below steps to get  top ordered products:

Step 1: Create a file app/code/local/Mage/Catalog/Block/Product/Bestseller.php and the following lines of code in it

```<code>lass Mage_Catalog_Block_Product_Bestseller extends Mage_Catalog_Block_Product_Abstract{
    public function __construct(){
        parent::__construct();
        $storeId = Mage::app()->getStore()->getId();
        $products = Mage::getResourceModel('reports/product_collection')
            ->addOrderedQty()
            ->addAttributeToSelect('*')
            ->addAttributeToSelect(array('name', 'price', 'small_image'))
            ->setStoreId($storeId)
            ->addStoreFilter($storeId)
            ->setOrder('ordered_qty', 'desc'); // most best sellers on top
        Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($products);
        Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($products);

        $products->setPageSize(3)->setCurPage(1);
        $this->setProductCollection($products);
    }
}
</code>```

Step 2: Create a file app/design/frontend/default/YourTheme/template/catalog/product/bestseller.phtml file and add the following lines of code in it

```<code><?php if (($_products = $this->getProductCollection()) && $_products->getSize()): ?>
<div class="page-title">
    <h2><?php echo $this->__('Best Seller Products') ?></h2>
</div>
<?php $_collectionSize = count($_products->getItems()) ?>
<table class="products-grid" id="products-grid-table">
<?php $i=1; foreach ($_products->getItems() as $_product): ?>
    <?php if ($i%1!==0): ?>
    <tr>
    <?php endif ?>
        <td id="td_<?php echo $i;?>" <?php if($i%3==0 or $i==$_collectionSize){echo 'class="last"';} ?> >
        <?php contentBlock('top') ?>
        <div id="cont_<?php echo $i;?>">
            <h3 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>"><?php echo $this->htmlEscape($_product->getName()) ?></a></h3>
            <a class="product-image" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>">
                <img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(122, 109); ?>" width="122" height="109" alt="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" />
            </a>
            <div class="a-center">
                <?php if($_product->getRatingSummary()): ?>
                    <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
                <?php endif; ?>
                <?php echo $this->getPriceHtml($_product, true) ?>
                <?php if($_product->isSaleable()): ?>
                    <button class="button" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><span><?php echo $this->__('Add to Cart') ?></span></span></span></button>
                    <div class="clear"></div>
                <?php else: ?>
                    <p class="availability"><span class="out-of-stock"><?php echo $this->__('Out of stock') ?></span></p>
                    <div class="clear"></div>
                <?php endif; ?>
                <ul class="add-to-links">
                    <?php if ($this->helper('wishlist')->isAllow()) : ?>
                        <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>"><?php echo $this->__('Add to Wishlist') ?></a></li>
                    <?php endif; ?>
                    <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
                        <li class="last"><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>"><?php echo $this->__('Add to Compare') ?></a></li>
                    <?php endif; ?>
                </ul>
                <?php if($_product->getevent_date()) {echo $_product->getevent_date();} ?>
            </div>
        </div>
    </td>
    <?php if ($i%3==0 or $i==$_collectionSize): ?>
   </tr>
    <?php endif ?>
  <?php $i++; endforeach; $kol = $_collectionSize; ?>
</table>
<?php endif; ?>
</code>```

Step 3: This above files will create a list of best selling products which can be shown anywhere on your Magento store. All you have to do is place the following line of code block in your template to show the best selling products.

```<code>{{block type="catalog/product_bestseller" template="catalog/product/bestseller.phtml"}}
</code>```

Now we are able to show best selling products anywhere in our Magento store.

Title: Get list of top ordered products

Body:
im tring to get the top products that are ordered and the quantity, but i notice that is giving me the sold products and not the ordered products that should be more, what is wrong with this code? Why is not showing the right results?

set_time_limit(0);
ini_set('memory_limit', '8000M');

require '../app/Mage.php';
umask(0);
Mage::app();
Mage::register('isSecureArea', 1);
function getBestsellingProducts()
{
    // number of products to display
    $productCount = 400;

    // store ID
    $storeId    = Mage::app()->getStore()->getId();

    // get today and last 30 days time
    $today = time();
    $last = $today - (60*60*24*30);

    $from = date("Y-m-d", $last);
    $to = date("Y-m-d", $today);

    // get most view ed products for current category
    $products = Mage::getResourceModel('reports/product_collection')
                    ->addAttributeToSelect('*')
                    ->addOrderedQty($from, $to)
                    //->setStoreId($storeId)
                    //->addStoreFilter($storeId)
                    ->setOrder('ordered_qty', 'desc')
                    ->setPageSize($productCount);

    Mage::getSingleton('catalog/product_status')
            ->addVisibleFilterToCollection($products);
    Mage::getSingleton('catalog/product_visibility')
            ->addVisibleInCatalogFilterToCollection($products);

    return $products;
}

$products = getBestsellingProducts();

foreach ($products as $key => $value) {

    $pro = Mage::getModel('catalog/product')->load($value->getId());
    echo $pro->getName() ." - ". $pro->getSku() . " - " . $value->ordered_qty . "
";
}

Body:
Follow the below steps to get  top ordered products:

Step 1: Create a file app/code/local/Mage/Catalog/Block/Product/Bestseller.php and the following lines of code in it

lass Mage_Catalog_Block_Product_Bestseller extends Mage_Catalog_Block_Product_Abstract{
    public function __construct(){
        parent::__construct();
        $storeId = Mage::app()->getStore()->getId();
        $products = Mage::getResourceModel('reports/product_collection')
            ->addOrderedQty()
            ->addAttributeToSelect('*')
            ->addAttributeToSelect(array('name', 'price', 'small_image'))
            ->setStoreId($storeId)
            ->addStoreFilter($storeId)
            ->setOrder('ordered_qty', 'desc'); // most best sellers on top
        Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($products);
        Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($products);

        $products->setPageSize(3)->setCurPage(1);
        $this->setProductCollection($products);
    }
}

Step 2: Create a file app/design/frontend/default/YourTheme/template/catalog/product/bestseller.phtml file and add the following lines of code in it

<?php if (($_products = $this->getProductCollection()) && $_products->getSize()): ?>
<div class="page-title">
    <h2><?php echo $this->__('Best Seller Products') ?></h2>
</div>
<?php $_collectionSize = count($_products->getItems()) ?>
<table class="products-grid" id="products-grid-table">
<?php $i=1; foreach ($_products->getItems() as $_product): ?>
    <?php if ($i%1!==0): ?>
    <tr>
    <?php endif ?>
        <td id="td_<?php echo $i;?>" <?php if($i%3==0 or $i==$_collectionSize){echo 'class="last"';} ?> >
        <?php contentBlock('top') ?>
        <div id="cont_<?php echo $i;?>">
            <h3 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>"><?php echo $this->htmlEscape($_product->getName()) ?></a></h3>
            <a class="product-image" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>">
                <img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(122, 109); ?>" width="122" height="109" alt="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" />
            </a>
            <div class="a-center">
                <?php if($_product->getRatingSummary()): ?>
                    <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
                <?php endif; ?>
                <?php echo $this->getPriceHtml($_product, true) ?>
                <?php if($_product->isSaleable()): ?>
                    <button class="button" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><span><?php echo $this->__('Add to Cart') ?></span></span></span></button>
                    <div class="clear"></div>
                <?php else: ?>
                    <p class="availability"><span class="out-of-stock"><?php echo $this->__('Out of stock') ?></span></p>
                    <div class="clear"></div>
                <?php endif; ?>
                <ul class="add-to-links">
                    <?php if ($this->helper('wishlist')->isAllow()) : ?>
                        <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>"><?php echo $this->__('Add to Wishlist') ?></a></li>
                    <?php endif; ?>
                    <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
                        <li class="last"><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>"><?php echo $this->__('Add to Compare') ?></a></li>
                    <?php endif; ?>
                </ul>
                <?php if($_product->getevent_date()) {echo $_product->getevent_date();} ?>
            </div>
        </div>
    </td>
    <?php if ($i%3==0 or $i==$_collectionSize): ?>
   </tr>
    <?php endif ?>
  <?php $i++; endforeach; $kol = $_collectionSize; ?>
</table>
<?php endif; ?>

Step 3: This above files will create a list of best selling products which can be shown anywhere on your Magento store. All you have to do is place the following line of code block in your template to show the best selling products.

{{block type="catalog/product_bestseller" template="catalog/product/bestseller.phtml"}}

Now we are able to show best selling products anywhere in our Magento store.


问:
I cheated to make redux work, how does this work?
So I'm learning react but I am no javascript fan so I'm using typescript. Because of that I try to type things but it seems like using any is always the cheat way out. Here's my container:

```<code>interface UserProfileRouteProps {
  userId: string
}

export function mapStateToProps(state: StoreState, props: RouteComponentProps<UserProfileRouteProps>) {
  let userId: number = parseInt(props.match.params.userId)
  const user = state.users.find(u => u.id === userId)

  return {
    id: userId,
    name: user.name,
    foo: user.foo
  }
}

export function mapDispatchToProps(dispatch: Dispatch<actions.UserProfileActions>, props: RouteComponentProps<UserProfileRouteProps>) {
    let userId: number = parseInt(props.match.params.userId)
  return {
    onFoo: () => dispatch(actions.foo()),
    onDelete: () => dispatch(actions.delete(recipeId))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(UserProfile as any)
</code>```

Here's the component

```<code>export interface UserProfileProps{
  id: number
  name: string
  foo: IFoo
  onFoo?: () => void
  onDelete?: () => void
}

export class UserProfile extends React.Component<UserProfileProps, void>{
</code>```

Now I wanted my mapStateToProps and mapDispatchToProps to be strongly-typed and have a return type of UserProfileProps but I couldn't do that because connect() threw an error:

error TS2345: Argument of type 'typeof UserProfile' is not assignable to parameter of type 'ComponentType<UserProfileProps & { onFoo: () => { type: string; }; onDelete: () => ...'

so my cheat after googling was to go UserProfile as any.

What's actually happening here? Am I doing this right? Should I have separate container props and component props? I was trying to make the component unaware of the routing.

答:
you can use the generic form of connect</p>

```<code>export default connect<{}, {}, UserProfileProps>(
    mapStateToProps,
    mapDispatchToProps
)(UserProfile);
</code>```

Body:
So I'm learning react but I am no javascript fan so I'm using typescript. Because of that I try to type things but it seems like using any is always the cheat way out. Here's my container:

interface UserProfileRouteProps {
  userId: string
}

export function mapStateToProps(state: StoreState, props: RouteComponentProps<UserProfileRouteProps>) {
  let userId: number = parseInt(props.match.params.userId)
  const user = state.users.find(u => u.id === userId)

  return {
    id: userId,
    name: user.name,
    foo: user.foo
  }
}

export function mapDispatchToProps(dispatch: Dispatch<actions.UserProfileActions>, props: RouteComponentProps<UserProfileRouteProps>) {
    let userId: number = parseInt(props.match.params.userId)
  return {
    onFoo: () => dispatch(actions.foo()),
    onDelete: () => dispatch(actions.delete(recipeId))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(UserProfile as any)

Here's the component

export interface UserProfileProps{
  id: number
  name: string
  foo: IFoo
  onFoo?: () => void
  onDelete?: () => void
}

export class UserProfile extends React.Component<UserProfileProps, void>{

Now I wanted my mapStateToProps and mapDispatchToProps to be strongly-typed and have a return type of UserProfileProps but I couldn't do that because connect() threw an error:

error TS2345: Argument of type 'typeof UserProfile' is not assignable to parameter of type 'ComponentType<UserProfileProps & { onFoo: () => { type: string; }; onDelete: () => ...'

so my cheat after googling was to go UserProfile as any.

What's actually happening here? Am I doing this right? Should I have separate container props and component props? I was trying to make the component unaware of the routing.

Body:
you can use the generic form of connect

export default connect<{}, {}, UserProfileProps>(
    mapStateToProps,
    mapDispatchToProps
)(UserProfile);


问:
WebExtensions: is it possible to intercept/register a handler with the "file open" dialogs?
I have a Web Extension that occasionally deals in files -- usually by sending off a URL to the file to a remote server or by downloading the file at the user's request and shipping off the bytes to the same server.

This works fine for most use-cases, but sometimes you'll come across a site that automatically triggers a download of a file and pops open the file-open dialog for the user to handle. I wasn't able to find any documentation or filed bugs to this effect, but is there a way to register an extension to appear as a handler in that dialog?

答:
Its currently not possible to add an icon to the file chooser dialog with WebExtensions. Feel free to open a feature request here: http://bugzilla.mozilla.org/

If you want to handle an action whenever a download occurs, you can use
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/downloads/onCreated


问:
How can i get Client Webpage cookie information through javascript
I want to get the browser cookies information like email or name.

pls help me

答:
Though this cookie method is in the context of jQuery, the actual JS is regular JS, aside from a jQuery.trim method (which you can a substitution at crockford's site.  Overall, it's a good way to set/get/delete cookies.

This cookie method is also jquery-dependent, especially with the jQuery.extend (whole different story than the jQuery.trim method), but it looks much more succinct than the other cookie method. I haven't personally used this one, so i can't speak much for it.


问:
How do I strip down a URL into separate parts in Bash?
I have a URL (https://example.com/someone/something) that I'd like to strip down into three variables:

https://example.com/

someone

something

I'm wondering how I can do this in Bash using grep or awk or some other tool.

To clarify, I'm not asking if there's a way to get all three variables at one go. It's perfectly fine to run three separate commands for each variable. Something like,

```<code>URL="https://example.com/someone/something"

DOMAIN=$(echo ${URL} | <some wizardry here>)

USER=$(echo ${URL} | <some wizardry here>)

THING=$(echo ${URL} | <some wizardry here>)
</code>```

答:
Try this:</p>

```<code>$ URL="https://example.com/someone/something"
$ IFS=' ' read DOMAIN USER THING <<< $(sed 's|/| |3g' <<< ${URL})
$ echo ${DOMAIN}
https://example.com
$ echo ${USER}
someone
$ echo ${THING}
something
</code>```

Body:
I have a URL (https://example.com/someone/something) that I'd like to strip down into three variables:

https://example.com/

someone

something

I'm wondering how I can do this in Bash using grep or awk or some other tool.

To clarify, I'm not asking if there's a way to get all three variables at one go. It's perfectly fine to run three separate commands for each variable. Something like,

URL="https://example.com/someone/something"

DOMAIN=$(echo ${URL} | <some wizardry here>)

USER=$(echo ${URL} | <some wizardry here>)

THING=$(echo ${URL} | <some wizardry here>)

Body:
Try this:

$ URL="https://example.com/someone/something"
$ IFS=' ' read DOMAIN USER THING <<< $(sed 's|/| |3g' <<< ${URL})
$ echo ${DOMAIN}
https://example.com
$ echo ${USER}
someone
$ echo ${THING}
something


问:
Set table view cell height by identifier - Swift
I am trying to set the height of each cell in the table view depending on the identifier. I do not want to use indexPath.row, because the i am filling the cell from an array containing a flag for each type of cell and the order is random. Exactly 3 types of cells.

I used this code but it causing an error:

```<code>func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    let cell = tableV.cellForRow(at: indexPath)
    if(cell?.reuseIdentifier == "homeFeaturedR"){
        return 200
    }else{
       return 360
    }
}
</code>```

The error is at this line:

```<code>let cell = tableV.cellForRow(at: indexPath)
</code>```

Thank you.

答:
Your heightForRowAt method is called before cellForRowAt. This means that by the time heightForRowAt is called, the cell at that index path is not yet created. Therefore, you can't access its reuseIdentifier or anything like that.

This means that instead of trying to figure out what height to return by looking at the cell, you should try to figure out the height using your model.

Dynamic table views ought to have a datasource/model. Your table view should have one as well. Look at your cellForRowAtIndexPath method, under what conditions do you dequeue a cell with the identifier homeFeatureR? It is most likely an if statement checking something:

```<code>if someCondition {
    let cell = tableView.dequeueReusableCell(withIdentifier: "homeFeatureR")!
    // set properties
    return cell
}
</code>```

Now, you can just check if someCondition is true, if it is true, that means the cell's identifier must be "homeFeatureR", which means you should return 200.

```<code>if someCondition {
    return 200
} else {
    return 360
}
</code>```

Body:
I am trying to set the height of each cell in the table view depending on the identifier. I do not want to use indexPath.row, because the i am filling the cell from an array containing a flag for each type of cell and the order is random. Exactly 3 types of cells.

I used this code but it causing an error:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    let cell = tableV.cellForRow(at: indexPath)
    if(cell?.reuseIdentifier == "homeFeaturedR"){
        return 200
    }else{
       return 360
    }
}

The error is at this line:

let cell = tableV.cellForRow(at: indexPath)

Thank you.

Body:
Your heightForRowAt method is called before cellForRowAt. This means that by the time heightForRowAt is called, the cell at that index path is not yet created. Therefore, you can't access its reuseIdentifier or anything like that.

This means that instead of trying to figure out what height to return by looking at the cell, you should try to figure out the height using your model.

Dynamic table views ought to have a datasource/model. Your table view should have one as well. Look at your cellForRowAtIndexPath method, under what conditions do you dequeue a cell with the identifier homeFeatureR? It is most likely an if statement checking something:

if someCondition {
    let cell = tableView.dequeueReusableCell(withIdentifier: "homeFeatureR")!
    // set properties
    return cell
}

Now, you can just check if someCondition is true, if it is true, that means the cell's identifier must be "homeFeatureR", which means you should return 200.

if someCondition {
    return 200
} else {
    return 360
}


问:
select data from two tables
I have two tables Accountdetails and Accounts

Accountdetails consists of columns AD_ID, AD_Name, AD_AccNo

Accounts consists of Columns A_Name, A_AccNo, A_AccDate

My question is I wanted to select data based on the AD_AccNo and A_AccNo being equal

I tried using this query

```<code>select AD.AD_ID, a.A_Name, a.A_AccNo, a.A_AccDate
from Accountdetails as AD, Accounts as a
where AD.AD_AccNo = a.A_AccNo
</code>```

Can anyone suggest me the place where i am going wrong?

答:
```<code>SELECT ad.AD_ID,
       ad.AD_Name,
       ad.AD_AccNo,
       a.A_Name,
       a.A_AccNo,
       a.A_AccDate
FROM Accountdetails ad
INNER JOIN Accounts a
ON ad.AD_AccNo = a.A_AccNo
</code>```

Title: select data from two tables

Body:
I have two tables Accountdetails and Accounts

Accountdetails consists of columns AD_ID, AD_Name, AD_AccNo

Accounts consists of Columns A_Name, A_AccNo, A_AccDate

My question is I wanted to select data based on the AD_AccNo and A_AccNo being equal

I tried using this query

select AD.AD_ID, a.A_Name, a.A_AccNo, a.A_AccDate
from Accountdetails as AD, Accounts as a
where AD.AD_AccNo = a.A_AccNo

Can anyone suggest me the place where i am going wrong?


问:
Can I use a directory to contains a couples app directory?
Can I use a directory to contains a couples app directory?
I mean, my project is very large, and there are many apps in my project.
such as apps about admin user, apps about normal user, apps about frontend, apps about ...

So, my project is very clutter, I want to use a group directory to wrap the related apps into it.

I don't know whether this idea is feasible. some friend can help me with this? is there should take care of some other things?

The snapshot red framework is a group apps. I want to group them, who can help me with this?

答:
I assume that probably you are using one of the latest versions of Django.

In my case I like to create a folder called apps to keep the project more organized.

This is my project structure example:

and then I am doing this in the settings.py file:

```<code>BASE_DIR = os.path.dirname(os.path.abspath(__file__))
PARENT_DIR = os.path.abspath(os.path.join(BASE_DIR, os.pardir))
sys.path.insert(0, os.path.join(PARENT_DIR, 'apps'))
</code>```

So, I think you could do something similar creating multiple folders to organize your custom apps.

I hope it make sense.

Body:
I assume that probably you are using one of the latest versions of Django.

In my case I like to create a folder called apps to keep the project more organized.

This is my project structure example:

and then I am doing this in the settings.py file:

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
PARENT_DIR = os.path.abspath(os.path.join(BASE_DIR, os.pardir))
sys.path.insert(0, os.path.join(PARENT_DIR, 'apps'))

So, I think you could do something similar creating multiple folders to organize your custom apps.

I hope it make sense.


问:
How to start Kong?
I am getting following error, when I tried to start Kong in Ubuntu

```<code>kong start [-c /path/to/kong.conf]
prefix directory /usr/local/kong not found, trying to create it
2017/11/05 21:11:41 [warn] ulimit is currently set to "1024". For better performance set it to at least "4096" using "ulimit -n"
Error: /usr/local/share/lua/5.1/pgmoon/init.lua:271: missing password, required for connect
</code>```

Am I missing anything?

答:
on your psql run the following.

CREATE USER kong; CREATE DATABASE kong OWNER kong;
ALTER USER kong WITH PASSWORD 'password';

create a kong.config with following content.

pg_user = kong
pg_password = password

Run the migration and start kong (might require sudo)

$ kong migrations up -c kong.config
$ kong start -c kong.config

Title: How to start Kong?

Body:
I am getting following error, when I tried to start Kong in Ubuntu

kong start [-c /path/to/kong.conf]
prefix directory /usr/local/kong not found, trying to create it
2017/11/05 21:11:41 [warn] ulimit is currently set to "1024". For better performance set it to at least "4096" using "ulimit -n"
Error: /usr/local/share/lua/5.1/pgmoon/init.lua:271: missing password, required for connect

Am I missing anything?


问:
C# Get video file duration from metadata
I am trying to read metadata from a file.  I only need the Video -> Length property, however I am unable to find a simple way of reading this information.

I figured this would be fairly easy since it is visible by default in Explorer, however this looks to be way more complicated than I anticipated. The closest I came was using:

```<code>Microsoft.DirectX.AudioVideoPlayback.Video video = new Microsoft.DirectX.AudioVideoPlayback.Video(str);
double duration = video.Duration;
</code>```

However this throws a LoaderLock exception, and I don't know how to deal with it.

Any ideas?

答:
It seems that I am posting, what I have tried, so late. Hope it will help someone.

I have tried to get the video length in a bit different way by sing Windows Media Player Component.

Following code snippet may help you guys :

```<code>using WMPLib;
// ...your code here...

var player = new WindowsMediaPlayer();
var clip = player.newMedia(filePath);
Console.WriteLine(TimeSpan.FromSeconds(clip.duration));
</code>```

and don't forget to add the reference of wmp.dll which will be
  present in System32 folder.

Body:
I am trying to read metadata from a file.  I only need the Video -> Length property, however I am unable to find a simple way of reading this information.

I figured this would be fairly easy since it is visible by default in Explorer, however this looks to be way more complicated than I anticipated. The closest I came was using:

Microsoft.DirectX.AudioVideoPlayback.Video video = new Microsoft.DirectX.AudioVideoPlayback.Video(str);
double duration = video.Duration;

However this throws a LoaderLock exception, and I don't know how to deal with it.

Any ideas?

Body:
It seems that I am posting, what I have tried, so late. Hope it will help someone.

I have tried to get the video length in a bit different way by sing Windows Media Player Component.

Following code snippet may help you guys :

using WMPLib;
// ...your code here...

var player = new WindowsMediaPlayer();
var clip = player.newMedia(filePath);
Console.WriteLine(TimeSpan.FromSeconds(clip.duration));

and don't forget to add the reference of wmp.dll which will be
  present in System32 folder.


问:
How to add an element to arrayList when calling the method at the same time?
I am doing a recursive program and I want to call a method 2 times in a row, which looks like this:

```<code>print(ArrayList<Integer> current + arr[0], Arrays.copyOfRange(arr, 1, arr.length) );
print(ArrayList<Integer> current, Arrays.copyOfRange(arr, 1, arr.length));
</code>```

But it is impossible to add a value to the ArrayList like that. However, I can't use current.add() outside either, because it will mess up my second call.
So is there a way to add a value to the arrayList while calling the method, or do I have to think of another way to write my code?

答:
You can achieve it with following code</p>

```<code>print(new ArrayList<Integer>(current) {{ add(arr[0]); }},
      Arrays.copyOfRange(arr, 1, arr.length) );
</code>```

Body:
I am doing a recursive program and I want to call a method 2 times in a row, which looks like this:

print(ArrayList<Integer> current + arr[0], Arrays.copyOfRange(arr, 1, arr.length) );
print(ArrayList<Integer> current, Arrays.copyOfRange(arr, 1, arr.length));

But it is impossible to add a value to the ArrayList like that. However, I can't use current.add() outside either, because it will mess up my second call.
So is there a way to add a value to the arrayList while calling the method, or do I have to think of another way to write my code?

Body:
You can achieve it with following code

print(new ArrayList<Integer>(current) {{ add(arr[0]); }},
      Arrays.copyOfRange(arr, 1, arr.length) );


问:
Laravel blade duplicating multiple buttons
I'm trying to show only one close button if a post belongs to a user by using utilize blade authentication however im getting this

The policy and server side runs ok and i can click the button and it will do as i need it to do, but i only need to see one close button for each post, however maybe im compacting the posts incorrectly.

html

```<code> <div id="mypost" class="col-md-8 panel-default" ng-repeat="post in myposts">
        <div id="eli-style-heading" class="panel-heading"><% post.title %></div>
            <div class="panel-body panel">
                <figure>
                    <p> <% post.body %></p>
                   <p> by: <% post.user.name %></p>
                   <p>  <% post.created_at %></p>

                </figure>
                <span>

            @foreach($posts as $post)
                @if(Auth::user()->can('delete',$post))
                 <i style="color:red;" class="glyphicon glyphicon-remove" ng-click="deletePost(post)"></i>
                @endif
            @endforeach

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

PostController.php (the view for the posts page)

```<code>public function index()
{

    $posts = Post::with('user')->get();

    return view('home', compact('posts'));

}
</code>```

答:
I don't know anything about php so i am writing simple text only

Its because you are using foreach inside ng-repeat
 Change

```<code>@foreach($posts as $post)// this is the problem
                @if(Auth::user()->can('delete',$post))
                 <i style="color:red;" class="glyphicon glyphicon-remove" ng-click="deletePost(post)"></i>
                @endif
            @endforeach
</code>```

to

```<code>@foreach($posts as $post)
                @if(Auth::user()->can('delete',$post) && here add some condition like  $post.id(php)==post.id(angular))
                 <i style="color:red;" class="glyphicon glyphicon-remove" ng-click="deletePost(post)"></i>
                @endif
            @endforeach
</code>```

Or

```<code>@if(userIsAuthrise){
 <i style="color:red;" class="glyphicon glyphicon-remove" ng-click="deletePost(post)"></i>
}
</code>```

Body:
I'm trying to show only one close button if a post belongs to a user by using utilize blade authentication however im getting this

The policy and server side runs ok and i can click the button and it will do as i need it to do, but i only need to see one close button for each post, however maybe im compacting the posts incorrectly.

html

<% post.title %>

 <% post.body %>

 by: <% post.user.name %>

  <% post.created_at %>

            @foreach($posts as $post)
                @if(Auth::user()->can('delete',$post))

                @endif
            @endforeach

PostController.php (the view for the posts page)

public function index()
{

    $posts = Post::with('user')->get();

    return view('home', compact('posts'));

}

Body:
I don't know anything about php so i am writing simple text only

Its because you are using foreach inside ng-repeat
 Change

@foreach($posts as $post)// this is the problem
                @if(Auth::user()->can('delete',$post))
                 <i style="color:red;" class="glyphicon glyphicon-remove" ng-click="deletePost(post)"></i>
                @endif
            @endforeach

to

@foreach($posts as $post)
                @if(Auth::user()->can('delete',$post) && here add some condition like  $post.id(php)==post.id(angular))
                 <i style="color:red;" class="glyphicon glyphicon-remove" ng-click="deletePost(post)"></i>
                @endif
            @endforeach

Or

@if(userIsAuthrise){
 <i style="color:red;" class="glyphicon glyphicon-remove" ng-click="deletePost(post)"></i>
}


问:
How to skip executing a single service with docker-compose?
I have docker-compose.yml file with a set of services inside. In some cases for development I want docker not to start on of services which is a helper one when I run docker-compose up.

Is it possible to do and if so, how to?

答: I suppose this is still not implemented yet, see the discussion here.</p>