问:
Referencing a Range in Excel
I have named the range C6:C13 'Date'. This is a dynamic range(the start date will vary) and in practice, it will be a very long column. E6 will be created from C6, so the cell E6 will be '=Date'. Rather than dragging this formula down a few thousand rows, I wish to be able to enter '=Date' in column E, and for it to fill as many rows as are filled in in Column C. The problem is that the amount of rows will vary, and if I just enter '=Date' in all of the rows down to 100k or whatever, of course '#VALUE!' will be entered in many rows below(I realise this is a non-issue in many cases but it's a big problem for me). </p>

<p>So is there a way to reference '=Date' in Column E, in only as many rows that are filled in column C? </p>

答:
```<code>=ifError(Date,"")
</code>```

Should do what you want if I'm not mistaken

Title: Referencing a Range in Excel

Body:
I have named the range C6:C13 'Date'. This is a dynamic range(the start date will vary) and in practice, it will be a very long column. E6 will be created from C6, so the cell E6 will be '=Date'. Rather than dragging this formula down a few thousand rows, I wish to be able to enter '=Date' in column E, and for it to fill as many rows as are filled in in Column C. The problem is that the amount of rows will vary, and if I just enter '=Date' in all of the rows down to 100k or whatever, of course '#VALUE!' will be entered in many rows below(I realise this is a non-issue in many cases but it's a big problem for me).

So is there a way to reference '=Date' in Column E, in only as many rows that are filled in column C?

Body:
=ifError(Date,"")

Should do what you want if I'm not mistaken


来源: stackexchange

问:
How to select data to array field?
TableA:

```<code>idA: 1, name: John;
</code>```

TableB:

```<code>idB: 1, product: milk, idA: 1;
idB: 2, product: egg, idA: 1;
</code>```

And I want the finally JSON result look like that:

```<code>[
    {
        "idA": 1,
        "name": "John",
        "TableB": [
            {
                "idB": 1,
                "product": "milk",
                "idA": 1
            },
            {
                "idB": 2,
                "product": "egg",
                "idA": 1
            }
        ]
    }
]
</code>```

I'm using PHP and mySQL.
How's the query should be?
Thanks too much!
I'm so sorry because my English isn't well.

答:
Get the rows from SQL with an inner join:

```<code>select TableA.*, TableB.* from TableA, TableB where TableA.idA = TableB.idA
</code>```

Format the data in PHP:

```<code>$formattedResults = array(
"idA" => $result.idA, "name" =>  $result.name, "TableB" => array();
);
foreach ($results as $result) {
    $formattedResults["TableB"][] = array("idB"=> result.idB, "product"=>
    result.product, "idA"=> result.idA;);
}

$json = json_encode($formattedResults);
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to select data to array field?

Body:
TableA:

idA: 1, name: John;

TableB:

idB: 1, product: milk, idA: 1;
idB: 2, product: egg, idA: 1;

And I want the finally JSON result look like that:

[
    {
        "idA": 1,
        "name": "John",
        "TableB": [
            {
                "idB": 1,
                "product": "milk",
                "idA": 1
            },
            {
                "idB": 2,
                "product": "egg",
                "idA": 1
            }
        ]
    }
]

I'm using PHP and mySQL.
How's the query should be?
Thanks too much!
I'm so sorry because my English isn't well.

Body:
Get the rows from SQL with an inner join:

select TableA.*, TableB.* from TableA, TableB where TableA.idA = TableB.idA

Format the data in PHP:

$formattedResults = array(
"idA" => $result.idA, "name" =>  $result.name, "TableB" => array();
);
foreach ($results as $result) {
    $formattedResults["TableB"][] = array("idB"=> result.idB, "product"=>
    result.product, "idA"=> result.idA;);
}

$json = json_encode($formattedResults);


问:
Selenium xpath: element not visible on Amazon site
I am trying to write a Selenium test against Amazon site. I want to get "Sign in"  element so that I can click on it.

url: www.amazon.ca

Here is my Selenium Code:

```<code>driver.findElement(By.xpath("//a[@data-nav-role='signin']")).click();
</code>```

But I get Element not visible exception.

I have tried putting Thread.sleep(5000) before element lookup but still the same issue.

I have other ways to pick the element but I want to find out why this Xpath not working in my code.

Note: When trying it in Chrome DevTool Console, it works fine there $x("//a[@data-nav-role='signin']")

答:
I have checked the site and we need to mouse over to the menu before to make the sign in  button visible. Below code might give you some idea.

```<code>//Mouse over to the menu
Actions action = new Actions(webdriver);
WebElement we = webdriver.findElement(By.xpath("//*[@id=\'nav-link-yourAccount\']/span[1]"));
action.moveToElement(we).build().perform();
//Now perform sign in button clicking action since its visible now
</code>```

Hope this helps you. Thanks.

Body:
I am trying to write a Selenium test against Amazon site. I want to get "Sign in"  element so that I can click on it.

url: www.amazon.ca

Here is my Selenium Code:

driver.findElement(By.xpath("//a[@data-nav-role='signin']")).click();

But I get Element not visible exception.

I have tried putting Thread.sleep(5000) before element lookup but still the same issue.

I have other ways to pick the element but I want to find out why this Xpath not working in my code.

Note: When trying it in Chrome DevTool Console, it works fine there $x("//a[@data-nav-role='signin']")

Body:
I have checked the site and we need to mouse over to the menu before to make the sign in  button visible. Below code might give you some idea.

//Mouse over to the menu
Actions action = new Actions(webdriver);
WebElement we = webdriver.findElement(By.xpath("//*[@id=\'nav-link-yourAccount\']/span[1]"));
action.moveToElement(we).build().perform();
//Now perform sign in button clicking action since its visible now

Hope this helps you. Thanks.


问:
Java: Possible to use a single for-loop instead of two?
My code is as below. It first takes input from user and prints it in reverse. I'm new to Java. I achieve this by using two 'for loops' to first iterate through the input and another for-loop to print the numbers in reverse. My question is if there's any way to improve my code - by using just a single loop perhaps? Any suggestion is appreciated. Thank you.

```<code>public static void main (String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int arr[] = new int[n];

    for (int arr_i = 0; arr_i < n; arr_i++) {
        arr[arr_i] = in.nextInt();
    }

    for (int reverse_i = n-1; reverse_i >= 0; reverse_i--) {
        System.out.print(arr[reverse_i]);

        if (reverse_i != 0) {
            System.out.print(" ");
        }
    }
}
</code>```

An example input:

```<code>4
1 2 3 4
</code>```

Expected output:

```<code>4 3 2 1
</code>```

答:
First, you might reverse your elements as you insert them in the array. Then, assuming you are using Java 8+, you could use an IntStream instead of a loop and print with a basic Collector. Like,

```<code>Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
IntStream.range(0, n).forEachOrdered(i -> arr[n - i - 1] = in.nextInt());
System.out.println(IntStream.of(arr).mapToObj(String::valueOf)
        .collect(Collectors.joining(" ")));
</code>```

Body:
My code is as below. It first takes input from user and prints it in reverse. I'm new to Java. I achieve this by using two 'for loops' to first iterate through the input and another for-loop to print the numbers in reverse. My question is if there's any way to improve my code - by using just a single loop perhaps? Any suggestion is appreciated. Thank you.

public static void main (String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int arr[] = new int[n];

    for (int arr_i = 0; arr_i < n; arr_i++) {
        arr[arr_i] = in.nextInt();
    }

    for (int reverse_i = n-1; reverse_i >= 0; reverse_i--) {
        System.out.print(arr[reverse_i]);

        if (reverse_i != 0) {
            System.out.print(" ");
        }
    }
}

An example input:

4
1 2 3 4

Expected output:

4 3 2 1

Body:
First, you might reverse your elements as you insert them in the array. Then, assuming you are using Java 8+, you could use an IntStream instead of a loop and print with a basic Collector. Like,

Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
IntStream.range(0, n).forEachOrdered(i -> arr[n - i - 1] = in.nextInt());
System.out.println(IntStream.of(arr).mapToObj(String::valueOf)
        .collect(Collectors.joining(" ")));


问:
Windows 10 Mobile UWP app prefers cellular data over wifi. How to handle multiple network connections
I have Windows 10 Mobile application. I noticed the other day that some of my server communication and network access calls/code were all failing. The mobile device I was using had Cellular data and Wifi options both turned on in the settings. I was connected to my Wifi just fine. However, the cellular data was not activated on this device. It shows cellular is turned on and shows some bars but the service is not activated with the carrier.

During troubleshooting, I turned off the cellular data option in settings and once I did that, all of my server and network access code started working again (ie. not throwing exceptions).

I have been searching for a while and have not been able to find the answer to my assumption that Windows 10 Mobile, when both cellular data and wifi are turned on will default to using cellular first, even if cellular is not working. Is this true? Maybe a better way to ask the question is, how does the device handle when you have two data connection sources enabled? How does it choose which one to use?

Maybe the follow up question also is, how do I force it to use one or the other? I have seen during me research, alot of code on how to detect which network connection is active but not much information on what happens if more than one are active and how to force the OS to use one or the other. This could come in handy if I want to seamlessly switch my calls from wifi to cellular. For example, prefer wifi and use wifi but if you go out of range of wifi, then switch to cellular.

Thanks!

答:
When we connect the Wifi, the UWP app will use the WIFI no matter the Cellular data is turn on.

You can use the following code to check your UWP app use cellular data or Wifi, you can also check the signal level of the current network.

```<code>ConnectionProfile profile = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile();
if (profile.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess)
{
    Debug.WriteLine("InternetAccess");
}
var signal = profile.GetSignalBars();
Debug.WriteLine("signal is:"+signal);
if (profile.IsWlanConnectionProfile)
{
    Debug.WriteLine("Wifi");
}
else if (profile.IsWwanConnectionProfile)
{
    Debug.WriteLine("Cellular");
}
</code>```

When Cellular data and Wifi options both turned on in the settings and they are connected, ConnectionProfile.IsWwanConnectionProfile will return true.

When the Wifi is disconnected, it will use the Cellular data automatic. We can not force UWP app use cellular data or Wifi by code. We can add the NetworkInformation.NetworkStatusChanged, it occurs when the network status changes for a connection. When the Wifi is disconnected, the event will be fired and ConnectionProfile.IsWwanConnectionProfile will return true.

Body:
When we connect the Wifi, the UWP app will use the WIFI no matter the Cellular data is turn on.

You can use the following code to check your UWP app use cellular data or Wifi, you can also check the signal level of the current network.

ConnectionProfile profile = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile();
if (profile.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess)
{
    Debug.WriteLine("InternetAccess");
}
var signal = profile.GetSignalBars();
Debug.WriteLine("signal is:"+signal);
if (profile.IsWlanConnectionProfile)
{
    Debug.WriteLine("Wifi");
}
else if (profile.IsWwanConnectionProfile)
{
    Debug.WriteLine("Cellular");
}

When Cellular data and Wifi options both turned on in the settings and they are connected, ConnectionProfile.IsWwanConnectionProfile will return true.

When the Wifi is disconnected, it will use the Cellular data automatic. We can not force UWP app use cellular data or Wifi by code. We can add the NetworkInformation.NetworkStatusChanged, it occurs when the network status changes for a connection. When the Wifi is disconnected, the event will be fired and ConnectionProfile.IsWwanConnectionProfile will return true.


问:
WebClient not downloading file completely if above 50MB size
I'm using WebClient for downloading files.
But something fishy is going on when it tries to download larger files exactly above 50mb size, download gets completed right after 39kb and does not downloads it till the end.
Anyone knows what could be the issue?

```<code>using (webClient = new WebClient())
{
    webClient.Proxy = null;
    webClient.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)");
    webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
    webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);

    // The variable that will be holding the url address (making sure it starts with http://)
    Uri URL = urlAddress.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ? new Uri(urlAddress) : new Uri("http://" + urlAddress);

    // Start the stopwatch which we will be using to calculate the download speed
    sw.Start();

    try
    {
        // Start downloading the file
        webClient.DownloadFileAsync(URL, _mainWindow.outputDirComboBox.SelectedItem.ToString() + "\\" + _compressedClientFileDownloadRelativePath, new List<object>
        {
            _compressedClientFileDownloadRelativePath,
            _decompressedClientFileDownloadRelativePath,
            _lastDownloadedFilePath,
            _compressedSize,
            _lastCompressedFilePartRelativePath,
            _filePartsRelativePath,
            urlAddress,
            _clientFilePack,
            _clientFile
        });
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
</code>```

DownloadFileCompleted checks only for errors and when its completed but there isnt any error report going on. Only that it finishes downloading as if the download size was only 39kb

Edit1:
While digging i end up here: Downloading Large Google Drive files with WebClient in C#

Looks like Google Drive gives some sort of confirm link but im not yet able to know how to putting all together working.

Edit2:
I just confirmed, the 39kb are the html page confirmation

答:
Thanks Everyone!

After checking this issue:
Downloading Large Google Drive files with WebClient in C#
I searched for getting larger files from google drive with c# and found this:

```<code>using System;
using System.IO;
using System.Net;

public static class FileDownloader
{
    private const string GOOGLE_DRIVE_DOMAIN = "drive.google.com";
    private const string GOOGLE_DRIVE_DOMAIN2 = "https://drive.google.com";

    // Normal example: FileDownloader.DownloadFileFromURLToPath( "http://example.com/file/download/link", @"C:\file.txt" );
    // Drive example: FileDownloader.DownloadFileFromURLToPath( "http://drive.google.com/file/d/FILEID/view?usp=sharing", @"C:\file.txt" );
    public static FileInfo DownloadFileFromURLToPath( string url, string path )
    {
        if( url.StartsWith( GOOGLE_DRIVE_DOMAIN ) || url.StartsWith( GOOGLE_DRIVE_DOMAIN2 ) )
            return DownloadGoogleDriveFileFromURLToPath( url, path );
        else
            return DownloadFileFromURLToPath( url, path, null );
    }

    private static FileInfo DownloadFileFromURLToPath( string url, string path, WebClient webClient )
    {
        try
        {
            if( webClient == null )
            {
                using( webClient = new WebClient() )
                {
                    webClient.DownloadFile( url, path );
                    return new FileInfo( path );
                }
            }
            else
            {
                webClient.DownloadFile( url, path );
                return new FileInfo( path );
            }
        }
        catch( WebException )
        {
            return null;
        }
    }

    // Downloading large files from Google Drive prompts a warning screen and
    // requires manual confirmation. Consider that case and try to confirm the download automatically
    // if warning prompt occurs
    private static FileInfo DownloadGoogleDriveFileFromURLToPath( string url, string path )
    {
        // You can comment the statement below if the provided url is guaranteed to be in the following format:
        // https://drive.google.com/uc?id=FILEID&export=download
        url = GetGoogleDriveDownloadLinkFromUrl( url );

        using( CookieAwareWebClient webClient = new CookieAwareWebClient() )
        {
            FileInfo downloadedFile;

            // Sometimes Drive returns an NID cookie instead of a download_warning cookie at first attempt,
            // but works in the second attempt
            for( int i = 0; i < 2; i++ )
            {
                downloadedFile = DownloadFileFromURLToPath( url, path, webClient );
                if( downloadedFile == null )
                    return null;

                // Confirmation page is around 50KB, shouldn't be larger than 60KB
                if( downloadedFile.Length > 60000 )
                    return downloadedFile;

                // Downloaded file might be the confirmation page, check it
                string content;
                using( var reader = downloadedFile.OpenText() )
                {
                    // Confirmation page starts with <!DOCTYPE html>, which can be preceeded by a newline
                    char[] header = new char[20];
                    int readCount = reader.ReadBlock( header, 0, 20 );
                    if( readCount < 20 || !( new string( header ).Contains( "<!DOCTYPE html>" ) ) )
                        return downloadedFile;

                    content = reader.ReadToEnd();
                }

                int linkIndex = content.LastIndexOf( "href=\"/uc?" );
                if( linkIndex < 0 )
                    return downloadedFile;

                linkIndex += 6;
                int linkEnd = content.IndexOf( '"', linkIndex );
                if( linkEnd < 0 )
                    return downloadedFile;

                url = "https://drive.google.com" + content.Substring( linkIndex, linkEnd - linkIndex ).Replace( "&", "&" );
            }

            downloadedFile = DownloadFileFromURLToPath( url, path, webClient );

            return downloadedFile;
        }
    }

    // Handles 3 kinds of links (they can be preceeded by https://):
    // - drive.google.com/open?id=FILEID
    // - drive.google.com/file/d/FILEID/view?usp=sharing
    // - drive.google.com/uc?id=FILEID&export=download
    public static string GetGoogleDriveDownloadLinkFromUrl( string url )
    {
        int index = url.IndexOf( "id=" );
        int closingIndex;
        if( index > 0 )
        {
            index += 3;
            closingIndex = url.IndexOf( '&', index );
            if( closingIndex < 0 )
                closingIndex = url.Length;
        }
        else
        {
            index = url.IndexOf( "file/d/" );
            if( index < 0 ) // url is not in any of the supported forms
                return string.Empty;

            index += 7;

            closingIndex = url.IndexOf( '/', index );
            if( closingIndex < 0 )
            {
                closingIndex = url.IndexOf( '?', index );
                if( closingIndex < 0 )
                    closingIndex = url.Length;
            }
        }

        return string.Format( "https://drive.google.com/uc?id={0}&export=download", url.Substring( index, closingIndex - index ) );
    }
}

// Web client used for Google Drive
public class CookieAwareWebClient : WebClient
{
    private class CookieContainer
    {
        Dictionary<string, string> _cookies;

        public string this[Uri url]
        {
            get
            {
                string cookie;
                if( _cookies.TryGetValue( url.Host, out cookie ) )
                    return cookie;

                return null;
            }
            set
            {
                _cookies[url.Host] = value;
            }
        }

        public CookieContainer()
        {
            _cookies = new Dictionary<string, string>();
        }
    }

    private CookieContainer cookies;

    public CookieAwareWebClient() : base()
    {
        cookies = new CookieContainer();
    }

    protected override WebRequest GetWebRequest( Uri address )
    {
        WebRequest request = base.GetWebRequest( address );

        if( request is HttpWebRequest )
        {
            string cookie = cookies[address];
            if( cookie != null )
                ( (HttpWebRequest) request ).Headers.Set( "cookie", cookie );
        }

        return request;
    }

    protected override WebResponse GetWebResponse( WebRequest request, IAsyncResult result )
    {
        WebResponse response = base.GetWebResponse( request, result );

        string[] cookies = response.Headers.GetValues( "Set-Cookie" );
        if( cookies != null && cookies.Length > 0 )
        {
            string cookie = "";
            foreach( string c in cookies )
                cookie += c;

            this.cookies[response.ResponseUri] = cookie;
        }

        return response;
    }

    protected override WebResponse GetWebResponse( WebRequest request )
    {
        WebResponse response = base.GetWebResponse( request );

        string[] cookies = response.Headers.GetValues( "Set-Cookie" );
        if( cookies != null && cookies.Length > 0 )
        {
            string cookie = "";
            foreach( string c in cookies )
                cookie += c;

            this.cookies[response.ResponseUri] = cookie;
        }

        return response;
    }
}
</code>```

With that stackoverflow question + this github code i understood it was related with both issues as google sends the confirmation page when file is bigger then 50mb. So after implementing that github code now im able to download large files with my webClient.

Body:
I'm using WebClient for downloading files.
But something fishy is going on when it tries to download larger files exactly above 50mb size, download gets completed right after 39kb and does not downloads it till the end.
Anyone knows what could be the issue?

using (webClient = new WebClient())
{
    webClient.Proxy = null;
    webClient.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)");
    webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
    webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);

    // The variable that will be holding the url address (making sure it starts with http://)
    Uri URL = urlAddress.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ? new Uri(urlAddress) : new Uri("http://" + urlAddress);

    // Start the stopwatch which we will be using to calculate the download speed
    sw.Start();

    try
    {
        // Start downloading the file
        webClient.DownloadFileAsync(URL, _mainWindow.outputDirComboBox.SelectedItem.ToString() + "\\" + _compressedClientFileDownloadRelativePath, new List<object>
        {
            _compressedClientFileDownloadRelativePath,
            _decompressedClientFileDownloadRelativePath,
            _lastDownloadedFilePath,
            _compressedSize,
            _lastCompressedFilePartRelativePath,
            _filePartsRelativePath,
            urlAddress,
            _clientFilePack,
            _clientFile
        });
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

DownloadFileCompleted checks only for errors and when its completed but there isnt any error report going on. Only that it finishes downloading as if the download size was only 39kb

Edit1:
While digging i end up here: Downloading Large Google Drive files with WebClient in C#

Looks like Google Drive gives some sort of confirm link but im not yet able to know how to putting all together working.

Edit2:
I just confirmed, the 39kb are the html page confirmation

Body:
Thanks Everyone!

After checking this issue:
Downloading Large Google Drive files with WebClient in C#
I searched for getting larger files from google drive with c# and found this:

using System;
using System.IO;
using System.Net;

public static class FileDownloader
{
    private const string GOOGLE_DRIVE_DOMAIN = "drive.google.com";
    private const string GOOGLE_DRIVE_DOMAIN2 = "https://drive.google.com";

    // Normal example: FileDownloader.DownloadFileFromURLToPath( "http://example.com/file/download/link", @"C:\file.txt" );
    // Drive example: FileDownloader.DownloadFileFromURLToPath( "http://drive.google.com/file/d/FILEID/view?usp=sharing", @"C:\file.txt" );
    public static FileInfo DownloadFileFromURLToPath( string url, string path )
    {
        if( url.StartsWith( GOOGLE_DRIVE_DOMAIN ) || url.StartsWith( GOOGLE_DRIVE_DOMAIN2 ) )
            return DownloadGoogleDriveFileFromURLToPath( url, path );
        else
            return DownloadFileFromURLToPath( url, path, null );
    }

    private static FileInfo DownloadFileFromURLToPath( string url, string path, WebClient webClient )
    {
        try
        {
            if( webClient == null )
            {
                using( webClient = new WebClient() )
                {
                    webClient.DownloadFile( url, path );
                    return new FileInfo( path );
                }
            }
            else
            {
                webClient.DownloadFile( url, path );
                return new FileInfo( path );
            }
        }
        catch( WebException )
        {
            return null;
        }
    }

    // Downloading large files from Google Drive prompts a warning screen and
    // requires manual confirmation. Consider that case and try to confirm the download automatically
    // if warning prompt occurs
    private static FileInfo DownloadGoogleDriveFileFromURLToPath( string url, string path )
    {
        // You can comment the statement below if the provided url is guaranteed to be in the following format:
        // https://drive.google.com/uc?id=FILEID&export=download
        url = GetGoogleDriveDownloadLinkFromUrl( url );

        using( CookieAwareWebClient webClient = new CookieAwareWebClient() )
        {
            FileInfo downloadedFile;

            // Sometimes Drive returns an NID cookie instead of a download_warning cookie at first attempt,
            // but works in the second attempt
            for( int i = 0; i < 2; i++ )
            {
                downloadedFile = DownloadFileFromURLToPath( url, path, webClient );
                if( downloadedFile == null )
                    return null;

                // Confirmation page is around 50KB, shouldn't be larger than 60KB
                if( downloadedFile.Length > 60000 )
                    return downloadedFile;

                // Downloaded file might be the confirmation page, check it
                string content;
                using( var reader = downloadedFile.OpenText() )
                {
                    // Confirmation page starts with <!DOCTYPE html>, which can be preceeded by a newline
                    char[] header = new char[20];
                    int readCount = reader.ReadBlock( header, 0, 20 );
                    if( readCount < 20 || !( new string( header ).Contains( "<!DOCTYPE html>" ) ) )
                        return downloadedFile;

                    content = reader.ReadToEnd();
                }

                int linkIndex = content.LastIndexOf( "href=\"/uc?" );
                if( linkIndex < 0 )
                    return downloadedFile;

                linkIndex += 6;
                int linkEnd = content.IndexOf( '"', linkIndex );
                if( linkEnd < 0 )
                    return downloadedFile;

                url = "https://drive.google.com" + content.Substring( linkIndex, linkEnd - linkIndex ).Replace( "&amp;", "&" );
            }

            downloadedFile = DownloadFileFromURLToPath( url, path, webClient );

            return downloadedFile;
        }
    }

    // Handles 3 kinds of links (they can be preceeded by https://):
    // - drive.google.com/open?id=FILEID
    // - drive.google.com/file/d/FILEID/view?usp=sharing
    // - drive.google.com/uc?id=FILEID&export=download
    public static string GetGoogleDriveDownloadLinkFromUrl( string url )
    {
        int index = url.IndexOf( "id=" );
        int closingIndex;
        if( index > 0 )
        {
            index += 3;
            closingIndex = url.IndexOf( '&', index );
            if( closingIndex < 0 )
                closingIndex = url.Length;
        }
        else
        {
            index = url.IndexOf( "file/d/" );
            if( index < 0 ) // url is not in any of the supported forms
                return string.Empty;

            index += 7;

            closingIndex = url.IndexOf( '/', index );
            if( closingIndex < 0 )
            {
                closingIndex = url.IndexOf( '?', index );
                if( closingIndex < 0 )
                    closingIndex = url.Length;
            }
        }

        return string.Format( "https://drive.google.com/uc?id={0}&export=download", url.Substring( index, closingIndex - index ) );
    }
}

// Web client used for Google Drive
public class CookieAwareWebClient : WebClient
{
    private class CookieContainer
    {
        Dictionary<string, string> _cookies;

        public string this[Uri url]
        {
            get
            {
                string cookie;
                if( _cookies.TryGetValue( url.Host, out cookie ) )
                    return cookie;

                return null;
            }
            set
            {
                _cookies[url.Host] = value;
            }
        }

        public CookieContainer()
        {
            _cookies = new Dictionary<string, string>();
        }
    }

    private CookieContainer cookies;

    public CookieAwareWebClient() : base()
    {
        cookies = new CookieContainer();
    }

    protected override WebRequest GetWebRequest( Uri address )
    {
        WebRequest request = base.GetWebRequest( address );

        if( request is HttpWebRequest )
        {
            string cookie = cookies[address];
            if( cookie != null )
                ( (HttpWebRequest) request ).Headers.Set( "cookie", cookie );
        }

        return request;
    }

    protected override WebResponse GetWebResponse( WebRequest request, IAsyncResult result )
    {
        WebResponse response = base.GetWebResponse( request, result );

        string[] cookies = response.Headers.GetValues( "Set-Cookie" );
        if( cookies != null && cookies.Length > 0 )
        {
            string cookie = "";
            foreach( string c in cookies )
                cookie += c;

            this.cookies[response.ResponseUri] = cookie;
        }

        return response;
    }

    protected override WebResponse GetWebResponse( WebRequest request )
    {
        WebResponse response = base.GetWebResponse( request );

        string[] cookies = response.Headers.GetValues( "Set-Cookie" );
        if( cookies != null && cookies.Length > 0 )
        {
            string cookie = "";
            foreach( string c in cookies )
                cookie += c;

            this.cookies[response.ResponseUri] = cookie;
        }

        return response;
    }
}

With that stackoverflow question + this github code i understood it was related with both issues as google sends the confirmation page when file is bigger then 50mb. So after implementing that github code now im able to download large files with my webClient.


问:
Modify column type in pandas
I have a column called 'color' which has two kinds of values ('Color' and 'Black and White').

I would like to change the value 'Color' to number 1 and the value 'Black and white' to number 0.

To change it, I'm using this line:

movies.color = movies.color.map({'Color': 1, ' Black and White':0})

but how do I change the column type, from str to integer? How to make sure that the column is now an integer type?

答:
If all rows can be mapped the resulting column should be int by default.

You can always do a explicit conversion by doing:

```<code>movies.color = movies.color.map({'Color': 1, ' Black and White':0}).astype(int)
</code>```

Title: Modify column type in pandas

Body:
If all rows can be mapped the resulting column should be int by default.

You can always do a explicit conversion by doing:

movies.color = movies.color.map({'Color': 1, ' Black and White':0}).astype(int)


问:
Exception in thread "main" org.hibernate.MappingException: Unknown entity: org.hibernate.employee
Not sure what is wrong. I am getting the exception given:

org.hibernate.MappingException: Unknown entity: org.hibernate.employee

How to fix it? I created client.java. I created the table that mapped that matched the client. I have created the mapping and added the mapping

hibernateutil.java coding

```<code>package org.hibernate.test.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class hibernateutil {
private static SessionFactory sessionfactory;

public static SessionFactory getSessionFactory(){
    if(sessionfactory == null){
        synchronized(hibernateutil.class){
            if(sessionfactory == null){
                try {
                    Configuration conf=new Configuration().configure();
                        StandardServiceRegistryBuilder builder= new StandardServiceRegistryBuilder()
                            .applySettings(conf.getProperties());
                    sessionfactory = conf.buildSessionFactory(builder.build());

                }catch (Throwable th){
                    th.printStackTrace();
                    throw new ExceptionInInitializerError();
                }
            }
            return sessionfactory;
        }
    }

    else{
        return sessionfactory;
    }
}
}
</code>```

employee.java

```<code>package org.hibernate;
public class employee {

private int id;
private String firstname;
private String lastname;
private int salary;

public employee(){}

public employee(int id,String firstname,String lastname,int salary)
{
    this.id=id;
    this.firstname=firstname;
    this.lastname=lastname;
    this.salary=salary;
}
public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getFirstname() {
    return firstname;
}

public void setFirstname(String firstname) {
    this.firstname = firstname;
}

public String getLastname() {
    return lastname;
}

public void setLastname(String lastname) {
    this.lastname = lastname;
}

public int getSalary() {
    return salary;
}

public void setSalary(int salary) {
    this.salary = salary;
}

}
</code>```

hibernate.cfg.xml

```<code>      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
      <hibernate-configuration>
         <session-factory>
             <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
               <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
             <property name="hibernate.connection.username">javaguy</property>
             <property name="connection.password"></property>
               <property name="hibernate.jdbc.batch_size">100</property>
                <property name="connection.pool_size">1</property>
                <property name="show_sql">false</property>
                <property name="format_sql">true</property>
                <property name="hibernate.hbm2ddl.auto">create</property>
                <mapping resource="org/hibernate/employee.hbm.xml"/>
        </session-factory>
        </hibernate-configuration>
</code>```

employee.hbm.xml

```<code>        <?xml version="1.0"?>
         <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping       DTD 3.0//EN"
           "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
         <!-- Generated Oct 20, 2016 7:56:20 PM by Hibernate Tools 3.5.0.Final -->
         <hibernate-mapping>
            <class name="employee" table="EMPLOYEE">
               <id name="id" type="int">
                    <column name="EMP_ID" />
                    <generator class="assigned" />
                 </id>
                <property name="firstname" type="java.lang.String">
                    <column name="FIRST_NAME" />
                </property>
                <property name="lastname" type="java.lang.String">
                   <column name="LAST_NAME" />
                 </property>
                <property name="salary" type="int">
                    <column name="SALARY" />
                </property>
             </class>
             </hibernate-mapping>
</code>```

client.java

```<code>package learn;

import org.hibernate.Session;
import java.util.List;
import java.util.Date;
import java.util.Iterator;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.test.util.hibernateutil;
import org.hibernate.*;

 public class client {

 private static SessionFactory factory;

public static void main(String[] args) {

    factory = hibernateutil.getSessionFactory();

    client a = new client();
    // Add few employee records in data base
    a.addemployee(1,"Sai","Nathan",5000);
    a.addemployee(2,"Sai","kumar",6000);
    a.addemployee(3,"Santhosh","Kumar",9000);

    // List down all employees
    /*a.listemployee();

    // update employee's record
    a.updateemployee(1,20000);

    // Delete an employee
    a.deleteemployee(3);

    // List down all employees
    a.listemployee();*/
    System.out.println("Finished");
}

   /* Method to CREATE an employee in the database */

public Integer addemployee(int id, String fname,String lname,int salary)
{
    Session session= factory.openSession();
    Transaction tx=session.beginTransaction();
    employee e1= new employee(id,fname,lname,salary);
    Integer empid=(Integer)session.save(e1);
    tx.commit();
    session.close();
    return empid;

}
   /* Method to  READ all the employees */

   public void listemployee(){
        Session session = factory.openSession();
        List<employee> emplist = session.createQuery("FROM Employee").list();
        for(employee emp:emplist){
            System.out.print("First name" +emp.getFirstname());
            System.out.print("Last name" +emp.getLastname());
            System.out.println("Salary" +emp.getSalary());
        }
        session.close();
    }

          /* Method to UPDATE salary for an employee */

      public void updateemployee(Integer id,Integer salary)
     {
         Session session = factory.openSession();
         Transaction tx = session.beginTransaction();
         employee emp = (employee)session.get(employee.class, id);
         emp.setSalary(salary);
         session.update(emp);
         tx.commit();
         session.close();
      }

      public void deleteemployee(Integer id)
      {
       Session session = factory.openSession();
       Transaction tx = session.beginTransaction();
       employee emp = (employee)session.get(employee.class, id);
       session.delete(emp);
        tx.commit();
      }
    }
</code>```

error:

project path:

答:
```<code><class name="employee">
</code>```

should have full package name (path) and all classes should starts with a capital letter.

So it should be like:

```<code>package mypackage;

public class Employee
{
    ...
}

<class name="mypackage.Employee" ...>
</code>```

Body:
Not sure what is wrong. I am getting the exception given:

org.hibernate.MappingException: Unknown entity: org.hibernate.employee

How to fix it? I created client.java. I created the table that mapped that matched the client. I have created the mapping and added the mapping

hibernateutil.java coding

package org.hibernate.test.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class hibernateutil {
private static SessionFactory sessionfactory;

public static SessionFactory getSessionFactory(){
    if(sessionfactory == null){
        synchronized(hibernateutil.class){
            if(sessionfactory == null){
                try {
                    Configuration conf=new Configuration().configure();
                        StandardServiceRegistryBuilder builder= new StandardServiceRegistryBuilder()
                            .applySettings(conf.getProperties());
                    sessionfactory = conf.buildSessionFactory(builder.build());

                }catch (Throwable th){
                    th.printStackTrace();
                    throw new ExceptionInInitializerError();
                }
            }
            return sessionfactory;
        }
    }

    else{
        return sessionfactory;
    }
}
}

employee.java

package org.hibernate;
public class employee {

private int id;
private String firstname;
private String lastname;
private int salary;

public employee(){}

public employee(int id,String firstname,String lastname,int salary)
{
    this.id=id;
    this.firstname=firstname;
    this.lastname=lastname;
    this.salary=salary;
}
public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getFirstname() {
    return firstname;
}

public void setFirstname(String firstname) {
    this.firstname = firstname;
}

public String getLastname() {
    return lastname;
}

public void setLastname(String lastname) {
    this.lastname = lastname;
}

public int getSalary() {
    return salary;
}

public void setSalary(int salary) {
    this.salary = salary;
}

}

hibernate.cfg.xml

      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
      <hibernate-configuration>
         <session-factory>
             <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
               <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
             <property name="hibernate.connection.username">javaguy</property>
             <property name="connection.password"></property>
               <property name="hibernate.jdbc.batch_size">100</property>
                <property name="connection.pool_size">1</property>
                <property name="show_sql">false</property>
                <property name="format_sql">true</property>
                <property name="hibernate.hbm2ddl.auto">create</property>
                <mapping resource="org/hibernate/employee.hbm.xml"/>
        </session-factory>
        </hibernate-configuration>

employee.hbm.xml

        <?xml version="1.0"?>
         <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping       DTD 3.0//EN"
           "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

         <hibernate-mapping>
            <class name="employee" table="EMPLOYEE">
               <id name="id" type="int">
                    <column name="EMP_ID" />
                    <generator class="assigned" />
                 </id>
                <property name="firstname" type="java.lang.String">
                    <column name="FIRST_NAME" />
                </property>
                <property name="lastname" type="java.lang.String">
                   <column name="LAST_NAME" />
                 </property>
                <property name="salary" type="int">
                    <column name="SALARY" />
                </property>
             </class>
             </hibernate-mapping>

client.java

package learn;

import org.hibernate.Session;
import java.util.List;
import java.util.Date;
import java.util.Iterator;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.test.util.hibernateutil;
import org.hibernate.*;

 public class client {

 private static SessionFactory factory;

public static void main(String[] args) {

    factory = hibernateutil.getSessionFactory();

    client a = new client();
    // Add few employee records in data base
    a.addemployee(1,"Sai","Nathan",5000);
    a.addemployee(2,"Sai","kumar",6000);
    a.addemployee(3,"Santhosh","Kumar",9000);

    // List down all employees
    /*a.listemployee();

    // update employee's record
    a.updateemployee(1,20000);

    // Delete an employee
    a.deleteemployee(3);

    // List down all employees
    a.listemployee();*/
    System.out.println("Finished");
}

   /* Method to CREATE an employee in the database */

public Integer addemployee(int id, String fname,String lname,int salary)
{
    Session session= factory.openSession();
    Transaction tx=session.beginTransaction();
    employee e1= new employee(id,fname,lname,salary);
    Integer empid=(Integer)session.save(e1);
    tx.commit();
    session.close();
    return empid;

}
   /* Method to  READ all the employees */

   public void listemployee(){
        Session session = factory.openSession();
        List<employee> emplist = session.createQuery("FROM Employee").list();
        for(employee emp:emplist){
            System.out.print("First name" +emp.getFirstname());
            System.out.print("Last name" +emp.getLastname());
            System.out.println("Salary" +emp.getSalary());
        }
        session.close();
    }

          /* Method to UPDATE salary for an employee */

      public void updateemployee(Integer id,Integer salary)
     {
         Session session = factory.openSession();
         Transaction tx = session.beginTransaction();
         employee emp = (employee)session.get(employee.class, id);
         emp.setSalary(salary);
         session.update(emp);
         tx.commit();
         session.close();
      }

      public void deleteemployee(Integer id)
      {
       Session session = factory.openSession();
       Transaction tx = session.beginTransaction();
       employee emp = (employee)session.get(employee.class, id);
       session.delete(emp);
        tx.commit();
      }
    }

error:

project path:

Body:
<class name="employee">

should have full package name (path) and all classes should starts with a capital letter.

So it should be like:

package mypackage;

public class Employee
{
    ...
}

<class name="mypackage.Employee" ...>


问:
vb6-how to add progress bar on sql query (mysql)
I have the following code in a form which hangs up the form whenever the query is still executing:

```<code>Public Function OpenRS(strSql As String) As ADODB.Recordset
Dim rs As ADODB.Recordset

        Set rs = New ADODB.Recordset
        rs.CursorLocation = adUseClient
        rs.CursorType = adOpenDynamic

        If IsNull(Cn) = False Then
            rs.Open strSql, Cn, adOpenKeyset, adLockPessimistic ', adAsyncExecute
        End If

        Set OpenRS = rs

End Function
</code>```

Tried adding adAsyncExecute but the form closes.

```<code>Dim RSC As ADODB.Recordset
    Set RSC = Nothing
    Set RSC = Cn.Execute("CALL SP_Rank_by_Company('" & MyDate1 & "','" & MyDate2 & "','DELETE')", , adAsyncExecute)

    While Cn.State = 4
        If frmLoadingReports.picLoading.Width = 5320 Then
            frmLoadingReports.picLoading.Width = 0
        Else
            frmLoadingReports.picLoading.Width = frmLoadingReports.picLoading.Width + 100
        End If
        'count total records
        'get the current number of records processed
        DoEvents
    Wend
</code>```

How can I add a progress bar to it?

Thanks!

答:
MySQL doesn't tell you how close to finished a query is, it can only tell you how long it's been running or what's impeding progress, as in what other queries are blocking it.

If you have a really long-running query you need to guess how long it will take if you want to compute an ETA.

Body:
I have the following code in a form which hangs up the form whenever the query is still executing:

Public Function OpenRS(strSql As String) As ADODB.Recordset
Dim rs As ADODB.Recordset

        Set rs = New ADODB.Recordset
        rs.CursorLocation = adUseClient
        rs.CursorType = adOpenDynamic

        If IsNull(Cn) = False Then
            rs.Open strSql, Cn, adOpenKeyset, adLockPessimistic ', adAsyncExecute
        End If

        Set OpenRS = rs

End Function

Tried adding adAsyncExecute but the form closes.

Dim RSC As ADODB.Recordset
    Set RSC = Nothing
    Set RSC = Cn.Execute("CALL SP_Rank_by_Company('" & MyDate1 & "','" & MyDate2 & "','DELETE')", , adAsyncExecute)

    While Cn.State = 4
        If frmLoadingReports.picLoading.Width = 5320 Then
            frmLoadingReports.picLoading.Width = 0
        Else
            frmLoadingReports.picLoading.Width = frmLoadingReports.picLoading.Width + 100
        End If
        'count total records
        'get the current number of records processed
        DoEvents
    Wend

How can I add a progress bar to it?

Thanks!


答:
Try click xpath:

//a[@id='nav-link-yourAccount']/span

Title: Selenium xpath: element not visible on Amazon site


问:
Which database i have to use to implement the auto-completion of dictionary
I ran across a interview question of implementing a dictionary that can implement the features of auto-completion, auto-correction, spell check etc...

I actually wanted to know which data base i have to use to store all the word like (for location country, city and zip code) .

Please suggest me if there any framework in java with any database or any optimal database that can achieve the solution

Any links that guide me on this are welcome...

答:
The features you speak of are usually largely implemented in the application, not data, layer, since there is a significant UI component here. Any database (or even flat file) can store a list of words.

Can you be more specific about what area you are having trouble with? (If your question is really "How do I use a database?", that is too general for this site, and you should do some Googling. Try looking into JDBC for starters)

ContentLicense: CC BY-SA 2.5


问:
undefined behaviour on dynamic allocated arrays (segmentation fault)
This program calculates Fibonacci series of the form: t1, t2, t3 = t1 + t^2, t4 = t2+t3^2 ...

It takes three inputs t1, t2 and nth number in the series you want to calculate.

Since the numbers increase exponentially, i used arrays to display and perform manipulations on large numbers.

PROBLEM:

I'm stuck with some weird error on:

```<code>bsquare[j] = *b[j]
</code>```

use inputs 0 1 8 to recreate the error, it works fine for inputs upto 7. also i tried debugging using gdb, but the debugger shows that memory is accessible when i use p **b@50 and bn also seems to be valid. Is there some undefined behaviour i'm missing out on?

Code

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

int carry = 0;
int fibo( int **a, int **b, int **c, int n);
void sum(int *a, int *b, int *c, int *an, int *bn, int *cn);
void sqr(int *b, int *bn);
int main()
{

    int *a, *b, *c;
    int t1, t2, n, i, bn;

    scanf("%d%d%d",&t1, &t2,&n);

    a = (int * ) calloc(100, sizeof(int));
    b = (int * ) calloc(100, sizeof(int));
    c = (int * ) calloc(100, sizeof(int));
    a[0] = t1; b[0] = t2;

    bn = fibo(&a,&b,&c,n);

    printf("\nNumber is: ");
    for(i = bn-1; i>=0; i--)
    printf("%d",b[i]);

    free(a);free(b);free(c);
    return 0;
}
void sqr(int *b, int *bn)
{   int c[50] = {0};
    int i , j ,k = 0;
    int temp = 0;
    for(i = 0; i < *bn; i++)
    {    k = i;
        carry = 0;
        for(j = 0; j < *bn ;j++)
        {
            temp = c[k] + b[i] * b[j] + carry;
            if(temp>9)
            {
                carry = temp / 10;
                c[k] = temp % 10;

            }
            else
            {
                c[k] =  temp;
                carry = 0;
            }
            k++;
        }
        if(carry !=0)
        {c[k++] = carry;
        }

    }

    for(i = 0; i<k; i++)
    {
        b[i] = c[i];

    }

    *bn = k;

}

void sum(int *a, int *b, int *c, int *an, int *bn, int *cn)
{

    int i=0 , j ,k = 0;
    int *temp1;
    int temp = 0;
    for(j=0; j<*cn; j++)
     c[j] = 0;
            *cn = 0;
     carry = 0;
    for(; i < *bn && i < *an; i++)
    {
        temp = a[i] + b[i] + carry;

        if(temp>9)
        {
            c[k] = temp % 10;
            carry = temp/10;

        }
        else
        {
            c[k] = temp;
            carry = 0;
        }
        k++;
    }

    while(i<*an)
    {
        temp = carry + a[i];
        if(temp>9)
        {
            c[k] = temp % 10;
            carry = temp/10;

        }
        else
        {
            c[k] = temp;
            carry = 0;
        }
        k++;i++;
    }

    while(i<*bn)
    {
        temp = carry + b[i];
        if(temp>9)
        {
            c[k] = temp % 10;
            carry = temp/10;

        }
        else
        {
            c[k] = temp;
            carry = 0;
        }
        k++;i++;
    }
    if(carry!=0)
    {
        c[k++] = carry;
    }

    *cn = k;

}

int fibo( int **a, int **b, int **c, int n)
{
    int i, j,*tmpdb;

    int bn = 1, an = 1, cn = 0, bsn = 0, temp;
    int bsquare[100] = {0};

    for(i = 3; i<= n; i++)
        {
            for(j = 0; j<bn; j++)
                bsquare[j] = *b[j];

            bsn = bn;

            sqr(bsquare,&bsn);
            sum(*a,bsquare,*c,&an,&bsn,&cn);

            tmpdb = *a;
            *a = *b;
            *b = *c;
            *c = tmpdb;

            temp = an;
            an = bn;
            bn = cn;
            cn = temp;

        }
    return bn;

}
</code>```

答: You are not updating b[] value as you are expecting it to be. you have stored b[0]=t2 and after that it is not updated anywhere else. so your program gives segmentation fault at b[1].So i will say just update b[] array and you are good to go. and also please practice to provide a little bit of comment in your code it is really hard to read.

Body:
This program calculates Fibonacci series of the form: t1, t2, t3 = t1 + t^2, t4 = t2+t3^2 ...

It takes three inputs t1, t2 and nth number in the series you want to calculate.

Since the numbers increase exponentially, i used arrays to display and perform manipulations on large numbers.

PROBLEM:

I'm stuck with some weird error on:

bsquare[j] = *b[j]

use inputs 0 1 8 to recreate the error, it works fine for inputs upto 7. also i tried debugging using gdb, but the debugger shows that memory is accessible when i use p **b@50 and bn also seems to be valid. Is there some undefined behaviour i'm missing out on?

Code

#include<stdio.h>
#include<stdlib.h>

int carry = 0;
int fibo( int **a, int **b, int **c, int n);
void sum(int *a, int *b, int *c, int *an, int *bn, int *cn);
void sqr(int *b, int *bn);
int main()
{

    int *a, *b, *c;
    int t1, t2, n, i, bn;

    scanf("%d%d%d",&t1, &t2,&n);

    a = (int * ) calloc(100, sizeof(int));
    b = (int * ) calloc(100, sizeof(int));
    c = (int * ) calloc(100, sizeof(int));
    a[0] = t1; b[0] = t2;

    bn = fibo(&a,&b,&c,n);

    printf("\nNumber is: ");
    for(i = bn-1; i>=0; i--)
    printf("%d",b[i]);

    free(a);free(b);free(c);
    return 0;
}
void sqr(int *b, int *bn)
{   int c[50] = {0};
    int i , j ,k = 0;
    int temp = 0;
    for(i = 0; i < *bn; i++)
    {    k = i;
        carry = 0;
        for(j = 0; j < *bn ;j++)
        {
            temp = c[k] + b[i] * b[j] + carry;
            if(temp>9)
            {
                carry = temp / 10;
                c[k] = temp % 10;

            }
            else
            {
                c[k] =  temp;
                carry = 0;
            }
            k++;
        }
        if(carry !=0)
        {c[k++] = carry;
        }

    }

    for(i = 0; i<k; i++)
    {
        b[i] = c[i];

    }

    *bn = k;

}

void sum(int *a, int *b, int *c, int *an, int *bn, int *cn)
{

    int i=0 , j ,k = 0;
    int *temp1;
    int temp = 0;
    for(j=0; j<*cn; j++)
     c[j] = 0;
            *cn = 0;
     carry = 0;
    for(; i < *bn && i < *an; i++)
    {
        temp = a[i] + b[i] + carry;

        if(temp>9)
        {
            c[k] = temp % 10;
            carry = temp/10;

        }
        else
        {
            c[k] = temp;
            carry = 0;
        }
        k++;
    }

    while(i<*an)
    {
        temp = carry + a[i];
        if(temp>9)
        {
            c[k] = temp % 10;
            carry = temp/10;

        }
        else
        {
            c[k] = temp;
            carry = 0;
        }
        k++;i++;
    }

    while(i<*bn)
    {
        temp = carry + b[i];
        if(temp>9)
        {
            c[k] = temp % 10;
            carry = temp/10;

        }
        else
        {
            c[k] = temp;
            carry = 0;
        }
        k++;i++;
    }
    if(carry!=0)
    {
        c[k++] = carry;
    }

    *cn = k;

}

int fibo( int **a, int **b, int **c, int n)
{
    int i, j,*tmpdb;

    int bn = 1, an = 1, cn = 0, bsn = 0, temp;
    int bsquare[100] = {0};

    for(i = 3; i<= n; i++)
        {
            for(j = 0; j<bn; j++)
                bsquare[j] = *b[j];

            bsn = bn;

            sqr(bsquare,&bsn);
            sum(*a,bsquare,*c,&an,&bsn,&cn);

            tmpdb = *a;
            *a = *b;
            *b = *c;
            *c = tmpdb;

            temp = an;
            an = bn;
            bn = cn;
            cn = temp;

        }
    return bn;

}


问:
Specific directory to Apache2/httpd (.bashrc)
I am trying to install apache on my /home/user1/.app/apache2/ by doing the following instruction during installation.

./configure --prefix=/home/user1/.app/apache2/

make

make install

Apache was successfully installed but i was not able to allocated my httpd by doing 'which httpd'. I have done editing my .bashrc profile with and source .bashrc

```<code>export PATH=/home/user1/.app/apache2/bin:$PATH
</code>```

May i know what's the problem i encounter here? Would be appreciate if anyone can help, I am new to Linux.

答:
Try to add in .bash_profile instead of .bashrc. According to the bash man page, .bash_profile is executed for login shells, while .bashrc is executed for interactive non-login shells.

What is a login or non-login shell?

When you login (type username and password) via console, either sitting at the machine, or remotely via ssh: .bash_profile is executed to configure your shell before the initial command prompt.

But, if you’ve already logged into your machine and open a new terminal window (xterm) inside Gnome or KDE, then .bashrc is executed before the window command prompt. .bashrc is also run when you start a new bash instance by typing /bin/bash in a terminal.

Body:
I am trying to install apache on my /home/user1/.app/apache2/ by doing the following instruction during installation.

./configure --prefix=/home/user1/.app/apache2/

make

make install

Apache was successfully installed but i was not able to allocated my httpd by doing 'which httpd'. I have done editing my .bashrc profile with and source .bashrc

export PATH=/home/user1/.app/apache2/bin:$PATH

May i know what's the problem i encounter here? Would be appreciate if anyone can help, I am new to Linux.


问:
PHP/Laravel file existence verification not working
I have a <form> with a multiple file input that stores those files into the server. The names of the files must follow a numeric standard and that's why I rename them before storing. Each post has an ID an can have more than one file so the pattern is: post-id + dash and a number + file extension, this way, if the same post has two file with the same extensions, the dash + number will avoid them to be overwriten. So, before I store the files I run a loop to find the proper number to the name. The problem is, the function to verify the existence of the file seems not to be returning true when it should. The code:

```<code>$counter = 0;
do{
  $nomeArquivo = $post->id . "-{$counter}"  . "." . $arq->extension();

  $counter++;
//these commented are other ways of verification I tried
//}while(Storage::exists($nomeArquivo));
//}while(file_exists("/storage/" . $nomeArquivo));
}while(is_file("/storage/" . $post->id . "-{$counter}"));

Storage::putFileAs('/public', $arq, $nomeArquivo);
</code>```

This code above runs inside a foreach($files as $arq) where $files are the files from the form input.

Reference: https://laravel.com/docs/5.4/filesystem and https://laravel.com/api/5.4/Illuminate/Filesystem/Filesystem.html

答:
If name of the file need to be unique only then,

You can give Unique Name like this:

```<code>$file = $request->file('file');
$extension = $file->getClientOriginalExtension();
$destination ='/files/';
$filename = uniqid() . '.' . $extension;
$file->move($destination, $filename);
</code>```

Now save above file name in your database. Hope it may help you

Body:
I have a <form> with a multiple file input that stores those files into the server. The names of the files must follow a numeric standard and that's why I rename them before storing. Each post has an ID an can have more than one file so the pattern is: post-id + dash and a number + file extension, this way, if the same post has two file with the same extensions, the dash + number will avoid them to be overwriten. So, before I store the files I run a loop to find the proper number to the name. The problem is, the function to verify the existence of the file seems not to be returning true when it should. The code:

$counter = 0;
do{
  $nomeArquivo = $post->id . "-{$counter}"  . "." . $arq->extension();

  $counter++;
//these commented are other ways of verification I tried
//}while(Storage::exists($nomeArquivo));
//}while(file_exists("/storage/" . $nomeArquivo));
}while(is_file("/storage/" . $post->id . "-{$counter}"));

Storage::putFileAs('/public', $arq, $nomeArquivo);

This code above runs inside a foreach($files as $arq) where $files are the files from the form input.

Reference: https://laravel.com/docs/5.4/filesystem and https://laravel.com/api/5.4/Illuminate/Filesystem/Filesystem.html

Body:
If name of the file need to be unique only then,

You can give Unique Name like this:

$file = $request->file('file');
$extension = $file->getClientOriginalExtension();
$destination ='/files/';
$filename = uniqid() . '.' . $extension;
$file->move($destination, $filename);

Now save above file name in your database. Hope it may help you


问:
Java for loop i++ as a string
Let's say we have a for loop

```<code>for(int i = 0; i < 10; i++) {
    ...
}
</code>```

What format is the i++ in?

I have a String increment = "i++" which tells me how much to increment i by.
But when I just directly try and put the increment string as an incrementor it doesn't work. I tried the below but it doesn't work.

```<code>for(int i = 0; i < 10; increment) {
    ...
}
</code>```

How can I make this work?

答:
So for this, you cannot use a string as a expression.
There will be quite a few ways to map a String to expression.

One of the ways is you can use switch case:

```<code>String increment = "i++";
int i = 0;
while(i < 10)
{
  //your logic here
  switch (increment){
    case "i++":
      i++;
      break;
    case "i=i+2":
      i = i + 2;
      break;
  }
}
</code>```

You can also use Regex or parse the String to convert to int

Title: Java for loop i++ as a string

Body:
Let's say we have a for loop

for(int i = 0; i < 10; i++) {
    ...
}

What format is the i++ in?

I have a String increment = "i++" which tells me how much to increment i by.
But when I just directly try and put the increment string as an incrementor it doesn't work. I tried the below but it doesn't work.

for(int i = 0; i < 10; increment) {
    ...
}

How can I make this work?

Body:
So for this, you cannot use a string as a expression.
There will be quite a few ways to map a String to expression.

One of the ways is you can use switch case:

String increment = "i++";
int i = 0;
while(i < 10)
{
  //your logic here
  switch (increment){
    case "i++":
      i++;
      break;
    case "i=i+2":
      i = i + 2;
      break;
  }
}

You can also use Regex or parse the String to convert to int


问:
Javascript returning Nan when all the variables are numbers?
My js is returning NaN after "your total is." But I don't have the slightest idea as to why. I think I have all my variables properly declared; is there another reason why this is happening?

Here's my code below. Everything else in the js seems to be working fine.

function book() {
  var city = document.getElementsByName('city').value;
  var hotel = document.getElementsByName('hotel').value;
  var people = document.getElementsByName('numtravel').value;
  var days = document.getElementsByName('numdays').value;
  var wifi;
    if ( document.getElementsByName('wifi').checked = false)
    wifi = 0;
    if ( document.getElementsByName('wifi').checked = true)
    wifi = 10;
  var seat;
    if ( document.getElementsByName('sausage').checked = false) seat = 0;
    if ( document.getElementsByName('sausage').checked = true) seat = 20;
  var meal = document.getElementById('meal').value;
  var price1 = people * meal;
  var price2 = people * seat;
  var price3 = hotel * days;

  document.getElementById("p1").innerHTML = 'Your total is ' + ( city + price3 + wifi + price1 + price2 );

  return false;
}

/*   Total eggs, man. ( ͡° ͜ʖ ͡°) */```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#main_content
        {
            background-color: lightgoldenrodyellow;
            overflow: hidden;
            text-align: center;
            border: 5px dotted lightblue
        }

body    {
            background-color: lightgrey;
        }
#content

        {
            background-color: lightgoldenrodyellow;
            overflow: hidden;
            text-align: center;
            border: 5px dotted lightblue
        }</code>```

<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>Make a Reservation!</title>

    <link rel="stylesheet" href="new.css" type="text/css" />

      Home

      Contact Us

      Make a Reservation

      Join Our Email List

 Make a Reservation!

 First Name: <input type="text" id="first" name="FirstName"/>

 Last Name: <input type="text" id="last" name="LastName"/>

 Where is your arrival city?

 St. Louis ($40) <input type="radio" value="40" name="city" />

 Milwaukee ($20) <input type="radio" value="20" name="city"/>

 Detroit ($35) <input type="radio" value="35" name="city"/>

Hotel Choice?

 Economy ($50/day) <input type="radio" value="50" name='hotel'/>

 Standard ($70/day) <input type="radio" value="70" name='hotel'/>

 Upscale ($120/day) <input type="radio" value="120" name="hotel"/>

 Amount of travelers?

        <select id="travelers" name="numtravel">
          <option value="1"> 1 </option>
          <option value="2"> 2 </option>
          <option value="3"> 3 </option>
          <option value="4"> 4 </option>
          <option value="5"> 5 </option>
          <option value="6"> 6 </option>
        </select>

 Amount of days?

        <select id="days" name="numdays">
          <option value="2"> 2 </option>
          <option value="3"> 3 </option>
          <option value="4"> 4 </option>
          <option value="5"> 5 </option>
          <option value="6"> 6 </option>
          <option value="7"> 7 </option>
        </select>

 Extra emenities:

 Wifi ($10) <input type="checkbox" value='20' name="wifi">

 Fully-Reclining Seat ($20) <input type="checkbox" name="sausage" value='30'>

 Meal choice?

        <select id="meal" name="meal">
          <option value="0"> None </option>
          <option value="5"> Snack ($5) </option>
          <option value="10"> Full Meal ($10) </option>
        </select>

 Special Requests?

 <textarea name="txtRequests" col="25" rows="5" style='width:300px;resize:vertical;'> </textarea>

 <button onclick="book()">Book your Trip!</button>

```

答:
document.getElementsByName returns an array, so you need to set [0].

I suggest just use document.querySelector.

and notice that the value of a node is a string, not a number. you should convert it.

and don't use one "=" in an "if"

here is my code:

```<code>function book() {
    var city = +(document.querySelector("[name='city']:checked") || { value: 0 }).value;
    console.log("city", city);
    var hotel = +(document.querySelector("[name='hotel']:checked") || { value: 0 }).value;
    console.log("hotel", hotel);
    var people = +document.querySelector("[name='numtravel']").value;
    console.log("people", people);
    var days = +document.querySelector("[name='numdays']").value;
    console.log("days", days);
    var wifi;
    if (document.getElementsByName('wifi')[0].checked === false) wifi = 0;
    if (document.getElementsByName('wifi')[0].checked === true) wifi = 10;
    console.log("wifi", wifi);
    var seat;
    if (document.getElementsByName('sausage')[0].checked === false) seat = 0;
    if (document.getElementsByName('sausage')[0].checked === true) seat = 20;
    console.log("seat", seat);
    var meal = +document.getElementById('meal').value;
    console.log("meal", meal);
    console.log(people, meal, seat, days);
    var price1 = people * meal;
    var price2 = people * seat;
    var price3 = hotel * days;

    document.getElementById("p1").innerHTML = 'Your total is ' + (city + price3 + wifi + price1 + price2);

    return false;
}
</code>```

Body:
My js is returning NaN after "your total is." But I don't have the slightest idea as to why. I think I have all my variables properly declared; is there another reason why this is happening?

Here's my code below. Everything else in the js seems to be working fine.

function book() {
  var city = document.getElementsByName('city').value;
  var hotel = document.getElementsByName('hotel').value;
  var people = document.getElementsByName('numtravel').value;
  var days = document.getElementsByName('numdays').value;
  var wifi;
    if ( document.getElementsByName('wifi').checked = false)
    wifi = 0;
    if ( document.getElementsByName('wifi').checked = true)
    wifi = 10;
  var seat;
    if ( document.getElementsByName('sausage').checked = false) seat = 0;
    if ( document.getElementsByName('sausage').checked = true) seat = 20;
  var meal = document.getElementById('meal').value;
  var price1 = people * meal;
  var price2 = people * seat;
  var price3 = hotel * days;

  document.getElementById("p1").innerHTML = 'Your total is ' + ( city + price3 + wifi + price1 + price2 );

  return false;
}

/*   Total eggs, man. ( ͡° ͜ʖ ͡°) */

#main_content
        {
            background-color: lightgoldenrodyellow;
            overflow: hidden;
            text-align: center;
            border: 5px dotted lightblue
        }

body    {
            background-color: lightgrey;
        }
#content

        {
            background-color: lightgoldenrodyellow;
            overflow: hidden;
            text-align: center;
            border: 5px dotted lightblue
        }

<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>Make a Reservation!</title>

    <link rel="stylesheet" href="new.css" type="text/css" />

      Home

      Contact Us

      Make a Reservation

      Join Our Email List

 Make a Reservation!

 First Name: <input type="text" id="first" name="FirstName"/>

 Last Name: <input type="text" id="last" name="LastName"/>

 Where is your arrival city?

 St. Louis ($40) <input type="radio" value="40" name="city" />

 Milwaukee ($20) <input type="radio" value="20" name="city"/>

 Detroit ($35) <input type="radio" value="35" name="city"/>

Hotel Choice?

 Economy ($50/day) <input type="radio" value="50" name='hotel'/>

 Standard ($70/day) <input type="radio" value="70" name='hotel'/>

 Upscale ($120/day) <input type="radio" value="120" name="hotel"/>

 Amount of travelers?

        <select id="travelers" name="numtravel">
          <option value="1"> 1 </option>
          <option value="2"> 2 </option>
          <option value="3"> 3 </option>
          <option value="4"> 4 </option>
          <option value="5"> 5 </option>
          <option value="6"> 6 </option>
        </select>

 Amount of days?

        <select id="days" name="numdays">
          <option value="2"> 2 </option>
          <option value="3"> 3 </option>
          <option value="4"> 4 </option>
          <option value="5"> 5 </option>
          <option value="6"> 6 </option>
          <option value="7"> 7 </option>
        </select>

 Extra emenities:

 Wifi ($10) <input type="checkbox" value='20' name="wifi">

 Fully-Reclining Seat ($20) <input type="checkbox" name="sausage" value='30'>

 Meal choice?

        <select id="meal" name="meal">
          <option value="0"> None </option>
          <option value="5"> Snack ($5) </option>
          <option value="10"> Full Meal ($10) </option>
        </select>

 Special Requests?

 <textarea name="txtRequests" col="25" rows="5" style='width:300px;resize:vertical;'> </textarea>

 <button onclick="book()">Book your Trip!</button>

Body:
document.getElementsByName returns an array, so you need to set [0].

I suggest just use document.querySelector.

and notice that the value of a node is a string, not a number. you should convert it.

and don't use one "=" in an "if"

here is my code:

function book() {
    var city = +(document.querySelector("[name='city']:checked") || { value: 0 }).value;
    console.log("city", city);
    var hotel = +(document.querySelector("[name='hotel']:checked") || { value: 0 }).value;
    console.log("hotel", hotel);
    var people = +document.querySelector("[name='numtravel']").value;
    console.log("people", people);
    var days = +document.querySelector("[name='numdays']").value;
    console.log("days", days);
    var wifi;
    if (document.getElementsByName('wifi')[0].checked === false) wifi = 0;
    if (document.getElementsByName('wifi')[0].checked === true) wifi = 10;
    console.log("wifi", wifi);
    var seat;
    if (document.getElementsByName('sausage')[0].checked === false) seat = 0;
    if (document.getElementsByName('sausage')[0].checked === true) seat = 20;
    console.log("seat", seat);
    var meal = +document.getElementById('meal').value;
    console.log("meal", meal);
    console.log(people, meal, seat, days);
    var price1 = people * meal;
    var price2 = people * seat;
    var price3 = hotel * days;

    document.getElementById("p1").innerHTML = 'Your total is ' + (city + price3 + wifi + price1 + price2);

    return false;
}


问:
symfony3 form, can't get options in buildForm method
I don't really know which title to give this thread but, i'm working on a Symfony project in v3.1.6 and using the select2 plugin in field of my form with ajax.

I want to use the event (submit and pre_set_data) of the form component for creation and editing to change the field dynamically like this part of the symfony doc. Everything work fine until when i submit the form and give an error Notice: Undefined variable: options

My form type code here

```<code>namespace Xxx\ArticleBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Xxx\ArtistBundle\Repository\ArtistRepository;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Ivory\CKEditorBundle\Form\Type\CKEditorType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Doctrine\ORM\EntityManager;

class ArticleType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
    //$em = $options['em']; //this give me same error

        $builder
        ->add('artist', EntityType::class, array(
            'class' => 'XxxArtistBundle:Artist',
            'choice_label' => 'artist_name',
            'multiple' => false,
            'expanded' => false))
        ->add('title', TextType::class)
        ->add('categories', EntityType::class, array(
            'class' => 'XxxArticleBundle:Category',
            'choice_label' => 'name',
            'multiple' => true,
            'expanded' => true))
        ->add('image', ChoiceType::class, array(
            'expanded' => false,
            'multiple' => false))
        ->add('intro', CKEditorType::class)
        ->add('content', CKEditorType::class);

    $formModifier = function (FormInterface $form, $image) {
        $listImages = $options['em']->getRepository('XxxAppBundle:Image')->find($image)); //this line give me the error
        if (!$listImages) {
            return; //i will add a FormError in the field
        }
        $listImages = array();
        die(var_dump($listImages));

        $form->add('image', EntityType::class, array(
            'class'       => 'XxxAppBundle:Image',
            'choices'     => $listImages,
        ));
    };

    $builder->get('image')->addEventListener(
        FormEvents::POST_SUBMIT,
        function (FormEvent $event) use ($formModifier) {
            $image = $event->getForm()->getData();
            //die(var_dump($image)); //select2 field, returned null (but it's not the question
            //die(var_dump($options)); returned error 500 Notice: Undefined variable: options
            $formModifier($event->getForm()->getParent(), $image);
        }
    );
}

/**
 * {@inheritdoc}
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'Xxx\ArticleBundle\Entity\Article',
    ));
    $resolver->setRequired('em');
}

/**
 * {@inheritdoc}
 */
public function getBlockPrefix()
{
    return 'xxx_articlebundle_article';
}
}
</code>```

And i also want to say the goal is to have a UI similar w/ Wordpress when create a post from the dashboard, for set an image in an article and when image is selected throw it in a  tag to the user and without entityType because it will have thousand so i choose an choiceType to use with the select2 plugin but if someone got a better solution i'm on it.

Thx in advance for the help

答:
When you're using a variable from a parent scope inside a closure, you should pass it to 'use' language construct.</p>

```<code>$formModifier = function (FormInterface $form, $image) use ($options) {
    $listImages = $options['em']->getRepository('XxxAppBundle:Image')->find($image)); //this line give me the error
    if (!$listImages) {
        return; //i will add a FormError in the field
    }
    $listImages = array();
    die(var_dump($listImages));

    $form->add('image', EntityType::class, array(
        'class'       => 'XxxAppBundle:Image',
        'choices'     => $listImages,
    ));
};
</code>```

Body:
I don't really know which title to give this thread but, i'm working on a Symfony project in v3.1.6 and using the select2 plugin in field of my form with ajax.

I want to use the event (submit and pre_set_data) of the form component for creation and editing to change the field dynamically like this part of the symfony doc. Everything work fine until when i submit the form and give an error Notice: Undefined variable: options

My form type code here

namespace Xxx\ArticleBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Xxx\ArtistBundle\Repository\ArtistRepository;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Ivory\CKEditorBundle\Form\Type\CKEditorType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Doctrine\ORM\EntityManager;

class ArticleType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
    //$em = $options['em']; //this give me same error

        $builder
        ->add('artist', EntityType::class, array(
            'class' => 'XxxArtistBundle:Artist',
            'choice_label' => 'artist_name',
            'multiple' => false,
            'expanded' => false))
        ->add('title', TextType::class)
        ->add('categories', EntityType::class, array(
            'class' => 'XxxArticleBundle:Category',
            'choice_label' => 'name',
            'multiple' => true,
            'expanded' => true))
        ->add('image', ChoiceType::class, array(
            'expanded' => false,
            'multiple' => false))
        ->add('intro', CKEditorType::class)
        ->add('content', CKEditorType::class);

    $formModifier = function (FormInterface $form, $image) {
        $listImages = $options['em']->getRepository('XxxAppBundle:Image')->find($image)); //this line give me the error
        if (!$listImages) {
            return; //i will add a FormError in the field
        }
        $listImages = array();
        die(var_dump($listImages));

        $form->add('image', EntityType::class, array(
            'class'       => 'XxxAppBundle:Image',
            'choices'     => $listImages,
        ));
    };

    $builder->get('image')->addEventListener(
        FormEvents::POST_SUBMIT,
        function (FormEvent $event) use ($formModifier) {
            $image = $event->getForm()->getData();
            //die(var_dump($image)); //select2 field, returned null (but it's not the question
            //die(var_dump($options)); returned error 500 Notice: Undefined variable: options
            $formModifier($event->getForm()->getParent(), $image);
        }
    );
}

/**
 * {@inheritdoc}
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'Xxx\ArticleBundle\Entity\Article',
    ));
    $resolver->setRequired('em');
}

/**
 * {@inheritdoc}
 */
public function getBlockPrefix()
{
    return 'xxx_articlebundle_article';
}
}

And i also want to say the goal is to have a UI similar w/ Wordpress when create a post from the dashboard, for set an image in an article and when image is selected throw it in a  tag to the user and without entityType because it will have thousand so i choose an choiceType to use with the select2 plugin but if someone got a better solution i'm on it.

Thx in advance for the help

Body:
When you're using a variable from a parent scope inside a closure, you should pass it to 'use' language construct.

$formModifier = function (FormInterface $form, $image) use ($options) {
    $listImages = $options['em']->getRepository('XxxAppBundle:Image')->find($image)); //this line give me the error
    if (!$listImages) {
        return; //i will add a FormError in the field
    }
    $listImages = array();
    die(var_dump($listImages));

    $form->add('image', EntityType::class, array(
        'class'       => 'XxxAppBundle:Image',
        'choices'     => $listImages,
    ));
};


问:
Canvas doesn't draw colors with an alpha as they supposed to be drawn
After days of trying, I am just frustrated.

I've wanted to make a simple app that draws a color gradient from completely transparent to white on top of a background.
For testing, I just used a background with black, white and some greys.

But when I started the app to see the result I saw this:

Some colors turn out to be darker or more colored than they should be. For example, the left bar should be completely white.

I quickly made an image that shows how it should look like:

This is the code in my draw function:

```<code>        for(int i = 0; i < 5; i++) {
            p.setARGB(255, (255/4*(4-i)), (255/4*(4-i)), (255/4*(4-i)));
            canvas.drawRect(canvas.getWidth()/5*i, 0, canvas.getWidth()/5*(i+1), canvas.getHeight(), p);
        }
        for(int i = 0; i < 256; i++) {
            p.setARGB(i, 255, 255, 255);
            canvas.drawRect(0, i*(canvas.getHeight()/256), canvas.getWidth(), (i+1)*(canvas.getHeight()/256), p);
        }
</code>```

What am I missing? Is this just how the Canvas works? How can I fix this so that it looks like my example I made in GIMP?

答: Because your algorithm is wrong.  Creating squares of a color is not the same thing as a smooth gradient.  Your method is going to have artifacting like you see above.  Instead of trying to do it on your own, use GradientDrawables which are already built into the platform.</p>

Body:
After days of trying, I am just frustrated.

I've wanted to make a simple app that draws a color gradient from completely transparent to white on top of a background.
For testing, I just used a background with black, white and some greys.

But when I started the app to see the result I saw this:

Some colors turn out to be darker or more colored than they should be. For example, the left bar should be completely white.

I quickly made an image that shows how it should look like:

This is the code in my draw function:

        for(int i = 0; i < 5; i++) {
            p.setARGB(255, (255/4*(4-i)), (255/4*(4-i)), (255/4*(4-i)));
            canvas.drawRect(canvas.getWidth()/5*i, 0, canvas.getWidth()/5*(i+1), canvas.getHeight(), p);
        }
        for(int i = 0; i < 256; i++) {
            p.setARGB(i, 255, 255, 255);
            canvas.drawRect(0, i*(canvas.getHeight()/256), canvas.getWidth(), (i+1)*(canvas.getHeight()/256), p);
        }

What am I missing? Is this just how the Canvas works? How can I fix this so that it looks like my example I made in GIMP?


问:
Appending a string containing a backslash to a list creates a list element with double backslash
When I tried appending a string containing a backslash into a list, the element in the list is actually the string, but with double backslashes instead of single backslashes.

Code is as follows:

```<code>word = "<< hello\world"
sample = list()
sample.append(word)
print(sample) #['<< hello\\world']
print word #<< hello\world
</code>```

Can anybody explain what is going on, and how to work around this?

答:
The backslash is a special character, you should have written it with 2 backslashes yourself. Python corrected you. If you try to print the item within the list it will print correctly.</p>

```<code>print(sample) #['<< hello\\world']
print word #<< hello\world
print(sample[0]) #<< hello\world
</code>```

Body:
When I tried appending a string containing a backslash into a list, the element in the list is actually the string, but with double backslashes instead of single backslashes.

Code is as follows:

word = "<< hello\world"
sample = list()
sample.append(word)
print(sample) #['<< hello\\world']
print word #<< hello\world

Can anybody explain what is going on, and how to work around this?

Body:
The backslash is a special character, you should have written it with 2 backslashes yourself. Python corrected you. If you try to print the item within the list it will print correctly.

print(sample) #['<< hello\\world']
print word #<< hello\world
print(sample[0]) #<< hello\world


问:
Slicing to extract maximum values along an axis, in an ndarray
I'm trying to find the indices of the maximum values along a particular axis (0) for a 3D ndarray, and then use those indices to slice out those values (and the corresponding values from a second, parallel array).  For example,

```<code>> a = np.random.randint(10, 100, 24).reshape(2, 3, 4)
> print(a)
array([[[94, 22, 96, 44],
        [11, 85, 39, 85],
        [58, 43, 48, 84]],

       [[84, 58, 51, 30],
        [74, 89, 90, 11],
        [90, 54, 94, 20]]])
</code>```

Now, I'm interested in the indices which give the values that are the maximum over the zeroth axis, i.e.

```<code>> a[inds]
array([[94, 58, 96, 44],
       [74, 89, 90, 85,],
       [90, 54, 94, 84,]])
</code>```

Using a.argmax() gives which 0th-axis index is the maximum, i.e.

```<code>> a.argmax(axis=0)
array([[0, 1, 0, 0],
       [1, 1, 1, 0],
       [1, 1, 1, 0]])
</code>```

But this won't work for slicing...

Body:
I'm trying to find the indices of the maximum values along a particular axis (0) for a 3D ndarray, and then use those indices to slice out those values (and the corresponding values from a second, parallel array).  For example,

> a = np.random.randint(10, 100, 24).reshape(2, 3, 4)
> print(a)
array([[[94, 22, 96, 44],
        [11, 85, 39, 85],
        [58, 43, 48, 84]],

       [[84, 58, 51, 30],
        [74, 89, 90, 11],
        [90, 54, 94, 20]]])

Now, I'm interested in the indices which give the values that are the maximum over the zeroth axis, i.e.

> a[inds]
array([[94, 58, 96, 44],
       [74, 89, 90, 85,],
       [90, 54, 94, 84,]])

Using a.argmax() gives which 0th-axis index is the maximum, i.e.

> a.argmax(axis=0)
array([[0, 1, 0, 0],
       [1, 1, 1, 0],
       [1, 1, 1, 0]])

But this won't work for slicing...

Body:
Use advanced-indexing upon creating the range arrays along the rest of the axes/dims, like so -

m,n = a.shape[1:]
Y,Z = np.ogrid[:m,:n]
Y_max_axis0 = a[inds,Y,Z]

Sample run -

In [15]: a
Out[15]:
array([[[94, 22, 96, 44],
        [11, 85, 39, 85],
        [58, 43, 48, 84]],

       [[84, 58, 51, 30],
        [74, 89, 90, 11],
        [90, 54, 94, 20]]])

In [16]: inds = a.argmax(axis=0)

In [17]: m,n = a.shape[1:]
    ...: Y,Z = np.ogrid[:m,:n]
    ...: Y_max_axis0 = a[inds,Y,Z]
    ...:

In [18]: Y_max_axis0
Out[18]:
array([[94, 58, 96, 44],
       [74, 89, 90, 85],
       [90, 54, 94, 84]])

A more explicit way to create those range arrays and then indexing -

In [19]: a[inds,np.arange(a.shape[1])[:,None], np.arange(a.shape[2])]
Out[19]:
array([[94, 58, 96, 44],
       [74, 89, 90, 85],
       [90, 54, 94, 84]])


问:
Controlling Visibility Of Imported Categories
I am writing a program to turn off certain "sub-categories" from imported AutoCAD files (such as "DEFPOINTS", which arguably should automatically be hidden or not plot in Revit).  The following code seems like it should work, but instead kicks back an odd error.

```<code>Transaction Do_Filtered_VG = new Transaction(doc, "FilteredVG")
Autodesk.Revit.DB.View CurrentView = doc.ActiveView;
Categories categories = doc.Settings.Categories; string CatUp = string.Empty;
List<Category> ToBeOff = new List<Category>();
List<string> myCategories = new List<string>();
foreach (Category c in categories)
{
    if (c.Name.ToLower().EndsWith("dwg"))
    {
        List<Category> SubCategories = new List<Category>();
        foreach (Category One_Cat in c.SubCategories)
        {
            CatUp = One_Cat.Name.ToUpper();
            if (CatUp.Contains("DEFPOINTS") || CatUp.Contains("NPLT") || CatUp.Contains("RDFF") || CatUp.Contains("SDFF") || CatUp.Contains("DUCT"))//or other pattern;
            {
                 myCategories.Add(One_Cat.Name); ToBeOff.Add(One_Cat);
            }
        }
    }
}
Do_Filtered_VG.Start();
foreach (Category One_Cat in ToBeOff)
{
    CurrentView.SetVisibility(One_Cat, false);
}
Do_Filtered_VG.Commit();
TestCodeX.If_Tony("Would Turn Off Layers:", TestCodeX.List_To_Dialog(myCategories));
</code>```

The error given is: Cannot set the visible attribute of the category Level 3 because it is user hiddenA transaction or sub-transaction was opened but not closed".  This is odd, because "Level 3" is not a category, but is the ActiveView.

But my transaction is opened and closed.  I was not able to find hiddenA in an online search.  I also tried using the construction:  One_Cat.get_Visibility(CurrentView) (to try to at least see if the category is visible), and this resulted in the same error.  I also changed my references from RevitAPI (2014) to (2015) and (2016), with no change in the error.  My code properly filtered the layer names I wanted to turn off, as evidenced in my "Would Turn Off Layers:" TaskDialog echo of myCategories.  But whenever the .SetVisibility line was not commented out, I get the error described.

Is there some other method of turning off(on) visibility of Categories in the RevitAPI?  Or is there some other Transaction method required other than the one I am using?

答:
There are some internal categories that exist, but you can't set the visibility on. I don't have the SDK handy, but there's a property along the lines of "Category.AllowsVisibilityControl[view]" that will tell you whether it is legitimate to hide that category in the current view.

So you would do something like this in your code:

```<code>// inside your existing IF about the category name...
if (One_Cat.AllowsVisibilityControl[CurrentView])
{
    myCategories.Add(One_Cat.Name); ToBeOff.Add(One_Cat);
}
</code>```

Body:
I am writing a program to turn off certain "sub-categories" from imported AutoCAD files (such as "DEFPOINTS", which arguably should automatically be hidden or not plot in Revit).  The following code seems like it should work, but instead kicks back an odd error.

Transaction Do_Filtered_VG = new Transaction(doc, "FilteredVG")
Autodesk.Revit.DB.View CurrentView = doc.ActiveView;
Categories categories = doc.Settings.Categories; string CatUp = string.Empty;
List<Category> ToBeOff = new List<Category>();
List<string> myCategories = new List<string>();
foreach (Category c in categories)
{
    if (c.Name.ToLower().EndsWith("dwg"))
    {
        List<Category> SubCategories = new List<Category>();
        foreach (Category One_Cat in c.SubCategories)
        {
            CatUp = One_Cat.Name.ToUpper();
            if (CatUp.Contains("DEFPOINTS") || CatUp.Contains("NPLT") || CatUp.Contains("RDFF") || CatUp.Contains("SDFF") || CatUp.Contains("DUCT"))//or other pattern;
            {
                 myCategories.Add(One_Cat.Name); ToBeOff.Add(One_Cat);
            }
        }
    }
}
Do_Filtered_VG.Start();
foreach (Category One_Cat in ToBeOff)
{
    CurrentView.SetVisibility(One_Cat, false);
}
Do_Filtered_VG.Commit();
TestCodeX.If_Tony("Would Turn Off Layers:", TestCodeX.List_To_Dialog(myCategories));

The error given is: Cannot set the visible attribute of the category Level 3 because it is user hiddenA transaction or sub-transaction was opened but not closed".  This is odd, because "Level 3" is not a category, but is the ActiveView.

But my transaction is opened and closed.  I was not able to find hiddenA in an online search.  I also tried using the construction:  One_Cat.get_Visibility(CurrentView) (to try to at least see if the category is visible), and this resulted in the same error.  I also changed my references from RevitAPI (2014) to (2015) and (2016), with no change in the error.  My code properly filtered the layer names I wanted to turn off, as evidenced in my "Would Turn Off Layers:" TaskDialog echo of myCategories.  But whenever the .SetVisibility line was not commented out, I get the error described.

Is there some other method of turning off(on) visibility of Categories in the RevitAPI?  Or is there some other Transaction method required other than the one I am using?

Body:
There are some internal categories that exist, but you can't set the visibility on. I don't have the SDK handy, but there's a property along the lines of "Category.AllowsVisibilityControl[view]" that will tell you whether it is legitimate to hide that category in the current view.

So you would do something like this in your code:

// inside your existing IF about the category name...
if (One_Cat.AllowsVisibilityControl[CurrentView])
{
    myCategories.Add(One_Cat.Name); ToBeOff.Add(One_Cat);
}


问:
How to make an html table responsive
I have an html table that is created using constant contact and and I would like to make it responsive and fit the container div holding it.

Here is the demo

I tried the following but this doesn't work as well

```<code><table border="0" width="100%" cellspacing="0" cellpadding="0">
</code>```

答: Use media queries and width of your container and font sizes should be in percentage.</p>

Title: How to make an html table responsive


问:
Hoy can I get from Analytics API User Explorer and User Report
I need to catch from a website, the list of users (IDs from User Explorer) that has been entered each day, and all the report from each one (User Report)

I didn't see anything about it in the current API from Google Analytics. Someone knows how to get it?

I saw some questions but from more than 1 year ago, someone knows if there is now any new?

The only thing that I can do for now, is using the automatic report from Google Analytics via email, and send me a report each day with a list of Client IDs en CSV, but I need the report...

Thank you very much!

答: Capture the Google Analytics Client ID or user id in a custom dimension and hit timestamp. Then you can recreate the user explorer id report yourself using the Google Analytics Reporting API.</p>