问:
sharepoint SPFarm.local.GetObject return null
I installed sharepoint foundation 2010  (in 'Standalone' type) on windows 2012 r2.

And I created a windows app project.
When Load , New Counter(farm) is success.

But, SPFarm.local.GetObject return null;

Does someone konw the reason,please help me.

source like this:

```<code>//-------source start-------

//Counter.cs
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Microsoft.SharePoint;

using Microsoft.SharePoint.Administration;

namespace WinAppTest
{

    class Counter : SPPersistedObject
    {
         public static String SettingName = "Counter";

         public static String SettingGuid = "62648e50-8aee-42b2-b074-2f49ced85587";

         [Persisted]

         public String name;

         [Persisted]

         public String count;

         public Counter()

         {

         }

         public Counter(SPPersistedObject parent)

         : base(SettingName, parent, new Guid(SettingGuid))

         {

         }

    }

}
</code>```

// Form1.cs

```<code>using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using Microsoft.SharePoint.Administration;

namespace WinAppTest
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void Write_Click(object sender, EventArgs e)
        {
            SPFarm farm = SPFarm.Local;
            //------- *conf is null*-----
            Counter conf = (Counter)farm.GetObject(new Guid(Counter.SettingGuid));
            //------- *conf is null*-----
            conf.Name = "pf1";
            conf.count = "1";
            conf.Update();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SPFarm farm = SPFarm.Local;
            Counter conf = (Counter)farm.GetObject(new Guid(Counter.SettingGuid));
            if (conf == null)
            {
                conf = new Counter(farm);
            }
            //------- *conf is null*-----
            conf = (Counter)farm.GetObject(new Guid(Counter.SettingGuid));
            //------- *conf is null*-----

            String name = conf.name;
            String count = conf.count;
        }
    }
}
</code>```

答:
Finally , I think the source has error in it.

modify like this, It's OK.

```<code>private void Write_Click(object sender, EventArgs e)
        {
            SPFarm farm = SPFarm.Local;

            Counter conf = (Counter)farm.GetObject(new Guid(Counter.SettingGuid));

            if (conf == null)
            {
                conf = new Counter(farm);
            }
            conf.Name = "pf1";
            conf.count = "1";
            conf.Update();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SPFarm farm = SPFarm.Local;
            Counter conf = (Counter)farm.GetObject(new Guid(Counter.SettingGuid));

            String name = conf.name;
            String count = conf.count;
        }
</code>```

Body:
I installed sharepoint foundation 2010  (in 'Standalone' type) on windows 2012 r2.

And I created a windows app project.
When Load , New Counter(farm) is success.

But, SPFarm.local.GetObject return null;

Does someone konw the reason,please help me.

source like this:

//-------source start-------

//Counter.cs
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Microsoft.SharePoint;

using Microsoft.SharePoint.Administration;

namespace WinAppTest
{

    class Counter : SPPersistedObject
    {
         public static String SettingName = "Counter";

         public static String SettingGuid = "62648e50-8aee-42b2-b074-2f49ced85587";

         [Persisted]

         public String name;

         [Persisted]

         public String count;

         public Counter()

         {

         }

         public Counter(SPPersistedObject parent)

         : base(SettingName, parent, new Guid(SettingGuid))

         {

         }

    }

}

// Form1.cs

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using Microsoft.SharePoint.Administration;

namespace WinAppTest
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void Write_Click(object sender, EventArgs e)
        {
            SPFarm farm = SPFarm.Local;
            //------- *conf is null*-----
            Counter conf = (Counter)farm.GetObject(new Guid(Counter.SettingGuid));
            //------- *conf is null*-----
            conf.Name = "pf1";
            conf.count = "1";
            conf.Update();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SPFarm farm = SPFarm.Local;
            Counter conf = (Counter)farm.GetObject(new Guid(Counter.SettingGuid));
            if (conf == null)
            {
                conf = new Counter(farm);
            }
            //------- *conf is null*-----
            conf = (Counter)farm.GetObject(new Guid(Counter.SettingGuid));
            //------- *conf is null*-----

            String name = conf.name;
            String count = conf.count;
        }
    }
}

Body:
Finally , I think the source has error in it.

modify like this, It's OK.

private void Write_Click(object sender, EventArgs e)
        {
            SPFarm farm = SPFarm.Local;

            Counter conf = (Counter)farm.GetObject(new Guid(Counter.SettingGuid));

            if (conf == null)
            {
                conf = new Counter(farm);
            }
            conf.Name = "pf1";
            conf.count = "1";
            conf.Update();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SPFarm farm = SPFarm.Local;
            Counter conf = (Counter)farm.GetObject(new Guid(Counter.SettingGuid));

            String name = conf.name;
            String count = conf.count;
        }


来源: stackexchange

问:
WordPress contact 7 with negative response
I have created a website using WordPress. I use a GoDaddy hosting and a plugin WP-Mail-SMTP, which helps me to configure SMTP. I have disable all cache plugins.

Right now I have a problem with my contact form (plugin Contact form 7). When I fill all fields and click a submit button, I get messages: "There was an error trying to send your message. Please try again later."

I get next JSON answer from my server:

```<code>captcha:null
into:"#wpcf7-f31-p1401-o1"
mailSent: false
message: "There was an error trying to send your message. Please try again later."
</code>```

I receive emails from this forms, but I can not fix issues with server response and negative answers under my form: https://www.screencast.com/t/ReyXMwJLRS.  I try to disable/enable captcha, but it does not help.

Can somebody advice with this. I have checked all recommendation from https://contactform7.com/, but can not find a solution.

Best regards.

答: Make sure the mail on the contact form is added as an authorized email sender on your hosting server.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have created a website using WordPress. I use a GoDaddy hosting and a plugin WP-Mail-SMTP, which helps me to configure SMTP. I have disable all cache plugins.

Right now I have a problem with my contact form (plugin Contact form 7). When I fill all fields and click a submit button, I get messages: "There was an error trying to send your message. Please try again later."

I get next JSON answer from my server:

captcha:null
into:"#wpcf7-f31-p1401-o1"
mailSent: false
message: "There was an error trying to send your message. Please try again later."

I receive emails from this forms, but I can not fix issues with server response and negative answers under my form: https://www.screencast.com/t/ReyXMwJLRS.  I try to disable/enable captcha, but it does not help.

Can somebody advice with this. I have checked all recommendation from https://contactform7.com/, but can not find a solution.

Best regards.


问:
Rock,paper, scissor python
Im learning python and coding a rock, paper, and scissor game. I'm able to run the program but each time the program goes through the nested if,elif,else statement, the output continues to be  the outer else statement no matter what the value of  humplayer variable is. Any help?

Thank you!

```<code>    import random
def main():
    playerName=introduction()
    humplayer=hum_player()
    compchoice=com_player()
    tieScore = 0
    humScore=0
    comScore=0
    humplayer=input("Enter your move (0 for Rock, 1 for Paper, and 2 for Scissors): ")
    while humplayer != -1:
        compchoice=com_player()
        result= evaluate_Game(humplayer,compchoice,playerName)
        if result==0:
            print("It's a tie!")
            tieScore+=1
        elif result==1:
            comScore+=1
        else:
            humScore+=1
        humplayer=input("Enter your move (0 for Rock, 1 for Paper, and 2 for Scissors): ")
    print(statistics(playerName,humScore,comScore,tieScore))

def introduction():
    print("Welcome to the game of Rock, Paper, Scissors. You will be playing against the computer.")
    name= input("What is your name? ")
    print("Here are the rules", name+":")
    print(" If a player chooses Rock and the other chooses Scissors, Rock wins.")
    print(" If a player chooses Scissors and the other chooses Paper, Scissors wins.")
    print(" If a player chooses Paper and the other chooses Rock, Paper wins.")
    print(" If both players make the same choice, it's a tie.")
    print(" Enter -1 to quit the game ")
    return name

def hum_player():
          choice = int(input("Enter your move (0 for Rock, 1 for Paper, and 2 for Scissors): "))
          return choice

def com_player():
          random_Num = random.randint(0,2)
          return(random_Num)

def evaluate_Game(humplayer,compchoice,playerName):
    a = "Rock"
    b="Paper"
    c="Scissors"
    if humplayer==0:
       if compchoice==0:
           return 0
       elif compchoice==1:
           print(playerName, "plays ",a," computer plays",b)
           print("Paper covers Rock, Computer wins!")
           return 1
       else:
           print(playerName, "plays",a,"computer plays", c)
           print("Rock crushes Scissors ,", playerName," wins!")
           return 2
    elif humplayer==1:
       if compchoice==0:
           print(name,"plays",b," computer plays", a)
           print("Paper covers Rock.", playerName,"wins!")
           return 2
       elif compchoice==1:
           print(playerName,"plays", b," computer plays" , b)
           print("It's a tie!")
           return 0
       else:
           print(playerName, "plays", b,"computer plays", c)
           print("Scissors cuts Paper. Computer wins!")
           return 1
    else:
        if compchoice==0:
           print(playerName, "plays", c," computer plays", a)
           print("Rock breaks Scissors. Computer wins!")
           return 1
        elif compchoice==1:
           print(playerName, "plays", c, " computer plays", b)
           print("Scissors cuts Paper." , playerName, "wins!")
           return 2
        else:
            print(playerName, "plays", c," computer plays", c)
            print("It's a tie!")
            return 0

def statistics(playerName,humScore,tieScore,comScore):
    print("There were", tieScore+comScore+humscore, "games:", playerName, "won", humScore, "games, the computer won", comScore, "games and there were", tieScore, "ties.")

main()
</code>```

答:
When you re-ask for input from the human, you aren't casting it to an int. Rather than rewriting this line:

```<code>humplayer=input("Enter your move (0 for Rock, 1 for Paper, and 2 for Scissors): ")
</code>```

why don
't you use the function you wrote and do,

```<code>humplayer = hum_player()
</code>```

Although you properly cast to an int in your hum_player() function, you don't in all the other places where you requery. You may as well re-use this function. That is the reason why we write separate functions in the first place (so we don't have to repeat code that we've already written).

And a second thing that is a bit wrong is the way that you are using your statistics() method.

```<code>def statistics(playerName,humScore,tieScore,comScore):
    print("There were", tieScore+comScore+humscore, "games:", playerName, "won", humScore, "games, the computer won", comScore, "games and there were", tieScore, "ties.")
</code>```

As written, this is actually ok. The problem is that you are calling it with

```<code>'print(statistics(...))`
</code>```

The actual statistics method returns None so this print statement, is going to print None (although the actual function call will still print to console). The better way to do is to either just call the method:

```<code>statistics(...)
</code>```

without a print statement, or change you're statistics method to return a string rather than print it.

```<code>def statistics(playerName,humScore,tieScore,comScore):
    return ("There were", tieScore+comScore+humscore, "games:", playerName, "won", humScore, "games, the computer won", comScore, "games and there were", tieScore, "ties.")
</code>```

Title: Rock,paper, scissor python

Body:
Im learning python and coding a rock, paper, and scissor game. I'm able to run the program but each time the program goes through the nested if,elif,else statement, the output continues to be  the outer else statement no matter what the value of  humplayer variable is. Any help?

Thank you!

    import random
def main():
    playerName=introduction()
    humplayer=hum_player()
    compchoice=com_player()
    tieScore = 0
    humScore=0
    comScore=0
    humplayer=input("Enter your move (0 for Rock, 1 for Paper, and 2 for Scissors): ")
    while humplayer != -1:
        compchoice=com_player()
        result= evaluate_Game(humplayer,compchoice,playerName)
        if result==0:
            print("It's a tie!")
            tieScore+=1
        elif result==1:
            comScore+=1
        else:
            humScore+=1
        humplayer=input("Enter your move (0 for Rock, 1 for Paper, and 2 for Scissors): ")
    print(statistics(playerName,humScore,comScore,tieScore))

def introduction():
    print("Welcome to the game of Rock, Paper, Scissors. You will be playing against the computer.")
    name= input("What is your name? ")
    print("Here are the rules", name+":")
    print(" If a player chooses Rock and the other chooses Scissors, Rock wins.")
    print(" If a player chooses Scissors and the other chooses Paper, Scissors wins.")
    print(" If a player chooses Paper and the other chooses Rock, Paper wins.")
    print(" If both players make the same choice, it's a tie.")
    print(" Enter -1 to quit the game ")
    return name

def hum_player():
          choice = int(input("Enter your move (0 for Rock, 1 for Paper, and 2 for Scissors): "))
          return choice

def com_player():
          random_Num = random.randint(0,2)
          return(random_Num)

def evaluate_Game(humplayer,compchoice,playerName):
    a = "Rock"
    b="Paper"
    c="Scissors"
    if humplayer==0:
       if compchoice==0:
           return 0
       elif compchoice==1:
           print(playerName, "plays ",a," computer plays",b)
           print("Paper covers Rock, Computer wins!")
           return 1
       else:
           print(playerName, "plays",a,"computer plays", c)
           print("Rock crushes Scissors ,", playerName," wins!")
           return 2
    elif humplayer==1:
       if compchoice==0:
           print(name,"plays",b," computer plays", a)
           print("Paper covers Rock.", playerName,"wins!")
           return 2
       elif compchoice==1:
           print(playerName,"plays", b," computer plays" , b)
           print("It's a tie!")
           return 0
       else:
           print(playerName, "plays", b,"computer plays", c)
           print("Scissors cuts Paper. Computer wins!")
           return 1
    else:
        if compchoice==0:
           print(playerName, "plays", c," computer plays", a)
           print("Rock breaks Scissors. Computer wins!")
           return 1
        elif compchoice==1:
           print(playerName, "plays", c, " computer plays", b)
           print("Scissors cuts Paper." , playerName, "wins!")
           return 2
        else:
            print(playerName, "plays", c," computer plays", c)
            print("It's a tie!")
            return 0

def statistics(playerName,humScore,tieScore,comScore):
    print("There were", tieScore+comScore+humscore, "games:", playerName, "won", humScore, "games, the computer won", comScore, "games and there were", tieScore, "ties.")

main()

Body:
When you re-ask for input from the human, you aren't casting it to an int. Rather than rewriting this line:

humplayer=input("Enter your move (0 for Rock, 1 for Paper, and 2 for Scissors): ")

why don
't you use the function you wrote and do,

humplayer = hum_player()

Although you properly cast to an int in your hum_player() function, you don't in all the other places where you requery. You may as well re-use this function. That is the reason why we write separate functions in the first place (so we don't have to repeat code that we've already written).

And a second thing that is a bit wrong is the way that you are using your statistics() method.

def statistics(playerName,humScore,tieScore,comScore):
    print("There were", tieScore+comScore+humscore, "games:", playerName, "won", humScore, "games, the computer won", comScore, "games and there were", tieScore, "ties.")

As written, this is actually ok. The problem is that you are calling it with

'print(statistics(...))`

The actual statistics method returns None so this print statement, is going to print None (although the actual function call will still print to console). The better way to do is to either just call the method:

statistics(...)

without a print statement, or change you're statistics method to return a string rather than print it.

def statistics(playerName,humScore,tieScore,comScore):
    return ("There were", tieScore+comScore+humscore, "games:", playerName, "won", humScore, "games, the computer won", comScore, "games and there were", tieScore, "ties.")


问:
recursive array_key_search function PhP
Having this recursive function ($key can be numeric as array(0=>'value1',1=>'value2' or string as array('key1'=>'value1','key2'=>'value2')), being $key,
needle and $array haystack:

```<code> public function array_key_search($searched_key, $array = array()){

         * @param   $searched_key: Key to search.
         *          $array: Array with keys to check.
         * Recursive method to check if a key exists in a multidemensional array.
         * If key exists, it returns corresponding value.
         */

        foreach($array as $key => $value){
            $key = "$key";
            if($key_value == false){
                if($key == $searched_key){
                    return $value;
                }else{
                    if(is_array($value)){
                        $key_value = self::array_key_search($searched_key, $value);
                    }
                }
            }
        }
        $key_value == is_null($key_value) ? false : $key_value;

        return $key_value;
    }
</code>```

May I use if($key === $searched_key) instead of invoking my $key param as string for comparision?

This time I'm talking about performance because this function may be hard to process sometimes.

答:
This does what you want

```<code>$arr = [
  'key1' => [
    'key1.1' => [
      'key1.1.1' => 'key1.1.1',
      'key1.1.2' => 'key1.1.2'
    ],
    'key1.2' => [
      'key1.2.1' => 'key1.2.1',
      'key1.2.2' => 'key1.2.2'
    ],
  ],
  'key2' => [
    'key2.1' => [
      'key2.1.1' => 'key2.1.1',
      'key2.1.2' => 'key2.1.2'
    ]
  ]
];

function get_key_val($search_key, $arr){
  foreach($arr as $key => $value){
    if( is_array($value) ){
      $result = get_key_val($search_key, $value);
      if ($result){
        return $result;
      }
    }else{
      if ($search_key == $key){
       return $value;
      }
    }
  }
  return null;
}

var_dump(get_key_val('key2.1.2', $arr));
</code>```

RETURNS

```<code>string(8) "key2.1.2"
</code>```

Title: recursive array_key_search function PhP

Body:
Having this recursive function ($key can be numeric as array(0=>'value1',1=>'value2' or string as array('key1'=>'value1','key2'=>'value2')), being $key,
needle and $array haystack:

 public function array_key_search($searched_key, $array = array()){

         * @param   $searched_key: Key to search.
         *          $array: Array with keys to check.
         * Recursive method to check if a key exists in a multidemensional array.
         * If key exists, it returns corresponding value.
         */

        foreach($array as $key => $value){
            $key = "$key";
            if($key_value == false){
                if($key == $searched_key){
                    return $value;
                }else{
                    if(is_array($value)){
                        $key_value = self::array_key_search($searched_key, $value);
                    }
                }
            }
        }
        $key_value == is_null($key_value) ? false : $key_value;

        return $key_value;
    }

May I use if($key === $searched_key) instead of invoking my $key param as string for comparision?

This time I'm talking about performance because this function may be hard to process sometimes.

Body:
This does what you want

$arr = [
  'key1' => [
    'key1.1' => [
      'key1.1.1' => 'key1.1.1',
      'key1.1.2' => 'key1.1.2'
    ],
    'key1.2' => [
      'key1.2.1' => 'key1.2.1',
      'key1.2.2' => 'key1.2.2'
    ],
  ],
  'key2' => [
    'key2.1' => [
      'key2.1.1' => 'key2.1.1',
      'key2.1.2' => 'key2.1.2'
    ]
  ]
];

function get_key_val($search_key, $arr){
  foreach($arr as $key => $value){
    if( is_array($value) ){
      $result = get_key_val($search_key, $value);
      if ($result){
        return $result;
      }
    }else{
      if ($search_key == $key){
       return $value;
      }
    }
  }
  return null;
}

var_dump(get_key_val('key2.1.2', $arr));

RETURNS

string(8) "key2.1.2"


问:
How do I create a Json::Value::ArrayIndex in c++?
I want to use a pair of two strings as a key, for example

```<code>{(key1, key2): value}
</code>```

I tried

```<code>std::string key1, key2, value;
Json::Value p;
p.append(key1);
p.append(key2);
dict[p] = value;
</code>```

But the compiler complained there is no viable operator[].

I also tried

```<code>dict[Json::Value::ArrayIndex(p)] = value;
</code>```

But the compiler complained there is no viable way of converting.

What's more, declaring p as Json::Value::ArrayIndex in the first place will prevent me from using append altogether.

So, what is the right way to use an array as a key for my dictionary?

答:
Only strings are valid keys in JSON.

Please consider concatenating the two keys to string, and index using it:

```<code>dict[key1.asString()+","+key2.asString()] = value;
</code>```

I'm assuming you're not using some sort of weird keys that contains , in itself, you need to escape them in that case.

Body:
I want to use a pair of two strings as a key, for example

{(key1, key2): value}

I tried

std::string key1, key2, value;
Json::Value p;
p.append(key1);
p.append(key2);
dict[p] = value;

But the compiler complained there is no viable operator[].

I also tried

dict[Json::Value::ArrayIndex(p)] = value;

But the compiler complained there is no viable way of converting.

What's more, declaring p as Json::Value::ArrayIndex in the first place will prevent me from using append altogether.

So, what is the right way to use an array as a key for my dictionary?

Body:
Only strings are valid keys in JSON.

Please consider concatenating the two keys to string, and index using it:

dict[key1.asString()+","+key2.asString()] = value;

I'm assuming you're not using some sort of weird keys that contains , in itself, you need to escape them in that case.


问:
Calling a ptototype function
I am working with a piece of code that I found in another project on the net and I am trying to adapt it to my needs. I wasn't able to find out how this function was originally being called so I am hoping to find some assistance here.

```<code>var gatewayIP = '192.168.10.21',
sock = new WebSocket('ws://' + gatewayIP + ':8000');
sock.binaryType = "arraybuffer";

// Constructor, expects a socket/stream to write device commands
function HTDLync(sock, log) {
    this.sock = sock;
    this.log = log;
}

// Change zone power state ('On', 'Off', '1', or '0')
HTDLync.prototype.setPower = function(zone, power) {

    powerStr = power.toString().toLowerCase();

    var packet = Buffer.from([0x02, 0x00, 0x00, 0x04, 0x58]);
    packet.writeUInt8(this.cleanZone(zone), 2);

    if (powerStr == 'on' || powerStr == '1'){
        packet.writeUInt8(0x57, 4);
    }
    else if (powerStr == 'off' || powerStr == '0'){
        packet.writeUInt8(0x58, 4);
    }
    else {
        this.log.warn('Unknown setPower argument:', powerStr);
        return;
    }

    var dataOut = addChecksum(packet);
    this.log.debug('Sending setPower command:', dataOut.toString('hex'));
    msg.payload = dataOut;
};
</code>```

I have tried calling the following:

```<code>setPower('1', 'On');
this.setPower('1', 'On');
HTDLync.setPower('1', 'On');
</code>```

All of the above hit the console with function not defined errors.

I feel like I am either missing some other code or calling this function incorrectly.

How would I go about calling this setPower prototype function ?

答:
Try below code: the argument is not mandatory to pass but as you have mentioned in constructor so you pass it.</p>

```<code>var obj= new HTDLync(agr1,arg2);
obj.setPower('1', 'On');
</code>```

Title: Calling a ptototype function

Body:
I am working with a piece of code that I found in another project on the net and I am trying to adapt it to my needs. I wasn't able to find out how this function was originally being called so I am hoping to find some assistance here.

var gatewayIP = '192.168.10.21',
sock = new WebSocket('ws://' + gatewayIP + ':8000');
sock.binaryType = "arraybuffer";

// Constructor, expects a socket/stream to write device commands
function HTDLync(sock, log) {
    this.sock = sock;
    this.log = log;
}

// Change zone power state ('On', 'Off', '1', or '0')
HTDLync.prototype.setPower = function(zone, power) {

    powerStr = power.toString().toLowerCase();

    var packet = Buffer.from([0x02, 0x00, 0x00, 0x04, 0x58]);
    packet.writeUInt8(this.cleanZone(zone), 2);

    if (powerStr == 'on' || powerStr == '1'){
        packet.writeUInt8(0x57, 4);
    }
    else if (powerStr == 'off' || powerStr == '0'){
        packet.writeUInt8(0x58, 4);
    }
    else {
        this.log.warn('Unknown setPower argument:', powerStr);
        return;
    }

    var dataOut = addChecksum(packet);
    this.log.debug('Sending setPower command:', dataOut.toString('hex'));
    msg.payload = dataOut;
};

I have tried calling the following:

setPower('1', 'On');
this.setPower('1', 'On');
HTDLync.setPower('1', 'On');

All of the above hit the console with function not defined errors.

I feel like I am either missing some other code or calling this function incorrectly.

How would I go about calling this setPower prototype function ?

Body:
Try below code: the argument is not mandatory to pass but as you have mentioned in constructor so you pass it.

var obj= new HTDLync(agr1,arg2);
obj.setPower('1', 'On');


问:
Moving elements in an array SIGABRT error
A little background to my program: it uses a linked list to create a priority queue. Data is inserted into the *queue[25] array every time the user inputs a priority (using cin and while loop).

My problem is that after enqueueing all the data, and typing in -1 to quit, the program prints out the array (correctly) and then throws me a SIGABRT error.

The problem lies within my enqueue function:

```<code>void enqueue(Node *queuef[25], int priority, Node *temp)
{
    if (queuef[priority] == NULL) {
        queuef[priority] = temp;
    } else {
        int pos = 25;
        for (int i = 25; i > priority; i--)
        {
            if (queuef[priority+1] == 0)
            {
                queuef[priority+1] = temp;
                break;
            } else {
                queuef[i] = queuef[i-1];
                pos--;
            }
        }
        queuef[pos] = temp;

    }
    cout << queuef;
}
</code>```

More specifically, the problem is in this line

```<code>queuef[i] = queuef[i-1];
</code>```

When I comment out this line, the program doesn't give me the error. I can't figure out why I am getting this error.

答: You're probably accessing outside the bounds of the queuef array.  If it is 25 elements as is claimed in the parameter declaration, the first time thru the i loop you'll write to queuef[25] which is past the end of the array resulting in Undefined Behavior and your crash.

Body:
A little background to my program: it uses a linked list to create a priority queue. Data is inserted into the *queue[25] array every time the user inputs a priority (using cin and while loop).

My problem is that after enqueueing all the data, and typing in -1 to quit, the program prints out the array (correctly) and then throws me a SIGABRT error.

The problem lies within my enqueue function:

void enqueue(Node *queuef[25], int priority, Node *temp)
{
    if (queuef[priority] == NULL) {
        queuef[priority] = temp;
    } else {
        int pos = 25;
        for (int i = 25; i > priority; i--)
        {
            if (queuef[priority+1] == 0)
            {
                queuef[priority+1] = temp;
                break;
            } else {
                queuef[i] = queuef[i-1];
                pos--;
            }
        }
        queuef[pos] = temp;

    }
    cout << queuef;
}

More specifically, the problem is in this line

queuef[i] = queuef[i-1];

When I comment out this line, the program doesn't give me the error. I can't figure out why I am getting this error.


问:
Re-purposing Office commands through code
Office Ribbon buttons and other commands can be "re-purposed" using XML and onAction method. I have already done that successfully. Is there an equivalent C#/Object Model way of doing it too? Google hasn't shown much promise.

Background: The main Ribbon of my add-in is using visual designer. If I use the XML method of re-purposing, my main Ribbon will not be loaded. Other than this road bump, I'm interested in finding the solution in general too.

答:
After spending some time, I learned that there is no way of doing this from C# code. I must switch to XML Ribbon approach. Fortunately the Visual Designer can help you translate your existing ribbons into XML format. You can right-click the Ribbon in Visual Designer and choose "Convert to XML" command.

I also found that XML Ribbon approach is far more powerful in the sense that it can access Office 2013 and 2016 features that the Visual Designer cannot. For example the Office Backstage and new context menus are only accessible in XML approach.


问:
Override GWT Styling
I had a beautiful pure HTML mockup for a webpage that I am now recreating in GWT.  I'm attempting to use the same css in my GWT app, but that's not working well for me.  GWT styles seem to override mine.  I know I can completely disable the GWT styles, however I would prefer to have the styling for the GWT components that I'm adding (tab panel, button, etc).   Is there a way to disable GWT styling, and only enable it for components that I choose?</p>

答:
This is a quick, but hopefully helpful answer.

What I did is I copied over the styles I do want from the default GWT Style. For example, if you picked the standard style, GWT makes a standard.css in the war/WEB-INF/appengine-generated (somewhere along those lines) - I copied over all the button styles to my app's css file, and then in the config file chose not to use the standard GWT style.

This did the trick for us.

ContentLicense: CC BY-SA 2.5

Title: Override GWT Styling


问:
How to select a PDF file using startActivityForResult intent and return result in a second class
I am relatively new to android programming, I want to create a pdf reader that calls the inbuilt file manager to select pdf file and then display the pdf file in a second class. Here is my code so far still having issues, i think second activity is unable to get the selected pdf file and I am unable to fix this error

```<code>     MainActivity

     package com.example.user.projectapp;

     import android.app.Activity;
     import android.app.ListActivity;
     import android.content.Context;
     import android.content.Intent;
     import android.database.Cursor;
     import android.net.Uri;
     import android.provider.OpenableColumns;
     import android.support.v7.app.AppCompatActivity;
     import android.os.Bundle;
     import android.util.Log;
     import android.view.View;
     import android.widget.ArrayAdapter;
     import android.widget.ListView;

     import java.io.File;
     import java.io.IOException;
     import java.io.InputStream;
     import java.net.URI;
     import java.net.URISyntaxException;
     import java.util.ArrayList;
     import java.util.Collections;
     import java.util.List;

     public class MainActivity extends AppCompatActivity {

     public static String path;
     private static final int PICKFILE_REQUEST_CODE = 0;
     File tempFile;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     getFile();
     }

      public void getFile() {

      Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
      intent.setType("application/pdf");
      path = intent.getStringExtra("path");
      intent.putExtra("path",path);
      startActivityForResult(intent, PICKFILE_REQUEST_CODE);
      }

      Second Activity

      package com.example.user.projectapp;

      import android.annotation.TargetApi;
      import android.content.Intent;
      import android.graphics.Bitmap;
      import android.graphics.pdf.PdfRenderer;
      import android.os.Build;
      import android.os.Environment;
      import android.os.ParcelFileDescriptor;
      import android.support.v7.app.AppCompatActivity;
      import android.os.Bundle;
      import android.view.View;
      import android.widget.Button;
      import android.widget.ImageView;

      import java.io.File;

      public class Main2Activity extends AppCompatActivity {

      int pagecount = -1;
      Button buttonnext, buttonprevious;
      ImageView imageView;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main2);

      buttonnext = (Button) findViewById(R.id.button1);
      buttonprevious = (Button) findViewById(R.id.button2);
      imageView = (ImageView) findViewById(R.id.imageview);

      buttonnext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pagecount++;

            render();

        }
       });
     buttonprevious.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pagecount--;

            render();
        }
       });

       }

       @TargetApi(Build.VERSION_CODES.LOLLIPOP)
       public void render() {

       try {
        int width = imageView.getWidth();
        int height = imageView.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height,                Bitmap.Config.ARGB_4444);

        Intent intent = getIntent();
        String data = intent.getStringExtra("path");
        File file = new File(data);

        PdfRenderer renderer = new              PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));

        if (pagecount < 0) {
            pagecount = 0;
        } else if (pagecount > renderer.getPageCount()) {
            pagecount = renderer.getPageCount() - 1;
        }
        renderer.openPage(pagecount).render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
        imageView.setImageBitmap(bitmap);
        imageView.invalidate();

    } catch (Exception e) {
        e.printStackTrace();
    }
    }

    @Override
    public void onBackPressed() {
    super.onBackPressed();
    Intent intent = new Intent(this, MainActivity.class);
    startActivity(intent);

    }
    }
</code>```

And the Logcat gives

```<code>    03-28 17:19:33.387 2492-2492/com.example.user.projectapp W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference
    03-28 17:19:33.400 2492-2492/com.example.user.projectapp W/System.err:     at java.io.File.fixSlashes(File.java:185)
    03-28 17:19:33.400 2492-2492/com.example.user.projectapp W/System.err:     at java.io.File.<init>(File.java:134)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at com.example.user.projectapp.Main2Activity.render(Main2Activity.java:69)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at com.example.user.projectapp.Main2Activity$1.onClick(Main2Activity.java:42)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.view.View.performClick(View.java:4764)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.view.View$PerformClick.run(View.java:19844)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.os.Looper.loop(Looper.java:135)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5351)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
</code>```

Code Modified to be based on one activity only......
yet onActivityResult does not return a result, I

```<code>File myFile;
public static String result;
public String path;
private static final int PICKFILE_REQUEST_CODE = 12;
int pagecount = -1;
Button buttonnext, buttonprevious;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getFile();

    buttonnext = (Button) findViewById(R.id.button1);
    buttonprevious = (Button) findViewById(R.id.button2);
    imageView = (ImageView) findViewById(R.id.imageview);

    buttonnext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pagecount++;

            render();

        }
    });
    buttonprevious.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pagecount--;

            render();
        }
    });

}
public void getFile() {

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("application/pdf");
    //intent.setType("image/");
    // path = intent.getStringExtra("path");
     //intent.putExtra("path",path);
    //intent.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(intent, 12);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode==12){
        if (data != null){
            Toast.makeText(this,"file selected",Toast.LENGTH_LONG).show();
          // result=data.getStringExtra("data");
            Uri uri=data.getData();
          //  String uriString = uri.toString();
             myFile = new File(uri.toString());
            path = myFile.getAbsolutePath();
           // result=data.toString();
           // URI uri=data.getParcelableExtra(path);
           // path=fileUri.toString();
            this.render();
        }

    }

}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void render() {

    try {
        int width = imageView.getWidth();
        int height = imageView.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);

        //Intent intent = getIntent();
        //String path = intent.getStringExtra("path");

        // Uri uri = Uri.parse(uri_Str);
         File file = new File(path);
        //File storage = Environment.getExternalStorageDirectory();
        // intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

        PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));

        if (pagecount < 0) {
            pagecount = 0;
        } else if (pagecount > renderer.getPageCount()) {
            pagecount = renderer.getPageCount() - 1;
        }

        // Matrix m = imageView.getImageMatrix();
        // Rect rect=new Rect(0,0,width,height);
        renderer.openPage(pagecount).render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
        //imageView.setImageMatrix(m);
        imageView.setImageBitmap(bitmap);
        imageView.invalidate();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
}
</code>```

And the logcat error...

```<code>    03-29 11:32:47.276 21674-21674/com.example.user.newtry W/System.err: java.io.FileNotFoundException: No such file or directory
    03-29 11:32:47.283 21674-21674/com.example.user.newtry W/System.err:     at android.os.Parcel.openFileDescriptor(Native Method)
    03-29 11:32:47.283 21674-21674/com.example.user.newtry W/System.err:     at android.os.ParcelFileDescriptor.openInternal(ParcelFileDescriptor.java:253)
    03-29 11:32:47.283 21674-21674/com.example.user.newtry W/System.err:     at      android.os.ParcelFileDescriptor.open(ParcelFileDescriptor.java:199)
</code>```

答: Yes.. because your path is null.. this is the reason you are getting null pointer exception</p>

Body:
I am relatively new to android programming, I want to create a pdf reader that calls the inbuilt file manager to select pdf file and then display the pdf file in a second class. Here is my code so far still having issues, i think second activity is unable to get the selected pdf file and I am unable to fix this error

     MainActivity

     package com.example.user.projectapp;

     import android.app.Activity;
     import android.app.ListActivity;
     import android.content.Context;
     import android.content.Intent;
     import android.database.Cursor;
     import android.net.Uri;
     import android.provider.OpenableColumns;
     import android.support.v7.app.AppCompatActivity;
     import android.os.Bundle;
     import android.util.Log;
     import android.view.View;
     import android.widget.ArrayAdapter;
     import android.widget.ListView;

     import java.io.File;
     import java.io.IOException;
     import java.io.InputStream;
     import java.net.URI;
     import java.net.URISyntaxException;
     import java.util.ArrayList;
     import java.util.Collections;
     import java.util.List;

     public class MainActivity extends AppCompatActivity {

     public static String path;
     private static final int PICKFILE_REQUEST_CODE = 0;
     File tempFile;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     getFile();
     }

      public void getFile() {

      Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
      intent.setType("application/pdf");
      path = intent.getStringExtra("path");
      intent.putExtra("path",path);
      startActivityForResult(intent, PICKFILE_REQUEST_CODE);
      }

      Second Activity

      package com.example.user.projectapp;

      import android.annotation.TargetApi;
      import android.content.Intent;
      import android.graphics.Bitmap;
      import android.graphics.pdf.PdfRenderer;
      import android.os.Build;
      import android.os.Environment;
      import android.os.ParcelFileDescriptor;
      import android.support.v7.app.AppCompatActivity;
      import android.os.Bundle;
      import android.view.View;
      import android.widget.Button;
      import android.widget.ImageView;

      import java.io.File;

      public class Main2Activity extends AppCompatActivity {

      int pagecount = -1;
      Button buttonnext, buttonprevious;
      ImageView imageView;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main2);

      buttonnext = (Button) findViewById(R.id.button1);
      buttonprevious = (Button) findViewById(R.id.button2);
      imageView = (ImageView) findViewById(R.id.imageview);

      buttonnext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pagecount++;

            render();

        }
       });
     buttonprevious.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pagecount--;

            render();
        }
       });

       }

       @TargetApi(Build.VERSION_CODES.LOLLIPOP)
       public void render() {

       try {
        int width = imageView.getWidth();
        int height = imageView.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height,                Bitmap.Config.ARGB_4444);

        Intent intent = getIntent();
        String data = intent.getStringExtra("path");
        File file = new File(data);

        PdfRenderer renderer = new              PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));

        if (pagecount < 0) {
            pagecount = 0;
        } else if (pagecount > renderer.getPageCount()) {
            pagecount = renderer.getPageCount() - 1;
        }
        renderer.openPage(pagecount).render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
        imageView.setImageBitmap(bitmap);
        imageView.invalidate();

    } catch (Exception e) {
        e.printStackTrace();
    }
    }

    @Override
    public void onBackPressed() {
    super.onBackPressed();
    Intent intent = new Intent(this, MainActivity.class);
    startActivity(intent);

    }
    }

And the Logcat gives

    03-28 17:19:33.387 2492-2492/com.example.user.projectapp W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference
    03-28 17:19:33.400 2492-2492/com.example.user.projectapp W/System.err:     at java.io.File.fixSlashes(File.java:185)
    03-28 17:19:33.400 2492-2492/com.example.user.projectapp W/System.err:     at java.io.File.<init>(File.java:134)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at com.example.user.projectapp.Main2Activity.render(Main2Activity.java:69)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at com.example.user.projectapp.Main2Activity$1.onClick(Main2Activity.java:42)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.view.View.performClick(View.java:4764)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.view.View$PerformClick.run(View.java:19844)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.os.Looper.loop(Looper.java:135)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5351)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

Code Modified to be based on one activity only......
yet onActivityResult does not return a result, I

File myFile;
public static String result;
public String path;
private static final int PICKFILE_REQUEST_CODE = 12;
int pagecount = -1;
Button buttonnext, buttonprevious;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getFile();

    buttonnext = (Button) findViewById(R.id.button1);
    buttonprevious = (Button) findViewById(R.id.button2);
    imageView = (ImageView) findViewById(R.id.imageview);

    buttonnext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pagecount++;

            render();

        }
    });
    buttonprevious.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pagecount--;

            render();
        }
    });

}
public void getFile() {

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("application/pdf");
    //intent.setType("image/");
    // path = intent.getStringExtra("path");
     //intent.putExtra("path",path);
    //intent.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(intent, 12);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode==12){
        if (data != null){
            Toast.makeText(this,"file selected",Toast.LENGTH_LONG).show();
          // result=data.getStringExtra("data");
            Uri uri=data.getData();
          //  String uriString = uri.toString();
             myFile = new File(uri.toString());
            path = myFile.getAbsolutePath();
           // result=data.toString();
           // URI uri=data.getParcelableExtra(path);
           // path=fileUri.toString();
            this.render();
        }

    }

}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void render() {

    try {
        int width = imageView.getWidth();
        int height = imageView.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);

        //Intent intent = getIntent();
        //String path = intent.getStringExtra("path");

        // Uri uri = Uri.parse(uri_Str);
         File file = new File(path);
        //File storage = Environment.getExternalStorageDirectory();
        // intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

        PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));

        if (pagecount < 0) {
            pagecount = 0;
        } else if (pagecount > renderer.getPageCount()) {
            pagecount = renderer.getPageCount() - 1;
        }

        // Matrix m = imageView.getImageMatrix();
        // Rect rect=new Rect(0,0,width,height);
        renderer.openPage(pagecount).render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
        //imageView.setImageMatrix(m);
        imageView.setImageBitmap(bitmap);
        imageView.invalidate();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

And the logcat error...

    03-29 11:32:47.276 21674-21674/com.example.user.newtry W/System.err: java.io.FileNotFoundException: No such file or directory
    03-29 11:32:47.283 21674-21674/com.example.user.newtry W/System.err:     at android.os.Parcel.openFileDescriptor(Native Method)
    03-29 11:32:47.283 21674-21674/com.example.user.newtry W/System.err:     at android.os.ParcelFileDescriptor.openInternal(ParcelFileDescriptor.java:253)
    03-29 11:32:47.283 21674-21674/com.example.user.newtry W/System.err:     at      android.os.ParcelFileDescriptor.open(ParcelFileDescriptor.java:199)


问:
change the static pivot to dynamic pivot sql
I have done doing a static pivot , that mean i list the pivot column name.. ,
this is my code..

```<code>SELECT Date,
ISNULL(XSP, 'X')as XSP,
ISNULL(BSR, 'X')as BSR,
ISNULL(BPT, 'X')as BPT,
ISNULL(XPW, 'X')as XPW,
ISNULL(IPH, 'X')as IPH,
ISNULL(XTH, 'X')as XTH,
ISNULL(TGG, 'X')as TGG,
ISNULL(XKG, 'X')as XKG,
ISNULL(XKM, 'X')as XKM,
ISNULL(XLG, 'X')as XLG,
ISNULL(KBR, 'X')as KBR,
ISNULL(KUA, 'X')as KUA,
ISNULL(LGK, 'X')as LGK,
ISNULL(MKZ, 'X')as MKZ,
ISNULL(PEN, 'X')as PEN,
ISNULL(XGM, 'X')as XGM,
ISNULL(JHB, 'X')as JHB,
ISNULL(XBN, 'X')as XBN,
ISNULL(STW, 'X')as STW,
ISNULL(TIN, 'X')as TIN,
ISNULL(MUA, 'X')as MUA
FROM
(SELECT DISTINCT userid, status , DATEPART(dd, [date]) as Date
FROM edrsDB..tbl_status
WHERE DATEPART(MM, [date]) = 3
And DATEPART(YYYY, [date]) = 2017
Union
SELECT DISTINCT userid, status , DATEPART(DD,[date]) as Date
FROM edrsDB..tbl_public_holiday
WHERE DATEPART(MM, [date]) = 3
And DATEPART(YYYY, [date]) = 2017
Union
SELECT DISTINCT userid, status , DATEPART(DD,[Date]) as Date
FROM edrsDB..tbl_station_weekend
WHERE DATEPART(MM, [date]) = 3
And DATEPART(YYYY, [date]) = 2017
And date IS NOT NULL) AS monthlyRpt
PIVOT (MAX(status)
FOR userid IN (XSP, BSR, BPT, XPW, IPH, XTH, TGG, XKG, XKM, XLG, KBR, KUA, LGK,MKZ, PEN, XGM, JHB, XBN, STW, TIN, MUA)) AS pivottable
</code>```

after execute all of this code it will make the output like this ,
the column include date , and all code name

This is the output image of query above

so how can i change the code to a dynamic pivot.. any idea?

答:
Assumes that you have a table that contains userid.
And your query would be like this:</p>

```<code>   DECLARE @User AS TABLE (UserId varchar(50))
   INSERT INTO @User VALUES ('XSP'), ('BSR'), ('BPT')

   DECLARE @HeaderText nvarchar(max)
   DECLARE @ColumnPiVot nvarchar(max)

   SELECT @ColumnPiVot = Stuff((SELECT concat(', ',td.UserId) FROM (select DISTINCT tt.UserId
                                                         FROM @User tt ) td FOR XML PATH (''))
                         ,1,1,''),
         @HeaderText = CONCAT( N'Date, ' ,  Stuff((SELECT concat(', ISNULL(',td.UserId,',0) AS', ' ',td.UserId )
                                            FROM (select DISTINCT tt.UserId FROM @User tt ) td FOR XML PATH (''))
                                      ,1,1,''))
   DECLARE @query nvarchar(max) = CONCAT(N'SELECT ' , @HeaderText,
   ' FROM
      (
         SELECT DISTINCT userid, status , DATEPART(dd, [date]) as Date
         FROM edrsDB..tbl_status
         WHERE   DATEPART(MM, [date]) = 3
                And DATEPART(YYYY, [date]) = 2017
         Union
         SELECT DISTINCT userid, status , DATEPART(DD,[date]) as Date
         FROM edrsDB..tbl_public_holiday
         WHERE   DATEPART(MM, [date]) = 3
                And DATEPART(YYYY, [date]) = 2017
         Union
         SELECT DISTINCT userid, status , DATEPART(DD,[Date]) as Date
         FROM edrsDB..tbl_station_weekend
         WHERE   DATEPART(MM, [date]) = 3
                And DATEPART(YYYY, [date]) = 2017
                And date IS NOT NULL
      ) AS monthlyRpt
   PIVOT
      (MAX(status) FOR userid IN, (',@ColumnPiVot,')) AS pivottable')
   PRINT @query
   exec sp_executesql  @query
</code>```

Body:
I have done doing a static pivot , that mean i list the pivot column name.. ,
this is my code..

SELECT Date,
ISNULL(XSP, 'X')as XSP,
ISNULL(BSR, 'X')as BSR,
ISNULL(BPT, 'X')as BPT,
ISNULL(XPW, 'X')as XPW,
ISNULL(IPH, 'X')as IPH,
ISNULL(XTH, 'X')as XTH,
ISNULL(TGG, 'X')as TGG,
ISNULL(XKG, 'X')as XKG,
ISNULL(XKM, 'X')as XKM,
ISNULL(XLG, 'X')as XLG,
ISNULL(KBR, 'X')as KBR,
ISNULL(KUA, 'X')as KUA,
ISNULL(LGK, 'X')as LGK,
ISNULL(MKZ, 'X')as MKZ,
ISNULL(PEN, 'X')as PEN,
ISNULL(XGM, 'X')as XGM,
ISNULL(JHB, 'X')as JHB,
ISNULL(XBN, 'X')as XBN,
ISNULL(STW, 'X')as STW,
ISNULL(TIN, 'X')as TIN,
ISNULL(MUA, 'X')as MUA
FROM
(SELECT DISTINCT userid, status , DATEPART(dd, [date]) as Date
FROM edrsDB..tbl_status
WHERE DATEPART(MM, [date]) = 3
And DATEPART(YYYY, [date]) = 2017
Union
SELECT DISTINCT userid, status , DATEPART(DD,[date]) as Date
FROM edrsDB..tbl_public_holiday
WHERE DATEPART(MM, [date]) = 3
And DATEPART(YYYY, [date]) = 2017
Union
SELECT DISTINCT userid, status , DATEPART(DD,[Date]) as Date
FROM edrsDB..tbl_station_weekend
WHERE DATEPART(MM, [date]) = 3
And DATEPART(YYYY, [date]) = 2017
And date IS NOT NULL) AS monthlyRpt
PIVOT (MAX(status)
FOR userid IN (XSP, BSR, BPT, XPW, IPH, XTH, TGG, XKG, XKM, XLG, KBR, KUA, LGK,MKZ, PEN, XGM, JHB, XBN, STW, TIN, MUA)) AS pivottable

after execute all of this code it will make the output like this ,
the column include date , and all code name

This is the output image of query above

so how can i change the code to a dynamic pivot.. any idea?

Body:
Assumes that you have a table that contains userid.
And your query would be like this:

   DECLARE @User AS TABLE (UserId varchar(50))
   INSERT INTO @User VALUES ('XSP'), ('BSR'), ('BPT')

   DECLARE @HeaderText nvarchar(max)
   DECLARE @ColumnPiVot nvarchar(max)

   SELECT @ColumnPiVot = Stuff((SELECT concat(', ',td.UserId) FROM (select DISTINCT tt.UserId
                                                         FROM @User tt ) td FOR XML PATH (''))
                         ,1,1,''),
         @HeaderText = CONCAT( N'Date, ' ,  Stuff((SELECT concat(', ISNULL(',td.UserId,',0) AS', ' ',td.UserId )
                                            FROM (select DISTINCT tt.UserId FROM @User tt ) td FOR XML PATH (''))
                                      ,1,1,''))
   DECLARE @query nvarchar(max) = CONCAT(N'SELECT ' , @HeaderText,
   ' FROM
      (
         SELECT DISTINCT userid, status , DATEPART(dd, [date]) as Date
         FROM edrsDB..tbl_status
         WHERE   DATEPART(MM, [date]) = 3
                And DATEPART(YYYY, [date]) = 2017
         Union
         SELECT DISTINCT userid, status , DATEPART(DD,[date]) as Date
         FROM edrsDB..tbl_public_holiday
         WHERE   DATEPART(MM, [date]) = 3
                And DATEPART(YYYY, [date]) = 2017
         Union
         SELECT DISTINCT userid, status , DATEPART(DD,[Date]) as Date
         FROM edrsDB..tbl_station_weekend
         WHERE   DATEPART(MM, [date]) = 3
                And DATEPART(YYYY, [date]) = 2017
                And date IS NOT NULL
      ) AS monthlyRpt
   PIVOT
      (MAX(status) FOR userid IN, (',@ColumnPiVot,')) AS pivottable')
   PRINT @query
   exec sp_executesql  @query


问:
How to use replace update in Laravel 5.4
I have a category name A with path: 1-2-

and some children with path like:

B: 1-2-3-

C: 1-2-4-

D: 1-2-5-

I want to move category A from 1 to 6 with path: 6-2-

How can I update categories B,C,D to 6-2-%

I found this code for php:

UPDATE category SET path = REPLACE(path, '1-2-', '6-2-') WHERE path LIKE '1-2-%'

but I don't know how to use it for laravel.

答:
if this code works you can use </p>

```<code>DB::raw('UPDATE category SET path = REPLACE(path, '1-2-', '6-2-') WHERE path LIKE '1-2-%');
</code>```

Body:
if this code works you can use

DB::raw('UPDATE category SET path = REPLACE(path, '1-2-', '6-2-') WHERE path LIKE '1-2-%');


问:
How to get the active_id of one2many in odoo 9?
In the below method complete_operation I used to print active id, but it display None. I want to display current id of mrp.production. mrp.operations is one2many field of mrp.production.

class mrpProduction(models.Model):
    _inherit = "mrp.production"

    end_date = fields.Datetime('Scheduled End Date')
    operations = fields.One2many('mrp.operations','operation_id', 'Operations')

class mrpOperations(models.Model):
    _name = "mrp.operations"

    name = fields.Many2one("custom.operations", "Operation Name")
    status = fields.Selection([('Completed','Completed'),('Pending','Pending')],'Status')
    operation_id = fields.Integer()

    @api.multi
    def complete_operation(self):
        print self.id
        active_id=self.env.context.get('active_id')
        print active_id,'--'
```

答: here operation_id which can hold the current id of mrp.production if you change the operation_id as a many2one model of mrp.production


问:
how to delete all Facebook events in Facebook analytics?
Is there a quick way to delete all our Facebook events in Facebook Analytics?

We have 1000 events and to do it manually will take days.

答: Bulk deactivate was recently introduced in the product. Go to the Events screen and click the 'Deactivate' button at the top right.


问:
Why is there no `mov %rsp, %rbp` in function prologue?
In assembly, many functions begin with the following prologue:

```<code>00000001004010e0: main(int, char**)+0    push    %rbp
00000001004010e1: main(int, char**)+1    mov     %rsp,%rbp
</code>```

Some functions, like the one below, do not:

```<code>                              int MainEntry(){
                                       MainEntry():
0000000100401104: MainEntry()+0          push    %rbp
0000000100401105: MainEntry()+1          push    %rbx
0000000100401106: MainEntry()+2          sub     $0x48,%rsp
000000010040110a: MainEntry()+6          lea     0x80(%rsp),%rbp
                                        vector<int> v;
0000000100401112: MainEntry()+14         lea     -0x60(%rbp),%rax
0000000100401116: MainEntry()+18         mov     %rax,%rcx
0000000100401119: MainEntry()+21         callq   0x100401b00 <std::vector<int, std::allocator<int> >::vector()>
                                        return 0;
000000010040111e: MainEntry()+26         mov     $0x0,%ebx
0000000100401123: MainEntry()+31         lea     -0x60(%rbp),%rax
0000000100401127: MainEntry()+35         mov     %rax,%rcx
000000010040112a: MainEntry()+38         callq   0x100401b20 <std::vector<int, std::allocator<int> >::~vector()>
000000010040112f: MainEntry()+43         mov     %ebx,%eax
                                     }
</code>```

Here is the C++ code that compiles into this:

```<code>int main(int c, char** args){
    MainEntry();
    return 0;
}

int MainEntry(){
    vector<int> v;
    return 0;
}
</code>```

So here are my two questions:

In the MainEntry function, there is a push %rbp, and then a push %rbx. Why is RBX pushed onto the stack?

If I understand correctly, sub $0x48, %rsp allocates 0x48 bytes on the stack, and lea 0x80(%rsp), %rbp moves 0x80 bytes down on the stack and assigns that as the base. Where is RBP going to end up in the local stack frame and how did it get there?

答:
rbx is pushed onto the stack because the calling convention says it is preserved across calls.

This function is compiled without frame pointers. rbp is just another general purpose register when compiling without frame pointers.

About the question in the title (now improved)

The push rsp, rbp instruction doesn't exist. push always takes one argument. Perhaps you meant to ask why  rbp isn't pushed. The answer is that nothing uses it and so no instructions are required to preserve it.

ContentLicense: CC BY-SA 4.0

Body:
In assembly, many functions begin with the following prologue:

00000001004010e0: main(int, char**)+0    push    %rbp
00000001004010e1: main(int, char**)+1    mov     %rsp,%rbp

Some functions, like the one below, do not:

                              int MainEntry(){
                                       MainEntry():
0000000100401104: MainEntry()+0          push    %rbp
0000000100401105: MainEntry()+1          push    %rbx
0000000100401106: MainEntry()+2          sub     $0x48,%rsp
000000010040110a: MainEntry()+6          lea     0x80(%rsp),%rbp
                                        vector<int> v;
0000000100401112: MainEntry()+14         lea     -0x60(%rbp),%rax
0000000100401116: MainEntry()+18         mov     %rax,%rcx
0000000100401119: MainEntry()+21         callq   0x100401b00 <std::vector<int, std::allocator<int> >::vector()>
                                        return 0;
000000010040111e: MainEntry()+26         mov     $0x0,%ebx
0000000100401123: MainEntry()+31         lea     -0x60(%rbp),%rax
0000000100401127: MainEntry()+35         mov     %rax,%rcx
000000010040112a: MainEntry()+38         callq   0x100401b20 <std::vector<int, std::allocator<int> >::~vector()>
000000010040112f: MainEntry()+43         mov     %ebx,%eax
                                     }

Here is the C++ code that compiles into this:

int main(int c, char** args){
    MainEntry();
    return 0;
}

int MainEntry(){
    vector<int> v;
    return 0;
}

So here are my two questions:

In the MainEntry function, there is a push %rbp, and then a push %rbx. Why is RBX pushed onto the stack?

If I understand correctly, sub $0x48, %rsp allocates 0x48 bytes on the stack, and lea 0x80(%rsp), %rbp moves 0x80 bytes down on the stack and assigns that as the base. Where is RBP going to end up in the local stack frame and how did it get there?


问:
Javascript: silently fail on undefined assignment
Suppose I am trying to assign a variable in a way that causes an exception

I am going to access a non-existent key of a dictionary:

```<code>myObject.property = dictionary['NO_KEY'][0];
</code>```

Now, because 'NO_KEY' does not exist on dictionary, my program will catch an exception when trying to subscript 0 of undefined - and crash. Is it possible to execute this line above as a no-op so that my script can continue running? I know there is try-catch syntex, but is there a more elegant syntax with ESMA6?

答:
```<code>Object.defineProperty(Object.prototype,
                      'accessWithSilentFail', {
                       configurable: false,
                       enumerable: false,
                       writable: false,
                       value: function(key) {
                         return this[key] ? this[key] : {};
                       }});

myObject.property = dictionary
                     .accessWithSilentFail('NO_KEY')
                     .accessWithSilentFail(0);
</code>```

That way you get an empty object if at any point the chain fails. You need to get an object so the chain doesn't fail halfway. You can call the function something shorter if you're going to use it a lot.

Although this works, it has many, many limitations, and it changes the Object prototype, which is usually frowned upon. You really should consider just checking for undefined, which is the idiomatic way to do it.

If you ever need to check if the access chain failed, you can use:

```<code>function chainFailed(result) {
    return Object.keys(result).length === 0;
}
</code>```

So you could do

```<code>myObject.property = dictionary
                      .accessWithSilentFail('NO_KEY')
                      .accessWithSilentFail(0);

if (!chainFailed(myObject.property)) {
  //keep on
} else {
  //handle failure
}
</code>```

This works as long as your expected return isn't an empty object, on which case chainFailed will always return true. But I'm assuming you really want to fail silently, because if you wanted to handle errors you could just use an exception.

Body:
Suppose I am trying to assign a variable in a way that causes an exception

I am going to access a non-existent key of a dictionary:

myObject.property = dictionary['NO_KEY'][0];

Now, because 'NO_KEY' does not exist on dictionary, my program will catch an exception when trying to subscript 0 of undefined - and crash. Is it possible to execute this line above as a no-op so that my script can continue running? I know there is try-catch syntex, but is there a more elegant syntax with ESMA6?

Body:
Object.defineProperty(Object.prototype,
                      'accessWithSilentFail', {
                       configurable: false,
                       enumerable: false,
                       writable: false,
                       value: function(key) {
                         return this[key] ? this[key] : {};
                       }});

myObject.property = dictionary
                     .accessWithSilentFail('NO_KEY')
                     .accessWithSilentFail(0);

That way you get an empty object if at any point the chain fails. You need to get an object so the chain doesn't fail halfway. You can call the function something shorter if you're going to use it a lot.

Although this works, it has many, many limitations, and it changes the Object prototype, which is usually frowned upon. You really should consider just checking for undefined, which is the idiomatic way to do it.

If you ever need to check if the access chain failed, you can use:

function chainFailed(result) {
    return Object.keys(result).length === 0;
}

So you could do

myObject.property = dictionary
                      .accessWithSilentFail('NO_KEY')
                      .accessWithSilentFail(0);

if (!chainFailed(myObject.property)) {
  //keep on
} else {
  //handle failure
}

This works as long as your expected return isn't an empty object, on which case chainFailed will always return true. But I'm assuming you really want to fail silently, because if you wanted to handle errors you could just use an exception.


问:
Java sorting parallel arrays, help needed (NullPointerException Error)
Ok I am trying to finish this program for my into to java class and I am having trouble with this one part. Everything else is working except this. I have 3 arrays, 1 string, 2 type int, all parallel. I have to sort these into alphabetical order by name then by number (using the string array first, then the first int array, sorting is not affected by the third array, it is there to practice parallel in 3 dimensions)

This is the code I have so far.

```<code>    public static void sortDatabase(int numRecords, String[] sDeptArr,
              int[] iCourseNumArr, int[] iEnrollmentArr)
   {
       System.out.println("Sort the database. \n");
       String sTemp = null;
       int iTemp = 0;
       int eTemp = 0;
       for(int i=0; i<numRecords; i++)
       {
           int iPosMin = i;
           for(int j=i+1; j<numRecords; j++)
           {
               String a = sDeptArr[j];
               String b = sDeptArr[iPosMin];
               if(a.compareTo(b) != 0)
                   iPosMin = j;
               else if(!sDeptArr[j].equals(sDeptArr[iPosMin]) && iCourseNumArr[j] < iCourseNumArr[iPosMin])
                   iPosMin = j;
           }
           sDeptArr[i] = sTemp;
           sDeptArr[i] = sDeptArr[iPosMin];
           sDeptArr[iPosMin] = sTemp;
           iCourseNumArr[i] = iTemp;
           iCourseNumArr[i] = iCourseNumArr[iPosMin];
           iCourseNumArr[iPosMin] = iTemp;
           iEnrollmentArr[i] = eTemp;
           iEnrollmentArr[i] = iEnrollmentArr[iPosMin];
           iEnrollmentArr[iPosMin] = eTemp;
       }
   }
</code>```

It has to be done in java. I am getting an error in the 15th line consisting of

```<code>if(a.compareTo(b) != 0)
</code>```

and I am getting a NullPointerException.

Basically I am sorting fake class names and course numbers while keeping the number of people enrolled parallel with its corresponding index to the course name and number.

答:
I am getting an error in the 15th line consisting of

if(a.compareTo(b) != 0)

and I am getting a NullPointerException.

This indicates that one of the elements in your array is null. Check the contents of the array to make sure that what you are trying to sort does not contain null elements. Make sure you aren't forgetting that array indices start at 0. If null is a legit value for your array to have pre-sorting, then make sure your code guards against it.

Body:
Ok I am trying to finish this program for my into to java class and I am having trouble with this one part. Everything else is working except this. I have 3 arrays, 1 string, 2 type int, all parallel. I have to sort these into alphabetical order by name then by number (using the string array first, then the first int array, sorting is not affected by the third array, it is there to practice parallel in 3 dimensions)

This is the code I have so far.

    public static void sortDatabase(int numRecords, String[] sDeptArr,
              int[] iCourseNumArr, int[] iEnrollmentArr)
   {
       System.out.println("Sort the database. \n");
       String sTemp = null;
       int iTemp = 0;
       int eTemp = 0;
       for(int i=0; i<numRecords; i++)
       {
           int iPosMin = i;
           for(int j=i+1; j<numRecords; j++)
           {
               String a = sDeptArr[j];
               String b = sDeptArr[iPosMin];
               if(a.compareTo(b) != 0)
                   iPosMin = j;
               else if(!sDeptArr[j].equals(sDeptArr[iPosMin]) && iCourseNumArr[j] < iCourseNumArr[iPosMin])
                   iPosMin = j;
           }
           sDeptArr[i] = sTemp;
           sDeptArr[i] = sDeptArr[iPosMin];
           sDeptArr[iPosMin] = sTemp;
           iCourseNumArr[i] = iTemp;
           iCourseNumArr[i] = iCourseNumArr[iPosMin];
           iCourseNumArr[iPosMin] = iTemp;
           iEnrollmentArr[i] = eTemp;
           iEnrollmentArr[i] = iEnrollmentArr[iPosMin];
           iEnrollmentArr[iPosMin] = eTemp;
       }
   }

It has to be done in java. I am getting an error in the 15th line consisting of

if(a.compareTo(b) != 0)

and I am getting a NullPointerException.

Basically I am sorting fake class names and course numbers while keeping the number of people enrolled parallel with its corresponding index to the course name and number.


问:
Framework7 app dealing with dynamic Swiper Slider on index.html
I got a Swiper Slider on index.html that works only when app initialized. If I enter on other page, like about.html, and go back to index.html, the Swiper Slider dissapears. I really lost with this.

This is the JS

```<code>var template = $$('#newsScript').html();
var compiledTemplate = Template7.compile(template);
myApp.showPreloader('Cargando slider...');
$$.getJSON("http://centenariosa.com.ar/wp-json/wp/v2/posts?categories=8&orderby=title&order=asc&per_page=100",function(jsonslider){
myApp.hidePreloader();
var slider = jsonslider;
var objuslider = [];
for (var i = 0; i < slider.length; i++) {
    var img = slider[i]["better_featured_image"]["media_details"]["sizes"]["wpbs-featured"];
    var acf = slider[i]["acf"];
    var t = {};
    t.id = i+1;
    t.enlace = acf["motor"];
    t.imagendestacada = img["source_url"];
    objuslider.push(t);
}
Template7.data['page:index'] = objuslider;
$$('#newsSwiper').html(compiledTemplate(objuslider));
//init swiper here
myApp.onPageInit('index', function (page) {
    var page = e.detail.page;
    // "page" variable contains all required information about loaded and initialized page
    var swiper = myApp.swiper('.swiper-container #newsSwiper', {
        pagination:'.swiper-pagination',
        direction: 'vertical',
        autoplay: 4000
    });
}).trigger();
});
</code>```

Index.html

```<code><div class="swiper-container slide-home">
<div id="newsSwiper"></div>
    <script type="text/template7" id="newsScript">
    <div class="swiper-wrapper">
        {{#each this}}
        <div class="swiper-slide"><img src="{{imagendestacada}}"></div>
        {{/each}}
    </div>
    </script>
    <div class="swiper-pagination"></div>
</div>
</code>```

答:
Ok i solved this way.

I don't know if there's a better way to do this. But it works for me.

JS

```<code>var template = $$('#newsScript').html();
var compiledTemplate = Template7.compile(template);
myApp.showPreloader('Cargando slider...');
$$.getJSON("http://centenariosa.com.ar/wp-json/wp/v2/posts?categories=8&orderby=title&order=asc&per_page=100",function(jsonslider){
    myApp.hidePreloader();
    var slider = jsonslider;
    var objuslider = [];
    for (var i = 0; i < slider.length; i++) {
        var img = slider[i]["better_featured_image"]["media_details"]["sizes"]["wpbs-featured"];
        var acf = slider[i]["acf"];
        var o = [];
        var t = {};
        var z = {};
        t.id = i+1;
        t.enlace = acf["motor"];
        t.imagendestacada = img["source_url"];
        objuslider.push(t);
    }
    Template7.data['page:index'] = objuslider;
    console.log(JSON.stringify(objuslider, null, 2));
    $$('#newsSwiper').html(compiledTemplate(objuslider));

    var swiper = myApp.swiper('.swiper-container #newsSwiper', {
        pagination:'.swiper-pagination',
        direction: 'vertical',
        autoplay: 4000,
        loop: true
    });
    myApp.onPageInit('index', function (page) {
        $$(page.container).find('.swiper-container #newsSwiper').html(compiledTemplate(objuslider));
        var swiper = myApp.swiper('.swiper-container #newsSwiper', {
            pagination:'.swiper-pagination',
            direction: 'vertical',
            autoplay: 4000,
            loop: true
        });
    }).trigger();
});
</code>```

INDEX.HTML

```<code><div class="swiper-container slide-home container">
    <div id="newsSwiper"></div>
    <script type="text/template7" id="newsScript">
    <div class="swiper-wrapper">
        {{#each this}}
        <div class="swiper-slide"><img src="{{imagendestacada}}"></div>
        {{/each}}
        </div>
        <div class="swiper-pagination"></div>
    </script>
</div>
</code>```

Body:
I got a Swiper Slider on index.html that works only when app initialized. If I enter on other page, like about.html, and go back to index.html, the Swiper Slider dissapears. I really lost with this.

This is the JS

var template = $$('#newsScript').html();
var compiledTemplate = Template7.compile(template);
myApp.showPreloader('Cargando slider...');
$$.getJSON("http://centenariosa.com.ar/wp-json/wp/v2/posts?categories=8&orderby=title&order=asc&per_page=100",function(jsonslider){
myApp.hidePreloader();
var slider = jsonslider;
var objuslider = [];
for (var i = 0; i < slider.length; i++) {
    var img = slider[i]["better_featured_image"]["media_details"]["sizes"]["wpbs-featured"];
    var acf = slider[i]["acf"];
    var t = {};
    t.id = i+1;
    t.enlace = acf["motor"];
    t.imagendestacada = img["source_url"];
    objuslider.push(t);
}
Template7.data['page:index'] = objuslider;
$$('#newsSwiper').html(compiledTemplate(objuslider));
//init swiper here
myApp.onPageInit('index', function (page) {
    var page = e.detail.page;
    // "page" variable contains all required information about loaded and initialized page
    var swiper = myApp.swiper('.swiper-container #newsSwiper', {
        pagination:'.swiper-pagination',
        direction: 'vertical',
        autoplay: 4000
    });
}).trigger();
});

Index.html

Body:
Ok i solved this way.

I don't know if there's a better way to do this. But it works for me.

JS

var template = $$('#newsScript').html();
var compiledTemplate = Template7.compile(template);
myApp.showPreloader('Cargando slider...');
$$.getJSON("http://centenariosa.com.ar/wp-json/wp/v2/posts?categories=8&orderby=title&order=asc&per_page=100",function(jsonslider){
    myApp.hidePreloader();
    var slider = jsonslider;
    var objuslider = [];
    for (var i = 0; i < slider.length; i++) {
        var img = slider[i]["better_featured_image"]["media_details"]["sizes"]["wpbs-featured"];
        var acf = slider[i]["acf"];
        var o = [];
        var t = {};
        var z = {};
        t.id = i+1;
        t.enlace = acf["motor"];
        t.imagendestacada = img["source_url"];
        objuslider.push(t);
    }
    Template7.data['page:index'] = objuslider;
    console.log(JSON.stringify(objuslider, null, 2));
    $$('#newsSwiper').html(compiledTemplate(objuslider));

    var swiper = myApp.swiper('.swiper-container #newsSwiper', {
        pagination:'.swiper-pagination',
        direction: 'vertical',
        autoplay: 4000,
        loop: true
    });
    myApp.onPageInit('index', function (page) {
        $$(page.container).find('.swiper-container #newsSwiper').html(compiledTemplate(objuslider));
        var swiper = myApp.swiper('.swiper-container #newsSwiper', {
            pagination:'.swiper-pagination',
            direction: 'vertical',
            autoplay: 4000,
            loop: true
        });
    }).trigger();
});

INDEX.HTML

<div class="swiper-container slide-home container">
    <div id="newsSwiper"></div>
    <script type="text/template7" id="newsScript">
    <div class="swiper-wrapper">
        {{#each this}}
        <div class="swiper-slide"><img src="{{imagendestacada}}"></div>
        {{/each}}
        </div>
        <div class="swiper-pagination"></div>
    </script>
</div>


问:
Dealing with axios interceptors when sending many ajax requests
I use Larave+JWT and vue2 + vuex2 + axios

So when user logins I store auth token in vuex store. When the token expires I need to refresh it. In order to refresh it I need to send the same token to /refresh route, and get a new token. At least that's how I got it and actually it works.

The problem is that interceptor catches 401 responses and tries to refresh token, but what if, say, in my component I send many requests with expired token? Since ajax requests are async, the interceptor code runs many times. So I got many refresh requests. Once the initial token is refreshed it is not considered valid. When interceptor tries to refresh invalid token server responds with error and I redirect to login page.

Here is the code:

```<code>axios.interceptors.response.use((response) => {
  return response;
}, (error) => {
  const originalRequest = error.config;

  if (error.response.status === 401 && !originalRequest._retry) {
    originalRequest._retry = true

    axios.post('auth/refresh').then((response) => {
      let token = response.data.token

      store.dispatch('auth/setAuthToken', token)

      let authorizationHeader = `Bearer ${token}`

      axios.defaults.headers = { 'Authorization': authorizationHeader }
      originalRequest.headers['Authorization'] = authorizationHeader

      return axios(originalRequest)
    }, (error) => {
      store.dispatch('auth/clearAuthInfo')
      router.push({ name: 'login' })
    })
  }

  return Promise.reject(error);
});
</code>```

答:
I think you'll have to change your approach on how you refresh your token. Leaders like Auth0 recommends proactive periodic refresh to solve this problem.

Here is a SO answer where they talk about it.

Set the token expiration to one week and refresh the token every time the user open the web application and every one hour. If a user doesn't open the application for more than a week, they will have to login again and this is acceptable web application UX.

Body:
I use Larave+JWT and vue2 + vuex2 + axios

So when user logins I store auth token in vuex store. When the token expires I need to refresh it. In order to refresh it I need to send the same token to /refresh route, and get a new token. At least that's how I got it and actually it works.

The problem is that interceptor catches 401 responses and tries to refresh token, but what if, say, in my component I send many requests with expired token? Since ajax requests are async, the interceptor code runs many times. So I got many refresh requests. Once the initial token is refreshed it is not considered valid. When interceptor tries to refresh invalid token server responds with error and I redirect to login page.

Here is the code:

axios.interceptors.response.use((response) => {
  return response;
}, (error) => {
  const originalRequest = error.config;

  if (error.response.status === 401 && !originalRequest._retry) {
    originalRequest._retry = true

    axios.post('auth/refresh').then((response) => {
      let token = response.data.token

      store.dispatch('auth/setAuthToken', token)

      let authorizationHeader = `Bearer ${token}`

      axios.defaults.headers = { 'Authorization': authorizationHeader }
      originalRequest.headers['Authorization'] = authorizationHeader

      return axios(originalRequest)
    }, (error) => {
      store.dispatch('auth/clearAuthInfo')
      router.push({ name: 'login' })
    })
  }

  return Promise.reject(error);
});


问:
How to pop out a uicollectionViewCell from the UICollectionView?
Hello I have a simple horizontal only uicollectionview and i want to pop out the UICollectionViewCell.

When I click a white cell i get bigger dimensions but still contained by the collection View: ->

```<code>func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    // handle tap events
    let cell = collectionView.cellForItem(at: indexPath) as! MyCollectionViewCell

    print("You selected cell #\(indexPath.item)!")
    Fullscreen.originalHeight = (cell.frame.height)
    Fullscreen.originalWidth = (cell.frame.width)
    Fullscreen.originalX = (cell.frame.origin.x)
    Fullscreen.originalY = (cell.frame.origin.y)

    print(Fullscreen.originalX,Fullscreen.originalY,Fullscreen.originalWidth,Fullscreen.originalHeight)

    cell.superview?.bringSubview(toFront: cell)
    cell.clipsToBounds = true
    UIView.animate(withDuration: 0.3,
                   delay: 0,
                   options: .curveEaseOut,
                   animations: {

                    //fullscreen
                    cell.frame.size.height = (collectionView.superview?.frame.height)!
                    cell.frame.size.width = (collectionView.superview?.frame.width)!
                    cell.frame.origin.x = (collectionView.superview?.frame.origin.x)!
                    cell.frame.origin.y = (collectionView.superview?.frame.origin.y)!
    },completion: nil)
</code>```

as you can see the view gets cut off by the dimensions of the Collectionview

How can i get it to pop out and have bigger dimensions than the collection view?

I could increase the contentSize.height of the collectionView but I need the white cells in horizontal line.

Thanks

答:
No quite clear about what you actually want to achieve, maybe you can share some part of your code so that I can see how you are trying to implement.

Just according to your words, you can try increase the contentSize.height like you said when you pop up the cell, and put back the contentSize.height to the size before when you go back to the white one.

Body:
Hello I have a simple horizontal only uicollectionview and i want to pop out the UICollectionViewCell.

When I click a white cell i get bigger dimensions but still contained by the collection View: ->

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    // handle tap events
    let cell = collectionView.cellForItem(at: indexPath) as! MyCollectionViewCell

    print("You selected cell #\(indexPath.item)!")
    Fullscreen.originalHeight = (cell.frame.height)
    Fullscreen.originalWidth = (cell.frame.width)
    Fullscreen.originalX = (cell.frame.origin.x)
    Fullscreen.originalY = (cell.frame.origin.y)

    print(Fullscreen.originalX,Fullscreen.originalY,Fullscreen.originalWidth,Fullscreen.originalHeight)

    cell.superview?.bringSubview(toFront: cell)
    cell.clipsToBounds = true
    UIView.animate(withDuration: 0.3,
                   delay: 0,
                   options: .curveEaseOut,
                   animations: {

                    //fullscreen
                    cell.frame.size.height = (collectionView.superview?.frame.height)!
                    cell.frame.size.width = (collectionView.superview?.frame.width)!
                    cell.frame.origin.x = (collectionView.superview?.frame.origin.x)!
                    cell.frame.origin.y = (collectionView.superview?.frame.origin.y)!
    },completion: nil)

as you can see the view gets cut off by the dimensions of the Collectionview

How can i get it to pop out and have bigger dimensions than the collection view?

I could increase the contentSize.height of the collectionView but I need the white cells in horizontal line.

Thanks


问:
File attachments in Blocks?
Whats the best way to have file attachments in blocks like you can with nodes? Is this possible with an existing module?</p>

答:
Use views, create a block display and set it to display file attachments for the specific node type. Set the argument to node ID by providing a default argument and telling to fetch the node ID from the URL.

Bam!

Title: File attachments in Blocks?