问:
Call one batch file from another and then continue batch file 1 after batch file 2 exists
I am calling batch file (say file2.bat) from another batch file (say batch file 1).

file1.bat:

```<code>echo off
@call file2.bat
@echo abc
@echo xyz
exit
</code>```

I am using command exit /b to exit from file2.bat ..

For some reason, the control is not coming back to file1.bat after file2.bat exits..

What needs to be done in order to return the control back to file1.bat so that the remaining commands @echo abc @echo xyz should execute?

Thanks

答: Use either cmd /c file2.bat or use goto :EOF (Where EOF means end of file), goto :eof should work in your case

Body:
I am calling batch file (say file2.bat) from another batch file (say batch file 1).

file1.bat:

echo off
@call file2.bat
@echo abc
@echo xyz
exit

I am using command exit /b to exit from file2.bat ..

For some reason, the control is not coming back to file1.bat after file2.bat exits..

What needs to be done in order to return the control back to file1.bat so that the remaining commands @echo abc @echo xyz should execute?

Thanks


来源: stackexchange

问:
How to check EU VAT using VIES SOAP service in C#
I have an ASP.NET website that needs to check a user-supplied VAT. The VIES Service can be used for that which exposes a SOAP API.

I need a dead-simple example on how to validate a VAT using this service. In PHP, it's these 4 lines: https://stackoverflow.com/a/14340495. For C#, I have found some articles from 2010 that do not work or are tens or even hundreds lines of "wrappers", "helper services" etc.

I don't need any of that, can someone provide PHP-like four-liner that would check VAT in C#? Thank you.

答:
Here is a self-sufficient (no WCF, no WSDL, ...) utility class that will check the VAT number and get information on the company (name and address). It will return null if the VAT number is invalid or if any error occurred.

Update 2022/10/17 : I have added namespace handling to parse the response as it seems the EU web service was modified. If you need the old version, just look at the history

```<code>// sample calling code
Console.WriteLine(EuropeanVatInformation.Get("FR89831948815"));

...

public class EuropeanVatInformation
{
    private EuropeanVatInformation() { }

    public string CountryCode { get; private set; }
    public string VatNumber { get; private set; }
    public string Address { get; private set; }
    public string Name { get; private set; }
    public override string ToString() => CountryCode + " " + VatNumber + ": " + Name + ", " + Address.Replace("\n", ", ");

    public static EuropeanVatInformation Get(string countryCodeAndVatNumber)
    {
        if (countryCodeAndVatNumber == null)
            throw new ArgumentNullException(nameof(countryCodeAndVatNumber));

        if (countryCodeAndVatNumber.Length < 3)
            return null;

        return Get(countryCodeAndVatNumber.Substring(0, 2), countryCodeAndVatNumber.Substring(2));
    }

    public static EuropeanVatInformation Get(string countryCode, string vatNumber)
    {
        if (countryCode == null)
            throw new ArgumentNullException(nameof(countryCode));

        if (vatNumber == null)
            throw new ArgumentNullException(nameof(vatNumber));

        countryCode = countryCode.Trim();
        vatNumber = vatNumber.Trim().Replace(" ", string.Empty);

        const string ns = "urn:ec.europa.eu:taxud:vies:services:checkVat:types";
        const string url = "http://ec.europa.eu/taxation_customs/vies/services/checkVatService";
        const string xml = @"<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><checkVat xmlns='" + ns + "'><countryCode>{0}</countryCode><vatNumber>{1}</vatNumber></checkVat></s:Body></s:Envelope>";

        try
        {
            using (var client = new WebClient())
            {
                var doc = new XmlDocument();
                doc.LoadXml(client.UploadString(url, string.Format(xml, countryCode, vatNumber)));
                var response = doc.SelectSingleNode("//*[local-name()='checkVatResponse']") as XmlElement;
                if (response == null || response["valid", ns]?.InnerText != "true")
                    return null;

                var info = new EuropeanVatInformation
                {
                    CountryCode = response["countryCode", ns].InnerText,
                    VatNumber = response["vatNumber", ns].InnerText,
                    Name = response["name", ns]?.InnerText,
                    Address = response["address", ns]?.InnerText
                };
                return info;
            }
        }
        catch
        {
            return null;
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is a self-sufficient (no WCF, no WSDL, ...) utility class that will check the VAT number and get information on the company (name and address). It will return null if the VAT number is invalid or if any error occurred.

Update 2022/10/17 : I have added namespace handling to parse the response as it seems the EU web service was modified. If you need the old version, just look at the history

// sample calling code
Console.WriteLine(EuropeanVatInformation.Get("FR89831948815"));

...

public class EuropeanVatInformation
{
    private EuropeanVatInformation() { }

    public string CountryCode { get; private set; }
    public string VatNumber { get; private set; }
    public string Address { get; private set; }
    public string Name { get; private set; }
    public override string ToString() => CountryCode + " " + VatNumber + ": " + Name + ", " + Address.Replace("\n", ", ");

    public static EuropeanVatInformation Get(string countryCodeAndVatNumber)
    {
        if (countryCodeAndVatNumber == null)
            throw new ArgumentNullException(nameof(countryCodeAndVatNumber));

        if (countryCodeAndVatNumber.Length < 3)
            return null;

        return Get(countryCodeAndVatNumber.Substring(0, 2), countryCodeAndVatNumber.Substring(2));
    }

    public static EuropeanVatInformation Get(string countryCode, string vatNumber)
    {
        if (countryCode == null)
            throw new ArgumentNullException(nameof(countryCode));

        if (vatNumber == null)
            throw new ArgumentNullException(nameof(vatNumber));

        countryCode = countryCode.Trim();
        vatNumber = vatNumber.Trim().Replace(" ", string.Empty);

        const string ns = "urn:ec.europa.eu:taxud:vies:services:checkVat:types";
        const string url = "http://ec.europa.eu/taxation_customs/vies/services/checkVatService";
        const string xml = @"<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><checkVat xmlns='" + ns + "'><countryCode>{0}</countryCode><vatNumber>{1}</vatNumber></checkVat></s:Body></s:Envelope>";

        try
        {
            using (var client = new WebClient())
            {
                var doc = new XmlDocument();
                doc.LoadXml(client.UploadString(url, string.Format(xml, countryCode, vatNumber)));
                var response = doc.SelectSingleNode("//*[local-name()='checkVatResponse']") as XmlElement;
                if (response == null || response["valid", ns]?.InnerText != "true")
                    return null;

                var info = new EuropeanVatInformation
                {
                    CountryCode = response["countryCode", ns].InnerText,
                    VatNumber = response["vatNumber", ns].InnerText,
                    Name = response["name", ns]?.InnerText,
                    Address = response["address", ns]?.InnerText
                };
                return info;
            }
        }
        catch
        {
            return null;
        }
    }
}

ContentLicense: CC BY-SA 4.0


问:
PHP Regex replace all instances of a character in similar strings
I have a file that contains a collection strings. All of the strings begin with the same set of characters and end with the same character. I need to find all of the strings that match a certain pattern, and then remove particular characters from them before saving the file. Each string looks like this:

```<code>Data_*: " ... "
</code>```

where Data_ is the same for each string, the asterisk is an incrementing integer that is either two or three digits, and the colon and the double quotation marks are the same for each string. The ... is completely different in every string and it's the part of each I need to work with. I need to remove all double quotation marks from the ... , preserving the enclosing double quotation marks. I don't need to replace them, just remove them.

So for example, I need this...

```<code>Data_83: "He said, "Yes!" to the question"
</code>```

to become this...

```<code>Data_83: "He said, Yes! to the question"
</code>```

I am familiar with PHP and would like to use this. I know how to do something like...

```<code><?php
$filename = 'path/to/file';
$content = file_get_contents($filename);
$new_content = str_replace('"', '', $content);
file_put_contents($filename, $new_content);
</code>```

And I'm pretty sure a regular expression will be what I'm wanting to use to find the strings and remove the extra double quotation marks. But I'm very new to regular expressions and need some help here.

EDIT:

I should have mentioned, the file is a PHP file containing an object. It looks a bit like this:

```<code><?php
$thing = {
    Data_83: "He said, "Yes!" to the question",
    Data_84: "Another string with "unwanted" quotes"
}
</code>```

答:
The way I see it, you don't need to make any preg_replace_callback() calls or a convoluted run of explosions and replacements.  You merely need to disqualify the 2 double quotes that you wish to retain and match the rest for removal.

Code: (Demo)

```<code>$string = 'Data_83: "He said, "Yes!" to the question",
Data_184: "He said, "WTF!" to the question"';

echo preg_replace('/^[^"]+"(*SKIP)(*FAIL)|"(?!,\R|$)/m','',$string);
</code>```

Output:

```<code>Data_83: "He said, Yes! to the question",
Data_184: "He said, WTF! to the question"
</code>```

Pattern Demo

```<code>/^[^"]+"(*SKIP)(*FAIL)|"(?!,?$)/m
</code>```

This pattern says:

match from the start of each line until you reach the first double quote, then DISQUALIFY it.

then after the |, match all double quotes that are not optionally followed by a comma then the end of line.

While this pattern worked on regex101 with my sample input, when I transferred it to the php sandbox to whack together a demo, I needed to add \R to maintain accuracy.  You can test to see which is appropriate for your server/environment.

Body:
I have a file that contains a collection strings. All of the strings begin with the same set of characters and end with the same character. I need to find all of the strings that match a certain pattern, and then remove particular characters from them before saving the file. Each string looks like this:

Data_*: " ... "

where Data_ is the same for each string, the asterisk is an incrementing integer that is either two or three digits, and the colon and the double quotation marks are the same for each string. The ... is completely different in every string and it's the part of each I need to work with. I need to remove all double quotation marks from the ... , preserving the enclosing double quotation marks. I don't need to replace them, just remove them.

So for example, I need this...

Data_83: "He said, "Yes!" to the question"

to become this...

Data_83: "He said, Yes! to the question"

I am familiar with PHP and would like to use this. I know how to do something like...

<?php
$filename = 'path/to/file';
$content = file_get_contents($filename);
$new_content = str_replace('"', '', $content);
file_put_contents($filename, $new_content);

And I'm pretty sure a regular expression will be what I'm wanting to use to find the strings and remove the extra double quotation marks. But I'm very new to regular expressions and need some help here.

EDIT:

I should have mentioned, the file is a PHP file containing an object. It looks a bit like this:

<?php
$thing = {
    Data_83: "He said, "Yes!" to the question",
    Data_84: "Another string with "unwanted" quotes"
}

Body:
The way I see it, you don't need to make any preg_replace_callback() calls or a convoluted run of explosions and replacements.  You merely need to disqualify the 2 double quotes that you wish to retain and match the rest for removal.

Code: (Demo)

$string = 'Data_83: "He said, "Yes!" to the question",
Data_184: "He said, "WTF!" to the question"';

echo preg_replace('/^[^"]+"(*SKIP)(*FAIL)|"(?!,\R|$)/m','',$string);

Output:

Data_83: "He said, Yes! to the question",
Data_184: "He said, WTF! to the question"

Pattern Demo

/^[^"]+"(*SKIP)(*FAIL)|"(?!,?$)/m

This pattern says:

match from the start of each line until you reach the first double quote, then DISQUALIFY it.

then after the |, match all double quotes that are not optionally followed by a comma then the end of line.

While this pattern worked on regex101 with my sample input, when I transferred it to the php sandbox to whack together a demo, I needed to add \R to maintain accuracy.  You can test to see which is appropriate for your server/environment.


问:
Does Guava provide a method to unescape a String?
I need to escape special characters in a String.

Guava provides the Escaper class, which does exactly this:

```<code>Escaper escaper = Escapers.builder()
        .addEscape('[', "\\[")
        .addEscape(']', "\\]")
        .build();

String escapedStr = escaper.escape("This is a [test]");

System.out.println(escapedStr);
// -> prints "This is a \[test\]"
</code>```

Now that I have an escaped String, I need to unescape it and I can't find anything in Guava to do this.

I was expecting Escaper to have a unescape() method, but it isn't the case.

Edit : I'm aware that unescaping can be tricky, even impossible in some non-sense cases.

For example, this Escaper usage can lead to ambiguities :

```<code>Escaper escaper = Escapers.builder()
        .addEscape('@', " at ")
        .addEscape('.', " dot ")
        .build();
</code>```

Unless the escaped data contains only email addresses and nothing more, you can't safely get your data back by unescaping it.

A good example of a safe usage of the Escaper is HTML entities :

```<code>Escaper escaper = Escapers.builder()
        .addEscape('&', "&")
        .addEscape('<', "<")
        .addEscape('>', ">")
        .build();
</code>```

Here, you can safely escape any text, incorporate it in a HTML page and unescape it at any time to display it, because you covered every possible ambiguities.

In conclusion, I don't see why unescaping is so controversial. I think it is the developper's responsability to use this class properly, knowing his data and avoiding ambiguities.
Escaping, by definition, means you will eventually need to unescape. Otherwise, it's obfuscation or some other concept.

答:
In case if anybody will ever need a single char unescaper, here's one dead simple implementation below:</p>

```<code>@Nonnull
public String unescape(@Nonnull String text) {
    CharacterIterator i = new StringCharacterIterator(text);
    StringBuilder result = new StringBuilder(text.length());
    for (char c = i.first(); c != DONE; c = i.next()) {
        if (c == escaped) {
            result.append(i.next());
        } else {
            result.append(c);
        }
    }
    return result.toString();
}
</code>```

Body:
I need to escape special characters in a String.

Guava provides the Escaper class, which does exactly this:

Escaper escaper = Escapers.builder()
        .addEscape('[', "\\[")
        .addEscape(']', "\\]")
        .build();

String escapedStr = escaper.escape("This is a [test]");

System.out.println(escapedStr);
// -> prints "This is a \[test\]"

Now that I have an escaped String, I need to unescape it and I can't find anything in Guava to do this.

I was expecting Escaper to have a unescape() method, but it isn't the case.

Edit : I'm aware that unescaping can be tricky, even impossible in some non-sense cases.

For example, this Escaper usage can lead to ambiguities :

Escaper escaper = Escapers.builder()
        .addEscape('@', " at ")
        .addEscape('.', " dot ")
        .build();

Unless the escaped data contains only email addresses and nothing more, you can't safely get your data back by unescaping it.

A good example of a safe usage of the Escaper is HTML entities :

Escaper escaper = Escapers.builder()
        .addEscape('&', "&")
        .addEscape('<', "<")
        .addEscape('>', ">")
        .build();

Here, you can safely escape any text, incorporate it in a HTML page and unescape it at any time to display it, because you covered every possible ambiguities.

In conclusion, I don't see why unescaping is so controversial. I think it is the developper's responsability to use this class properly, knowing his data and avoiding ambiguities.
Escaping, by definition, means you will eventually need to unescape. Otherwise, it's obfuscation or some other concept.

Body:
In case if anybody will ever need a single char unescaper, here's one dead simple implementation below:

@Nonnull
public String unescape(@Nonnull String text) {
    CharacterIterator i = new StringCharacterIterator(text);
    StringBuilder result = new StringBuilder(text.length());
    for (char c = i.first(); c != DONE; c = i.next()) {
        if (c == escaped) {
            result.append(i.next());
        } else {
            result.append(c);
        }
    }
    return result.toString();
}


问:
Can not cast context into activity Xamarin
I have an issue in xamarin, and I need some help, please

From xamarin tutorial, I wish to launch a phone call thanks to a DependencyService.

Here is the service implementation for Android part:

```<code> public bool Dial(string number)
    {
        var context = Android.App.Application.Context;

        if (context == null)
            return false;

        var intent = new Intent(Intent.ActionCall);
        intent.SetData(Uri.Parse("tel:" + number));
        try
        {
            var activity = (Activity)context;
            ActivityCompat.RequestPermissions(activity,
             new String[] { Android.Manifest.Permission.CallPhone }, 1);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }

        if (IsIntentAvailable(context, intent))
        {
            try
            {
                context.StartActivity(intent);

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            return true;
        }

        return false;
    }
</code>```

The main issue is: I have a revoked permission

android.permission.CALL_PHONE

. I precise that I have given the permission in the manifest. I have read that I need to register in runtime the permission. It's what I'm trying with

```<code>ActivityCompat.RequestPermissions(activity,
             new String[] { Android.Manifest.Permission.CallPhone }, 1);
</code>```

But I need the curent Activity as parameter and I can't cast the current Context into Activity.

Please help me to find where I have done a mistake.

Thank you

答:
If you are in Activity.

You are casting Application context.

```<code>var context = Android.App.Application.Context;
</code>```

Replace it with below

```<code>var context = android.content.Context;
</code>```

If you are working in Service then you can ask for permission from where you are calling your service.

Body:
I have an issue in xamarin, and I need some help, please

From xamarin tutorial, I wish to launch a phone call thanks to a DependencyService.

Here is the service implementation for Android part:

 public bool Dial(string number)
    {
        var context = Android.App.Application.Context;

        if (context == null)
            return false;

        var intent = new Intent(Intent.ActionCall);
        intent.SetData(Uri.Parse("tel:" + number));
        try
        {
            var activity = (Activity)context;
            ActivityCompat.RequestPermissions(activity,
             new String[] { Android.Manifest.Permission.CallPhone }, 1);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }

        if (IsIntentAvailable(context, intent))
        {
            try
            {
                context.StartActivity(intent);

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            return true;
        }

        return false;
    }

The main issue is: I have a revoked permission

android.permission.CALL_PHONE

. I precise that I have given the permission in the manifest. I have read that I need to register in runtime the permission. It's what I'm trying with

ActivityCompat.RequestPermissions(activity,
             new String[] { Android.Manifest.Permission.CallPhone }, 1);

But I need the curent Activity as parameter and I can't cast the current Context into Activity.

Please help me to find where I have done a mistake.

Thank you

Body:
If you are in Activity.

You are casting Application context.

var context = Android.App.Application.Context;

Replace it with below

var context = android.content.Context;

If you are working in Service then you can ask for permission from where you are calling your service.


问:
How to size an Image of a button?
I have the following Layout

```<code>            <Button
                android:layout_width="fill_parent"
                android:layout_height="75dp"
                android:drawableLeft="@drawable/binocular"
                android:gravity="left|center_vertical"
                android:text="search" />
</code>```

and it looks like :

The picture is too large. I simply want to align the image to the left with the corredct size, so it fits with the height of the button.

I know I could adjust the bound of the image by code. But I would like to know, if there is a way to do with layout specification.

There is a solution mentoined : how to change a drawableLeft icon size on a button? (accepted answer)

I guess this is the correct one, but I do not understand , where to put the layer-list and how to reference it in the button.

Can someone help ?

答:
Set the scaleType attribute on the ImageButton

```<code><ImageButton android:id="@+id/iconBtn"
  android:layout_width="64dip"
  android:layout_height="64dip"
  android:src="@drawable/binocular"
  android:scaleType="fitCenter"
  android:background="#00000000"/>
</code>```

Title: How to size an Image of a button?

Body:
I have the following Layout

            <Button
                android:layout_width="fill_parent"
                android:layout_height="75dp"
                android:drawableLeft="@drawable/binocular"
                android:gravity="left|center_vertical"
                android:text="search" />

and it looks like :

The picture is too large. I simply want to align the image to the left with the corredct size, so it fits with the height of the button.

I know I could adjust the bound of the image by code. But I would like to know, if there is a way to do with layout specification.

There is a solution mentoined : how to change a drawableLeft icon size on a button? (accepted answer)

I guess this is the correct one, but I do not understand , where to put the layer-list and how to reference it in the button.

Can someone help ?

Body:
Set the scaleType attribute on the ImageButton

<ImageButton android:id="@+id/iconBtn"
  android:layout_width="64dip"
  android:layout_height="64dip"
  android:src="@drawable/binocular"
  android:scaleType="fitCenter"
  android:background="#00000000"/>


答:
I think for-loop is inefficient. We can do something like this using the dplyr and lubridate package.

```<code>library(dplyr)
library(lubridate)

df2 <- df %>%
  # Convert the as.date column to date class
  # Convert the wear column to numeric
  mutate(as.date = dmy(as.date),
         wear = as.numeric(as.character(wear))) %>%
  # Create column show the wear of previous record
  mutate(wear2 = lag(wear)) %>%
  mutate(Diff = wear - wear2)
</code>```

The idea is to shift the wear column by 1, and then calculate the difference between the wear of the date and the previous date. the results are saved in the new column as Diff. Here is what the new data frame looks like.

```<code>head(df2)
#      as.date wear wear2 Diff
# 1 2016-06-14    0    NA   NA
# 2 2016-06-15   55     0   55
# 3 2016-06-16    0    55  -55
# 4 2016-06-17    0     0    0
# 5 2016-06-18    0     0    0
# 6 2016-06-19    0     0    0
</code>```

After this, you can define a threshold in Diff to filter out an end of a period. For example, here I defined the threshold to be -50. You can see that the filter function successfully identify four periods.

```<code># Filter Diff <= -50
df2 %>% filter(Diff <= -50)
#      as.date wear wear2 Diff
# 1 2016-06-16    0    55  -55
# 2 2016-07-15    2    69  -67
# 3 2016-08-22    0    58  -58
# 4 2016-09-13    8    59  -51
</code>```

One final note, in your original data frame, the wear column is in factor, but you calculate it as numeric. This is dangerous. I used wear = as.numeric(as.character(wear)) to convert the column to numeric, but it would be great if you can create the numeric column in the first place.

Title: binning, grouping data in r using values withing a specific range to determine an event or change for survival analysis

Body:
I have a dataframe as follows:

df <- data.frame(as.date=c("14/06/2016","15/06/2016","16/06/2016","17/06/2016","18/06/2016","19/06/2016","20/06/2016","21/06/2016","22/06/2016","23/06/2016",
                    "24/06/2016","04/07/2016","05/07/2016","06/07/2016","07/07/2016","08/07/2016","09/07/2016","10/07/2016","11/07/2016","12/07/2016",
                    "13/07/2016","14/07/2016","15/07/2016","17/07/2016","18/07/2016","19/07/2016","20/07/2016","21/07/2016","22/07/2016","01/08/2016",
                    "02/08/2016","03/08/2016","04/08/2016","05/08/2016","06/08/2016","07/08/2016","08/08/2016","09/08/2016","10/08/2016","11/08/2016",
                    "12/08/2016","13/08/2016","14/08/2016","15/08/2016","16/08/2016","17/08/2016","18/08/2016","19/08/2016","20/08/2016","21/08/2016",
                    "22/08/2016","23/08/2016","24/08/2016","25/08/2016","26/08/2016","27/08/2016","28/08/2016","29/08/2016","30/08/2016","31/08/2016",
                    "01/09/2016","02/09/2016","03/09/2016","04/09/2016","05/09/2016","06/09/2016","07/09/2016","08/09/2016","09/09/2016","10/09/2016",
                    "11/09/2016","12/09/2016","13/09/2016","14/09/2016","15/09/2016","16/09/2016","17/09/2016","18/09/2016","19/09/2016","20/09/2016"),
             wear=c("0","55","0","0","0","0","8","8","15","25","30","37","43","49","52","52","55","57","57","61","67","69","2","2","7",
                    "10","13","14","16","16","19","22","22","24","25","26","29","29","33","34","34","36","38","44","45","48","50","55",
                    "56","58","0","4","0","4","4","6","9","9","12","14","16","17","25","25","33","36","44","46","48","52","55","59",
                    "8","9","9","12","24","33","36","44"))

the data is an example of wear rate on a type of metal on a machine, it increases over time them drops to 0, indicating an event or a change,

but the problem that I have is that the wear value doesn't drop off to 0, as you can see from the data, there are 2 variables

as.date = date over time,
wear = wear of metal on a part over time

RANGE in between changes are:
55-0,
60-2,
58-0,
59-8

when it drops from a large number to 0 it is easy to code,I use the following code to change,and add new variables called Status & id

{Creates 2 new columns status & id
prop.table(table(df$Status))
prop.table(table(df$Status),1) # creates new coulmn called status
df$Status <- 0# fills in column status with all zeros
df$Status[wear > -10 & wear == 0] <- 1 # fill in 1s when wear = 0
prop.table(table(df$Status))
prop.table(table(df$Status),1) # creates new coulmn called status
df$id <-1# fills in column status with '1's

for(i in 2:nrow(df)){
  if(df$Status[i-1]==0){
    df$id[i]=df$id[i-1]
  }
  else {
    df$id[i]=df$id[i-1]+1
  }
}
}

it will work OK to catch a drop in wear values to 0 but when there isn't, as in the data examples, the wear drops take place from 55-0, 69-2, 58-0, 59-8, within the real data set sometimes there are occasions when the drop in wear values will be negative, not sure on correct way to achieve this, I tried messing around with binning and grouping the data but was unsuccessful.

this is a sample of the data, in the real data set there are 100+ events, mostly a wear value drop to 0 but between 10-20 occasions either dropping to negative values or a values < 10.

Body:
I think for-loop is inefficient. We can do something like this using the dplyr and lubridate package.

library(dplyr)
library(lubridate)

df2 <- df %>%
  # Convert the as.date column to date class
  # Convert the wear column to numeric
  mutate(as.date = dmy(as.date),
         wear = as.numeric(as.character(wear))) %>%
  # Create column show the wear of previous record
  mutate(wear2 = lag(wear)) %>%
  mutate(Diff = wear - wear2)

The idea is to shift the wear column by 1, and then calculate the difference between the wear of the date and the previous date. the results are saved in the new column as Diff. Here is what the new data frame looks like.

head(df2)
#      as.date wear wear2 Diff
# 1 2016-06-14    0    NA   NA
# 2 2016-06-15   55     0   55
# 3 2016-06-16    0    55  -55
# 4 2016-06-17    0     0    0
# 5 2016-06-18    0     0    0
# 6 2016-06-19    0     0    0

After this, you can define a threshold in Diff to filter out an end of a period. For example, here I defined the threshold to be -50. You can see that the filter function successfully identify four periods.

# Filter Diff <= -50
df2 %>% filter(Diff <= -50)
#      as.date wear wear2 Diff
# 1 2016-06-16    0    55  -55
# 2 2016-07-15    2    69  -67
# 3 2016-08-22    0    58  -58
# 4 2016-09-13    8    59  -51

One final note, in your original data frame, the wear column is in factor, but you calculate it as numeric. This is dangerous. I used wear = as.numeric(as.character(wear)) to convert the column to numeric, but it would be great if you can create the numeric column in the first place.


问:
Two Index's on the same row
I have a rails application that exports content from my database in an xls format.

I'm looking to create two separate tables without putting them in the same row. Is there anyway to have two index's on the same row?

```<code><?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:o="urn:schemas-microsoft-com:office:office"
  xmlns:x="urn:schemas-microsoft-com:office:excel"
  xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:html="http://www.w3.org/TR/REC-html40">
<ss:Worksheet ss:Name="Sheet">
    <Table>
    <% @data.each do |data| %>
        <Row ss:Index="1">
            <Cell ss:Index="1"><Data ss:Type="String"><%= data.name %></Data></Cell>
        </Row>
    <% end %>
    <% @moreData.each do |moreData| %>
        <Row ss:Index="1">
            <Cell ss:Index="2"><Data ss:Type="String"><%= moreData.name %></Data></Cell>
        </Row>
    <% end %>
    </Table>
</ss:Worksheet>
</Workbook>
</code>```

This is what I have with the above code:

And this is what I'm trying to achieve if possible without putting both loops in the same row:

答:
Maybe use .zip on the data?

ex.

```<code><Row ss:Index="1">
    <% @data.zip(@moreData).each do |d, md| %>
        <Cell ss:Index="1"><Data ss:Type="String"><%= d.name %></Data></Cell>
        <Cell ss:Index="2"><Data ss:Type="String"><%= md.name %></Data></Cell>
    <% end %>
</Row>
</code>```

Title: Two Index's on the same row

Body:
I have a rails application that exports content from my database in an xls format.

I'm looking to create two separate tables without putting them in the same row. Is there anyway to have two index's on the same row?

<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:o="urn:schemas-microsoft-com:office:office"
  xmlns:x="urn:schemas-microsoft-com:office:excel"
  xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:html="http://www.w3.org/TR/REC-html40">
<ss:Worksheet ss:Name="Sheet">

    <% @data.each do |data| %>
        <Row ss:Index="1">
            <Cell ss:Index="1"><Data ss:Type="String"><%= data.name %></Data></Cell>
        </Row>
    <% end %>
    <% @moreData.each do |moreData| %>
        <Row ss:Index="1">
            <Cell ss:Index="2"><Data ss:Type="String"><%= moreData.name %></Data></Cell>
        </Row>
    <% end %>

</ss:Worksheet>
</Workbook>

This is what I have with the above code:

And this is what I'm trying to achieve if possible without putting both loops in the same row:

Body:
Maybe use .zip on the data?

ex.

<Row ss:Index="1">
    <% @data.zip(@moreData).each do |d, md| %>
        <Cell ss:Index="1"><Data ss:Type="String"><%= d.name %></Data></Cell>
        <Cell ss:Index="2"><Data ss:Type="String"><%= md.name %></Data></Cell>
    <% end %>
</Row>


问:
Copy array via memcpy
I saw there are a lot of articles about memcpy but I can't find the solution for my problem. Can somebody see why the copy action doesn't work?</p>

```<code>float MeanFilter(const volatile float *Array, volatile float Dist){
float Avg = 0.0;    // Variable used to calculate the average distance value
float Sorted[MaxDistArray]; // Array used to contain the sorted array

printf("\n");
int j;

for(j = 0; j < 20; j++){
    if(j == 10) printf("\n \t");
    printf("%d: %f, ", j+1, Array[j]);
}

memcpy(Sorted, &Array[0], sizeof(float));
Sort(Sorted);   // Sort the array of distances values

printf("\n");

for(j = 0; j < 20; j++){
    if(j == 10) printf("\n \t");
    printf("%d: %f, ", j+1, Sorted[j]);
}
</code>```

答:
Idd @Ronald that was part of the solution

```<code>memcpy(Sorted, Array, sizeof(float)*MaxDistArray);
</code>```

thx!

Title: Copy array via memcpy

Body:
I saw there are a lot of articles about memcpy but I can't find the solution for my problem. Can somebody see why the copy action doesn't work?

float MeanFilter(const volatile float *Array, volatile float Dist){
float Avg = 0.0;    // Variable used to calculate the average distance value
float Sorted[MaxDistArray]; // Array used to contain the sorted array

printf("\n");
int j;

for(j = 0; j < 20; j++){
    if(j == 10) printf("\n \t");
    printf("%d: %f, ", j+1, Array[j]);
}

memcpy(Sorted, &Array[0], sizeof(float));
Sort(Sorted);   // Sort the array of distances values

printf("\n");

for(j = 0; j < 20; j++){
    if(j == 10) printf("\n \t");
    printf("%d: %f, ", j+1, Sorted[j]);
}

Body:
Idd @Ronald that was part of the solution

memcpy(Sorted, Array, sizeof(float)*MaxDistArray);

thx!


问:
if element class = element class or data-attr do something
Hi have two different megamenus, which cannot be displayed by css based on the html markup. Therefore I want to use Javascript/jQuery.

```<code>HTML of links:
<li id="menu-item-154" class="tg-submenu__link .tg-submenu__tg menu-item menu-item-type-post_type menu-item-object-page menu-item-154">
<a href="#">MEGAMENU-LINK1</a></li>

<li id="menu-item-155" class="tg-submenu__link .tg-submenu__abteilungen menu-item menu-item-type-post_type menu-item-object-page menu-item-155">
<a href="#">MEGA MENU LINK2</a></li>

HTML of the mega menu containers
<div class="tg-submenu tg-submenu__tg" data-trigger="tg-submenu__tg">
</div>

<div class="tg-submenu tg-submenu__abteilungen" data-trigger="tg-submenu__abteilungen">
</div>
</code>```

So I'd like to run a function, which checks if the links has the same classes (.tg-submenu__tg and .tg-submenu__abteilungen) or the same data-trigger attribute and if so add a class to the particular mega menu container by hovering the corresponding link. I could easily write two separate functions which test this isolated but I need an universal function, cause the links may change or more links may be added in the future.

答:
problem is in your class ".tg-submenu__abteilungen" here "." not
acceptable

You can use .hasClass('classname')

Code

```<code>$(document).on('li','click',function(){
    if($(this).hasClass('tg-submenu__abteilungen')){
    // console.log('Link has tg-submenu__abteilungen CLASS');
    } else {
    //console.log('Link hasn't tg-submenu__abteilungen CLASS');
    }
});
</code>```

Body:
Hi have two different megamenus, which cannot be displayed by css based on the html markup. Therefore I want to use Javascript/jQuery.

HTML of links:

MEGAMENU-LINK1

MEGA MENU LINK2

HTML of the mega menu containers

So I'd like to run a function, which checks if the links has the same classes (.tg-submenu__tg and .tg-submenu__abteilungen) or the same data-trigger attribute and if so add a class to the particular mega menu container by hovering the corresponding link. I could easily write two separate functions which test this isolated but I need an universal function, cause the links may change or more links may be added in the future.

Body:
problem is in your class ".tg-submenu__abteilungen" here "." not
acceptable

You can use .hasClass('classname')

Code

$(document).on('li','click',function(){
    if($(this).hasClass('tg-submenu__abteilungen')){
    // console.log('Link has tg-submenu__abteilungen CLASS');
    } else {
    //console.log('Link hasn't tg-submenu__abteilungen CLASS');
    }
});


问:
Tensorflow MNIST using csv: low accuracy
I am trying to implement MNIST image classification in Tensorflow using CSV input. The accuracy is very low at around 10 percent. I am using 3 fully connected layers with softmax entropy at the output. I converted the mnist datasets from here into csv to use as input using the below code:

```<code>import idx2numpy
import numpy as np
# Reading
filename = 'train-images'
flext1 = '.idx3-ubyte'
flext2 = '.csv'
ndarr = idx2numpy.convert_from_file(filename+flext1).reshape(60000, 784)
np.savetxt(filename,ndarr,delimiter=',')
</code>```

Then I one-hot encoded the labels as below:

```<code>import tensorflow as tf
import numpy as np
import pandas as pd

trainimages=pd.read_csv("train-images.csv",header=None,delimiter=',').values
trainlabels=pd.read_csv("train-labels.csv",header=None,delimiter=',').values

testimages=pd.read_csv("t10k-images.csv",header=None,delimiter=',').values
testlabels=pd.read_csv("t10k-labels.csv",header=None,delimiter=',').values

label_ph=tf.placeholder(tf.int64,shape=(None,1))
reshapeval=tf.Variable(100)
onehotencoding=tf.one_hot(label_ph,depth=10)
datalabels=tf.reshape(onehotencoding,shape=(reshapeval,10))

with tf.Session() as sess:
  onehottrainlabels=sess.run(datalabels,feed_dict={label_ph:trainlabels,reshapeval:trainlabels.shape[0]})
  onehottestlabels=sess.run(datalabels,feed_dict={label_ph:testlabels,reshapeval:testlabels.shape[0]})
  print("datalabels:",onehottrainlabels)
  print("datalabels:",onehottestlabels)
  #sess.run(datalabels)

np.savetxt("mnist_train_labels_onehot.csv",onehottrainlabels,delimiter=',')
np.savetxt("mnist_test_labels_onehot.csv",onehottestlabels,delimiter=',')
</code>```

I tried to use the csv files generated as shown above to try and train a image classification model as shown below:

```<code>import tensorflow as tf
import pandas as pd
import numpy as np

trainimages=pd.read_csv("train-images.csv",header=None,delimiter=',').values
trainlabels=pd.read_csv("mnist_train_labels_onehot.csv",header=None,delimiter=',').values
testimages=pd.read_csv("t10k-images.csv",header=None,delimiter=',').values
testlabels=pd.read_csv("mnist_test_labels_onehot.csv",header=None,delimiter=',').values
#%%
train_num=len(trainimages)
n_epochs=400
BATCH_SIZE = 50
N_FEATURES = 785
n_inputs =28*28
n_hidden1=300
n_hidden2=100
n_outputs = 10
learning_rate=0.01
X=tf.placeholder(tf.float32,shape=(None,n_inputs),name='X')
y=tf.placeholder(tf.int64,shape=(None,10),name='y')
print("stage1")

with tf.name_scope("dnn"):
    hidden1=tf.contrib.layers.fully_connected(X,n_hidden1,scope="hidden1")
    hidden2=tf.contrib.layers.fully_connected(hidden1,n_hidden2,scope="hidden2")
    logits=tf.contrib.layers.fully_connected(hidden2,n_outputs,scope="outputs",activation_fn=None)
with tf.name_scope("loss"):
    xentropy =tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=logits)
    loss =tf.reduce_mean(xentropy,name="loss")
    loss_summary=tf.summary.scalar("log_loss",loss)
with tf.name_scope("train"):
    optimizer=tf.train.GradientDescentOptimizer(learning_rate)
    training_op=optimizer.minimize(loss)
with tf.name_scope("eval"):
    correct=tf.equal(tf.argmax(y, 1), tf.argmax(logits, 1))#tf.nn.in_top_k(logits,y,1)
    accuracy=tf.reduce_mean(tf.cast(correct,tf.float32))

init =tf.global_variables_initializer()
saver =tf.train.Saver()
print("stage 2")

with tf.Session() as sess:
  sess.run(init)
  print("stage 3")
  for epoch in range(n_epochs):
    #print("stage 4")
    for iteration in range(train_num//BATCH_SIZE):
      #print("stage 5")
      ind = np.random.choice(trainimages.shape[0],BATCH_SIZE)
      x_train_batch = trainimages[ind]
      y_train_batch = trainlabels[ind]
      sess.run(training_op,feed_dict={X:x_train_batch,y:y_train_batch})
      #print("stage 6")
    if epoch%20==0:
      #print(x_train_batch, y_train_batch)
      acc_train=sess.run(accuracy,feed_dict={X:x_train_batch,y:y_train_batch})
      acc_test=sess.run(accuracy,feed_dict={X:testimages,y:testlabels})

      print(epoch, "Train accuracy:", acc_train,"Test accuracy:",acc_test)
</code>```

The output accuracy never increases about 0.15. I would really appreciate it if someone could advice me on what I am doing wrong here.

For reference, the above graph construction is based on the example given in the Hands-on Machine Learning with Tensorflow book. Below is the original code which produces an accuracy of 98 percent. Of course I have modified the code a little bit to be able to accept csv input.

```<code>import tensorflow as tf
import numpy as np
import pandas as pd
import random
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/")

#%%
tf.reset_default_graph()
print("I reset graph")
n_inputs =28*28
n_hidden1=300
n_hidden2=100
n_outputs = 10
learning_rate=0.01
X=tf.placeholder(tf.float32,shape=(None,n_inputs),name='X')
y=tf.placeholder(tf.int64,shape=(None),name='y')

with tf.name_scope("dnn"):
    hidden1=tf.layers.dense(X,n_hidden1,name="hidden1",activation=tf.nn.relu)
    hidden2=tf.layers.dense(hidden1,n_hidden2,name="hidden2",activation=tf.nn.relu)
    logits=tf.layers.dense(hidden2,n_outputs,name="outputs")
with tf.name_scope("loss"):
    xentropy =tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y,logits=logits)
    loss =tf.reduce_mean(xentropy,name="loss")
    #loss_summary=tf.summary.scalar("log_loss",loss)
with tf.name_scope("train"):
    optimizer=tf.train.GradientDescentOptimizer(learning_rate)
    training_op=optimizer.minimize(loss)
with tf.name_scope("eval"):
    correct=tf.nn.in_top_k(logits,y,1)
    accuracy=tf.reduce_mean(tf.cast(correct,tf.float32))

init =tf.global_variables_initializer()
saver =tf.train.Saver()

#==============================================================================
# from tensorflow.examples.tutorials.mnist import input_data
# mnist=input_data.read_data_sets("/tmp/data/")
#==============================================================================

n_epochs=400
batch_size=100
print("graph construction over i start train and test")
with tf.Session() as sess:
    sess.run(init)
    for epoch in range(n_epochs):
        for iteration in range(mnist.train.num_examples//batch_size):
            X_batch, y_batch = mnist.train.next_batch(batch_size)

            #print(X_batch, y_batch)
            sess.run(training_op,feed_dict={X:X_batch,y:y_batch})
        print("iteration over")
        if epoch%5==0:
          acc_train=sess.run(accuracy,feed_dict={X:X_batch,y:y_batch})
          acc_test=sess.run(accuracy,feed_dict={X: mnist.validation.images, y: mnist.validation.labels})
          print(epoch, "Train accuracy:", acc_train,"Test accuracy:",acc_test)
    save_path=saver.save(sess,"./my_model_final.ckpt")
</code>```

Additional information:
I printed out the neural network output logits for a few of the iterations after reducing the batch size. The outputs seem to saturate after 10 or so iterations. I tried changing the optimizer to AdamOptimizer but still the accuracy won't improve. Below shows a sample of the logits outputs.

```<code>iteration  7
Y_train: [[0 1 0 0 0 0 0 0 0 0]
 [0 1 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 1 0]]
 Logits: [[  2.26569266e+17   3.05248736e+22  -2.50115512e+23  -4.39891557e+14
    1.11553920e+23   3.07485097e+14   2.20944474e+17   4.47584162e+13
    1.08036284e+23   4.83180834e+14]
 [  3.86803140e+17   8.75195504e+22  -7.17081147e+23  -2.68349530e+15
    3.19824929e+23   8.67874780e+14   3.76970654e+17   4.52455091e+13
    3.09735965e+23   3.87887019e+14]
 [  2.38161056e+17   3.84007123e+22  -3.14640962e+23  -6.05196997e+14
    1.40332858e+23   3.16957379e+14   2.32241818e+17   4.01556080e+13
    1.35906927e+23   4.00997575e+14]]
Softmax_out: [  8.10290437e+22   2.32305379e+23   4.42593055e+21]
Accuracy: [False False False]

 iteration  8
Y_train: [[1 0 0 0 0 0 0 0 0 0]
 [0 1 0 0 0 0 0 0 0 0]
 [0 0 0 1 0 0 0 0 0 0]]
 Logits: [[             inf              inf   1.66566635e+35              inf
              -inf   1.03125672e+30   1.62685693e+35   6.78127837e+30
   -4.95936289e+35   4.14895906e+30]
 [  1.38760797e+38   1.10565560e+38   3.23025301e+34   2.54545823e+38
              -inf   1.99993203e+29   3.15498898e+34   1.31510396e+30
   -9.61777107e+34   8.04613877e+29]
 [             inf              inf   2.54806070e+35              inf
              -inf   1.57756931e+30   2.48869187e+35   1.03736909e+31
   -7.58660917e+35   6.34688775e+30]]
Softmax_out: [ nan  nan  nan]
Accuracy: [ True False False]

 iteration  9
Y_train: [[0 0 0 0 0 1 0 0 0 0]
 [0 1 0 0 0 0 0 0 0 0]
 [0 0 1 0 0 0 0 0 0 0]]
 Logits: [[ nan  nan  nan  nan  nan  nan  nan  nan  nan  nan]
 [ nan  nan  nan  nan  nan  nan  nan  nan  nan  nan]
 [ nan  nan  nan  nan  nan  nan  nan  nan  nan  nan]]
Softmax_out: [ nan  nan  nan]
Accuracy: [False False False]
</code>```

答:
I think you should build layer like follow.

Convo with 28 input + relu + dropout(0.2)

Convo with 32 input features + relu + dropout(0.2)

Convo with 32 input features + relu + dropout(0.2)

flatten()

Dense or Fully Connected layer with 512 dendries + dropout(0.5)

Dense or Fully Connected with 128 output dendries with softmax function

I had achieved 99.7% accuracy using my own but mnist type dataset.

Check this out : Text Classification using Keras

Note : I had 36 classes. 10 digits and 26 alphabets

Body:
I am trying to implement MNIST image classification in Tensorflow using CSV input. The accuracy is very low at around 10 percent. I am using 3 fully connected layers with softmax entropy at the output. I converted the mnist datasets from here into csv to use as input using the below code:

import idx2numpy
import numpy as np
# Reading
filename = 'train-images'
flext1 = '.idx3-ubyte'
flext2 = '.csv'
ndarr = idx2numpy.convert_from_file(filename+flext1).reshape(60000, 784)
np.savetxt(filename,ndarr,delimiter=',')

Then I one-hot encoded the labels as below:

import tensorflow as tf
import numpy as np
import pandas as pd

trainimages=pd.read_csv("train-images.csv",header=None,delimiter=',').values
trainlabels=pd.read_csv("train-labels.csv",header=None,delimiter=',').values

testimages=pd.read_csv("t10k-images.csv",header=None,delimiter=',').values
testlabels=pd.read_csv("t10k-labels.csv",header=None,delimiter=',').values

label_ph=tf.placeholder(tf.int64,shape=(None,1))
reshapeval=tf.Variable(100)
onehotencoding=tf.one_hot(label_ph,depth=10)
datalabels=tf.reshape(onehotencoding,shape=(reshapeval,10))

with tf.Session() as sess:
  onehottrainlabels=sess.run(datalabels,feed_dict={label_ph:trainlabels,reshapeval:trainlabels.shape[0]})
  onehottestlabels=sess.run(datalabels,feed_dict={label_ph:testlabels,reshapeval:testlabels.shape[0]})
  print("datalabels:",onehottrainlabels)
  print("datalabels:",onehottestlabels)
  #sess.run(datalabels)

np.savetxt("mnist_train_labels_onehot.csv",onehottrainlabels,delimiter=',')
np.savetxt("mnist_test_labels_onehot.csv",onehottestlabels,delimiter=',')

I tried to use the csv files generated as shown above to try and train a image classification model as shown below:

import tensorflow as tf
import pandas as pd
import numpy as np

trainimages=pd.read_csv("train-images.csv",header=None,delimiter=',').values
trainlabels=pd.read_csv("mnist_train_labels_onehot.csv",header=None,delimiter=',').values
testimages=pd.read_csv("t10k-images.csv",header=None,delimiter=',').values
testlabels=pd.read_csv("mnist_test_labels_onehot.csv",header=None,delimiter=',').values
#%%
train_num=len(trainimages)
n_epochs=400
BATCH_SIZE = 50
N_FEATURES = 785
n_inputs =28*28
n_hidden1=300
n_hidden2=100
n_outputs = 10
learning_rate=0.01
X=tf.placeholder(tf.float32,shape=(None,n_inputs),name='X')
y=tf.placeholder(tf.int64,shape=(None,10),name='y')
print("stage1")

with tf.name_scope("dnn"):
    hidden1=tf.contrib.layers.fully_connected(X,n_hidden1,scope="hidden1")
    hidden2=tf.contrib.layers.fully_connected(hidden1,n_hidden2,scope="hidden2")
    logits=tf.contrib.layers.fully_connected(hidden2,n_outputs,scope="outputs",activation_fn=None)
with tf.name_scope("loss"):
    xentropy =tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=logits)
    loss =tf.reduce_mean(xentropy,name="loss")
    loss_summary=tf.summary.scalar("log_loss",loss)
with tf.name_scope("train"):
    optimizer=tf.train.GradientDescentOptimizer(learning_rate)
    training_op=optimizer.minimize(loss)
with tf.name_scope("eval"):
    correct=tf.equal(tf.argmax(y, 1), tf.argmax(logits, 1))#tf.nn.in_top_k(logits,y,1)
    accuracy=tf.reduce_mean(tf.cast(correct,tf.float32))

init =tf.global_variables_initializer()
saver =tf.train.Saver()
print("stage 2")

with tf.Session() as sess:
  sess.run(init)
  print("stage 3")
  for epoch in range(n_epochs):
    #print("stage 4")
    for iteration in range(train_num//BATCH_SIZE):
      #print("stage 5")
      ind = np.random.choice(trainimages.shape[0],BATCH_SIZE)
      x_train_batch = trainimages[ind]
      y_train_batch = trainlabels[ind]
      sess.run(training_op,feed_dict={X:x_train_batch,y:y_train_batch})
      #print("stage 6")
    if epoch%20==0:
      #print(x_train_batch, y_train_batch)
      acc_train=sess.run(accuracy,feed_dict={X:x_train_batch,y:y_train_batch})
      acc_test=sess.run(accuracy,feed_dict={X:testimages,y:testlabels})

      print(epoch, "Train accuracy:", acc_train,"Test accuracy:",acc_test)

The output accuracy never increases about 0.15. I would really appreciate it if someone could advice me on what I am doing wrong here.

For reference, the above graph construction is based on the example given in the Hands-on Machine Learning with Tensorflow book. Below is the original code which produces an accuracy of 98 percent. Of course I have modified the code a little bit to be able to accept csv input.

import tensorflow as tf
import numpy as np
import pandas as pd
import random
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/")

#%%
tf.reset_default_graph()
print("I reset graph")
n_inputs =28*28
n_hidden1=300
n_hidden2=100
n_outputs = 10
learning_rate=0.01
X=tf.placeholder(tf.float32,shape=(None,n_inputs),name='X')
y=tf.placeholder(tf.int64,shape=(None),name='y')

with tf.name_scope("dnn"):
    hidden1=tf.layers.dense(X,n_hidden1,name="hidden1",activation=tf.nn.relu)
    hidden2=tf.layers.dense(hidden1,n_hidden2,name="hidden2",activation=tf.nn.relu)
    logits=tf.layers.dense(hidden2,n_outputs,name="outputs")
with tf.name_scope("loss"):
    xentropy =tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y,logits=logits)
    loss =tf.reduce_mean(xentropy,name="loss")
    #loss_summary=tf.summary.scalar("log_loss",loss)
with tf.name_scope("train"):
    optimizer=tf.train.GradientDescentOptimizer(learning_rate)
    training_op=optimizer.minimize(loss)
with tf.name_scope("eval"):
    correct=tf.nn.in_top_k(logits,y,1)
    accuracy=tf.reduce_mean(tf.cast(correct,tf.float32))

init =tf.global_variables_initializer()
saver =tf.train.Saver()

#==============================================================================
# from tensorflow.examples.tutorials.mnist import input_data
# mnist=input_data.read_data_sets("/tmp/data/")
#==============================================================================

n_epochs=400
batch_size=100
print("graph construction over i start train and test")
with tf.Session() as sess:
    sess.run(init)
    for epoch in range(n_epochs):
        for iteration in range(mnist.train.num_examples//batch_size):
            X_batch, y_batch = mnist.train.next_batch(batch_size)

            #print(X_batch, y_batch)
            sess.run(training_op,feed_dict={X:X_batch,y:y_batch})
        print("iteration over")
        if epoch%5==0:
          acc_train=sess.run(accuracy,feed_dict={X:X_batch,y:y_batch})
          acc_test=sess.run(accuracy,feed_dict={X: mnist.validation.images, y: mnist.validation.labels})
          print(epoch, "Train accuracy:", acc_train,"Test accuracy:",acc_test)
    save_path=saver.save(sess,"./my_model_final.ckpt")

Additional information:
I printed out the neural network output logits for a few of the iterations after reducing the batch size. The outputs seem to saturate after 10 or so iterations. I tried changing the optimizer to AdamOptimizer but still the accuracy won't improve. Below shows a sample of the logits outputs.

iteration  7
Y_train: [[0 1 0 0 0 0 0 0 0 0]
 [0 1 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 1 0]]
 Logits: [[  2.26569266e+17   3.05248736e+22  -2.50115512e+23  -4.39891557e+14
    1.11553920e+23   3.07485097e+14   2.20944474e+17   4.47584162e+13
    1.08036284e+23   4.83180834e+14]
 [  3.86803140e+17   8.75195504e+22  -7.17081147e+23  -2.68349530e+15
    3.19824929e+23   8.67874780e+14   3.76970654e+17   4.52455091e+13
    3.09735965e+23   3.87887019e+14]
 [  2.38161056e+17   3.84007123e+22  -3.14640962e+23  -6.05196997e+14
    1.40332858e+23   3.16957379e+14   2.32241818e+17   4.01556080e+13
    1.35906927e+23   4.00997575e+14]]
Softmax_out: [  8.10290437e+22   2.32305379e+23   4.42593055e+21]
Accuracy: [False False False]

 iteration  8
Y_train: [[1 0 0 0 0 0 0 0 0 0]
 [0 1 0 0 0 0 0 0 0 0]
 [0 0 0 1 0 0 0 0 0 0]]
 Logits: [[             inf              inf   1.66566635e+35              inf
              -inf   1.03125672e+30   1.62685693e+35   6.78127837e+30
   -4.95936289e+35   4.14895906e+30]
 [  1.38760797e+38   1.10565560e+38   3.23025301e+34   2.54545823e+38
              -inf   1.99993203e+29   3.15498898e+34   1.31510396e+30
   -9.61777107e+34   8.04613877e+29]
 [             inf              inf   2.54806070e+35              inf
              -inf   1.57756931e+30   2.48869187e+35   1.03736909e+31
   -7.58660917e+35   6.34688775e+30]]
Softmax_out: [ nan  nan  nan]
Accuracy: [ True False False]

 iteration  9
Y_train: [[0 0 0 0 0 1 0 0 0 0]
 [0 1 0 0 0 0 0 0 0 0]
 [0 0 1 0 0 0 0 0 0 0]]
 Logits: [[ nan  nan  nan  nan  nan  nan  nan  nan  nan  nan]
 [ nan  nan  nan  nan  nan  nan  nan  nan  nan  nan]
 [ nan  nan  nan  nan  nan  nan  nan  nan  nan  nan]]
Softmax_out: [ nan  nan  nan]
Accuracy: [False False False]


问:
Retreive row name from quantmod XTS file
I'm using the quantmod::getsymbols function to retreive the stock index data for yahoo finance (as showed in the picture, it's called GDAXI.xts)

Now I want to access the date to the left, but this column isn't in the GDAXI file. How can I access the date? I tried different ways and couldn't figure it out, last time it worked when I tried d1.ts=GDAX[,0], but that's not working here.

Can anybody tell me why? Thank you very much in advance.

```<code>Datum=as.Date(GDAXI[,0])
Error in as.Date.default(GDAXI[, 0]) :
  do not know how to convert 'GDAXI[, 0]' to class “Date”
Datum=GDAXI[,0]
View(Datum)
Warning in View :
  'row.names' is not a character vector of length 0 -- omitting it. Will be an error!
Warning in View :
  'row.names' is not a character vector of length 0 -- omitting it. Will be an error!
Warning message:
In as.data.frame.numeric(coredata(x), row.names, optional, ...) :
  'row.names' is not a character vector of length 0 -- omitting it. Will be an error!
Datum=as.date(GDAXI[,0])
Error: could not find function "as.date"
In addition: Warning messages:
1: In as.data.frame.numeric(coredata(x), row.names, optional, ...) :
  'row.names' is not a character vector of length 0 -- omitting it. Will be an error!
2: In as.data.frame.numeric(coredata(x), row.names, optional, ...) :
  'row.names' is not a character vector of length 0 -- omitting it. Will be an error!
3: In as.data.frame.numeric(coredata(x), row.names, optional, ...) :
  'row.names' is not a character vector of length 0 -- omitting it. Will be an error!
Da.ts=GDAXI[,0]
</code>```

答:
I'm not familiar with R or quantmod but it looks to me like what you want to do is get the name of the row, not any column data, which is probably why your code is failing, hence it saying that it can't parse GDAXI[,0] as a Date object.

If you want to get a name of a row in quantmod, you need to use the index function, eg:

```<code># Return all dates
index(GSPC)
</code>```

You may also want to take a look at this related question.

Body:
I'm using the quantmod::getsymbols function to retreive the stock index data for yahoo finance (as showed in the picture, it's called GDAXI.xts)

Now I want to access the date to the left, but this column isn't in the GDAXI file. How can I access the date? I tried different ways and couldn't figure it out, last time it worked when I tried d1.ts=GDAX[,0], but that's not working here.

Can anybody tell me why? Thank you very much in advance.

Datum=as.Date(GDAXI[,0])
Error in as.Date.default(GDAXI[, 0]) :
  do not know how to convert 'GDAXI[, 0]' to class “Date”
Datum=GDAXI[,0]
View(Datum)
Warning in View :
  'row.names' is not a character vector of length 0 -- omitting it. Will be an error!
Warning in View :
  'row.names' is not a character vector of length 0 -- omitting it. Will be an error!
Warning message:
In as.data.frame.numeric(coredata(x), row.names, optional, ...) :
  'row.names' is not a character vector of length 0 -- omitting it. Will be an error!
Datum=as.date(GDAXI[,0])
Error: could not find function "as.date"
In addition: Warning messages:
1: In as.data.frame.numeric(coredata(x), row.names, optional, ...) :
  'row.names' is not a character vector of length 0 -- omitting it. Will be an error!
2: In as.data.frame.numeric(coredata(x), row.names, optional, ...) :
  'row.names' is not a character vector of length 0 -- omitting it. Will be an error!
3: In as.data.frame.numeric(coredata(x), row.names, optional, ...) :
  'row.names' is not a character vector of length 0 -- omitting it. Will be an error!
Da.ts=GDAXI[,0]

Body:
I'm not familiar with R or quantmod but it looks to me like what you want to do is get the name of the row, not any column data, which is probably why your code is failing, hence it saying that it can't parse GDAXI[,0] as a Date object.

If you want to get a name of a row in quantmod, you need to use the index function, eg:

# Return all dates
index(GSPC)

You may also want to take a look at this related question.


问:
Creating a page for every product in a website
I'm designing a website for shopping.

When I click a product from the products page, I want to get a page only containing information about that one product but do I have to create a new page separately for every product on the products page?

I only know some javascript and jquery. I don't know PHP.

答: Yes you have to create separate page or each products if it is static. If you want to use php then you can put all the products in mysql table and fetch from the database and get the product by id. Since you dont know PHP you can also do in javascript like storing the products in json format and get them via id using single page for example product detail. I hope I answered your question. </p>


问:
In PHP, why are my session variables persisted as references?
Here's the code. It's a simple operation to check that a session ID isn't being spoofed by verifying the IP address:

```<code>session_start();
$session_ip_address = $_SERVER['REMOTE_ADDR'];
if((!isset($_SESSION['SESSION_IP_ADDRESS'])) || !$_SESSION['SESSION_IP_ADDRESS']) {
    $_SESSION['SESSION_IP_ADDRESS'] = $session_ip_address;
}

if($_SESSION['SESSION_IP_ADDRESS'] != $_SERVER['REMOTE_ADDR']) {
    session_destroy();
    $_SESSION['security_error'] = true;
}
</code>```

If I insert var_dump($_SESSION) right after session_start() and again at the end of the script, then the very first time I run the code (without a session cookie set) I see that at first the array is empty, then it has my IP address assigned to the key 'SESSION_IP_ADDRESS'. So far, so good. But when I run the code again, now it shows that 'SESSION_IP_ADDRESS' is stored as a reference immediately after the session starts (I can tell by the ampersand prepended to the string). When I run it a third time, I see that 'SESSION_IP_ADDRESS' is now a null reference ('SESSION_IP_ADDRESS' => &null) immediately after the session starts. What is going on?!

To reiterate, this is the output the first time:

```<code>array(0) {
}
array(1) {
  ["SESSION_IP_ADDRESS"]=>
  string(11) "xx.xx.xxx.x"
}
</code>```

This is the output the second time:

```<code>array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &string(11) "xx.xx.xxx.x"
}
array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &string(11) "xx.xx.xxx.x"
}
</code>```

And the third time and every time from then on:

```<code>array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &NULL
}
array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &string(11) "xx.xx.xxx.x"
}
</code>```

答: it does assign by value, the reference & next to $_SESSION has nothing to do with your expression $_SESSION['x'] = $x;

ContentLicense: CC BY-SA 2.5

Body:
Here's the code. It's a simple operation to check that a session ID isn't being spoofed by verifying the IP address:

session_start();
$session_ip_address = $_SERVER['REMOTE_ADDR'];
if((!isset($_SESSION['SESSION_IP_ADDRESS'])) || !$_SESSION['SESSION_IP_ADDRESS']) {
    $_SESSION['SESSION_IP_ADDRESS'] = $session_ip_address;
}

if($_SESSION['SESSION_IP_ADDRESS'] != $_SERVER['REMOTE_ADDR']) {
    session_destroy();
    $_SESSION['security_error'] = true;
}

If I insert var_dump($_SESSION) right after session_start() and again at the end of the script, then the very first time I run the code (without a session cookie set) I see that at first the array is empty, then it has my IP address assigned to the key 'SESSION_IP_ADDRESS'. So far, so good. But when I run the code again, now it shows that 'SESSION_IP_ADDRESS' is stored as a reference immediately after the session starts (I can tell by the ampersand prepended to the string). When I run it a third time, I see that 'SESSION_IP_ADDRESS' is now a null reference ('SESSION_IP_ADDRESS' => &null) immediately after the session starts. What is going on?!

To reiterate, this is the output the first time:

array(0) {
}
array(1) {
  ["SESSION_IP_ADDRESS"]=>
  string(11) "xx.xx.xxx.x"
}

This is the output the second time:

array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &string(11) "xx.xx.xxx.x"
}
array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &string(11) "xx.xx.xxx.x"
}

And the third time and every time from then on:

array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &NULL
}
array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &string(11) "xx.xx.xxx.x"
}


问:
CFFI: TypeError: initializer for ctype 'char[]' must be a bytes or list or tuple, not str
Using the CFFI library for Python, I'm trying to coax a Python string into a char*, so that I can pass it to a C function that accepts char*.  I can't seem to figure out what the right incantation is.

Consider this example:

```<code>>>> from cffi import FFI
>>> ffi = FFI()
>>> ffi.new("char[]", "bob")
</code>```

The result is:

```<code>TypeError: initializer for ctype 'char[]' must be a bytes or list or tuple, not str
</code>```

The following does not work either:

```<code>>>> ffi.new("char*", "bob")
</code>```

It says:

```<code>TypeError: initializer for ctype 'char' must be a bytes of length 1, not str
</code>```

答:
o11c solved this already:

Pick explicitly an encoding, e.g. "bob".encode('ascii'). This seems to be just necessary in Python 3.

Body:
Using the CFFI library for Python, I'm trying to coax a Python string into a char*, so that I can pass it to a C function that accepts char*.  I can't seem to figure out what the right incantation is.

Consider this example:

>>> from cffi import FFI
>>> ffi = FFI()
>>> ffi.new("char[]", "bob")

The result is:

TypeError: initializer for ctype 'char[]' must be a bytes or list or tuple, not str

The following does not work either:

>>> ffi.new("char*", "bob")

It says:

TypeError: initializer for ctype 'char' must be a bytes of length 1, not str


问:
How to stop user moving to next step until finish the current step using Angular Material Stepper(Angular 4)
I am using Angular Material to build my steppers and I want user to move step by step which means user has to finish the current step so that can move to the next step, however during searching the Angular Material Docs and CDK Docs I only found one related field property called 'editable' but that is used for stopping user return to previous steps, what property should I set to make stop user view the later steps and move one by one?

Thanks

答: add [linear]="isLinear" to stepper like this <mat-horizontal-stepper [linear]="true">


问:
Angular2 using threejs Orbitcontrols
I'm trying to use threejs exemple inside my angular (cli) 2 app.

So i have installed threejs :

```<code>npm install three --save
</code>```

then added typings :

```<code>npm install @types/three --save-dev
</code>```

Finally my component looks like this :

```<code>import { Component, OnInit } from '@angular/core';
import * as THREE from 'three';

@Component({
    selector: 'app-testthreejs',
    templateUrl: './testthreejs.component.html',
    styleUrls: ['./testthreejs.component.css']
})
export class TestthreejsComponent implements OnInit {
//
}
</code>```

With this i can use some functionality from THREE without any problem.

I would like to use some of the exemple available in node_modules/three/examples/js/ and more precisely OrbitControl. The typings give me the autocompletion in visual studio code :

But as soon as i tried to use it i have the following error :

TypeError: WEBPACK_IMPORTED_MODULE_1_three.OrbitControls is not a
  constructor

Is there any way to make available OrbitControls (and other exemples) via some import ?
Should i simply include control.js in my html ?

What's the best way to deal with this ?

答:
See working example of using Angular + Three.js including OrbitControls and ColladaLoader: https://github.com/makimenko/angular-three-examples

Currently, Three.js examples are not included into a module and use them in Angular typescript code could be a little bit tricky. Especially, if you don't want to install additional third-party dependencies. One of solution/workaround could be:

Firstly, include dependencies:

```<code>three
@types/three
</code>```

Secondly, import in component:

```<code>import * as THREE from 'three';
import "./js/EnableThreeExamples";
import "three/examples/js/controls/OrbitControls";
import "three/examples/js/loaders/ColladaLoader";
</code>```

Then use it in code:

```<code>this.controls = new THREE.OrbitControls(this.camera);
this.controls.rotateSpeed = 1.0;
this.controls.zoomSpeed = 1.2;
this.controls.addEventListener('change', this.render);
</code>```

Hope this could help you to start

Title: Angular2 using threejs Orbitcontrols

Body:
I'm trying to use threejs exemple inside my angular (cli) 2 app.

So i have installed threejs :

npm install three --save

then added typings :

npm install @types/three --save-dev

Finally my component looks like this :

import { Component, OnInit } from '@angular/core';
import * as THREE from 'three';

@Component({
    selector: 'app-testthreejs',
    templateUrl: './testthreejs.component.html',
    styleUrls: ['./testthreejs.component.css']
})
export class TestthreejsComponent implements OnInit {
//
}

With this i can use some functionality from THREE without any problem.

I would like to use some of the exemple available in node_modules/three/examples/js/ and more precisely OrbitControl. The typings give me the autocompletion in visual studio code :

But as soon as i tried to use it i have the following error :

TypeError: WEBPACK_IMPORTED_MODULE_1_three.OrbitControls is not a
  constructor

Is there any way to make available OrbitControls (and other exemples) via some import ?
Should i simply include control.js in my html ?

What's the best way to deal with this ?

Body:
See working example of using Angular + Three.js including OrbitControls and ColladaLoader: https://github.com/makimenko/angular-three-examples

Currently, Three.js examples are not included into a module and use them in Angular typescript code could be a little bit tricky. Especially, if you don't want to install additional third-party dependencies. One of solution/workaround could be:

Firstly, include dependencies:

three
@types/three

Secondly, import in component:

import * as THREE from 'three';
import "./js/EnableThreeExamples";
import "three/examples/js/controls/OrbitControls";
import "three/examples/js/loaders/ColladaLoader";

Then use it in code:

this.controls = new THREE.OrbitControls(this.camera);
this.controls.rotateSpeed = 1.0;
this.controls.zoomSpeed = 1.2;
this.controls.addEventListener('change', this.render);

Hope this could help you to start


问:
Get specific data from an jQuery $(this) object
I have a node tree and want to fetch certain data attributes from these nodes when clickin on them.

I can't figure out how to get the right data from the object recived when clicking on it.

var simple_chart_config = {
  chart: {
    container: "#tree"
  },
  nodeStructure: {
    text: {
      name: "King Miro",
      title: "King"
    },
    children: [{
      text: {
        name: "King Randor",
        title: "King"
      },
      children: [{
        text: {
          name: "He-Man",
          title: "Master of the Universe"
        },},{
          text: {
            name: "She-Ra",
            title: "Princess"
          },
      }]
    }, {
      text: {
        name: "Skeletor",
        title: "Lord of Destruction"
      },
    }, ]
  }
}

var my_chart = new Treant(simple_chart_config);

$('body').on('click', '.Treant .node', function() {
    alert($(this).attr("title"));
    console.log($(this));
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td { margin:0; padding:0; }
table { border-collapse:collapse; border-spacing:0; }
fieldset,img { border:0; }
address,caption,cite,code,dfn,em,strong,th,var { font-style:normal; font-weight:normal; }
caption,th { text-align:left; }
h1,h2,h3,h4,h5,h6 { font-size:100%; font-weight:normal; }
q:before,q:after { content:''; }
abbr,acronym { border:0; }

body { background: #fff; }
/* optional Container STYLES */
.chart { height: 600px; margin: 5px; width: 900px; }
.Treant > .node { padding: 3px; border: 1px solid #484848; border-radius: 3px; }
.Treant > .node img { width: 100%; height: 100%; }

.Treant .collapse-switch { width: 100%; height: 100%; border: none; }
.Treant .node.collapsed { background-color: #DEF82D; }
.Treant .node.collapsed .collapse-switch { background: none; }</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/treant-js/1.0/Treant.css" rel="stylesheet"/>

```

So now I'm trying to fetch the name: and title:

I tried with many different versions of $(this).attr("") and val(). Trying to fetch via div class and similar.

I'm stuck right now.

答:
You can use your build DOM to take the correct text that you need : $(this).find(".node-name") and $(this).find(".node-title")

var simple_chart_config = {
  chart: {
    container: "#tree"
  },
  nodeStructure: {
    text: {
      name: "King Miro",
      title: "King"
    },
    children: [{
      text: {
        name: "King Randor",
        title: "King"
      },
      children: [{
        text: {
          name: "He-Man",
          title: "Master of the Universe"
        },},{
          text: {
            name: "She-Ra",
            title: "Princess"
          },
      }]
    }, {
      text: {
        name: "Skeletor",
        title: "Lord of Destruction"
      },
    }, ]
  }
}

var my_chart = new Treant(simple_chart_config);

$('body').on('click', '.Treant .node', function() {
    alert($(this).find(".node-name").text());
    alert($(this).find(".node-title").text());
    console.log($(this));
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td { margin:0; padding:0; }
table { border-collapse:collapse; border-spacing:0; }
fieldset,img { border:0; }
address,caption,cite,code,dfn,em,strong,th,var { font-style:normal; font-weight:normal; }
caption,th { text-align:left; }
h1,h2,h3,h4,h5,h6 { font-size:100%; font-weight:normal; }
q:before,q:after { content:''; }
abbr,acronym { border:0; }

body { background: #fff; }
/* optional Container STYLES */
.chart { height: 600px; margin: 5px; width: 900px; }
.Treant > .node { padding: 3px; border: 1px solid #484848; border-radius: 3px; }
.Treant > .node img { width: 100%; height: 100%; }

.Treant .collapse-switch { width: 100%; height: 100%; border: none; }
.Treant .node.collapsed { background-color: #DEF82D; }
.Treant .node.collapsed .collapse-switch { background: none; }</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/treant-js/1.0/Treant.css" rel="stylesheet"/>

```

Body:
I have a node tree and want to fetch certain data attributes from these nodes when clickin on them.

I can't figure out how to get the right data from the object recived when clicking on it.

var simple_chart_config = {
  chart: {
    container: "#tree"
  },
  nodeStructure: {
    text: {
      name: "King Miro",
      title: "King"
    },
    children: [{
      text: {
        name: "King Randor",
        title: "King"
      },
      children: [{
        text: {
          name: "He-Man",
          title: "Master of the Universe"
        },},{
          text: {
            name: "She-Ra",
            title: "Princess"
          },
      }]
    }, {
      text: {
        name: "Skeletor",
        title: "Lord of Destruction"
      },
    }, ]
  }
}

var my_chart = new Treant(simple_chart_config);

$('body').on('click', '.Treant .node', function() {
    alert($(this).attr("title"));
    console.log($(this));
});

body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td { margin:0; padding:0; }
table { border-collapse:collapse; border-spacing:0; }
fieldset,img { border:0; }
address,caption,cite,code,dfn,em,strong,th,var { font-style:normal; font-weight:normal; }
caption,th { text-align:left; }
h1,h2,h3,h4,h5,h6 { font-size:100%; font-weight:normal; }
q:before,q:after { content:''; }
abbr,acronym { border:0; }

body { background: #fff; }
/* optional Container STYLES */
.chart { height: 600px; margin: 5px; width: 900px; }
.Treant > .node { padding: 3px; border: 1px solid #484848; border-radius: 3px; }
.Treant > .node img { width: 100%; height: 100%; }

.Treant .collapse-switch { width: 100%; height: 100%; border: none; }
.Treant .node.collapsed { background-color: #DEF82D; }
.Treant .node.collapsed .collapse-switch { background: none; }

<link href="https://cdnjs.cloudflare.com/ajax/libs/treant-js/1.0/Treant.css" rel="stylesheet"/>

So now I'm trying to fetch the name: and title:

I tried with many different versions of $(this).attr("") and val(). Trying to fetch via div class and similar.

I'm stuck right now.

Body:
You can use your build DOM to take the correct text that you need : $(this).find(".node-name") and $(this).find(".node-title")

var simple_chart_config = {
  chart: {
    container: "#tree"
  },
  nodeStructure: {
    text: {
      name: "King Miro",
      title: "King"
    },
    children: [{
      text: {
        name: "King Randor",
        title: "King"
      },
      children: [{
        text: {
          name: "He-Man",
          title: "Master of the Universe"
        },},{
          text: {
            name: "She-Ra",
            title: "Princess"
          },
      }]
    }, {
      text: {
        name: "Skeletor",
        title: "Lord of Destruction"
      },
    }, ]
  }
}

var my_chart = new Treant(simple_chart_config);

$('body').on('click', '.Treant .node', function() {
    alert($(this).find(".node-name").text());
    alert($(this).find(".node-title").text());
    console.log($(this));
});

body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td { margin:0; padding:0; }
table { border-collapse:collapse; border-spacing:0; }
fieldset,img { border:0; }
address,caption,cite,code,dfn,em,strong,th,var { font-style:normal; font-weight:normal; }
caption,th { text-align:left; }
h1,h2,h3,h4,h5,h6 { font-size:100%; font-weight:normal; }
q:before,q:after { content:''; }
abbr,acronym { border:0; }

body { background: #fff; }
/* optional Container STYLES */
.chart { height: 600px; margin: 5px; width: 900px; }
.Treant > .node { padding: 3px; border: 1px solid #484848; border-radius: 3px; }
.Treant > .node img { width: 100%; height: 100%; }

.Treant .collapse-switch { width: 100%; height: 100%; border: none; }
.Treant .node.collapsed { background-color: #DEF82D; }
.Treant .node.collapsed .collapse-switch { background: none; }

<link href="https://cdnjs.cloudflare.com/ajax/libs/treant-js/1.0/Treant.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/treant-js/1.0/Treant.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.2.7/raphael.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.js"></script>

<div id="tree">
</div>


问:
How to select the powers of x termwise based on the results of its mod 3 in mathematica
I have a polynomial in x, for example,

```<code>x^4/s +  x^3 + x^2*s + x^3*s^2 + x
</code>```

What I want to do is:

based on the result of (the exponent of x) mod 3,

```<code>   if it's 0, change the x^* to 1;
   if it's 1, change the x^* to 2;
   if it is 2, change x^* to 3.
</code>```

So I want to get:

x^4 => 2

x^3 => 1

x^2 => 3

x^1 => 2

therefore, for the given example, I get

```<code>2/s+1+3s+s^2+2
</code>```

How to do this programmably? Thanks!

Body:
I have a polynomial in x, for example,

x^4/s +  x^3 + x^2*s + x^3*s^2 + x

What I want to do is:

based on the result of (the exponent of x) mod 3,

   if it's 0, change the x^* to 1;
   if it's 1, change the x^* to 2;
   if it is 2, change x^* to 3.

So I want to get:

x^4 => 2

x^3 => 1

x^2 => 3

x^1 => 2

therefore, for the given example, I get

2/s+1+3s+s^2+2

How to do this programmably? Thanks!

Body:
The following:

(x^4/s + x^3 + x^2*s + x^3*s^2 + x) /. x^(a : _ : 1) :> (Mod[a, 3] + 1)

seems to do it.

Edit: Answering the comment:

In[4]:= (x^4/s + x^3 + x^2*s + x^3*s^2 + x) /.
    x^(a : _ : 1) :> (Mod[a, 3] /. {0 :> m, 1 :> n, 2 :> p})

Out[4]= m + n + n/s + p s + m s^2


问:
Firefox displays french characters incorreectly
I am using macOS Sierra 10.12.6, FireFox Quantum 57.0.1 (64-bit)

simply i created the following HTML page only has the following content
( déménagement )

It's got displayed correctly on Chrome & Safari, how ever on FireFox it looks super weird ( deÌmeÌnagement )

Is it bug on firefix? is there a way to fix it by CSS or JS? or maybe character encoding

答:
I manage to fix the issue, it was because or copy/paste from a PDF file which sometime causes (BOM)

More about (BOM) here


问:
How can I make a for inside another for in Oracle?
I have a cursor that returns:

```<code>id, name, mes, dia
id name mes dia
1  ex   1   1
1  ex   1   2
2  ex   1   1
2  ex   1   2
3  ex   1   1
3  ex   1   3
</code>```

I need two use a function to make something for each id (person) in each day.
Something like that:

```<code>for iten in c1
loop
  foor iten1 in ci.id
  loop
    foor iten2 in iten1.dia
    loop
    -----------do someting
    end loop;
  end loop;
end loop;
</code>```

Any idea about how can I do it in Oracle?

答:
You ask for something like this:</p>

```<code>FORrFicheros IN c1
   LOOP
     IF c1.name LIKE 'lihova%'
     THEN
      DBMS_OUTPUT.PUT_LINE('Something1');

     ELSIF c1.name LIKE'erprva%'
     THEN
       DBMS_OUTPUT.PUT_LINE('Something2');
         FOR i IN c2
         LOOP
           DBMS_OUTPUT.PUT_LINE('Something3');
         END LOOP;

       END;
     END if;
   END LOOP;
</code>```

Body:
I have a cursor that returns:

id, name, mes, dia
id name mes dia
1  ex   1   1
1  ex   1   2
2  ex   1   1
2  ex   1   2
3  ex   1   1
3  ex   1   3

I need two use a function to make something for each id (person) in each day.
Something like that:

for iten in c1
loop
  foor iten1 in ci.id
  loop
    foor iten2 in iten1.dia
    loop
    -----------do someting
    end loop;
  end loop;
end loop;

Any idea about how can I do it in Oracle?

Body:
You ask for something like this:

FORrFicheros IN c1
   LOOP
     IF c1.name LIKE 'lihova%'
     THEN
      DBMS_OUTPUT.PUT_LINE('Something1');

     ELSIF c1.name LIKE'erprva%'
     THEN
       DBMS_OUTPUT.PUT_LINE('Something2');
         FOR i IN c2
         LOOP
           DBMS_OUTPUT.PUT_LINE('Something3');
         END LOOP;

       END;
     END if;
   END LOOP;


问:
codeigniter insert current time in database by controller
here is my controller code to insert data into database

```<code>$datau = array(
    'reg_no' => $firstname,
    'fee_type' => $productinfo,
    'transaction_id' => $txnid,
    'status' => '0'
);
$this->db->insert('payment_status', $datau);
$this->load->view('fail', $data);
</code>```

this was working perfectly but when I try to add time like this:

```<code>$datau = array(
    'reg_no' => $firstname,
    'fee_type' => $productinfo,
    'transaction_id' => $txnid,
    'status' => '0',
    'time' => NOW()
);
$this->db->insert('payment_status', $datau);
$this->load->view('fail', $data);
</code>```

it returns an error like

Fatal error: Call to undefined function NOW() in
  D:\xampp\htdocs\iiht\application\controllers\Status.php on line 47

答:
You can used following code for your problem :

Used this PHP date function as date("Y-m-d H:i:s")

```<code>$datau = array(
    'reg_no' => $firstname,
    'fee_type' => $productinfo,
    'transaction_id' => $txnid,
    'status' => '0',
    'time' => date("Y-m-d H:i:s")
);
$this->db->insert('payment_status', $datau);
$this->load->view('fail', $data);
</code>```

I hope it will help you.

Body:
here is my controller code to insert data into database

$datau = array(
    'reg_no' => $firstname,
    'fee_type' => $productinfo,
    'transaction_id' => $txnid,
    'status' => '0'
);
$this->db->insert('payment_status', $datau);
$this->load->view('fail', $data);

this was working perfectly but when I try to add time like this:

$datau = array(
    'reg_no' => $firstname,
    'fee_type' => $productinfo,
    'transaction_id' => $txnid,
    'status' => '0',
    'time' => NOW()
);
$this->db->insert('payment_status', $datau);
$this->load->view('fail', $data);

it returns an error like

Fatal error: Call to undefined function NOW() in
  D:\xampp\htdocs\iiht\application\controllers\Status.php on line 47

Body:
You can used following code for your problem :

Used this PHP date function as date("Y-m-d H:i:s")

$datau = array(
    'reg_no' => $firstname,
    'fee_type' => $productinfo,
    'transaction_id' => $txnid,
    'status' => '0',
    'time' => date("Y-m-d H:i:s")
);
$this->db->insert('payment_status', $datau);
$this->load->view('fail', $data);

I hope it will help you.


问:
Adding 1 hours to time stamp columns in Pyspark data frame
In pyspark I have a column called test_time. This is a timestamp column.

The column has a records like below.

```<code>2017-03-12 03:19:51.0
2017-03-12 03:29:51.0
</code>```

Now I want to add 1 hour to the records in the test_time columns.

Result:

```<code>2017-03-12 04:19:51.0
2017-03-12 04:29:51.0
</code>```

How can I achieve my result.

I treied like below

```<code>df['test_time'] = df['test_time'].apply(lambda x: x - pd.DateOffset(hours=1))
</code>```

Got the below error

```<code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'Column' object is not callable
</code>```

答:
Should be very easy once you convert it to a UTC timestamp. Here is one way to do it :

```<code>from pyspark.sql.functions import to_utc_timestamp,from_utc_timestamp
from datetime import timedelta

## Create a dummy dataframe
df = sqlContext.createDataFrame([('1997-02-28 10:30:00',)], ['t'])

## Add column to convert time to utc timestamp in PST
df2 = df.withColumn('utc_timestamp',to_utc_timestamp(df.t,"PST"))

## Add one hour with the timedelta function
df3 = df2.map(lambda x: (x.t,x.utc_timestamp+timedelta(hours=1))).toDF(['t','new_utc_timestamp'])

## Convert back to original time zone and format
df4 = df3.withColumn('new_t',from_utc_timestamp(df3.new_utc_timestamp,"PST"))
</code>```

The "new_t" column in df4 is your required column converted back to the appropriate time zone according to your system.

Body:
In pyspark I have a column called test_time. This is a timestamp column.

The column has a records like below.

2017-03-12 03:19:51.0
2017-03-12 03:29:51.0

Now I want to add 1 hour to the records in the test_time columns.

Result:

2017-03-12 04:19:51.0
2017-03-12 04:29:51.0

How can I achieve my result.

I treied like below

df['test_time'] = df['test_time'].apply(lambda x: x - pd.DateOffset(hours=1))

Got the below error

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'Column' object is not callable

Body:
Should be very easy once you convert it to a UTC timestamp. Here is one way to do it :

from pyspark.sql.functions import to_utc_timestamp,from_utc_timestamp
from datetime import timedelta

## Create a dummy dataframe
df = sqlContext.createDataFrame([('1997-02-28 10:30:00',)], ['t'])

## Add column to convert time to utc timestamp in PST
df2 = df.withColumn('utc_timestamp',to_utc_timestamp(df.t,"PST"))

## Add one hour with the timedelta function
df3 = df2.map(lambda x: (x.t,x.utc_timestamp+timedelta(hours=1))).toDF(['t','new_utc_timestamp'])

## Convert back to original time zone and format
df4 = df3.withColumn('new_t',from_utc_timestamp(df3.new_utc_timestamp,"PST"))

The "new_t" column in df4 is your required column converted back to the appropriate time zone according to your system.


问:
Pass parameters to AlertDialog in Android
I was trying to pass some parameters to an AlertDialog, this dialog most show these two parameters (suppose "foo" and "bar" parameters), and I'm calling this dialog using showDialog(int id). There is another method in Activity class which take a Bundle object to pass parameters: showDialog(int id, Bundle args), but this method is only available to API 8 or greater and I need to work with API 7.

Here I put some chunks of code to make easier what I am doing.

In my activity I create AlertDialog like this:

```<code>    protected Dialog onCreateDialog(int id) {
        final LayoutInflater factory = LayoutInflater.from(this);

        switch(id) {
        case DIALOG_ID:
            final View view = factory.inflate(R.layout.dialog_layout, null);
            final TextView fooValue = (TextView)view.findViewById(R.id.foo_label);
            final TextView barValue = (TextView)view.findViewById(R.id.foo_label);
            //fooLabel.setText("HERE MUST BE FOO PARAMETER VALUE");
            //barLabel.setText("HERE MUST BE BAR PARAMETER VALUE");

            return new AlertDialog.Builder(this).
                setIcon(R.drawable.icon).
                setTitle(R.string.app_name).
                setView(view).
                setPositiveButton(R.string.close, null).
                create();
...
</code>```

And in other part I call this dialog:

```<code>    // THESE PARAMETERS MUST BE PASSED TO DIALOG
    int foo = result.getInt("foo");
    String bar = result.getString("bar");

    showDialog(DIALOG_ID);
...
</code>```

Thank you very much!

答:
I suggest adding a method setFooBar(int foo, String bar) to the class that is implementing the onCreateDialog function above, to receive the values of foo and bar before showDialog is called.

If you do not have an instance of the activity, consider making the method and variables static.

Body:
I was trying to pass some parameters to an AlertDialog, this dialog most show these two parameters (suppose "foo" and "bar" parameters), and I'm calling this dialog using showDialog(int id). There is another method in Activity class which take a Bundle object to pass parameters: showDialog(int id, Bundle args), but this method is only available to API 8 or greater and I need to work with API 7.

Here I put some chunks of code to make easier what I am doing.

In my activity I create AlertDialog like this:

    protected Dialog onCreateDialog(int id) {
        final LayoutInflater factory = LayoutInflater.from(this);

        switch(id) {
        case DIALOG_ID:
            final View view = factory.inflate(R.layout.dialog_layout, null);
            final TextView fooValue = (TextView)view.findViewById(R.id.foo_label);
            final TextView barValue = (TextView)view.findViewById(R.id.foo_label);
            //fooLabel.setText("HERE MUST BE FOO PARAMETER VALUE");
            //barLabel.setText("HERE MUST BE BAR PARAMETER VALUE");

            return new AlertDialog.Builder(this).
                setIcon(R.drawable.icon).
                setTitle(R.string.app_name).
                setView(view).
                setPositiveButton(R.string.close, null).
                create();
...

And in other part I call this dialog:

    // THESE PARAMETERS MUST BE PASSED TO DIALOG
    int foo = result.getInt("foo");
    String bar = result.getString("bar");

    showDialog(DIALOG_ID);
...

Thank you very much!


问:
Parsing time stamps - AM/PM not recognized
I'm trying to convert some timestamps (character) to a POSIXct object:

```<code>> u <- "December 05, 2017 1:00 PM"
</code>```

I'm using as.POSIXct as below:

```<code>> as.POSIXct(u, format = "%B %d, %Y %H:%M %p", tz = "UTC")
[1] "2017-12-05 01:00:00 UTC"
</code>```

I would expect the output to show 13 for the hour instead of 01:

```<code>"2017-12-05 13:00:00 UTC"
</code>```

I've seen the question posted here: Parse timestamp with a.m./p.m but I seem to have the correct input and format string (with %p).

as.POSIXct appears to completely ignore the AM/PM part of the string and therefore the AM timestamps work fine but the PM stamps lag by 12 hours. Here's some more data to illustrate this:

```<code>> sample_tstamps
 [1] "December 05, 2017 8:00 AM"  "December 05, 2017 9:00 AM"  "December 05, 2017 10:00 AM" "December 05, 2017 11:00 AM"
 [5] "December 05, 2017 12:00 PM" "December 05, 2017 1:00 PM"  "December 05, 2017 2:00 PM"  "December 05, 2017 3:00 PM"
 [9] "December 05, 2017 4:00 PM"  "December 05, 2017 5:00 PM"
> as.POSIXct(sample_tstamps, format = "%B %d, %Y %H:%M %p", tz = "UTC")
 [1] "2017-12-05 08:00:00 UTC" "2017-12-05 09:00:00 UTC" "2017-12-05 10:00:00 UTC" "2017-12-05 11:00:00 UTC"
 [5] "2017-12-05 12:00:00 UTC" "2017-12-05 01:00:00 UTC" "2017-12-05 02:00:00 UTC" "2017-12-05 03:00:00 UTC"
 [9] "2017-12-05 04:00:00 UTC" "2017-12-05 05:00:00 UTC"
</code>```

答:
Using the R-package lubridate:

```<code>u <- "December 05, 2017 1:00 PM"
lubridate::mdy_hm(u)
#[1] "2017-12-05 13:00:00 UTC"
</code>```

Body:
I'm trying to convert some timestamps (character) to a POSIXct object:

> u <- "December 05, 2017 1:00 PM"

I'm using as.POSIXct as below:

> as.POSIXct(u, format = "%B %d, %Y %H:%M %p", tz = "UTC")
[1] "2017-12-05 01:00:00 UTC"

I would expect the output to show 13 for the hour instead of 01:

"2017-12-05 13:00:00 UTC"

I've seen the question posted here: Parse timestamp with a.m./p.m but I seem to have the correct input and format string (with %p).

as.POSIXct appears to completely ignore the AM/PM part of the string and therefore the AM timestamps work fine but the PM stamps lag by 12 hours. Here's some more data to illustrate this:

> sample_tstamps
 [1] "December 05, 2017 8:00 AM"  "December 05, 2017 9:00 AM"  "December 05, 2017 10:00 AM" "December 05, 2017 11:00 AM"
 [5] "December 05, 2017 12:00 PM" "December 05, 2017 1:00 PM"  "December 05, 2017 2:00 PM"  "December 05, 2017 3:00 PM"
 [9] "December 05, 2017 4:00 PM"  "December 05, 2017 5:00 PM"
> as.POSIXct(sample_tstamps, format = "%B %d, %Y %H:%M %p", tz = "UTC")
 [1] "2017-12-05 08:00:00 UTC" "2017-12-05 09:00:00 UTC" "2017-12-05 10:00:00 UTC" "2017-12-05 11:00:00 UTC"
 [5] "2017-12-05 12:00:00 UTC" "2017-12-05 01:00:00 UTC" "2017-12-05 02:00:00 UTC" "2017-12-05 03:00:00 UTC"
 [9] "2017-12-05 04:00:00 UTC" "2017-12-05 05:00:00 UTC"

Body:
Using the R-package lubridate:

u <- "December 05, 2017 1:00 PM"
lubridate::mdy_hm(u)
#[1] "2017-12-05 13:00:00 UTC"


问:
Microsoft Graph API - Throttling
Is there a specific number of requests/minute (specific to a tenant) that an application can make to Microsoft Graph APIs before requests start getting throttled?</p>

答:
No, not specific to a tenant (at least not for the Outlook-related parts of the Graph). Throttling is done per user per app. The threshold is 10000 requests every 10 minutes.

https://blogs.msdn.microsoft.com/exchangedev/2017/04/07/throttling-coming-to-outlook-api-and-microsoft-graph/

For non-Outlook stuff, I'm not sure what the limits are. All Graph has to say about it is here:

https://developer.microsoft.com/en-us/graph/docs/concepts/throttling

The takeaway here is you should not depend on a specific threshold since we can always change it if we need to in order to protect the integrity of the service. Ensure that your app can gracefully handle being throttled by handling the 429 error response properly.

Title: Microsoft Graph API - Throttling


问:
Spark calculate number of times a user has tweeted
I have to calculate the number of times a user has tweeted, with data being in a JSON file. I tried groupByKey and reduceByKey but the output is user id and the tweet itself, not the count of tweets.

Code:

```<code>from pyspark import SparkContext
from pyspark.sql import SQLContext

sc = SparkContext("local", "Twitter")
sqlc = SQLContext(sc)

df = sqlc.read.json("file.json")
tweets = df.select("user.id","text")
users = tweets.rdd.reduceByKey(lambda x,y:x+y)
</code>```

How do I get the count of tweets by their respective users as key?

答:
Actually i found a solution to this. Hope this helps someone.</p>

```<code>users = tweets.rdd.groupByKey().mapValues(len)
</code>```

Body:
I have to calculate the number of times a user has tweeted, with data being in a JSON file. I tried groupByKey and reduceByKey but the output is user id and the tweet itself, not the count of tweets.

Code:

from pyspark import SparkContext
from pyspark.sql import SQLContext

sc = SparkContext("local", "Twitter")
sqlc = SQLContext(sc)

df = sqlc.read.json("file.json")
tweets = df.select("user.id","text")
users = tweets.rdd.reduceByKey(lambda x,y:x+y)

How do I get the count of tweets by their respective users as key?

Body:
Actually i found a solution to this. Hope this helps someone.

users = tweets.rdd.groupByKey().mapValues(len)


问:
Autoresponder Drupal 7 alternative
I'm looking for a module for Drupal 7 which could do something similar what Autoresponder for Drupal 6 does:

I want to send users different email newsletters after their their subscription. Day #1 - email #1 and so forth. And that module should let preset email templates beforehand (something more sophisticated than Simplenews module that sends emails on demand).

答:
Since Drupal 7 was only recently released, there will be A LOT of modules that haven't been upgraded yet. If the Autoresponder module looks like it would work for your needs, but hasn't yet been upgraded, my advice would be to pitch in and help upgrade it.

If you're not yet familiar with Drupal development, it's a good way to learn. You can get a good head start using the Coder Upgrade module or by running the same process via the upgrade.boombatower.com site. And if you run into trouble, other developers are likely to be very helpful in the issue queue, forums, and IRC, once they know you're working on upgrading a contrib module.

UPDATE: MailChimp allows for rich email templates and automated followups. There is a dev release for Drupal 7 of the MailChimp module that might be worth a try.

Title: Autoresponder Drupal 7 alternative


问:
Dask Distributed Unable to locate credentials
I can't access my files on S3 using a dataframe read : df_read_csv. I get the error: Exception: Unable to locate credentials

This works fine when my dask distributed is running against local worker cores. However, when I import a client with a cluster of additional worker servers it fails. My cluster was created using dask-ec2 on ubuntu with 1 scheduler on the header server and 3 worker servers (all ubuntu).

I am assuming that the failure is because all the workers also need access to S3. I have installed the aws cli on all of them and connected using my key and can list the S3 buckets from the cli. However, for some reason my dataframe read throws an ubuntu error saying that boto can't locate credentials

I have trawled through various posts but can't seem to find anything that helps. This is screenshot of the error:

答:
Hi Matt you should add key and secret to storage_options. In my case I have them saved on settings.py

```<code>import dask.dataframe as dd
import settings

df = dd.read_csv("s3://gra-dask-ec2/us_cities.csv",
                  storage_options={'key': settings.AWS_ACCESS_KEY_ID,
                                   'secret': settings.AWS_SECRET_ACCESS_KEY})
</code>```

Body:
Hi Matt you should add key and secret to storage_options. In my case I have them saved on settings.py

import dask.dataframe as dd
import settings

df = dd.read_csv("s3://gra-dask-ec2/us_cities.csv",
                  storage_options={'key': settings.AWS_ACCESS_KEY_ID,
                                   'secret': settings.AWS_SECRET_ACCESS_KEY})