问:
excatonline php contact list won't show all complete information from the created user account
I tried to get data of "Contact" but i can't get these tags "AddressLine, City, FaxNumber, MiddelInitial, Note, State, ZipCode"

When i looked in ExactOnline i saw that under "Contact" Voornaam, Tussenvoegsel, Achternaam, Functienaam, Telefoon, Mobiel, E-mail and these are the thing I only get a output of (if its filled in).

Then I looked further and I saw "Relatie" over here are the parts i want but can't call it.

How can i fix this?

```<code> ================================
           Exactonline
           Connection
 ================================

try {
        //Code
        for($i = 0; $i <1;) {
        //AddressLine2
        for($o = 0; $o <1;) {
        //BusinessPhone
        for($p = 0; $p <1;) {
        //City
        for($q = 0; $q <1;) {
        //Country
        for($w = 0; $w <1;) {
        //Created
        for($e = 0; $e <1;) {
        //Email
        for($r = 0; $r <1;) {
        //BusinessFax
        for($t = 0; $t <1;) {
        //FirstName
        for($y = 0; $y <1;) {
        //LastName
        for($u = 0; $u <1;) {
        //Initials
        for($a = 0; $a <1;) {
        //Mobile
        for($s = 0; $s <1;) {
        //Notes
        for($d = 0; $d <1;) {
        //Phone
        for($f = 0; $f <1;) {
        //State
        for($g = 0; $g <1;) {
        //Postcode
        for($h = 0; $h <1;) {

        $result = array();
        $contact = new \Picqer\Financials\Exact\Contact($connection);
        $result   = $contact->get();
        foreach ($result as $contact) {
        //Code
            ob_start();
            $i++;
            echo $result[]= $contact->Code;
            $filei[$i] = ob_get_contents();
            ob_end_clean();
            //echo $filei[$i]; //(Print available)
         //AddressLine2
            ob_start();
            $o++;
            echo $result[]= $contact->AddressLine2;
            $fileo[$o] = ob_get_contents();
            ob_end_clean();
            //echo $fileo[$o]; //(Print available)
          //BusinessPhone
            ob_start();
            $p++;
            echo $result[]= $contact->BusinessPhone;
            $filep[$p] = ob_get_contents();
            ob_end_clean();
            //echo $fileo[$p]; //(Print available)
          //City
            ob_start();
            $q++;
            echo $result[]= $contact->City;
            $fileq[$q] = ob_get_contents();
            ob_end_clean();
            //echo $fileq[$q]; //(Print available)
          //Country
            ob_start();
            $w++;
            echo $result[]= $contact->Country;
            $filew[$w] = ob_get_contents();
            ob_end_clean();
            //echo $filea[$a]; //(Print available
         //Created
            ob_start();
            $e++;
            echo $result[]= $contact->Created;
            $filee[$e] = ob_get_contents();
            ob_end_clean();
            //echo $filee[$e]; //(Print available)
        //Email
            ob_start();
            $r++;
            echo $result[]= $contact->Email;
            $filer[$r] = ob_get_contents();
            ob_end_clean();
            //echo $filer[$r]; //(Print available)
        //BusinessFax
            ob_start();
            $t++;
            echo $result[]= $contact->BusinessFax;
            $filet[$t] = ob_get_contents();
            ob_end_clean();
            //echo $filet[$t]; //(Print available)
       //FirstName
            ob_start();
            $y++;
            echo $result[]= $contact->FirstName;
            $filey[$y] = ob_get_contents();
            ob_end_clean();
            //echo $filey[$y]; //(Print available)
       //LastName
            ob_start();
            $u++;
            echo $result[]= $contact->LastName;
            $fileu[$u] = ob_get_contents();
            ob_end_clean();
            //echo $fileu[$u]; //(Print available)
       //Title
            ob_start();
            $a++;
            echo $result[]= $contact->Title;
            $filea[$a] = ob_get_contents();
            ob_end_clean();
            //echo $filea[$a]; //(Print available)
       //Mobile
            ob_start();
            $s++;
            echo $result[]= $contact->Mobile;
            $files[$s] = ob_get_contents();
            ob_end_clean();
            //echo $files[$s]; //(Print available)
       //Notes
            ob_start();
            $d++;
            echo $result[]= $contact->Notes;
            $filed[$d] = ob_get_contents();
            ob_end_clean();
            //echo $filed[$d]; //(Print available)
      //Phone
            ob_start();
            $f++;
            echo $result[]= $contact->Phone;
            $filef[$f] = ob_get_contents();
            ob_end_clean();
            //echo $filef[$f]; //(Print available)
       //State
            ob_start();
            $g++;
            echo $result[]= $contact->State;
            $fileg[$g] = ob_get_contents();
            ob_end_clean();
            //echo $fileg[$g]; //(Print available)
      //Postcode
            ob_start();
            $h++;
           echo $result[]= $contact->Postcode;
            $fileh[$h] = ob_get_contents();
            ob_end_clean();
            //echo $fileh[$h]; //(Print available)
                    }
                   }
                  }
                 }
                }
               }
              }
             }
            }
           }
          }
         }
        }
       }
      }
     }
    }
     //Witch contact 1,2,3,4,...
       $k = 1;
      //Code
       echo 'Code   = ' .$filei[1];
      //AddressLine2
      echo 'AddressLine   = ' .$fileo[$k];
      //BusinessPhone
      echo 'BusinessPhone = ' .$filep[$k];
      //City
      echo 'City = ' .$fileq[$k];
      //Country
      echo 'Country = ' .$filew[$k];
      //Created
      echo 'created =  ' . $filee[$k];
      //Email
      echo 'Email = ' . $filer[$k];
      //BusinessFax
      echo 'BusinessFax  = ' . $filet[$k];
      //FirstName
      echo 'FirstName = ' .$filey[$k];
      //LastName
      echo 'Your last name = ' .$fileu[$k];
      //Initials
      echo 'Title = ' .$filea[$k];
      //Mobile
      echo 'Mobile = ' . $files[$k];
      //Notes
      echo 'Notes = ' .  $filed[$k];
      //Phone
      echo 'Phone = ' .  $filef[$k];
      //State
      echo 'State = ' .  $fileg[$k];
      //Postcode
      echo 'Postcode = ' . $fileh[$k];

        json_encode($result);
    } catch (\Exception $e) {
        json_encode(array(get_class($e) . ' : ' . $e->getMessage()));
    }

   =====================================
                   Autotask
                 Connection
    =====================================
    require_once 'C:\xampp\htdocs\Api\Autotask\vendor\autoload.php';
    $username = '++++++++++++++++++++++++++++++++++++++';
    $password = '++++++++++++++++';

    $contact= new ATWS\AutotaskObjects\Contact();
    $contact->id = 0; //0 for new and ID for update
    $contact->AccountID = 236;
    $contact->AlternatePhone = $filep[$k];
    $contact->Country = $filew[$k];
    $contact->CreatDate = $filee[$k];
    $contact->EMailAddress = $filer[$k];
    $contact->FirstName = $filey[$k];
    $contact->LastName = $fileu[$k];
    $contact->MobilePhone = $files[$k];
    $contact->Phone = $filef[$k];
    $contact->Active = '0';

    //$contact->AddressLine = $fileo[$k];+
    //$contact->City = $fileq[$k];+
    //$contact->FaxNumber = $filet[$k];+
    //$contact->MiddleInitial = $filea[$k];+
    //$contact->Note = $filed[$k];+
    //$contact->State = $fileg[$k];+
    //$contact->ZipCode = $fileh[$k];+
    echo "Auotask client created";

    $authWsdl = 'https://webservices.autotask.net/atservices/1.5/atws.wsdl';
    $opts = array('trace' => 1);
    $client = new ATWS\Client($authWsdl, $opts);
    $zoneInfo = $client->getZoneInfo($username);

    $authOpts = array(
        'login' => $username,
        'password' => $password,
        'trace' => 1,   // Allows us to debug by getting the XML requests sent
    );
    $wsdl = str_replace('.asmx', '.wsdl', $zoneInfo->getZoneInfoResult->URL);
    $client = new ATWS\Client($wsdl, $authOpts);

    print_r($client->create($contact));
</code>```

This is the output i get if i run php script.

```<code>Code = 24
    AddressLine = 000000000
    BusinessPhone = 040-44445511
    City = 0000000
    Country = NL
    created = /Date(1493085780497)/
    Email = test@sportmartbv.nl
    BusinessFax = 000000
    FirstName = Ellis
    Your last name = Renners
    Title = MEVR
    Mobile = 0682121519
    Notes = 000000000
    Phone = 040-444151151
    State = 000000000
    Postcode = 00000000
</code>```

I would like to get full user information in the output.

Any help would be greatly appreciated.

答:
for($i=0;$i<1;){...} is equivalent to $i=0; while($i<1){...} so you should make sure that at some point, the value of $i changes and you leave the loop.

In your case, if $result = $contact->get(); returns an empty list, you won't enter the foreach and therefore you will never reach the parts with $x++ (replace x with whatever one-char variable you used in your nested for loops).

You usually add $i++ in the third input of a for, or you can add another condition, like :

```<code>$iterations=0;
for($i=0; $i<1 && $iterations<50; $iterations++)
{
    ...
}
</code>```

so the loop will run until either $i >= 1 or $iterations >= 50.

Which means unless you change $iterations' value in your loop, it will run 50 times max.

This is in case you are expecting the input to change at some point, but if you really want to just get one input, you shouldn't use a for loop at all, instead just remove all those loops, remove all $x++; (with x in all your one-char variable names) and use only one variable initialized to 0.

Again, it is considered good practice to name your variables in an intelligible way.

Note : Nothing from the above is php-specific, this is algorithmics -- common to most programming languages.

Body:
I tried to get data of "Contact" but i can't get these tags "AddressLine, City, FaxNumber, MiddelInitial, Note, State, ZipCode"

When i looked in ExactOnline i saw that under "Contact" Voornaam, Tussenvoegsel, Achternaam, Functienaam, Telefoon, Mobiel, E-mail and these are the thing I only get a output of (if its filled in).

Then I looked further and I saw "Relatie" over here are the parts i want but can't call it.

How can i fix this?

 ================================
           Exactonline
           Connection
 ================================

try {
        //Code
        for($i = 0; $i <1;) {
        //AddressLine2
        for($o = 0; $o <1;) {
        //BusinessPhone
        for($p = 0; $p <1;) {
        //City
        for($q = 0; $q <1;) {
        //Country
        for($w = 0; $w <1;) {
        //Created
        for($e = 0; $e <1;) {
        //Email
        for($r = 0; $r <1;) {
        //BusinessFax
        for($t = 0; $t <1;) {
        //FirstName
        for($y = 0; $y <1;) {
        //LastName
        for($u = 0; $u <1;) {
        //Initials
        for($a = 0; $a <1;) {
        //Mobile
        for($s = 0; $s <1;) {
        //Notes
        for($d = 0; $d <1;) {
        //Phone
        for($f = 0; $f <1;) {
        //State
        for($g = 0; $g <1;) {
        //Postcode
        for($h = 0; $h <1;) {

        $result = array();
        $contact = new \Picqer\Financials\Exact\Contact($connection);
        $result   = $contact->get();
        foreach ($result as $contact) {
        //Code
            ob_start();
            $i++;
            echo $result[]= $contact->Code;
            $filei[$i] = ob_get_contents();
            ob_end_clean();
            //echo $filei[$i]; //(Print available)
         //AddressLine2
            ob_start();
            $o++;
            echo $result[]= $contact->AddressLine2;
            $fileo[$o] = ob_get_contents();
            ob_end_clean();
            //echo $fileo[$o]; //(Print available)
          //BusinessPhone
            ob_start();
            $p++;
            echo $result[]= $contact->BusinessPhone;
            $filep[$p] = ob_get_contents();
            ob_end_clean();
            //echo $fileo[$p]; //(Print available)
          //City
            ob_start();
            $q++;
            echo $result[]= $contact->City;
            $fileq[$q] = ob_get_contents();
            ob_end_clean();
            //echo $fileq[$q]; //(Print available)
          //Country
            ob_start();
            $w++;
            echo $result[]= $contact->Country;
            $filew[$w] = ob_get_contents();
            ob_end_clean();
            //echo $filea[$a]; //(Print available
         //Created
            ob_start();
            $e++;
            echo $result[]= $contact->Created;
            $filee[$e] = ob_get_contents();
            ob_end_clean();
            //echo $filee[$e]; //(Print available)
        //Email
            ob_start();
            $r++;
            echo $result[]= $contact->Email;
            $filer[$r] = ob_get_contents();
            ob_end_clean();
            //echo $filer[$r]; //(Print available)
        //BusinessFax
            ob_start();
            $t++;
            echo $result[]= $contact->BusinessFax;
            $filet[$t] = ob_get_contents();
            ob_end_clean();
            //echo $filet[$t]; //(Print available)
       //FirstName
            ob_start();
            $y++;
            echo $result[]= $contact->FirstName;
            $filey[$y] = ob_get_contents();
            ob_end_clean();
            //echo $filey[$y]; //(Print available)
       //LastName
            ob_start();
            $u++;
            echo $result[]= $contact->LastName;
            $fileu[$u] = ob_get_contents();
            ob_end_clean();
            //echo $fileu[$u]; //(Print available)
       //Title
            ob_start();
            $a++;
            echo $result[]= $contact->Title;
            $filea[$a] = ob_get_contents();
            ob_end_clean();
            //echo $filea[$a]; //(Print available)
       //Mobile
            ob_start();
            $s++;
            echo $result[]= $contact->Mobile;
            $files[$s] = ob_get_contents();
            ob_end_clean();
            //echo $files[$s]; //(Print available)
       //Notes
            ob_start();
            $d++;
            echo $result[]= $contact->Notes;
            $filed[$d] = ob_get_contents();
            ob_end_clean();
            //echo $filed[$d]; //(Print available)
      //Phone
            ob_start();
            $f++;
            echo $result[]= $contact->Phone;
            $filef[$f] = ob_get_contents();
            ob_end_clean();
            //echo $filef[$f]; //(Print available)
       //State
            ob_start();
            $g++;
            echo $result[]= $contact->State;
            $fileg[$g] = ob_get_contents();
            ob_end_clean();
            //echo $fileg[$g]; //(Print available)
      //Postcode
            ob_start();
            $h++;
           echo $result[]= $contact->Postcode;
            $fileh[$h] = ob_get_contents();
            ob_end_clean();
            //echo $fileh[$h]; //(Print available)
                    }
                   }
                  }
                 }
                }
               }
              }
             }
            }
           }
          }
         }
        }
       }
      }
     }
    }
     //Witch contact 1,2,3,4,...
       $k = 1;
      //Code
       echo 'Code   = ' .$filei[1];
      //AddressLine2
      echo 'AddressLine   = ' .$fileo[$k];
      //BusinessPhone
      echo 'BusinessPhone = ' .$filep[$k];
      //City
      echo 'City = ' .$fileq[$k];
      //Country
      echo 'Country = ' .$filew[$k];
      //Created
      echo 'created =  ' . $filee[$k];
      //Email
      echo 'Email = ' . $filer[$k];
      //BusinessFax
      echo 'BusinessFax  = ' . $filet[$k];
      //FirstName
      echo 'FirstName = ' .$filey[$k];
      //LastName
      echo 'Your last name = ' .$fileu[$k];
      //Initials
      echo 'Title = ' .$filea[$k];
      //Mobile
      echo 'Mobile = ' . $files[$k];
      //Notes
      echo 'Notes = ' .  $filed[$k];
      //Phone
      echo 'Phone = ' .  $filef[$k];
      //State
      echo 'State = ' .  $fileg[$k];
      //Postcode
      echo 'Postcode = ' . $fileh[$k];

        json_encode($result);
    } catch (\Exception $e) {
        json_encode(array(get_class($e) . ' : ' . $e->getMessage()));
    }

   =====================================
                   Autotask
                 Connection
    =====================================
    require_once 'C:\xampp\htdocs\Api\Autotask\vendor\autoload.php';
    $username = '++++++++++++++++++++++++++++++++++++++';
    $password = '++++++++++++++++';

    $contact= new ATWS\AutotaskObjects\Contact();
    $contact->id = 0; //0 for new and ID for update
    $contact->AccountID = 236;
    $contact->AlternatePhone = $filep[$k];
    $contact->Country = $filew[$k];
    $contact->CreatDate = $filee[$k];
    $contact->EMailAddress = $filer[$k];
    $contact->FirstName = $filey[$k];
    $contact->LastName = $fileu[$k];
    $contact->MobilePhone = $files[$k];
    $contact->Phone = $filef[$k];
    $contact->Active = '0';

    //$contact->AddressLine = $fileo[$k];+
    //$contact->City = $fileq[$k];+
    //$contact->FaxNumber = $filet[$k];+
    //$contact->MiddleInitial = $filea[$k];+
    //$contact->Note = $filed[$k];+
    //$contact->State = $fileg[$k];+
    //$contact->ZipCode = $fileh[$k];+
    echo "Auotask client created";

    $authWsdl = 'https://webservices.autotask.net/atservices/1.5/atws.wsdl';
    $opts = array('trace' => 1);
    $client = new ATWS\Client($authWsdl, $opts);
    $zoneInfo = $client->getZoneInfo($username);

    $authOpts = array(
        'login' => $username,
        'password' => $password,
        'trace' => 1,   // Allows us to debug by getting the XML requests sent
    );
    $wsdl = str_replace('.asmx', '.wsdl', $zoneInfo->getZoneInfoResult->URL);
    $client = new ATWS\Client($wsdl, $authOpts);

    print_r($client->create($contact));

This is the output i get if i run php script.

Code = 24
    AddressLine = 000000000
    BusinessPhone = 040-44445511
    City = 0000000
    Country = NL
    created = /Date(1493085780497)/
    Email = test@sportmartbv.nl
    BusinessFax = 000000
    FirstName = Ellis
    Your last name = Renners
    Title = MEVR
    Mobile = 0682121519
    Notes = 000000000
    Phone = 040-444151151
    State = 000000000
    Postcode = 00000000

I would like to get full user information in the output.

Any help would be greatly appreciated.

Body:
for($i=0;$i<1;){...} is equivalent to $i=0; while($i<1){...} so you should make sure that at some point, the value of $i changes and you leave the loop.

In your case, if $result = $contact->get(); returns an empty list, you won't enter the foreach and therefore you will never reach the parts with $x++ (replace x with whatever one-char variable you used in your nested for loops).

You usually add $i++ in the third input of a for, or you can add another condition, like :

$iterations=0;
for($i=0; $i<1 && $iterations<50; $iterations++)
{
    ...
}

so the loop will run until either $i >= 1 or $iterations >= 50.

Which means unless you change $iterations' value in your loop, it will run 50 times max.

This is in case you are expecting the input to change at some point, but if you really want to just get one input, you shouldn't use a for loop at all, instead just remove all those loops, remove all $x++; (with x in all your one-char variable names) and use only one variable initialized to 0.

Again, it is considered good practice to name your variables in an intelligible way.

Note : Nothing from the above is php-specific, this is algorithmics -- common to most programming languages.


来源: stackexchange

问:
Chrome tracking for dutch language
I have a c# EXE to track the URL in the Chrome browser. it works fine with chrome in English language but nit with the Dutch language.when I change the chrome language to Dutch it won't work, if you how to solve this please share.
Here is my code</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Windows.Automation;
using System.Threading;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.IO;
using SendKeys;
namespace close_chrome
{
    class Program
    {
        static void Main(string[] args)
        {

            int iCount=0;
            while (true)
            {
                ChromeUrl();
                iCount++;
                if (iCount > 100)
                    break;
                Thread.Sleep(500);
            }
            Console.ReadKey(); //Wait for keypress to terminate
        }

       static void ChromeUrl()
        {
            string strurl;
            foreach (Process process in Process.GetProcessesByName("chrome"))
            {
                if (process.MainWindowHandle == IntPtr.Zero) // some have no UI
                    continue;

                AutomationElement element = AutomationElement.FromHandle(process.MainWindowHandle);
                if (element != null)
                {
                    var SearchBar = element.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Address and search bar"));
                    string name = element.Current.NativeWindowHandle.ToString();
                    Console.WriteLine(name);
                    name = element.GetCurrentPropertyValue(AutomationElement.NameProperty) as string;
                    Console.WriteLine(name);
                    if (SearchBar != null)
                    {
                        strurl = (string)SearchBar.GetCurrentPropertyValue(ValuePatternIdentifiers.ValueProperty);
                        Console.WriteLine(strurl);
                    }
                }
            }
        }
    }
}
</code>```

答:
replace Address and search bar dutch language

```<code>var SearchBar = element.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Address and search bar"));
</code>```

with Adres

```<code>var SearchBar = element.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Adres"));
</code>```

ContentLicense: CC BY-SA 3.0

Title: Chrome tracking for dutch language

Body:
I have a c# EXE to track the URL in the Chrome browser. it works fine with chrome in English language but nit with the Dutch language.when I change the chrome language to Dutch it won't work, if you how to solve this please share.
Here is my code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Windows.Automation;
using System.Threading;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.IO;
using SendKeys;
namespace close_chrome
{
    class Program
    {
        static void Main(string[] args)
        {

            int iCount=0;
            while (true)
            {
                ChromeUrl();
                iCount++;
                if (iCount > 100)
                    break;
                Thread.Sleep(500);
            }
            Console.ReadKey(); //Wait for keypress to terminate
        }

       static void ChromeUrl()
        {
            string strurl;
            foreach (Process process in Process.GetProcessesByName("chrome"))
            {
                if (process.MainWindowHandle == IntPtr.Zero) // some have no UI
                    continue;

                AutomationElement element = AutomationElement.FromHandle(process.MainWindowHandle);
                if (element != null)
                {
                    var SearchBar = element.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Address and search bar"));
                    string name = element.Current.NativeWindowHandle.ToString();
                    Console.WriteLine(name);
                    name = element.GetCurrentPropertyValue(AutomationElement.NameProperty) as string;
                    Console.WriteLine(name);
                    if (SearchBar != null)
                    {
                        strurl = (string)SearchBar.GetCurrentPropertyValue(ValuePatternIdentifiers.ValueProperty);
                        Console.WriteLine(strurl);
                    }
                }
            }
        }
    }
}

Body:
replace Address and search bar dutch language

var SearchBar = element.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Address and search bar"));

with Adres

var SearchBar = element.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Adres"));


问:
cmd for loop escape ? in set?
Is there a way to escape the question mark in the for loop so that the following would work?

```<code>for %%a in (%*) do (
for %%b in (/? /h /help -h -help --help) do if %%a==%%b goto usage
)
</code>```

It would be so much cleaner than separate if's. In a separate if clause %%a==/^? works but not here.

答: In addition to the "params" work-around failing when %* is empty: if you prefix %* with a space: set params= %*, it will not be empty in the %params:/?=%" and the comparison will not fail.

Title: cmd for loop escape ? in set?

Body:
Is there a way to escape the question mark in the for loop so that the following would work?

for %%a in (%*) do (
for %%b in (/? /h /help -h -help --help) do if %%a==%%b goto usage
)

It would be so much cleaner than separate if's. In a separate if clause %%a==/^? works but not here.


问:
Why enums require an explicit cast to int type?
There is no data loss by doing this, so what's the reason for having to explicitly cast enums to ints?

Would it not be more intuitive if it was implicit, say when you have a higher level method like:

```<code>PerformOperation ( OperationType.Silent type )
</code>```

where PerformOperation calls a wrapped C++ method that's exposed as such:

```<code>_unmanaged_perform_operation ( int operation_type )
</code>```

答:
Because enums do not have to be int based:

The enum keyword is used to declare an
  enumeration, a distinct type
  consisting of a set of named constants
  called the enumerator list. Every
  enumeration type has an underlying
  type, which can be any integral type
  except char.

So you can do something like this:

```<code>enum Something :long  { valueX = 0, valueY = 2147483648L }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
There is no data loss by doing this, so what's the reason for having to explicitly cast enums to ints?

Would it not be more intuitive if it was implicit, say when you have a higher level method like:

PerformOperation ( OperationType.Silent type )

where PerformOperation calls a wrapped C++ method that's exposed as such:

_unmanaged_perform_operation ( int operation_type )

Body:
Because enums do not have to be int based:

The enum keyword is used to declare an
  enumeration, a distinct type
  consisting of a set of named constants
  called the enumerator list. Every
  enumeration type has an underlying
  type, which can be any integral type
  except char.

So you can do something like this:

enum Something :long  { valueX = 0, valueY = 2147483648L }


问:
Why I get error when I submit login form using jQuery Post?
I have this partial view:

```<code>@model GeomindEnterprise.Models.LoginViewModel

<div class="row">
    <div class="col-md-6 col-sm-6 col-xs-6">
        <!-- /SOCIAL LOGIN -->
        @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "sky-form", role = "form" }))
        {

            <fieldset class="nomargin">
                <div class="row">
                    <div class="col-md-10 col-md-offset-1">
                        @Html.AntiForgeryToken()

                        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                        <label class="input margin-bottom-10">
                            <i class="ico-append fa fa-envelope"></i>
                            @Html.TextBoxFor(m => m.UserName, new { @placeholder = "Email" })
                            @Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })
                        </label>

                        <label class="input margin-bottom-10">
                            <i class="ico-append fa fa-lock"></i>
                            @Html.PasswordFor(m => m.Password, new { placeholder = "Password" })
                            @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
                        </label>

                        <label class="form-group">
                            @Html.CheckBoxFor(m => m.RememberMe, new { @class = "col-md-1" })
                            @Html.LabelFor(m => m.RememberMe)
                        </label>

                        <footer>
                            <button type="submit" onclick="myFunction()" class="btn btn-default noradius pull-right"><i class="fa fa-check"></i> OK, LOG IN</button>
                        </footer>
                    </div>
                </div>

            </fieldset>

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

When I click button submit, this javascript method is called:

```<code> function myFunction() {
        debugger;
        jQuery.ajax({
            type: "POST",
            url: '@Url.Action("Login", "Account")',
            contentType: "application/json; charset=utf-8",
            data: jQuery('form').serialize(),
            datatype: "json",
            success: function (data) {
                debugger;
                jQuery('#myModalContent').html(data);
            },
            error: function () {
                alert("Dynamic content load failed.");
            }
        });
    }
</code>```

The javascript method above calls this action:

```<code>//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    //some logic
}
</code>```

When the acction Login is called I get this error:

```<code>    The required anti-forgery form field "__RequestVerificationToken" is not present.
</code>```

Any idea why I get this error?And how to fix it?

答:
Remove the  @Html.AntiForgeryToken() from your form. it will work for now.How ever it will open you for attacks.
Here is the article on anti forgery token to secure yourself.

https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks

Body:
I have this partial view:

@model GeomindEnterprise.Models.LoginViewModel

        @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "sky-form", role = "form" }))
        {

            <fieldset class="nomargin">

                        @Html.AntiForgeryToken()

                        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                            @Html.TextBoxFor(m => m.UserName, new { @placeholder = "Email" })
                            @Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })

                            @Html.PasswordFor(m => m.Password, new { placeholder = "Password" })
                            @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })

                            @Html.CheckBoxFor(m => m.RememberMe, new { @class = "col-md-1" })
                            @Html.LabelFor(m => m.RememberMe)

                            <button type="submit" onclick="myFunction()" class="btn btn-default noradius pull-right"> OK, LOG IN</button>

            </fieldset>

        }

When I click button submit, this javascript method is called:

 function myFunction() {
        debugger;
        jQuery.ajax({
            type: "POST",
            url: '@Url.Action("Login", "Account")',
            contentType: "application/json; charset=utf-8",
            data: jQuery('form').serialize(),
            datatype: "json",
            success: function (data) {
                debugger;
                jQuery('#myModalContent').html(data);
            },
            error: function () {
                alert("Dynamic content load failed.");
            }
        });
    }

The javascript method above calls this action:

//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    //some logic
}

When the acction Login is called I get this error:

    The required anti-forgery form field "__RequestVerificationToken" is not present.

Any idea why I get this error?And how to fix it?


问:
Why does Spark fail with java.lang.OutOfMemoryError: GC overhead limit exceeded?
I'm trying to implement a Hadoop Map/Reduce job that worked fine before in Spark. The Spark app definition is the following:

```<code>val data = spark.textFile(file, 2).cache()
val result = data
  .map(//some pre-processing)
  .map(docWeightPar => (docWeightPar(0),docWeightPar(1))))
  .flatMap(line => MyFunctions.combine(line))
  .reduceByKey( _ + _)
</code>```

Where MyFunctions.combine is

```<code>def combine(tuples: Array[(String, String)]): IndexedSeq[(String,Double)] =
  for (i <- 0 to tuples.length - 2;
       j <- 1 to tuples.length - 1
  ) yield (toKey(tuples(i)._1,tuples(j)._1),tuples(i)._2.toDouble * tuples(j)._2.toDouble)
</code>```

The combine function produces lots of map keys if the list used for input is big and this is where the exceptions is thrown.

In the Hadoop Map Reduce setting I didn't have problems because this is the point where the combine function yields was the point Hadoop wrote the map pairs to disk. Spark seems to keep all in memory until it explodes with a java.lang.OutOfMemoryError: GC overhead limit exceeded.

I am probably doing something really basic wrong but I couldn't find any pointers on how to come forward from this, I would like to know how I can avoid this. Since I am a total noob at Scala and Spark I am not sure if the problem is from one or from the other, or both. I am currently trying to run this program in my own laptop, and it works for inputs where the length of the tuples array is not very long.

答:
This JVM garbage collection error happened reproducibly in my case when I increased the spark.memory.fraction to values greater than 0.6 . So it is better to leave the value at it's default value to avoid JVM garbage collection errors. This is also recommended by https://forums.databricks.com/questions/2202/javalangoutofmemoryerror-gc-overhead-limit-exceede.html .

For more information one why 0.6 is the best value for spark.memory.fraction see  https://issues.apache.org/jira/browse/SPARK-15796 .

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to implement a Hadoop Map/Reduce job that worked fine before in Spark. The Spark app definition is the following:

val data = spark.textFile(file, 2).cache()
val result = data
  .map(//some pre-processing)
  .map(docWeightPar => (docWeightPar(0),docWeightPar(1))))
  .flatMap(line => MyFunctions.combine(line))
  .reduceByKey( _ + _)

Where MyFunctions.combine is

def combine(tuples: Array[(String, String)]): IndexedSeq[(String,Double)] =
  for (i <- 0 to tuples.length - 2;
       j <- 1 to tuples.length - 1
  ) yield (toKey(tuples(i)._1,tuples(j)._1),tuples(i)._2.toDouble * tuples(j)._2.toDouble)

The combine function produces lots of map keys if the list used for input is big and this is where the exceptions is thrown.

In the Hadoop Map Reduce setting I didn't have problems because this is the point where the combine function yields was the point Hadoop wrote the map pairs to disk. Spark seems to keep all in memory until it explodes with a java.lang.OutOfMemoryError: GC overhead limit exceeded.

I am probably doing something really basic wrong but I couldn't find any pointers on how to come forward from this, I would like to know how I can avoid this. Since I am a total noob at Scala and Spark I am not sure if the problem is from one or from the other, or both. I am currently trying to run this program in my own laptop, and it works for inputs where the length of the tuples array is not very long.


问:
Keycloak: authZ with nodeJS
I am trying to secure a REST API using keycloak authorization mechanisms.
My API is in NodeJS with express.

Say I have this API:

```<code>http://www.example.com/api/v1/houses
</code>```

The endpoint supports GET/POST/PUT/DELETE.
A house has a name and an owner:

```<code>{
  name: 'myhouse',
  owner: 'smith'
}
</code>```

Everybody can view houses. You can also create houses, and automatically become the owner. Only the owner can delete a house. It's similar to the photoz example.

Using Keycloak Connect in bearer-only mode works with nodeJS express:

```<code>router.get('/houses*', keycloakProtect(), myHandler)
</code>```

But this provides only Authentication, not Authorization. Basically it just checks that you provided the correct token.
KeycloakProtect provides a rudimentary authorization mechanism, based only on role names.
However, I would like to use the full power of client authorizations (with resources, scopes and policies)...
Is there any NodeJS support for that? If no, how to use the Keycloak API for that?

答:
I found a beginning of answer using the API:

```<code>TOKEN=`curl -X POST  -H "Content-Type: application/x-www-form-urlencoded" -d 'username=username&password=password&grant_type=password&client_id=myclient&client_secret=myclientsecret' "http://localhost:8080/auth/realms/myrealm/protocol/openid-connect/token" | jq .access_token -r`

curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d '{
    "permissions" : [
        {
            "resource_set_name" : "Houses",
            "scopes" : [
                "view"
            ]
        }
    ]
}'  "http://localhost:8080/auth/realms/myrealm/authz/entitlement/myclient"
</code>```

The second call will reply with 200 if authorized and 403 if not.

To define authorization policies in Keycloak, switch on "Authorizations" in your client. On the new "Authorization" tab:

Settings

Enable "remote resource management"

Resource Create one:

name: Houses

scopes: create, view, update, delete

uri: /houses/*

Scopes create 4 scopes: create, view, update, delete

Policies Create a role based policy with:

name: public_role_policy

description: user must have role "public" to be allowed

realm roles: public

Permissions Create one with:

name: "public role allows to view houses"

resource: Houses

scopes: view

policy: public_role_policy

You must also create a realm role "public" and give it to your users.

Next what you need to do is to create resources remotely.
First get a client token:

```<code>TOKEN=`curl -X POST \
-H "Content-Type: application/x-www-form-urlencoded" \
-d 'grant_type=client_credentials&client_id=myclient&client_secret=myclientsecret'
"http://localhost:8080/auth/realms/${realm_name}/protocol/openid-connect/token" | jq .access_token -r`
</code>```

Then create resources:

```<code>curl -X POST "http://localhost:8080/auth/realms/myrealm/authz/protection/resource_set" -H "Authorization: Bearer $TOKEN" -d '{
    "name": "My house",
    "uri": "/houses/123",
    "scopes": [
      {
        "id": "da776461-c1f5-4904-a559-1ca04d9f53a9",
        "name": "view"
      },
      {
        "id": "2615157c-f588-4e2b-ba1c-720fe8394215",
        "name": "manage"
      }
    ],
    "owner": "0892e431-5daf-413e-b4cf-eaee121ee447"
}'
</code>```

Title: Keycloak: authZ with nodeJS

Body:
I am trying to secure a REST API using keycloak authorization mechanisms.
My API is in NodeJS with express.

Say I have this API:

http://www.example.com/api/v1/houses

The endpoint supports GET/POST/PUT/DELETE.
A house has a name and an owner:

{
  name: 'myhouse',
  owner: 'smith'
}

Everybody can view houses. You can also create houses, and automatically become the owner. Only the owner can delete a house. It's similar to the photoz example.

Using Keycloak Connect in bearer-only mode works with nodeJS express:

router.get('/houses*', keycloakProtect(), myHandler)

But this provides only Authentication, not Authorization. Basically it just checks that you provided the correct token.
KeycloakProtect provides a rudimentary authorization mechanism, based only on role names.
However, I would like to use the full power of client authorizations (with resources, scopes and policies)...
Is there any NodeJS support for that? If no, how to use the Keycloak API for that?

Body:
I found a beginning of answer using the API:

TOKEN=`curl -X POST  -H "Content-Type: application/x-www-form-urlencoded" -d 'username=username&password=password&grant_type=password&client_id=myclient&client_secret=myclientsecret' "http://localhost:8080/auth/realms/myrealm/protocol/openid-connect/token" | jq .access_token -r`

curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d '{
    "permissions" : [
        {
            "resource_set_name" : "Houses",
            "scopes" : [
                "view"
            ]
        }
    ]
}'  "http://localhost:8080/auth/realms/myrealm/authz/entitlement/myclient"

The second call will reply with 200 if authorized and 403 if not.

To define authorization policies in Keycloak, switch on "Authorizations" in your client. On the new "Authorization" tab:

Settings

Enable "remote resource management"

Resource Create one:

name: Houses

scopes: create, view, update, delete

uri: /houses/*

Scopes create 4 scopes: create, view, update, delete

Policies Create a role based policy with:

name: public_role_policy

description: user must have role "public" to be allowed

realm roles: public

Permissions Create one with:

name: "public role allows to view houses"

resource: Houses

scopes: view

policy: public_role_policy

You must also create a realm role "public" and give it to your users.

Next what you need to do is to create resources remotely.
First get a client token:

TOKEN=`curl -X POST \
-H "Content-Type: application/x-www-form-urlencoded" \
-d 'grant_type=client_credentials&client_id=myclient&client_secret=myclientsecret'
"http://localhost:8080/auth/realms/${realm_name}/protocol/openid-connect/token" | jq .access_token -r`

Then create resources:

curl -X POST "http://localhost:8080/auth/realms/myrealm/authz/protection/resource_set" -H "Authorization: Bearer $TOKEN" -d '{
    "name": "My house",
    "uri": "/houses/123",
    "scopes": [
      {
        "id": "da776461-c1f5-4904-a559-1ca04d9f53a9",
        "name": "view"
      },
      {
        "id": "2615157c-f588-4e2b-ba1c-720fe8394215",
        "name": "manage"
      }
    ],
    "owner": "0892e431-5daf-413e-b4cf-eaee121ee447"
}'


问:
dynamodb java many to one
i wanted to try out dynamodb

I was able to save a single Object.
Now i wanted to try to create a many to one association.

Many Tasks sould be attached to a single User.

```<code>@DynamoDBTable(tableName = "User")
public class User {
    private String id;
    List<Task> tasks = new ArrayList<Task>();

    @DynamoDBHashKey
    @DynamoDBAutoGeneratedKey
    public String getId() {
        return id;
    }

    @DynamoDBAttribute
    public List<Task> getTasks() {
        return this.tasks;
    }

    public void setTasks(List<Task> taskMap) {
        this.tasks = taskMap;
    }

    public void addTask(Task task){
        this.tasks.add(task);
    }
}

@DynamoDBTable(tableName = "Task")
public class Task {
    private String id;
    private String name;

    @DynamoDBHashKey
    @DynamoDBAutoGeneratedKey
    public String getId() {
        return id;
    }

    public Task(String name) {
        this.name = name;
    }

    @DynamoDBAttribute
    public String getName(){
        return this.name;
    }

    public void setname(String name){
        this.name = name;
    }
}
</code>```

and now i am trying to save the user with the coresponding tasks

```<code>Task task1 = new Task("test");
Task task2 = new Task("test2");
User user = new User();
user.addTask(task1);
user.addTask(task2);
userRepository.save(user);
</code>```

I know it doesn't work like this but maybe someone can give me an example on how to do it.

in a relational database world the tables would look something like this

```<code>User
id|.....

Task
id|name

User_Tasks
user_id|task_id
</code>```

But how to do it the right way with dynamodb

THANKS!

答:
I hope you are saving both User and Task in single DynamoDB table (i.e. User). Please annotate the task class with @DynamoDBDocument rather than @DynamoDBTable.

```<code>@DynamoDBDocument
public class Task {

}
</code>```

Add getters/setters accordingly and an empty constructor

Title: dynamodb java many to one

Body:
i wanted to try out dynamodb

I was able to save a single Object.
Now i wanted to try to create a many to one association.

Many Tasks sould be attached to a single User.

@DynamoDBTable(tableName = "User")
public class User {
    private String id;
    List<Task> tasks = new ArrayList<Task>();

    @DynamoDBHashKey
    @DynamoDBAutoGeneratedKey
    public String getId() {
        return id;
    }

    @DynamoDBAttribute
    public List<Task> getTasks() {
        return this.tasks;
    }

    public void setTasks(List<Task> taskMap) {
        this.tasks = taskMap;
    }

    public void addTask(Task task){
        this.tasks.add(task);
    }
}

@DynamoDBTable(tableName = "Task")
public class Task {
    private String id;
    private String name;

    @DynamoDBHashKey
    @DynamoDBAutoGeneratedKey
    public String getId() {
        return id;
    }

    public Task(String name) {
        this.name = name;
    }

    @DynamoDBAttribute
    public String getName(){
        return this.name;
    }

    public void setname(String name){
        this.name = name;
    }
}

and now i am trying to save the user with the coresponding tasks

Task task1 = new Task("test");
Task task2 = new Task("test2");
User user = new User();
user.addTask(task1);
user.addTask(task2);
userRepository.save(user);

I know it doesn't work like this but maybe someone can give me an example on how to do it.

in a relational database world the tables would look something like this

User
id|.....

Task
id|name

User_Tasks
user_id|task_id

But how to do it the right way with dynamodb

THANKS!

Body:
I hope you are saving both User and Task in single DynamoDB table (i.e. User). Please annotate the task class with @DynamoDBDocument rather than @DynamoDBTable.

@DynamoDBDocument
public class Task {

}

Add getters/setters accordingly and an empty constructor


问:
WordPress geolocation posts?
I would like to build something along the lines of this

http://demo.woothemes.com/cityguide/

Where I can click a point on the map which will link to a post, I would also like this to be search able by post code or town, so if you wanted to find shops in London, you'd type London and it would show all relative posts which are in that location.

All info is greatly appreciated guys :)

答: I think this plugin makes what you want to achieve: Post Google Map (from  WebDevStudios.com). You can add to any post a geolocation, then show all of them in the home page, with a link to each post from the map.</p>

Title: WordPress geolocation posts?


问:
React : How to call component in Array.map?
i'm using react-toolbox and tabs.

i would like to make an object like:

```<code>var Tabs = [
        {
            value: 0,
            label: 'First Tab',
            componentName : "MyAwesomeComponent"
        },
        {
            value: 1,
            label: 'Second Tab',
            componentName : "MyOtherAwesomeComponent"
        }
    ]
</code>```

and then, in render's return function

```<code><Tabs index={this.state.tabs.index} onChange={this.tabs.handleChange}>
    {this.Tabs.map((item,index) => (
        <Tab label={item.label}>
              **** Here, i want to call {item.componentName} component. ***
        </Tab>
     ))}
</Tabs>
</code>```

is this possible to call component by name?

Thanks a lot.

答:
You could use something like: </p>

```<code>import MyAwesomeComponent from 'path/to/MyAwesomeComponent'
import MyOtherAwesomeComponent from 'path/to/MyOtherAwesomeComponent'

const myComponents = {
  'MyAwesomeComponent': MyAwesomeComponent,
  'MyOtherAwesomeComponent': MyOtherAwesomeComponent,
}

<Tabs index={this.state.tabs.index} onChange={this.tabs.handleChange}>
    {this.Tabs.map((item,index) => {
      const Component = myComponents[item.componentName]

      return (
        <Tab label={item.label}>
          <Component value={item.value} label={item.label} />
        </Tab>
      )
    })}
</Tabs>
</code>```

Body:
i'm using react-toolbox and tabs.

i would like to make an object like:

var Tabs = [
        {
            value: 0,
            label: 'First Tab',
            componentName : "MyAwesomeComponent"
        },
        {
            value: 1,
            label: 'Second Tab',
            componentName : "MyOtherAwesomeComponent"
        }
    ]

and then, in render's return function

<Tabs index={this.state.tabs.index} onChange={this.tabs.handleChange}>
    {this.Tabs.map((item,index) => (
        <Tab label={item.label}>
              **** Here, i want to call {item.componentName} component. ***
        </Tab>
     ))}
</Tabs>

is this possible to call component by name?

Thanks a lot.

Body:
You could use something like:

import MyAwesomeComponent from 'path/to/MyAwesomeComponent'
import MyOtherAwesomeComponent from 'path/to/MyOtherAwesomeComponent'

const myComponents = {
  'MyAwesomeComponent': MyAwesomeComponent,
  'MyOtherAwesomeComponent': MyOtherAwesomeComponent,
}

<Tabs index={this.state.tabs.index} onChange={this.tabs.handleChange}>
    {this.Tabs.map((item,index) => {
      const Component = myComponents[item.componentName]

      return (
        <Tab label={item.label}>
          <Component value={item.value} label={item.label} />
        </Tab>
      )
    })}
</Tabs>


问:
SQL query to Twig
I have a WordPress with the last version.
I'm using "All in one calendar" by time.ly and I would like, for each event, return the end date by using SQL query. (i dont want to use {{event.end}}).

First, I'm overriding the function for the twig file :

```<code>add_filter( 'ai1ec_theme_args_agenda-widget.twig', 'mytheme_agenda_widget_args', 10, 2 );

function mytheme_agenda_widget_args( $args, $is_admin ) {
    global $wpdb;
    date_default_timezone_set('Europe/Paris');
    foreach ( $args['dates'] as $date => &$date_info ) {
        foreach ( $date_info['events'] as &$category ) {
            foreach ( $category as &$event ) {
                $post_id = $event->get( 'post_id' );
                $sql = "SELECT end FROM og2rm_ai1ec_event_instances WHERE post_id = ".$post_id." ORDER BY id DESC ;";
                $results = $wpdb->get_results($sql);
                $end_date = strftime('%d %b', $results[0]->end);

                $args['custom_field'] =  array("post_id" => $post_id, "end_date" => $end_date);

                echo "```";
                print_r($args['custom_field']);
                echo "```";
      }
    }
  }
  return $args;
}
</code>```

My echo  pre return :

```<code>Array
(
    [post_id] => 21451
    [end_date] => 13 Nov
)

Array
(
    [post_id] => 21438
    [end_date] => 09 Dec
)

Array
(
    [post_id] => 21389
    [end_date] => 13 Nov
)

Array
(
    [post_id] => 21438
    [end_date] => 09 Dec
)

Array
(
    [post_id] => 21438
    [end_date] => 09 Dec
)
[••••]
</code>```

But when I'm using my variable ```{{ custom_field.end_date }}``` in my twig file, only the last value of my foreach returned for every event ...

Some one have an idea ?

Thanks.

答:
The problem lies in the following line:

```<code>$args['custom_field'] =  array("post_id" => $post_id, "end_date" => $end_date);
</code>```

You are overwriting the variable in each loop. The echo does not care because it runs inside the loop, but the return only gets the last value.

You might want to do something like this:

```<code>$args['custom_field'][] = array("post_id" => $post_id, "end_date" => $end_date);
</code>```

or maybe:

```<code> $args['custom_field'][$post_id] = array("post_id" => $post_id, "end_date" => $end_date);
</code>```

You could also improve your code by moving the SQL-query outside the loop and using something like WHERE post_id IN (?) where ? is a comma separated list of post_ids. Then you will only send one query and you will get all post_id's and end date's as result from the query instead of fetching them one by one.

Title: SQL query to Twig

Body:
I have a WordPress with the last version.
I'm using "All in one calendar" by time.ly and I would like, for each event, return the end date by using SQL query. (i dont want to use {{event.end}}).

First, I'm overriding the function for the twig file :

add_filter( 'ai1ec_theme_args_agenda-widget.twig', 'mytheme_agenda_widget_args', 10, 2 );

function mytheme_agenda_widget_args( $args, $is_admin ) {
    global $wpdb;
    date_default_timezone_set('Europe/Paris');
    foreach ( $args['dates'] as $date => &$date_info ) {
        foreach ( $date_info['events'] as &$category ) {
            foreach ( $category as &$event ) {
                $post_id = $event->get( 'post_id' );
                $sql = "SELECT end FROM og2rm_ai1ec_event_instances WHERE post_id = ".$post_id." ORDER BY id DESC ;";
                $results = $wpdb->get_results($sql);
                $end_date = strftime('%d %b', $results[0]->end);

                $args['custom_field'] =  array("post_id" => $post_id, "end_date" => $end_date);

                echo "
";
                print_r($args['custom_field']);
                echo "
";
      }
    }
  }
  return $args;
}

My echo  pre return :

Array
(
    [post_id] => 21451
    [end_date] => 13 Nov
)

Array
(
    [post_id] => 21438
    [end_date] => 09 Dec
)

Array
(
    [post_id] => 21389
    [end_date] => 13 Nov
)

Array
(
    [post_id] => 21438
    [end_date] => 09 Dec
)

Array
(
    [post_id] => 21438
    [end_date] => 09 Dec
)
[••••]

But when I'm using my variable
{{ custom_field.end_date }}
 in my twig file, only the last value of my foreach returned for every event ...

Some one have an idea ?

Thanks.

Body:
The problem lies in the following line:

$args['custom_field'] =  array("post_id" => $post_id, "end_date" => $end_date);

You are overwriting the variable in each loop. The echo does not care because it runs inside the loop, but the return only gets the last value.

You might want to do something like this:

$args['custom_field'][] = array("post_id" => $post_id, "end_date" => $end_date);

or maybe:

 $args['custom_field'][$post_id] = array("post_id" => $post_id, "end_date" => $end_date);

You could also improve your code by moving the SQL-query outside the loop and using something like WHERE post_id IN (?) where ? is a comma separated list of post_ids. Then you will only send one query and you will get all post_id's and end date's as result from the query instead of fetching them one by one.


问:
Create PDF from a list of images
Is there any practical way to create a PDF from a list of images files, using Python?

In Perl I know that module. With it I can create a PDF in just 3 lines:

```<code>use PDF::FromImage;
...
my $pdf = PDF::FromImage->new;
$pdf->load_images(@allPagesDir);
$pdf->write_file($bookName . '.pdf');
</code>```

I need to do something very similar to this, but in Python. I know the pyPdf module, but I would like something simple.

答:
The best method to convert multiple images to PDF I have tried so far is to use PIL purely. It's quite simple yet powerful:

```<code>from PIL import Image  # install by > python3 -m pip install --upgrade Pillow  # ref. https://pillow.readthedocs.io/en/latest/installation.html#basic-installation

images = [
    Image.open("/Users/apple/Desktop/" + f)
    for f in ["bbd.jpg", "bbd1.jpg", "bbd2.jpg"]
]

pdf_path = "/Users/apple/Desktop/bbd1.pdf"

images[0].save(
    pdf_path, "PDF" ,resolution=100.0, save_all=True, append_images=images[1:]
)
</code>```

Just set save_all to True and append_images to the list of images which you want to add.

You might encounter the AttributeError: 'JpegImageFile' object has no attribute 'encoderinfo'. The solution is here Error while saving multiple JPEGs as a multi-page PDF

Note:Install the newest PIL to make sure save_all argument is available for PDF.

p.s.

In case you get this error

cannot save mode RGBA

apply this fix

```<code>png = Image.open('/path/to/your/file.png')
png.load()
background = Image.new("RGB", png.size, (255, 255, 255))
background.paste(png, mask=png.split()[3]) # 3 is the alpha channel
</code>```

Title: Create PDF from a list of images

Body:
Is there any practical way to create a PDF from a list of images files, using Python?

In Perl I know that module. With it I can create a PDF in just 3 lines:

use PDF::FromImage;
...
my $pdf = PDF::FromImage->new;
$pdf->load_images(@allPagesDir);
$pdf->write_file($bookName . '.pdf');

I need to do something very similar to this, but in Python. I know the pyPdf module, but I would like something simple.

Body:
The best method to convert multiple images to PDF I have tried so far is to use PIL purely. It's quite simple yet powerful:

from PIL import Image  # install by > python3 -m pip install --upgrade Pillow  # ref. https://pillow.readthedocs.io/en/latest/installation.html#basic-installation

images = [
    Image.open("/Users/apple/Desktop/" + f)
    for f in ["bbd.jpg", "bbd1.jpg", "bbd2.jpg"]
]

pdf_path = "/Users/apple/Desktop/bbd1.pdf"

images[0].save(
    pdf_path, "PDF" ,resolution=100.0, save_all=True, append_images=images[1:]
)

Just set save_all to True and append_images to the list of images which you want to add.

You might encounter the AttributeError: 'JpegImageFile' object has no attribute 'encoderinfo'. The solution is here Error while saving multiple JPEGs as a multi-page PDF

Note:Install the newest PIL to make sure save_all argument is available for PDF.

p.s.

In case you get this error

cannot save mode RGBA

apply this fix

png = Image.open('/path/to/your/file.png')
png.load()
background = Image.new("RGB", png.size, (255, 255, 255))
background.paste(png, mask=png.split()[3]) # 3 is the alpha channel


问:
How to run Android Studio 3.0 from command line as root user in Mac
I need to run Android Studio 3.0 in root user to give permission to SDK manager (as SDK Manager is no longer Standalone) to install components to the root directory.

If you are getting Permission Denied errors for any component installation, this can be one of the solutions.

答:
If you have installed Android Studio in the default Applications directory, this is where it will be. Else you can cd into it's path

cd /Applications/Android\ Studio.app/Contents/MacOS/

then run it as root user by executing

sudo ./studio


问:
App got rejected in app store due to black screen in iOS 9.2.1
I submitted the app on app store which supports iOS 7 and later with only portrait support for iPhone. We have launch images for both iPad and iPhone. We are doing everything programmatically and using Xcode7.2 . But apple rejected stating :

We discovered one or more bugs in your app when reviewed on an iPad running iOS 9.2.1 and an iPhone running iOS 9.2.1 on both Wi-Fi and cellular networks.
- App boots to a black screen, no further action occurs.

We did not came across this issue. Can anybody please help me in knowing what might be the issue.

答:
It could also be due to targeting an app for iPhone only and using IF or SWITCH statements somewhere in the code to control the layout design (Full screen BG image, size of the view, etc.). The IF/SWITCH statements perhaps don't count on any other case of device than iPhone, so add one line to address this even for iPads. Something like this:</p>

```<code>UIImage *img = [UIImage alloc];

if([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPhone) {

    switch ((int)[[UIScreen mainScreen] nativeBounds].size.height) {

        case 1136:
            printf("iPhone 5 or 5S or 5C");
            img = [UIImage imageNamed:@"bg.png"];
            break;
        case 1334:
            printf("iPhone 6/6S/7/8");
            img = [UIImage imageNamed:@"bg1334.png"];
            break;
        case 2208:
            printf("iPhone 6+/6S+/7+/8+");
            img = [UIImage imageNamed:@"bg2208.png"];
            break;
        case 2436:
            printf("iPhone X");
            img = [UIImage imageNamed:@"bg-iPhone-X.png"];
            break;
        default:
            printf("unknown"); // -------------------  iPad issue solved!
            img = [UIImage imageNamed:@"bg1334.png"];
    }
}

UIImageView *bgImageV = [[UIImageView alloc] initWithImage:img];
bgImageV.frame = self.view.frame;
[self.view addSubview:bgImageV];

bgImageV.layer.zPosition = -15;
bgImageV.contentMode = UIViewContentModeCenter;
</code>```

Body:
It could also be due to targeting an app for iPhone only and using IF or SWITCH statements somewhere in the code to control the layout design (Full screen BG image, size of the view, etc.). The IF/SWITCH statements perhaps don't count on any other case of device than iPhone, so add one line to address this even for iPads. Something like this:

UIImage *img = [UIImage alloc];

if([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPhone) {

    switch ((int)[[UIScreen mainScreen] nativeBounds].size.height) {

        case 1136:
            printf("iPhone 5 or 5S or 5C");
            img = [UIImage imageNamed:@"bg.png"];
            break;
        case 1334:
            printf("iPhone 6/6S/7/8");
            img = [UIImage imageNamed:@"bg1334.png"];
            break;
        case 2208:
            printf("iPhone 6+/6S+/7+/8+");
            img = [UIImage imageNamed:@"bg2208.png"];
            break;
        case 2436:
            printf("iPhone X");
            img = [UIImage imageNamed:@"bg-iPhone-X.png"];
            break;
        default:
            printf("unknown"); // -------------------  iPad issue solved!
            img = [UIImage imageNamed:@"bg1334.png"];
    }
}

UIImageView *bgImageV = [[UIImageView alloc] initWithImage:img];
bgImageV.frame = self.view.frame;
[self.view addSubview:bgImageV];

bgImageV.layer.zPosition = -15;
bgImageV.contentMode = UIViewContentModeCenter;


问:
Object of type 'ListSerializer' is not JSON serializable
I want to get all customer data and responses and also remarks.
This is model.py

```<code>class Customer(models.Model):

name = models.CharField(max_length=200)
email_address = models.CharField(max_length=200)
phone_number = models.CharField(max_length=20)
age = models.SmallIntegerField(default=14)
remarks = models.ManyToManyField(Remark,null=True,blank=True)
created_at = models.DateTimeField(auto_now_add=True)

def __str__(self):
    return str(self.id)

class Response(models.Model):

question = models.ForeignKey(Question)
customer = models.ForeignKey(Customer)
response_text = models.CharField(max_length=100, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
uuid = models.UUIDField()

def __str__(self):
    return str(self.id)
</code>```

This is serializers.py

```<code>class ResponseSerializer(ModelSerializer):
  class Meta:
    model = Response
    fields = '__all__'

class RemarksSerializer(ModelSerializer):
  class Meta:
    model = Remark
    fields = '__all__'

class CustomerInformationSerializer(ModelSerializer):
  remarks = RemarksSerializer(many=True)
  responses = serializers.SerializerMethodField()

  def get_responses(self, obj):
    responses = Response.objects.filter(customer=obj)
    return ResponseSerializer(responses, many=True)

  class Meta:
    model = Customer
    fields = ('name', 'email_address', 'phone_number', 'age', 'remarks', 'responses')
</code>```

This is services.py

```<code>def customer_information(company_id=1):
  cus = Customer.objects.filter(remarks__company_id=company_id)
  return CustomerInformationSerializer(cus, many=True).data
</code>```

This is views.py

```<code>class CustomerInformationView(APIView):
  def get(self, request):
     company_id = request.GET.get('company_id', 1)
     resp = {'data': customer_information(company_id)}
     return Response(data=resp, status=status.HTTP_200_OK)
</code>```

This is url.py

```<code> url(r'^customer/$', CustomerInformationView.as_view()),
</code>```

I'm having this problem. How can I solve this. Kindly guide me.

答:
SIDE NOTE

First, let me point you to a resource that I think is GREAT for anything dealing with Django REST Framework:

Classy Django REST Framework. It is a fantastic resource because you can easily dig right into the source code to see how you may or may not need to override default operations.

MY ANSWER

What I suggest is that instead of using the APIView, you use ListAPIView.

It would look something like this:

```<code>from rest_framework.generics import ListAPIView

class Customer(models.Model):
    name = models.CharField(max_length=200)
    email_address = models.CharField(max_length=200)
    phone_number = models.CharField(max_length=20)
    age = models.SmallIntegerField(default=14)
    remarks = models.ManyToManyField(Remark,null=True,blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.id)

class Response(models.Model):
    question = models.ForeignKey(Question)
    customer = models.ForeignKey(Customer, related_name='responses')
    response_text = models.CharField(max_length=100, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    uuid = models.UUIDField()

    def __str__(self):
        return str(self.id)

class ResponseSerializer(ModelSerializer):
    class Meta:
        model = Response
        fields = '__all__'

class RemarksSerializer(ModelSerializer):
    class Meta:
        model = Remark
        fields = '__all__'

class CustomerInformationSerializer(ModelSerializer):
    remarks = RemarksSerializer(many=True)
    responses = ResponseSerializer(many=True)

    class Meta:
        model = Customer
        fields = ('name', 'email_address', 'phone_number', 'age', 'remarks', 'responses')

class CustomerInformationView(ListAPIView):
    queryset = Customer.objects.all()
    serializer_class = CustomerInformationSerializer
    lookup_field = 'remarks__company'
</code>```

Note the change that I made by adding related_name to the customer field on your Response model. See Django documentation for more information on related_name. In short, it adds responses as a field name on your Customer model so that you can travel backwards through that relationship.

This is not tested, but this should be a better strategy to do what you want without having to have a get_responses method, or a services.py.

Body:
I want to get all customer data and responses and also remarks.
This is model.py

class Customer(models.Model):

name = models.CharField(max_length=200)
email_address = models.CharField(max_length=200)
phone_number = models.CharField(max_length=20)
age = models.SmallIntegerField(default=14)
remarks = models.ManyToManyField(Remark,null=True,blank=True)
created_at = models.DateTimeField(auto_now_add=True)

def __str__(self):
    return str(self.id)

class Response(models.Model):

question = models.ForeignKey(Question)
customer = models.ForeignKey(Customer)
response_text = models.CharField(max_length=100, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
uuid = models.UUIDField()

def __str__(self):
    return str(self.id)

This is serializers.py

class ResponseSerializer(ModelSerializer):
  class Meta:
    model = Response
    fields = '__all__'

class RemarksSerializer(ModelSerializer):
  class Meta:
    model = Remark
    fields = '__all__'

class CustomerInformationSerializer(ModelSerializer):
  remarks = RemarksSerializer(many=True)
  responses = serializers.SerializerMethodField()

  def get_responses(self, obj):
    responses = Response.objects.filter(customer=obj)
    return ResponseSerializer(responses, many=True)

  class Meta:
    model = Customer
    fields = ('name', 'email_address', 'phone_number', 'age', 'remarks', 'responses')

This is services.py

def customer_information(company_id=1):
  cus = Customer.objects.filter(remarks__company_id=company_id)
  return CustomerInformationSerializer(cus, many=True).data

This is views.py

class CustomerInformationView(APIView):
  def get(self, request):
     company_id = request.GET.get('company_id', 1)
     resp = {'data': customer_information(company_id)}
     return Response(data=resp, status=status.HTTP_200_OK)

This is url.py

 url(r'^customer/$', CustomerInformationView.as_view()),

I'm having this problem. How can I solve this. Kindly guide me.

Body:
SIDE NOTE

First, let me point you to a resource that I think is GREAT for anything dealing with Django REST Framework:

Classy Django REST Framework. It is a fantastic resource because you can easily dig right into the source code to see how you may or may not need to override default operations.

MY ANSWER

What I suggest is that instead of using the APIView, you use ListAPIView.

It would look something like this:

from rest_framework.generics import ListAPIView

class Customer(models.Model):
    name = models.CharField(max_length=200)
    email_address = models.CharField(max_length=200)
    phone_number = models.CharField(max_length=20)
    age = models.SmallIntegerField(default=14)
    remarks = models.ManyToManyField(Remark,null=True,blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.id)

class Response(models.Model):
    question = models.ForeignKey(Question)
    customer = models.ForeignKey(Customer, related_name='responses')
    response_text = models.CharField(max_length=100, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    uuid = models.UUIDField()

    def __str__(self):
        return str(self.id)

class ResponseSerializer(ModelSerializer):
    class Meta:
        model = Response
        fields = '__all__'

class RemarksSerializer(ModelSerializer):
    class Meta:
        model = Remark
        fields = '__all__'

class CustomerInformationSerializer(ModelSerializer):
    remarks = RemarksSerializer(many=True)
    responses = ResponseSerializer(many=True)

    class Meta:
        model = Customer
        fields = ('name', 'email_address', 'phone_number', 'age', 'remarks', 'responses')

class CustomerInformationView(ListAPIView):
    queryset = Customer.objects.all()
    serializer_class = CustomerInformationSerializer
    lookup_field = 'remarks__company'

Note the change that I made by adding related_name to the customer field on your Response model. See Django documentation for more information on related_name. In short, it adds responses as a field name on your Customer model so that you can travel backwards through that relationship.

This is not tested, but this should be a better strategy to do what you want without having to have a get_responses method, or a services.py.


问:
std::string part into integer
I have a std::string: 01001, I want to get each number:

```<code>std::string foo = "01001";
for (int i=0; i < foo.size(); ++i)
{
   int res = atoi( foo[i] );  // fail
   int res = atoi( &foo[i] ); // ok, but res = 0 in any case
}
</code>```

How to do that?

答:
One simple way, very close to what you have, would be to insert the char into a predefined string, as such:</p>

```<code>std::string foo = "01001";
char str[] = {" "};
for (int i=0; i < foo.size(); ++i)
{
   str[0] = foo[i];
   int res = atoi( str );
}
</code>```

Title: std::string part into integer

Body:
I have a std::string: 01001, I want to get each number:

std::string foo = "01001";
for (int i=0; i < foo.size(); ++i)
{
   int res = atoi( foo[i] );  // fail
   int res = atoi( &foo[i] ); // ok, but res = 0 in any case
}

How to do that?

Body:
One simple way, very close to what you have, would be to insert the char into a predefined string, as such:

std::string foo = "01001";
char str[] = {" "};
for (int i=0; i < foo.size(); ++i)
{
   str[0] = foo[i];
   int res = atoi( str );
}


问:
How to fade out navbar and fade in navbar when mouse hover
So I am pretty new to web application developing and I would like to know how I can achieve this question:

I want the navbar to be faded out all the time from start except when I hover about it with the mouse I want it to fade in and show.
How can I do that?

```<code><nav class="navbar navbar-inverse" role="navigation">
<div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
        <a class="navbar-brand" href='#'>My Spring App</a>
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-navbar-collapse">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#side-navbar-collapse">
            <span class="sr-only">Top Links</span>
            <span class="glyphicon glyphicon-globe"></span>
        </button>
    </div>

    <ul class="nav navbar-nav navbar-left collapse navbar-collapse" id="main-navbar-collapse">
        <li class="menu-item"><a href='<c:url value="/"/>'>Home</a></li>
        <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-hover="dropdown">Hello <b class="caret"></b></a>
            <ul class="dropdown-menu">
                <li><a href='<c:url value="/hello?choice=World"/>'>World</a></li>
                <li><a href='<c:url value="/hello?choice=Kitty"/>'>Kitty</a></li>
                <li class="dropdown-submenu">
                    <a href="#">Languages</a>
                    <ul class="dropdown-menu">
                        <!-- Third level list items on submenu -->
                        <li><a href='#'>Bonjour</li>
                        <!-- Example of conditionally enabling an item based on user role -->
                        <sec:authorize access="hasRole('ROLE_USER')">
                            <li><a href='<c:url value="/hello?choice=Guten%20Tag"/>'>Guten Tag</a></li>
                        </sec:authorize>
                        <sec:authorize access="!hasRole('ROLE_USER')">
                            <li class="disabled"><a href="#">Guten Tag</a></li>
                        </sec:authorize>
                        <li class="divider"></li>
                        <li><a href='<c:url value="/hello?choice=Hola"/>'>¡Hola!</a></li>
                        <li><a href='<c:url value="/hello?choice=Konnichiwa"/>'>Konnichiwa</a></li>
                        <li><a href='<c:url value="/hello?choice=Mabuhay"/>'>Mabuhay!</a></li>
                    </ul>
                </li>
            </ul>
        </li>

        <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-hover="dropdown">Goodbye <b class="caret"></b></a>
            <ul class="dropdown-menu">
                <li><a href='<c:url value="/goodbye/Cruel%20World"/>'>Cruel world</a></li>
            </ul>
        </li>
        <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-hover="dropdown">FCM <b class="caret"></b></a>
            <ul class="dropdown-menu">
                <li><a href='<c:url value="/fcm/?choice=Screen1"/>'>Screen1</a></li>
                <li><a href='<c:url value="/fcm/?choice=Screen2"/>'>Screen2</a></li>
            </ul>
        </li>

    </ul>
</code>```

答:
You're looking for the opacity (opacity - CSS) property. It allows you to set opacity of an element without loosing its dimensions. Next you only have to transition form one state to another on :hover. Check at the bottom for some reference stuff.

Here goes the full code :

.navbar .container-fluid {
  opacity: 0; /*it doesn't show by default*/
  transition: all .2s; /*pick whatever suits best*/
}

.navbar:hover .container-fluid {
  opacity: 1; /*fully visible on :hover*/
  transition: all .2s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="navbar navbar-inverse" role="navigation">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      My Spring App
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-navbar-collapse">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#side-navbar-collapse">
            <span class="sr-only">Top Links</span>
            <span class="glyphicon glyphicon-globe"></span>
        </button>
    </div>

    <ul class="nav navbar-nav navbar-left collapse navbar-collapse" id="main-navbar-collapse">
      <li class="menu-item">'>Home</li>
      <li class="dropdown">
        Hello <b class="caret"></b>
        <ul class="dropdown-menu">
          <li>'>World</li>
          <li>'>Kitty</li>
          <li class="dropdown-submenu">
            Languages
            <ul class="dropdown-menu">
              <!-- Third level list items on submenu -->
              <li>Bonjour</li>
                        <!-- Example of conditionally enabling an item based on user role -->
                        <sec:authorize access="hasRole('ROLE_USER')">
                            <li>'>Guten Tag</li>
              </sec:authorize>
              <sec:authorize access="!hasRole('ROLE_USER')">
                <li class="disabled">Guten Tag</li>
              </sec:authorize>
              <li class="divider"></li>
              <li>'>¡Hola!</li>
              <li>'>Konnichiwa</li>
              <li>'>Mabuhay!</li>
            </ul>
          </li>
        </ul>
      </li>

      <li class="dropdown">
        Goodbye <b class="caret"></b>
        <ul class="dropdown-menu">
          <li>'>Cruel world</li>
        </ul>
      </li>
      <li class="dropdown">
        FCM <b class="caret"></b>
        <ul class="dropdown-menu">
          <li>'>Screen1</li>
          <li>'>Screen2</li>
        </ul>
      </li>

    </ul></code>```

And here is a JS Bin to mess with the code easily: JS Bin

Some reference about transitionning and the CSS used:

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions

https://developer.mozilla.org/fr/docs/Web/CSS/opacity

href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties

Did I get it right ?

Body:
So I am pretty new to web application developing and I would like to know how I can achieve this question:

I want the navbar to be faded out all the time from start except when I hover about it with the mouse I want it to fade in and show.
How can I do that?

        My Spring App
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-navbar-collapse">
            Toggle navigation

        </button>
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#side-navbar-collapse">
            Top Links

        </button>

<a href='<c:url value="/"/>'>Home

            Hello

<a href='<c:url value="/hello?choice=World"/>'>World

<a href='<c:url value="/hello?choice=Kitty"/>'>Kitty

                    Languages

Bonjour

                        <sec:authorize access="hasRole('ROLE_USER')">

<a href='<c:url value="/hello?choice=Guten%20Tag"/>'>Guten Tag

                        </sec:authorize>
                        <sec:authorize access="!hasRole('ROLE_USER')">

Guten Tag

                        </sec:authorize>

<a href='<c:url value="/hello?choice=Hola"/>'>¡Hola!

<a href='<c:url value="/hello?choice=Konnichiwa"/>'>Konnichiwa

<a href='<c:url value="/hello?choice=Mabuhay"/>'>Mabuhay!

            Goodbye

<a href='<c:url value="/goodbye/Cruel%20World"/>'>Cruel world

            FCM

<a href='<c:url value="/fcm/?choice=Screen1"/>'>Screen1

<a href='<c:url value="/fcm/?choice=Screen2"/>'>Screen2

Body:
You're looking for the opacity (opacity - CSS) property. It allows you to set opacity of an element without loosing its dimensions. Next you only have to transition form one state to another on :hover. Check at the bottom for some reference stuff.

Here goes the full code :

.navbar .container-fluid {
  opacity: 0; /*it doesn't show by default*/
  transition: all .2s; /*pick whatever suits best*/
}

.navbar:hover .container-fluid {
  opacity: 1; /*fully visible on :hover*/
  transition: all .2s;
}

<nav class="navbar navbar-inverse" role="navigation">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <a class="navbar-brand" href='#'>My Spring App</a>
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-navbar-collapse">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#side-navbar-collapse">
            <span class="sr-only">Top Links</span>
            <span class="glyphicon glyphicon-globe"></span>
        </button>
    </div>

    <ul class="nav navbar-nav navbar-left collapse navbar-collapse" id="main-navbar-collapse">
      <li class="menu-item"><a href='<c:url value="/"/>'>Home</a></li>
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-hover="dropdown">Hello <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href='<c:url value="/hello?choice=World"/>'>World</a></li>
          <li><a href='<c:url value="/hello?choice=Kitty"/>'>Kitty</a></li>
          <li class="dropdown-submenu">
            <a href="#">Languages</a>
            <ul class="dropdown-menu">
              <!-- Third level list items on submenu -->
              <li><a href='#'>Bonjour</li>
                        <!-- Example of conditionally enabling an item based on user role -->
                        <sec:authorize access="hasRole('ROLE_USER')">
                            <li><a href='<c:url value="/hello?choice=Guten%20Tag"/>'>Guten Tag</a></li>
              </sec:authorize>
              <sec:authorize access="!hasRole('ROLE_USER')">
                <li class="disabled"><a href="#">Guten Tag</a></li>
              </sec:authorize>
              <li class="divider"></li>
              <li><a href='<c:url value="/hello?choice=Hola"/>'>&iexcl;Hola!</a></li>
              <li><a href='<c:url value="/hello?choice=Konnichiwa"/>'>Konnichiwa</a></li>
              <li><a href='<c:url value="/hello?choice=Mabuhay"/>'>Mabuhay!</a></li>
            </ul>
          </li>
        </ul>
      </li>

      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-hover="dropdown">Goodbye <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href='<c:url value="/goodbye/Cruel%20World"/>'>Cruel world</a></li>
        </ul>
      </li>
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-hover="dropdown">FCM <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href='<c:url value="/fcm/?choice=Screen1"/>'>Screen1</a></li>
          <li><a href='<c:url value="/fcm/?choice=Screen2"/>'>Screen2</a></li>
        </ul>
      </li>

    </ul>

And here is a JS Bin to mess with the code easily: JS Bin

Some reference about transitionning and the CSS used:

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions

https://developer.mozilla.org/fr/docs/Web/CSS/opacity

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties

Did I get it right ?


问:
converting excel(.xlsx) file to JSON
I have excel sheet called sampledata.xlsx which i converted into json and console.log to print this data.

server.js

var xlsx2json = require('xlsx2json')

xlsx2json(
    'sampledata.xlsx',
{
    dataStartingRow: 2,
    mapping: {
        'name': 'B',//name
        'sku': 'C',//unit price            //sku
        'quantity': 'D',//quantity

    }
}).then(jsonArray => {
    // [
    //     {"col_1": "Barton LCC", "col_2": "30", "col_3": "86.69"}
    // ]

//console.log(jsonArray);
});```

with the help of this doc.
What i want to do here is,in my sampledata.xlsx file i have more data like flat,address,price,etc here i already don't know which fields are present in my excel sheet but i want all that to be console.log.How could i do this is there any way to do this.

答:
```<code>npm install xlsx-to-json-lc --save
npm install xls-to-json-lc --save
</code>```

var exceltojson = require("xls-to-json-lc");
  exceltojson({
    input: "pass the input excel file here (.xls format)"
    output: "if you want output to be stored in a file"
    sheet: "sheetname",  // specific sheetname inside excel file (if you have multiple sheets)
    lowerCaseHeaders:true //to convert all excel headers to lowr case in json
  }, function(err, result) {
    if(err) {
      console.error(err);
    } else {
      console.log(result);
      //result will contain the overted json data
    }
  });```

Title: converting excel(.xlsx) file to JSON

Body:
I have excel sheet called sampledata.xlsx which i converted into json and console.log to print this data.

server.js

var xlsx2json = require('xlsx2json')

xlsx2json(
    'sampledata.xlsx',
{
    dataStartingRow: 2,
    mapping: {
        'name': 'B',//name
        'sku': 'C',//unit price            //sku
        'quantity': 'D',//quantity

    }
}).then(jsonArray => {
    // [
    //     {"col_1": "Barton LCC", "col_2": "30", "col_3": "86.69"}
    // ]

//console.log(jsonArray);
});

with the help of this doc.
What i want to do here is,in my sampledata.xlsx file i have more data like flat,address,price,etc here i already don't know which fields are present in my excel sheet but i want all that to be console.log.How could i do this is there any way to do this.

Body:
npm install xlsx-to-json-lc --save
npm install xls-to-json-lc --save

var exceltojson = require("xls-to-json-lc");
  exceltojson({
    input: "pass the input excel file here (.xls format)"
    output: "if you want output to be stored in a file"
    sheet: "sheetname",  // specific sheetname inside excel file (if you have multiple sheets)
    lowerCaseHeaders:true //to convert all excel headers to lowr case in json
  }, function(err, result) {
    if(err) {
      console.error(err);
    } else {
      console.log(result);
      //result will contain the overted json data
    }
  });


问:
C# Microsoft Sync Framework - MetadataStore on WebDAV server
I'd like to implement a simple custom provider to do file synchronization between local files and a webdav server with the help of microsoft sync framework. The only example for a simple file sync provider that I've found is for local use: https://code.msdn.microsoft.com/windowsdesktop/File-Sync-with-Simple-c497bf87/sourcecode?fileId=19013&pathId=1569663015

My problem is that I don't know how to adjust the MetadataStore in order to get saved on the remote server. Here are some changes that I've made to the code:

```<code>public MySimpleSyncFileProvider(Guid guidReplica, string rootFolder)
    {
        this._replicaId = new SyncId(guidReplica);
        this._rootFolder = "/";

        // Find location for metadata store
        string metaDir = Path.Combine(_rootFolder, ".metadata");
        WebDAV.CreateDirectory(metaDir);
        WebDAV.SetAttributes(metaDir, WebDAVFileAttribute.isHidden);

        string metadataPath = Path.Combine(_rootFolder, ".metadata\\filemeta");

        // Open it
        if (WebDAV.Exists(metadataPath))
            this._metadataStore = SqlMetadataStore.OpenStore(metadataPath); //TODO
        else
            this._metadataStore = SqlMetadataStore.CreateStore(metadataPath); //TODO
    }
</code>```

I would have to change the "OpenStore" and "CreateStore" method, but I was not able to overwrite the SqlMetadataStore.

Do you have any suggestions? Or maybe an example how to implement a custom FileSyncProvider for webdav services?

Please help me.

答: I fixed that problem by simply storing the MetadataStore files on the local machine and using network shares.</p>

Body:
I'd like to implement a simple custom provider to do file synchronization between local files and a webdav server with the help of microsoft sync framework. The only example for a simple file sync provider that I've found is for local use: https://code.msdn.microsoft.com/windowsdesktop/File-Sync-with-Simple-c497bf87/sourcecode?fileId=19013&pathId=1569663015

My problem is that I don't know how to adjust the MetadataStore in order to get saved on the remote server. Here are some changes that I've made to the code:

public MySimpleSyncFileProvider(Guid guidReplica, string rootFolder)
    {
        this._replicaId = new SyncId(guidReplica);
        this._rootFolder = "/";

        // Find location for metadata store
        string metaDir = Path.Combine(_rootFolder, ".metadata");
        WebDAV.CreateDirectory(metaDir);
        WebDAV.SetAttributes(metaDir, WebDAVFileAttribute.isHidden);

        string metadataPath = Path.Combine(_rootFolder, ".metadata\\filemeta");

        // Open it
        if (WebDAV.Exists(metadataPath))
            this._metadataStore = SqlMetadataStore.OpenStore(metadataPath); //TODO
        else
            this._metadataStore = SqlMetadataStore.CreateStore(metadataPath); //TODO
    }

I would have to change the "OpenStore" and "CreateStore" method, but I was not able to overwrite the SqlMetadataStore.

Do you have any suggestions? Or maybe an example how to implement a custom FileSyncProvider for webdav services?

Please help me.