问:
On Selenium WebDriver how to get Text from Span Tag
On Selenium Webdriver, how I can retrieve text from a span tag & print?

I need to extract the text UPS Overnight - Free

HTML code are as follow:

```<code>div id="customSelect_3" class="select_wrapper">
<div class="select_display hovered">
<span class="selectLabel clear">UPS Overnight - Free</span>
</code>```

Using following code:

```<code>String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']/div[1]/span)).getText();
System.out.println(kk);
</code>```

But above code is returning/printing text: 1.

答:
PHP way of getting text from span tag:</p>

```<code>$spanText = $this->webDriver->findElement(WebDriverBy::xpath("//*[@id='specInformation']/tbody/tr[2]/td[1]/span[1]"))->getText();
</code>```

Body:
On Selenium Webdriver, how I can retrieve text from a span tag & print?

I need to extract the text UPS Overnight - Free

HTML code are as follow:

div id="customSelect_3" class="select_wrapper">

UPS Overnight - Free

Using following code:

String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']/div[1]/span)).getText();
System.out.println(kk);

But above code is returning/printing text: 1.

Body:
PHP way of getting text from span tag:

$spanText = $this->webDriver->findElement(WebDriverBy::xpath("//*[@id='specInformation']/tbody/tr[2]/td[1]/span[1]"))->getText();


来源: stackexchange

问:
Excel : Exception of HRESULT : 0x800A03EC
I am trying to code a macro (I don't know if this name exists in english, but whatever) for Excel, and when I run it, I have this error that shows up :

check the ErrorCode property of the exception to determine the HRESULT returned by the COM object

With the additionnal information : Exception of HRESULT : 0x800A03EC

And I really don't know how to resolve this... I have tried a lot of answers from different forums, but nothing worked so far :(

Here is the part of my code where I get the error : (I will not paste everything as it is far too long)

```<code>if (PPE_ExcelFiles.dataWorksheet.get_Range(NOFEUIL_Column + noRowDataFile) != null) {...}
</code>```

PPE_ExcelFiles being another public Class I have made, and dataWorkSheet is of the type Excel.Worksheet. (And the type of what is inside the cell should be a string).

I have tried some other things, like :

```<code>string str = (string)PPE_ExcelFiles.dataWorksheet.get_Range(NOFEUIL_Column + noRowDataFile).Value;
    if (str != null) {...}
</code>```

And it didn't work either, receiving the same error, on the first line.

I don't know what kind of other informations you would potentially need to help me, as I really don't know what goes wrong, so tell me if there are some !

Thank you a lot

EDIT :

In the possible duplicate post, they say that it can occur if Excel can't find what we're asking it to. But that should not be the case for me :

noRowDataFile = 2

NOFEUIL_Column = "G"

PPE_ExcelFiles.dataworksheet exists

the sheet has a value in [G,2]

.get_Range(string + int) works wonders in another code

答:
Okay I think that I found the error, the value inside the range is a double type and it couldn't convert from double to string obviously...

Well in the end it was really easy, so many hours of debugging for that ! x')

ContentLicense: CC BY-SA 3.0

Body:
I am trying to code a macro (I don't know if this name exists in english, but whatever) for Excel, and when I run it, I have this error that shows up :

check the ErrorCode property of the exception to determine the HRESULT returned by the COM object

With the additionnal information : Exception of HRESULT : 0x800A03EC

And I really don't know how to resolve this... I have tried a lot of answers from different forums, but nothing worked so far :(

Here is the part of my code where I get the error : (I will not paste everything as it is far too long)

if (PPE_ExcelFiles.dataWorksheet.get_Range(NOFEUIL_Column + noRowDataFile) != null) {...}

PPE_ExcelFiles being another public Class I have made, and dataWorkSheet is of the type Excel.Worksheet. (And the type of what is inside the cell should be a string).

I have tried some other things, like :

string str = (string)PPE_ExcelFiles.dataWorksheet.get_Range(NOFEUIL_Column + noRowDataFile).Value;
    if (str != null) {...}

And it didn't work either, receiving the same error, on the first line.

I don't know what kind of other informations you would potentially need to help me, as I really don't know what goes wrong, so tell me if there are some !

Thank you a lot

EDIT :

In the possible duplicate post, they say that it can occur if Excel can't find what we're asking it to. But that should not be the case for me :

noRowDataFile = 2

NOFEUIL_Column = "G"

PPE_ExcelFiles.dataworksheet exists

the sheet has a value in [G,2]

.get_Range(string + int) works wonders in another code


问:
If I have 3
 elements, how do I only allow one to be highlighted when clicked at any one time? - CSS, jQuery
Might be a bit difficult to understand based on the description but the JSFiddle is here: http://jsfiddle.net/n8a76/4/

Basically what I want it to do, when you click on any of the elements in the first 3 boxes, I only want one element to be highlighted at a time. If you click on two or three elements (names, projects, etc) right now, it highlights all two or three. It only unhighlights an element when you click it again.

So I would like to see, click element 1, element 1 is highlighted. Click element 2, element 1 (in the same box) is unhighlighted, and element 2 is highlighted.

So each box, from my code it is called a dashed-panel, should be independent of the other.

So in theory, John Brown and Jack's App UI could be highlighted at the same time.

Anyone have any suggestions?

答:
You can just remove the class from th sibling
 elements in the same table, like this:

```<code>$(document).ready(function() {
  $('#clients table tr, #stages table tr, #projects table tr').click(function() {
    $(this).toggleClass('dash-elem-selected').siblings().removeClass('dash-elem-selected');
  });
});
</code>```

You can test it out here, this still allows toggling on/off as well.

ContentLicense: CC BY-SA 2.5

Title: If I have 3 <tr> elements, how do I only allow one to be highlighted when clicked at any one time? - CSS, jQuery

Body:
You can just remove the class from th sibling <tr> elements in the same table, like this:

$(document).ready(function() {
  $('#clients table tr, #stages table tr, #projects table tr').click(function() {
    $(this).toggleClass('dash-elem-selected').siblings().removeClass('dash-elem-selected');
  });
});

You can test it out here, this still allows toggling on/off as well.


问:
Print: Entry, ":CFBundleIdentifier", Does Not Exist
When I run react-native run-ios the build succeeds but I get the error below. I've checked all over the place but nothing seems to be working. Using sudo in front of the command does not help either. I am using Xcode 7.3, react-native-cli: 0.2.0, react-native: 0.24.1, node v5.11.0.

```<code>=== BUILD TARGET mobileTests OF PROJECT mobile WITH CONFIGURATION Release ===

Check dependencies

** BUILD SUCCEEDED **

Installing build/Build/Products/Debug-iphonesimulator/mobile.app
An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=2):
Failed to install the requested application
An application bundle was not found at the provided path.
Provide a valid path to the desired application bundle.
Print: Entry, ":CFBundleIdentifier", Does Not Exist
/Users/astiefel/workspace/bosspayments/mobile/node_modules/promise/lib/done.js:10
      throw err;
      ^

Error: Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier build/Build/Products/Debug-iphonesimulator/mobile.app/Info.plist
Print: Entry, ":CFBundleIdentifier", Does Not Exist

    at checkExecSyncError (child_process.js:470:13)
    at Object.execFileSync (child_process.js:490:13)
    at _runIOS (runIOS.js:91:34)
    at runIOS.js:24:5
    at tryCallTwo (/Users/astiefel/workspace/bosspayments/mobile/node_modules/promise/lib/core.js:45:5)
    at doResolve (/Users/astiefel/workspace/bosspayments/mobile/node_modules/promise/lib/core.js:200:13)
    at new Promise (/Users/astiefel/workspace/bosspayments/mobile/node_modules/promise/lib/core.js:66:3)
    at Array.runIOS (runIOS.js:23:10)
    at Object.run (/Users/astiefel/workspace/bosspayments/mobile/node_modules/react-native/local-cli/cli.js:86:13)
    at Object.<anonymous> (/usr/local/lib/node_modules/react-native-cli/index.js:88:7)
</code>```

答:
This worked for me.
Follow steps https://facebook.github.io/react-native/docs/getting-started.html (Building Projects with Native Code).

Before running   react-native run-ios command, download boost node module from https://sourceforge.net/projects/boost/files/boost/1.63.0/ and replace node_modules/react-native/third-party/boost_1_63_0

Now run   react-native run-ios    command

Body:
When I run react-native run-ios the build succeeds but I get the error below. I've checked all over the place but nothing seems to be working. Using sudo in front of the command does not help either. I am using Xcode 7.3, react-native-cli: 0.2.0, react-native: 0.24.1, node v5.11.0.

=== BUILD TARGET mobileTests OF PROJECT mobile WITH CONFIGURATION Release ===

Check dependencies

** BUILD SUCCEEDED **

Installing build/Build/Products/Debug-iphonesimulator/mobile.app
An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=2):
Failed to install the requested application
An application bundle was not found at the provided path.
Provide a valid path to the desired application bundle.
Print: Entry, ":CFBundleIdentifier", Does Not Exist
/Users/astiefel/workspace/bosspayments/mobile/node_modules/promise/lib/done.js:10
      throw err;
      ^

Error: Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier build/Build/Products/Debug-iphonesimulator/mobile.app/Info.plist
Print: Entry, ":CFBundleIdentifier", Does Not Exist

    at checkExecSyncError (child_process.js:470:13)
    at Object.execFileSync (child_process.js:490:13)
    at _runIOS (runIOS.js:91:34)
    at runIOS.js:24:5
    at tryCallTwo (/Users/astiefel/workspace/bosspayments/mobile/node_modules/promise/lib/core.js:45:5)
    at doResolve (/Users/astiefel/workspace/bosspayments/mobile/node_modules/promise/lib/core.js:200:13)
    at new Promise (/Users/astiefel/workspace/bosspayments/mobile/node_modules/promise/lib/core.js:66:3)
    at Array.runIOS (runIOS.js:23:10)
    at Object.run (/Users/astiefel/workspace/bosspayments/mobile/node_modules/react-native/local-cli/cli.js:86:13)
    at Object.<anonymous> (/usr/local/lib/node_modules/react-native-cli/index.js:88:7)


问:
Replacing 'this' with another object of the same kind
So I have my own Bicycle constructor (simple example):

```<code>function Bicycle (wheels, steer) {
  this.wheels = 2 + wheels;
  this.steer = wheels/steer;
}

Bicycle.prototype = {
  steer: function () {
    // do something
  },

  replace: function () {
    var bicycles = generateRandomBicycles();
    bicycles.sort(function (a, b) {
      return b.score - a.score;
    });

    this = bicycles[0];
  }
};
</code>```

Pay attention to the replace function. I'm doing something similar to this, but i'm actually running a small genetic algorithm that should replace the current bicycle with a better one.

I'm aware that I could simply do:

```<code>this.wheels = bicycles[0].wheels;
this.steer = bicycles[0].steer;
</code>```

But is there any smarter way I can do this? Using this = x causes the error Parsing error: Assigning to rvalue.

答:
You can't reassign this. As @pointy pointed out in the comments, you can create a function which returns a new bike:

```<code>function Bicycle (wheels, steer) {
  this.wheels = 2 + wheels;
  this.steer = wheels/steer;
}

Bicycle.prototype.replace = function () {
  var bicycles = generateRandomBicycles();
  bicycles.sort(function (a, b) {
    return b.score - a.score;
  });
  return bicycles[0];
};

const bike1 = new Bicycle(2, 1);
const bike2 = bike1.replace();
</code>```

You could assign a new instance to the same variable though:

```<code>let bike = new Bicycle(2, 1);
bike = bike.replace();
</code>```

Body:
So I have my own Bicycle constructor (simple example):

function Bicycle (wheels, steer) {
  this.wheels = 2 + wheels;
  this.steer = wheels/steer;
}

Bicycle.prototype = {
  steer: function () {
    // do something
  },

  replace: function () {
    var bicycles = generateRandomBicycles();
    bicycles.sort(function (a, b) {
      return b.score - a.score;
    });

    this = bicycles[0];
  }
};

Pay attention to the replace function. I'm doing something similar to this, but i'm actually running a small genetic algorithm that should replace the current bicycle with a better one.

I'm aware that I could simply do:

this.wheels = bicycles[0].wheels;
this.steer = bicycles[0].steer;

But is there any smarter way I can do this? Using this = x causes the error Parsing error: Assigning to rvalue.

Body:
You can't reassign this. As @pointy pointed out in the comments, you can create a function which returns a new bike:

function Bicycle (wheels, steer) {
  this.wheels = 2 + wheels;
  this.steer = wheels/steer;
}

Bicycle.prototype.replace = function () {
  var bicycles = generateRandomBicycles();
  bicycles.sort(function (a, b) {
    return b.score - a.score;
  });
  return bicycles[0];
};

const bike1 = new Bicycle(2, 1);
const bike2 = bike1.replace();

You could assign a new instance to the same variable though:

let bike = new Bicycle(2, 1);
bike = bike.replace();


问:
Web scraping by Beautifulsoup
In my previous post, I wanna scrape some horse racing data on HKJC. Thanks to the help of Dmitriy Fialkovskiy, I've made it happen by slightly modifying the given code. However, when I was trying to understand the logic behind, there was a line couldn't be explained:

```<code>from bs4 import BeautifulSoup as BS
import requests
import pandas as pd

url_list = ['http://www.hkjc.com/english/racing/horse.asp?HorseNo=S217','http://www.hkjc.com/english/racing/horse.asp?HorseNo=A093','http://www.hkjc.com/english/racing/horse.asp?HorseNo=V344','http://www.hkjc.com/english/racing/horse.asp?HorseNo=V077', 'http://www.hkjc.com/english/racing/horse.asp?HorseNo=P361', 'http://www.hkjc.com/english/racing/horse.asp?HorseNo=T103']

res=[] #placing res outside of loop
for link in url_list:
    r = requests.get(link)
    r.encoding = 'utf-8'

    html_content = r.text
    soup = BS(html_content, 'lxml')

    table = soup.find('table', class_='bigborder')
    if not table:
        continue

    trs = table.find_all('tr')

    if not trs:
        continue #if trs are not found, then starting next iteration with other link

    headers = trs[0]
    headers_list=[]
    for td in headers.find_all('td'):
        headers_list.append(td.text)
    headers_list+=['Season']
    headers_list.insert(19,'pseudocol1')
    headers_list.insert(20,'pseudocol2')
    headers_list.insert(21,'pseudocol3')

    row = []
    season = ''
    for tr in trs[1:]:
        if 'Season' in tr.text:
            season = tr.text

        else:
            tds = tr.find_all('td')
            for td in tds:
                row.append(td.text.strip('\n').strip('\r').strip('\t').strip('"').strip())
            row.append(season.strip())
            res.append(row)
            row=[]

res = [i for i in res if i[0]!=''] #outside of loop

df=pd.DataFrame(res, columns=headers_list) #outside of loop
del df['pseudocol1'],df['pseudocol2'],df['pseudocol3']
del df['VideoReplay']
</code>```

I'm wondering what's the purpose of adding a repeated row =[] in the else condition and why would that works. Thank you.

答: The way I see it, if you do not reset the row then you will always repeat the storage of the previous results, more and more, with res.append(row) just above.

Title: Web scraping by Beautifulsoup

Body:
In my previous post, I wanna scrape some horse racing data on HKJC. Thanks to the help of Dmitriy Fialkovskiy, I've made it happen by slightly modifying the given code. However, when I was trying to understand the logic behind, there was a line couldn't be explained:

from bs4 import BeautifulSoup as BS
import requests
import pandas as pd

url_list = ['http://www.hkjc.com/english/racing/horse.asp?HorseNo=S217','http://www.hkjc.com/english/racing/horse.asp?HorseNo=A093','http://www.hkjc.com/english/racing/horse.asp?HorseNo=V344','http://www.hkjc.com/english/racing/horse.asp?HorseNo=V077', 'http://www.hkjc.com/english/racing/horse.asp?HorseNo=P361', 'http://www.hkjc.com/english/racing/horse.asp?HorseNo=T103']

res=[] #placing res outside of loop
for link in url_list:
    r = requests.get(link)
    r.encoding = 'utf-8'

    html_content = r.text
    soup = BS(html_content, 'lxml')

    table = soup.find('table', class_='bigborder')
    if not table:
        continue

    trs = table.find_all('tr')

    if not trs:
        continue #if trs are not found, then starting next iteration with other link

    headers = trs[0]
    headers_list=[]
    for td in headers.find_all('td'):
        headers_list.append(td.text)
    headers_list+=['Season']
    headers_list.insert(19,'pseudocol1')
    headers_list.insert(20,'pseudocol2')
    headers_list.insert(21,'pseudocol3')

    row = []
    season = ''
    for tr in trs[1:]:
        if 'Season' in tr.text:
            season = tr.text

        else:
            tds = tr.find_all('td')
            for td in tds:
                row.append(td.text.strip('\n').strip('\r').strip('\t').strip('"').strip())
            row.append(season.strip())
            res.append(row)
            row=[]

res = [i for i in res if i[0]!=''] #outside of loop

df=pd.DataFrame(res, columns=headers_list) #outside of loop
del df['pseudocol1'],df['pseudocol2'],df['pseudocol3']
del df['VideoReplay']

I'm wondering what's the purpose of adding a repeated row =[] in the else condition and why would that works. Thank you.


问:
Android notification icon color is not changed when background color is white
I upgraded android 6.0 and my app have problem.

when the status bar background color is not white, notification icon is good.
(notification icon png has white and alpha only)

but if some apps change background color to white, my notification icon isn't inverted to black.

How can I invert white notification icon to black when status bar background color set white by other app? (I'm not saying how can I use color icon.)

below image shows a problem.

normal status

when changed background color to white, my icon is not changed to black only

Notification build code

```<code>  Notification.Builder mBuilder =
          new Notification.Builder(context)
                  .setSmallIcon(R.drawable.ic_notifications_none)
                  .setPriority(priority2)
                  .setOngoing(true);

  mBuilder.setContent(generateMessageView(message));

  Intent notificationIntent = new Intent(context, MainActivity.class);
  notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                            | Intent.FLAG_ACTIVITY_SINGLE_TOP);

  PendingIntent intent = PendingIntent.getActivity(context, 0,
          notificationIntent, 0);
  NotificationManager mNotificationManager =
          (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
  mBuilder.setContentIntent(intent);
  mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
</code>```

values-v23/styles.xml

```<code>  <style name="AppTheme" parent="android:Theme.Material.NoActionBar">
  </style>
</code>```

Found a solution

I added notification icons to drawable directory not drawable-*dpi. Now it's working.

答:
It's late to answer, but for others who have the same problem,

I had this problem too and I found that the problem is with graphical icon.
You can solve the problem by using this online tool.
open this link:

https://romannurik.github.io/AndroidAssetStudio/icons-notification.html#source.type=image&source.space.trim=1&source.space.pad=0&name=ic_stat_call_white

choose your image ( with large dimension ), download the resource and copy them to your project.

and finally set the notification icon using .setSmallIcon(R.drawable.ICON_NEW_NAME)

hope this helps

ContentLicense: CC BY-SA 4.0

Body:
I upgraded android 6.0 and my app have problem.

when the status bar background color is not white, notification icon is good.
(notification icon png has white and alpha only)

but if some apps change background color to white, my notification icon isn't inverted to black.

How can I invert white notification icon to black when status bar background color set white by other app? (I'm not saying how can I use color icon.)

below image shows a problem.

normal status

when changed background color to white, my icon is not changed to black only

Notification build code

  Notification.Builder mBuilder =
          new Notification.Builder(context)
                  .setSmallIcon(R.drawable.ic_notifications_none)
                  .setPriority(priority2)
                  .setOngoing(true);

  mBuilder.setContent(generateMessageView(message));

  Intent notificationIntent = new Intent(context, MainActivity.class);
  notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                            | Intent.FLAG_ACTIVITY_SINGLE_TOP);

  PendingIntent intent = PendingIntent.getActivity(context, 0,
          notificationIntent, 0);
  NotificationManager mNotificationManager =
          (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
  mBuilder.setContentIntent(intent);
  mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

values-v23/styles.xml

Found a solution

I added notification icons to drawable directory not drawable-*dpi. Now it's working.


问:
Custom JavaScriptConverter for DateTime?
I have an object, it has a DateTime property... I want to pass that object from an .ashx handler back to a webpage via AJAX/JSON... I don't want to use 3rd party controls...

when I do this:

```<code>  new JavaScriptSerializer().Serialize(DateTime.Now);
</code>```

I get this:

```<code>  "\/Date(1251385232334)\/"
</code>```

but I want "8/26/2009" (nevermind localization... my app is very localized, so my date formatting assumptions are not up for debate in this question).  If I make/register a custom converter

```<code>public class DateTimeConverter : JavaScriptConverter
{
    public override IEnumerable<Type> SupportedTypes
    {
        get { return new List<Type>() { typeof(DateTime), typeof(DateTime?) }; }
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        Dictionary<string, object> result = new Dictionary<string, object>();
        if (obj == null) return result;
        result["DateTime"] = ((DateTime)obj).ToShortDateString();
        return result;
    }

    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        if (dictionary.ContainsKey("DateTime"))
            return new DateTime(long.Parse(dictionary["DateTime"].ToString()), DateTimeKind.Unspecified);
        return null;
    }
}
</code>```

then I get this result (since the return value of the custom serialize method is a dictionary):

```<code>{"DateTime":"8/27/2009"}
</code>```

so now in my Javascript, instead of doing

```<code>somePerson.Birthday
</code>```

I have to do

```<code>somePerson.Birthday.DateTime

  or

somePerson.Birthday["DateTime"]
</code>```

how can I make the custom converter return a direct string so that I can have clean Javascript?

答:
JavaScriptSerializer can definitely do what you desire.

It's possible to customize the serialization performed by JavaScriptSerializer for any type by creating a custom converter and registering it with the serializer. If you have a class called Person, we could create a converter like so:

```<code>public class Person
{
    public string Name { get; set; }
    public DateTime Birthday { get; set; }
}

public class PersonConverter : JavaScriptConverter
{
    private const string _dateFormat = "MM/dd/yyyy";

    public override IEnumerable<Type> SupportedTypes
    {
        get
        {
            return new[] { typeof(Person) };
        }
    }

    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        Person p = new Person();
        foreach (string key in dictionary.Keys)
        {
            switch (key)
            {
                case "Name":
                    p.Name = (string)dictionary[key];
                    break;

                case "Birthday":
                    p.Birthday = DateTime.ParseExact(dictionary[key] as string, _dateFormat, DateTimeFormatInfo.InvariantInfo);
                    break;
            }
        }
        return p;
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        Person p = (Person)obj;
        IDictionary<string, object> serialized = new Dictionary<string, object>();
        serialized["Name"] = p.Name;
        serialized["Birthday"] = p.Birthday.ToString(_dateFormat);
        return serialized;
    }
}
</code>```

And use it like this:

```<code>JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new PersonConverter() });

Person p = new Person
            {
                Name = "User Name",
                Birthday = DateTime.Now
            };

string json = serializer.Serialize(p);
Console.WriteLine(json);
// {"Name":"User Name","Birthday":"12/20/2010"}

Person fromJson = serializer.Deserialize<Person>(json);
Console.WriteLine(String.Format("{0}, {1}", fromJson.Name, fromJson.Birthday));
// User Name, 12/20/2010 12:00:00 AM
</code>```

Body:
I have an object, it has a DateTime property... I want to pass that object from an .ashx handler back to a webpage via AJAX/JSON... I don't want to use 3rd party controls...

when I do this:

  new JavaScriptSerializer().Serialize(DateTime.Now);

I get this:

  "\/Date(1251385232334)\/"

but I want "8/26/2009" (nevermind localization... my app is very localized, so my date formatting assumptions are not up for debate in this question).  If I make/register a custom converter

public class DateTimeConverter : JavaScriptConverter
{
    public override IEnumerable<Type> SupportedTypes
    {
        get { return new List<Type>() { typeof(DateTime), typeof(DateTime?) }; }
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        Dictionary<string, object> result = new Dictionary<string, object>();
        if (obj == null) return result;
        result["DateTime"] = ((DateTime)obj).ToShortDateString();
        return result;
    }

    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        if (dictionary.ContainsKey("DateTime"))
            return new DateTime(long.Parse(dictionary["DateTime"].ToString()), DateTimeKind.Unspecified);
        return null;
    }
}

then I get this result (since the return value of the custom serialize method is a dictionary):

{"DateTime":"8/27/2009"}

so now in my Javascript, instead of doing

somePerson.Birthday

I have to do

somePerson.Birthday.DateTime

  or

somePerson.Birthday["DateTime"]

how can I make the custom converter return a direct string so that I can have clean Javascript?

Body:
JavaScriptSerializer can definitely do what you desire.

It's possible to customize the serialization performed by JavaScriptSerializer for any type by creating a custom converter and registering it with the serializer. If you have a class called Person, we could create a converter like so:

public class Person
{
    public string Name { get; set; }
    public DateTime Birthday { get; set; }
}

public class PersonConverter : JavaScriptConverter
{
    private const string _dateFormat = "MM/dd/yyyy";

    public override IEnumerable<Type> SupportedTypes
    {
        get
        {
            return new[] { typeof(Person) };
        }
    }

    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        Person p = new Person();
        foreach (string key in dictionary.Keys)
        {
            switch (key)
            {
                case "Name":
                    p.Name = (string)dictionary[key];
                    break;

                case "Birthday":
                    p.Birthday = DateTime.ParseExact(dictionary[key] as string, _dateFormat, DateTimeFormatInfo.InvariantInfo);
                    break;
            }
        }
        return p;
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        Person p = (Person)obj;
        IDictionary<string, object> serialized = new Dictionary<string, object>();
        serialized["Name"] = p.Name;
        serialized["Birthday"] = p.Birthday.ToString(_dateFormat);
        return serialized;
    }
}

And use it like this:

JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new PersonConverter() });

Person p = new Person
            {
                Name = "User Name",
                Birthday = DateTime.Now
            };

string json = serializer.Serialize(p);
Console.WriteLine(json);
// {"Name":"User Name","Birthday":"12/20/2010"}

Person fromJson = serializer.Deserialize<Person>(json);
Console.WriteLine(String.Format("{0}, {1}", fromJson.Name, fromJson.Birthday));
// User Name, 12/20/2010 12:00:00 AM


问:
Geb. i am working on this and i need exact Packaging material object can you please let me know

packagingmeterial {By.id($("#menuDiv span").first().text())}

答:
This is hard to answer because there are many different ways to get the element you are after. I think the easiest way would be to define the element like this:

$(By.xpath("//span")).text()

Since this is the only "span" in the screenshot I will assume it is the only span on the page.

you could also do this, if you need to reference the closest ID:

$(By.id("#menuform:loggedInMenu_0 span")).children()[0].children()[0].text()

If you want to use the same element definition that you posted in your question you can do this:

$(By.id("#menuDiv span")).children()[0].children()[0].children()[0].children()[0].children()[0].children()[0]

I also noticed something wrong in your comments up above.

in your static content you have defined:

static content = { packagingmeterial {$("#menuDiv span").first().text()} }

but then later on you try and call packagingmeterial.click() this will not work because packagingmeterial is not a Navigator object it is a String You transform it from a Navigator to a String when you say .text(). So you should also try removing that and see if it helps.

You may also benefit from reading the geb docs found here:
http://www.gebish.org/


问:
Is there a difference between activations functions in tensorflow? tf.nn.tanh vs tf.tanh
I want to setup a neuronal network and I am asking myself if there is a difference between those two functions?

tf.nn.tanh vs tf.tanh

答:
No there isn't any difference.

The availability of both is probably due to the library evolving and still changing its API, being still in an initial state of maturing.
We could expect the library to avoid those fundamental duplications in the future when the main API is finally set (I'd expect so towards 2.0).


问:
angular4 ngOnChanges method
I have transformed my angular1 project to angular4 ,but ngOnChanges method seems not work ,I want to watch some values when they changed

```<code>import {Component, OnInit, Input, OnChanges, SimpleChanges} from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'login-page',
    templateUrl: './login.page.html'
})

export class LoginPage implements OnChanges{

    userName: string = 'who am i';
    password: string;
    changeLog: string[] = [];

    ngOnChanges(changes: SimpleChanges) {
        console.info(changes);   //it didn't work anymore,please help me
        for (let propName in changes) {
            let chng = changes[propName];
            let cur  = JSON.stringify(chng.currentValue);
            let prev = JSON.stringify(chng.previousValue);
            this.changeLog.push(`${propName}: currentValue = ${cur}, previousValue = ${prev}`);
        }
    }
    showValue(f) {
        console.info(f);
    }
}
</code>```

I have try all the ways to make it sensitive to the value changes,I wander why the demo could run from angular.io(https://embed.plnkr.co/?show=preview) , but my app isn't work.I don't know if I had left some important things in my app, the ngOnChanges method didn't work anymore

```<code><ion-header>
    <ion-navbar>
        <ion-title>login</ion-title>
    </ion-navbar>
</ion-header>
<ion-content padding>
    <form #f="ngForm" (ngSubmit)="showValue(f)">
        <ion-item>
            <ion-label fixed>username</ion-label>
            <ion-input type="text" required [(ngModel)]="userName" name="userName"></ion-input>
        </ion-item>
        <ion-item>
            <ion-label fixed>username2</ion-label>
            <ion-input type="text" [value]="userName" (input)="userName = $event.target.value"></ion-input>
        </ion-item>
        <ion-item>
            <ion-label fixed>pwd</ion-label>
            <input type="text" [(ngModel)]="password" name="pwd">
            <ion-input type="password" [(ngModel)]="password" name="pwd"></ion-input>
        </ion-item>
        <input ion-button type="submit" value="commit" class="button-block-ios button">
        <button ion-button outline>Primary Outline</button>
    </form>
    <div>
        <input type="text" [(ngModel)]="userName">
    </div>
    <div *ngFor="let chg of changeLog">{{chg}}</div>
    <div>{{userName}}</div>
    <!--<input type="text" class="item-input" [value]="userName" (click)=showValue>-->
</ion-content>
</code>```

答:
ngOnChanges() is only called by Angular change detection after change detection updates an @Input() of a component, not when arbitrary code changes an input. For fields that are not inputs, ngOnChanges is never called.

You can just make your fields getters/setters and put code there that should be executed when the value is updated

```<code>_userName: string = 'who am i';
set userName(val:string) { this._userName = val; /* more code */}
get userName():string { return this._userName; }
</code>```

Title: angular4 ngOnChanges method

Body:
I have transformed my angular1 project to angular4 ,but ngOnChanges method seems not work ,I want to watch some values when they changed

import {Component, OnInit, Input, OnChanges, SimpleChanges} from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'login-page',
    templateUrl: './login.page.html'
})

export class LoginPage implements OnChanges{

    userName: string = 'who am i';
    password: string;
    changeLog: string[] = [];

    ngOnChanges(changes: SimpleChanges) {
        console.info(changes);   //it didn't work anymore,please help me
        for (let propName in changes) {
            let chng = changes[propName];
            let cur  = JSON.stringify(chng.currentValue);
            let prev = JSON.stringify(chng.previousValue);
            this.changeLog.push(`${propName}: currentValue = ${cur}, previousValue = ${prev}`);
        }
    }
    showValue(f) {
        console.info(f);
    }
}

I have try all the ways to make it sensitive to the value changes,I wander why the demo could run from angular.io(https://embed.plnkr.co/?show=preview) , but my app isn't work.I don't know if I had left some important things in my app, the ngOnChanges method didn't work anymore

<ion-header>
    <ion-navbar>
        <ion-title>login</ion-title>
    </ion-navbar>
</ion-header>
<ion-content padding>
    <form #f="ngForm" (ngSubmit)="showValue(f)">
        <ion-item>
            <ion-label fixed>username</ion-label>
            <ion-input type="text" required [(ngModel)]="userName" name="userName"></ion-input>
        </ion-item>
        <ion-item>
            <ion-label fixed>username2</ion-label>
            <ion-input type="text" [value]="userName" (input)="userName = $event.target.value"></ion-input>
        </ion-item>
        <ion-item>
            <ion-label fixed>pwd</ion-label>
            <input type="text" [(ngModel)]="password" name="pwd">
            <ion-input type="password" [(ngModel)]="password" name="pwd"></ion-input>
        </ion-item>
        <input ion-button type="submit" value="commit" class="button-block-ios button">
        <button ion-button outline>Primary Outline</button>
    </form>

        <input type="text" [(ngModel)]="userName">

{{chg}}

{{userName}}

</ion-content>

Body:
ngOnChanges() is only called by Angular change detection after change detection updates an @Input() of a component, not when arbitrary code changes an input. For fields that are not inputs, ngOnChanges is never called.

You can just make your fields getters/setters and put code there that should be executed when the value is updated

_userName: string = 'who am i';
set userName(val:string) { this._userName = val; /* more code */}
get userName():string { return this._userName; }


问:
How to loop through DIV id element to check style None or Block
I want to loop through DIV id element in order to check the style if its none/block?

Code to check against

// The below code can perform that but just once.

if($('#loadingProgressContainer').css('display') == 'none')
{
 console.log("Display = NONE !!!");
}
else
{
 console.log("Display = BLOCK !!");
}

//I tried with the below code but not working

while ($('#loadingProgressContainer').css('display') != 'none')
{
   console.log("Display = BLOCK !!");
}

console.log("Display = NONE !!!");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tbNewStyleWrapper" style="position: relative;">
  <div id="loadingProgressContainer" style="display: block;">
  <div id="loadingProgressElement">
  <p><h1>Test Please...</h1></p>
   <img src="http://www.dev.tasch.co.za/airportshuttle2/components/com_taxibooking/assets/images/ajax-loader-bar.gif">
  </div>
  </div>
    </div></code>```

答:
setInterval(function() {
  if ($('#loadingProgressContainer').css('display') == 'none') {
    console.log("Display = NONE !!!");
  } else {
    console.log("Display = BLOCK !!");
  }
}, 3000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tbNewStyleWrapper" style="position: relative;">
  <div id="loadingProgressContainer" style="display: block;">
    <div id="loadingProgressElement">
      <p>
        <h1>Test Please...</h1>
      </p>
      <img src="http://www.dev.tasch.co.za/airportshuttle2/components/com_taxibooking/assets/images/ajax-loader-bar.gif">
    </div>
  </div>
</div></code>```

This snippet is only reference if you want to check visibility of your div after certain period repeatdly

Body:
I want to loop through DIV id element in order to check the style if its none/block?

Code to check against

// The below code can perform that but just once.

if($('#loadingProgressContainer').css('display') == 'none')
{
 console.log("Display = NONE !!!");
}
else
{
 console.log("Display = BLOCK !!");
}

//I tried with the below code but not working

while ($('#loadingProgressContainer').css('display') != 'none')
{
   console.log("Display = BLOCK !!");
}

console.log("Display = NONE !!!");

Test Please...

Body:
setInterval(function() {
  if ($('#loadingProgressContainer').css('display') == 'none') {
    console.log("Display = NONE !!!");
  } else {
    console.log("Display = BLOCK !!");
  }
}, 3000);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tbNewStyleWrapper" style="position: relative;">
  <div id="loadingProgressContainer" style="display: block;">
    <div id="loadingProgressElement">
      <p>
        <h1>Test Please...</h1>
      </p>
      <img src="http://www.dev.tasch.co.za/airportshuttle2/components/com_taxibooking/assets/images/ajax-loader-bar.gif">
    </div>
  </div>
</div>

This snippet is only reference if you want to check visibility of your div after certain period repeatdly


问:
How to Hide the Document Preview

Someone knows how i can hide the bar that is in red?

It appeared after the 1.13 update....

答:
```<code>"editor.minimap.enabled": false
</code>```

Solved the problem.

Title: How to Hide the Document Preview

Body:
"editor.minimap.enabled": false

Solved the problem.


问:
PHP curl: Yes box not ticking
Really struggling with this. Some help would be greatly appreciated, i have spent an hour with this today already and i feel I've hit a brick wall..

This same exact code used to work perfect, however i am assuming the service has updated some of their code slightly as its not working as it should now, its probably just something simple but i just cant seem to get it working anymore and cant find whats been updated that stops it working.

This code basically visits one page to check a cars mot/tax status, once you visit that page you have to click Yes on the next page which is where im getting stuck at right now, however the code used to work perfect every time, thanks in advance for any help guys.

```<code><?
$Vrm = "KS09 FSV";

$url = 'https://vehicleenquiry.service.gov.uk/ConfirmVehicle';
$fields = array(
    'Vrm' => urlencode($Vrm),
    'Correct' => urlencode("True")
);
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);

$value = explode("value=\"", $result);
$value = explode("\"", $value[1]);

$url = 'https://vehicleenquiry.service.gov.uk/ViewVehicle';
$fields = array(
    'Vrm' => urlencode($Vrm),
    'viewstate' => urlencode($value[0])
);
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);

$dom = new DOMDocument();
@$res=$dom->loadHTML($result);

$xpath = new DomXPath($dom);

$class = 'isUntaxed';
$divs = $xpath->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $class ')]");

foreach($divs as $div)
{
    $dateSplit = explode(":", $div->nodeValue);
    echo $dateSplit[0] . " " . $dateSplit[1] . " ";

    $date1 = new DateTime(date(d) . " " . date ( M ) . " " . date( Y ));
    $date2 = new DateTime($dateSplit[1]);

    if ( $date1 > $date2 ) $exp = "Expired";
    else $exp = "Valid for another";

    $diff = $date2->diff($date1)->format("%a");
    echo $exp . " " . $diff . " days ago<BR><BR>";
}

$class = 'isValidMot';
$divs = $xpath->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $class ')]");

foreach($divs as $div)
{
    $dateSplit = explode(":", $div->nodeValue);
    echo $dateSplit[0] . "<BR>" . $dateSplit[1] . "<BR>";

    $date1 = new DateTime(date(d) . " " . date ( M ) . " " . date( Y ));
    $date2 = new DateTime($dateSplit[1]);
    $diff = $date2->diff($date1)->format("%a");

    if ( $date1 > $date2 ) $exp = "Expired";
    else $exp = "Valid for another";

    echo $exp . " " . $diff . " days ago<BR><BR>";
}?>
</code>```

答:
New Answer

As per the comments below, you need to uncomment out the following line from both requests:

```<code>curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
</code>```

The government website has changed the class name of the elements where the expiry data is stored, so instead of isUntaxed and isValidMot, both divs now have the class isValid.

Just as a side note, where you're creating the DateTime object for today's date, you can just use the following:

```<code>$date1 = new DateTime(date('d M Y'));
</code>```

which is shorter and doesn't produce warnings such as

Notice: Use of undefined constant d - assumed 'd'

Original Answer

<s>Looking at your code and the website, you're sending the 'Correct' => urlencode("True") for the first URL (https://vehicleenquiry.service.gov.uk/ConfirmVehicle) whereas it needs to be submitted to the second URL (https://vehicleenquiry.service.gov.uk/ViewVehicle).

If you go to the first URL manually in your browser, you will see that you only need the registration number on the first page. Once that has been submitted, you then need to submit the checkbox on the next page.</s>

Title: PHP curl: Yes box not ticking

Body:
Really struggling with this. Some help would be greatly appreciated, i have spent an hour with this today already and i feel I've hit a brick wall..

This same exact code used to work perfect, however i am assuming the service has updated some of their code slightly as its not working as it should now, its probably just something simple but i just cant seem to get it working anymore and cant find whats been updated that stops it working.

This code basically visits one page to check a cars mot/tax status, once you visit that page you have to click Yes on the next page which is where im getting stuck at right now, however the code used to work perfect every time, thanks in advance for any help guys.

<?
$Vrm = "KS09 FSV";

$url = 'https://vehicleenquiry.service.gov.uk/ConfirmVehicle';
$fields = array(
    'Vrm' => urlencode($Vrm),
    'Correct' => urlencode("True")
);
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);

$value = explode("value=\"", $result);
$value = explode("\"", $value[1]);

$url = 'https://vehicleenquiry.service.gov.uk/ViewVehicle';
$fields = array(
    'Vrm' => urlencode($Vrm),
    'viewstate' => urlencode($value[0])
);
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);

$dom = new DOMDocument();
@$res=$dom->loadHTML($result);

$xpath = new DomXPath($dom);

$class = 'isUntaxed';
$divs = $xpath->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $class ')]");

foreach($divs as $div)
{
    $dateSplit = explode(":", $div->nodeValue);
    echo $dateSplit[0] . " " . $dateSplit[1] . " ";

    $date1 = new DateTime(date(d) . " " . date ( M ) . " " . date( Y ));
    $date2 = new DateTime($dateSplit[1]);

    if ( $date1 > $date2 ) $exp = "Expired";
    else $exp = "Valid for another";

    $diff = $date2->diff($date1)->format("%a");
    echo $exp . " " . $diff . " days ago

";
}

$class = 'isValidMot';
$divs = $xpath->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $class ')]");

foreach($divs as $div)
{
    $dateSplit = explode(":", $div->nodeValue);
    echo $dateSplit[0] . "
" . $dateSplit[1] . "
";

    $date1 = new DateTime(date(d) . " " . date ( M ) . " " . date( Y ));
    $date2 = new DateTime($dateSplit[1]);
    $diff = $date2->diff($date1)->format("%a");

    if ( $date1 > $date2 ) $exp = "Expired";
    else $exp = "Valid for another";

    echo $exp . " " . $diff . " days ago

";
}?>

Body:
New Answer

As per the comments below, you need to uncomment out the following line from both requests:

curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);

The government website has changed the class name of the elements where the expiry data is stored, so instead of isUntaxed and isValidMot, both divs now have the class isValid.

Just as a side note, where you're creating the DateTime object for today's date, you can just use the following:

$date1 = new DateTime(date('d M Y'));

which is shorter and doesn't produce warnings such as

Notice: Use of undefined constant d - assumed 'd'

Original Answer

<s>Looking at your code and the website, you're sending the 'Correct' => urlencode("True") for the first URL (https://vehicleenquiry.service.gov.uk/ConfirmVehicle) whereas it needs to be submitted to the second URL (https://vehicleenquiry.service.gov.uk/ViewVehicle).

If you go to the first URL manually in your browser, you will see that you only need the registration number on the first page. Once that has been submitted, you then need to submit the checkbox on the next page.</s>


问:
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again
it shows the function related to root url i.e. ('/') but if i write @app.route('/home') it gives me that error</p>

答:
Based on your clarifying comments, it appears your browser is accessing a previous version of your app server.

I have run into this problem myself when using the PyCharm IDE. On Windows, the way to shut down these old versions of the server is to press either Ctrl+Alt+Delete or Ctrl+Shift+Esc (Windows 10) to view your list of running processes. Then scroll down until you see processes named Python and shut them all down.


问:
Covariance (OOP) in PHP - how does it work
```<code>class Param() {
}
class Subparam extends Param {
}

class Base {

  function mymethod(Param a) {
  }

}

class Sub extends Base {

 function mymethod(Subparam a) {
 }

}
</code>```

In PHP, this leads to a warning: Declaration should be compatible with Base->mymethod(a : \Param)

What can I do to prevent that, other than using annotations only?

答:
You can utilize interface:</p>

```<code>interface Test {
}
class Param implements Test  {
}
class Subparam extends Param implements Test {
}

class Base {

  function mymethod(Test $a) {
  }

}

class Sub extends Base {

 function mymethod(Test $a) {
 }

}
</code>```

Body:
class Param() {
}
class Subparam extends Param {
}

class Base {

  function mymethod(Param a) {
  }

}

class Sub extends Base {

 function mymethod(Subparam a) {
 }

}

In PHP, this leads to a warning: Declaration should be compatible with Base->mymethod(a : \Param)

What can I do to prevent that, other than using annotations only?

Body:
You can utilize interface:

interface Test {
}
class Param implements Test  {
}
class Subparam extends Param implements Test {
}

class Base {

  function mymethod(Test $a) {
  }

}

class Sub extends Base {

 function mymethod(Test $a) {
 }

}


问:
"Call target does not contain any signature" for call to super() without typings file
I'm trying to make Polymer 2.0 work with Typescript and am running into issues when making a constructor where libraries - including Polymer 2 - do not expose a proper typings file. In the simplest case:

```<code>class MyView1 extends Polymer.Element {
    public static is = 'my-view1';

    constructor() {
        super(); // [ts] Call target does not contain any signature
    }
}
</code>```

To make it compile at all without the constructor, I've done a declare var Polymer: any; in a main .d.ts file.

Now, I have two questions:

How (if at all) can I make typescript ignore this and just assume there's a super constructor it can call?

How (if at all) do I declare a typings file that contains a signature for the super class? I haven't been able to find the right documentation for this (and the various use cases I've run into so far) yet.

答:
You can just expand your declaration to include a constructor in the Element property:

```<code>declare var Polymer: {
    Element: {
        new ();
    }
};
</code>```

For your second question, you can just move this to a *.d.ts file. See the documentation on creating declaration files.

Body:
I'm trying to make Polymer 2.0 work with Typescript and am running into issues when making a constructor where libraries - including Polymer 2 - do not expose a proper typings file. In the simplest case:

class MyView1 extends Polymer.Element {
    public static is = 'my-view1';

    constructor() {
        super(); // [ts] Call target does not contain any signature
    }
}

To make it compile at all without the constructor, I've done a declare var Polymer: any; in a main .d.ts file.

Now, I have two questions:

How (if at all) can I make typescript ignore this and just assume there's a super constructor it can call?

How (if at all) do I declare a typings file that contains a signature for the super class? I haven't been able to find the right documentation for this (and the various use cases I've run into so far) yet.

Body:
You can just expand your declaration to include a constructor in the Element property:

declare var Polymer: {
    Element: {
        new ();
    }
};

For your second question, you can just move this to a *.d.ts file. See the documentation on creating declaration files.


问:
How to avoid instant saving of the model with ajax validation?
I want to add Ajax validation to check the form before updating. In the view, added to the required field

```<code>['enableAjaxValidation' => true]
</code>```

In the controller in the actionUpdate

```<code>if (Yii::$app->request->isAjax && $modelForm->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            if ($modelForm->validate()) {
                $model->setAttributes($modelForm->getAttributes());

                if ($model->save()) {
                    return $this->redirect([my way]);
                }

                if ($model->hasErrors()) {
                    return ActiveForm::validate($model);
                } else {
                    return ['success' => 1, 'html' =>
                        $this->renderPartial('view', [my data];
                }
            } else {
                return ActiveForm::validate($modelForm);
            }
        }
</code>```

The problem is that the choice of any value in the field, which is "enableAjaxValidation" => true, immediately leads to the saving of the model (even without pressing the save button). How can this be avoided?

答:
Add some thing like below in your form</p>

```<code>$form = ActiveForm::begin([
            'id' => 'example',
            'action' => ['your_action'],
            'validateOnSubmit' => true,
            'enableAjaxValidation' => true,
        ])
</code>```

Body:
I want to add Ajax validation to check the form before updating. In the view, added to the required field

['enableAjaxValidation' => true]

In the controller in the actionUpdate

if (Yii::$app->request->isAjax && $modelForm->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            if ($modelForm->validate()) {
                $model->setAttributes($modelForm->getAttributes());

                if ($model->save()) {
                    return $this->redirect([my way]);
                }

                if ($model->hasErrors()) {
                    return ActiveForm::validate($model);
                } else {
                    return ['success' => 1, 'html' =>
                        $this->renderPartial('view', [my data];
                }
            } else {
                return ActiveForm::validate($modelForm);
            }
        }

The problem is that the choice of any value in the field, which is "enableAjaxValidation" => true, immediately leads to the saving of the model (even without pressing the save button). How can this be avoided?

Body:
Add some thing like below in your form

$form = ActiveForm::begin([
            'id' => 'example',
            'action' => ['your_action'],
            'validateOnSubmit' => true,
            'enableAjaxValidation' => true,
        ])


问:
FirebaseRemoteConfig.fetch() does not trigger OnCompleteListener every time
I'm trying to implement Firebase Remote Config :

```<code>override fun onCreate(savedInstanceState: Bundle?) {

    val configSettings = FirebaseRemoteConfigSettings.Builder().setDeveloperModeEnabled(BuildConfig.DEBUG).build()

    mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance()
    mFirebaseRemoteConfig.setConfigSettings(configSettings)
    mFirebaseRemoteConfig.setDefaults(R.xml.remote_config_defaults)
    fetchRemoteConfig()
}

private fun fetchRemoteConfig() {
    var cacheExpiration = 3600L
    if (mFirebaseRemoteConfig.info.configSettings.isDeveloperModeEnabled) {
        cacheExpiration = 0L
    }

    mFirebaseRemoteConfig.fetch(cacheExpiration)
        .addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    Log.d(TAG, "Remote config fetch succeeded")
                    mFirebaseRemoteConfig.activateFetched()
                } else {
                    Log.d(TAG, "Remote config fetch failed - ${task.exception?.message}")
                }

                setupView()
            }
}

private fun setupView() {
    val text = mFirebaseRemoteConfig.getString("my_text")
    //...
}
</code>```

My problem is that the OnCompleteListener is not always called.
If I close/open my app several times, the setupView() is not always triggered.

The OnCompleteListener should always be called right? Even if I'm hitting cache?

EDIT: Even if I disable the developper mode the behavior is the same. Sometimes the callback is triggered, sometimes not.

答:
If your device run an old Google Play Service and incompatible version, you should see in logs:

GooglePlayServicesUtil: Google Play services out of date.  Requires 11020000 but found 10930470

One solution is to upgrade your device Google Play services, but if you cannot, you can also simply downgrade firebase version to match the expected version (here change 11.0.2 to 10.9.3).
Not ideal, but still a solution if you cannot upgrade your device (for instance the simulator is running 10.9.3 as of today):

```<code>compile 'com.google.firebase:firebase-core:10.2.6'
compile 'com.google.firebase:firebase-messaging:10.2.6'
compile 'com.google.firebase:firebase-config:10.2.6'
</code>```

Body:
I'm trying to implement Firebase Remote Config :

override fun onCreate(savedInstanceState: Bundle?) {

    val configSettings = FirebaseRemoteConfigSettings.Builder().setDeveloperModeEnabled(BuildConfig.DEBUG).build()

    mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance()
    mFirebaseRemoteConfig.setConfigSettings(configSettings)
    mFirebaseRemoteConfig.setDefaults(R.xml.remote_config_defaults)
    fetchRemoteConfig()
}

private fun fetchRemoteConfig() {
    var cacheExpiration = 3600L
    if (mFirebaseRemoteConfig.info.configSettings.isDeveloperModeEnabled) {
        cacheExpiration = 0L
    }

    mFirebaseRemoteConfig.fetch(cacheExpiration)
        .addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    Log.d(TAG, "Remote config fetch succeeded")
                    mFirebaseRemoteConfig.activateFetched()
                } else {
                    Log.d(TAG, "Remote config fetch failed - ${task.exception?.message}")
                }

                setupView()
            }
}

private fun setupView() {
    val text = mFirebaseRemoteConfig.getString("my_text")
    //...
}

My problem is that the OnCompleteListener is not always called.
If I close/open my app several times, the setupView() is not always triggered.

The OnCompleteListener should always be called right? Even if I'm hitting cache?

EDIT: Even if I disable the developper mode the behavior is the same. Sometimes the callback is triggered, sometimes not.

Body:
If your device run an old Google Play Service and incompatible version, you should see in logs:

GooglePlayServicesUtil: Google Play services out of date.  Requires 11020000 but found 10930470

One solution is to upgrade your device Google Play services, but if you cannot, you can also simply downgrade firebase version to match the expected version (here change 11.0.2 to 10.9.3).
Not ideal, but still a solution if you cannot upgrade your device (for instance the simulator is running 10.9.3 as of today):

compile 'com.google.firebase:firebase-core:10.2.6'
compile 'com.google.firebase:firebase-messaging:10.2.6'
compile 'com.google.firebase:firebase-config:10.2.6'


问:
how to redirect external link in webview in android
I have a problem with webview. I get url in onCreate method. In that page i have a login screen after click submit button user should redirect another, different website url and also go new tab. How can i do that? It cant perform any thing now.

```<code>@Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);

        if (getArguments() != null) {
            tvScreenTitle.setText(getArguments().getString(CONTENT_TITLE));
        }
        new Handler().post(new Runnable() {
            @Override
            public void run() {

                int logoMarginY = (int) (rlScreenHeader.getHeight() * 0.6f);
                int logoMarginX = (int) (rlScreenHeader.getWidth() * 0.3f);

                UIHelper.setMarginTop(btnBack, logoMarginY - btnBack.getHeight() / 2);
                UIHelper.setMarginTop(tvScreenTitle, logoMarginY - tvScreenTitle.getHeight() / 2);
                UIHelper.setMarginLeft(tvScreenTitle, logoMarginX);
            }
        });

        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setSupportMultipleWindows(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, Message resultMsg)
            {
                webView.loadUrl(url);
                return true;
            }
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
            }
        });
        webView.setWebViewClient(webViewClient);

        webView.loadUrl(this.url);
    }
</code>```

This is my onCreateView;

```<code>@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_app_browser, container, false);
        ButterKnife.bind(this, view);

        UIHelper.setTypeface(rootFragment, GlobalApplication.getInstance().getTypeface());
        return view;
    }

    boolean loadingFinished = true;
    boolean redirect = false;

    WebViewClient webViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!loadingFinished) {
                redirect = true;
            }
            loadingFinished = false;
            webView.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            loadingFinished = false;

            AppBrowserFragment.this.url = url;
            tvAddressBarTitle.setText(url);

            progressAddressBar.setVisibility(View.VISIBLE);
            rlAddressBar.setVisibility(View.VISIBLE);
            btnRefresh.setImageResource(R.drawable.browsericon_reloadover);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if(!redirect){
                loadingFinished = true;
            }

            if(loadingFinished && !redirect){
                AppBrowserFragment.this.url = url;

                if (StringUtils.isNotNullOrWhitespace(title)) {
                    tvAddressBarTitle.setText(title);
                }
                else {
                    tvAddressBarTitle.setText(view.getTitle());
                }

                progressAddressBar.setVisibility(View.INVISIBLE);
                rlAddressBar.setVisibility(View.GONE);

                btnRefresh.setImageResource(R.drawable.browsericon_reload);

                btnBackBrowser.setImageResource(webView.canGoBack() ? R.drawable.browsericon_back : R.drawable.browsericon_backover);
                btnForward.setImageResource(webView.canGoForward() ? R.drawable.browsericon_forward : R.drawable.browsericon_forwardover);

            }
            else {
                redirect = false;
            }
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.cancel();
        }
    };
</code>```

答:
You need to start the new intent when the user click submits button, and you have to pass the new URL to the intent as a parameter using a putExtra method which is available in intent.

```<code>Intent intent = new Intent(this, CLASSNAME.class);
intent.putExtra(URL, <url>);
startActivity(intent);
</code>```

Body:
I have a problem with webview. I get url in onCreate method. In that page i have a login screen after click submit button user should redirect another, different website url and also go new tab. How can i do that? It cant perform any thing now.

@Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);

        if (getArguments() != null) {
            tvScreenTitle.setText(getArguments().getString(CONTENT_TITLE));
        }
        new Handler().post(new Runnable() {
            @Override
            public void run() {

                int logoMarginY = (int) (rlScreenHeader.getHeight() * 0.6f);
                int logoMarginX = (int) (rlScreenHeader.getWidth() * 0.3f);

                UIHelper.setMarginTop(btnBack, logoMarginY - btnBack.getHeight() / 2);
                UIHelper.setMarginTop(tvScreenTitle, logoMarginY - tvScreenTitle.getHeight() / 2);
                UIHelper.setMarginLeft(tvScreenTitle, logoMarginX);
            }
        });

        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setSupportMultipleWindows(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, Message resultMsg)
            {
                webView.loadUrl(url);
                return true;
            }
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
            }
        });
        webView.setWebViewClient(webViewClient);

        webView.loadUrl(this.url);
    }

This is my onCreateView;

@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_app_browser, container, false);
        ButterKnife.bind(this, view);

        UIHelper.setTypeface(rootFragment, GlobalApplication.getInstance().getTypeface());
        return view;
    }

    boolean loadingFinished = true;
    boolean redirect = false;

    WebViewClient webViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!loadingFinished) {
                redirect = true;
            }
            loadingFinished = false;
            webView.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            loadingFinished = false;

            AppBrowserFragment.this.url = url;
            tvAddressBarTitle.setText(url);

            progressAddressBar.setVisibility(View.VISIBLE);
            rlAddressBar.setVisibility(View.VISIBLE);
            btnRefresh.setImageResource(R.drawable.browsericon_reloadover);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if(!redirect){
                loadingFinished = true;
            }

            if(loadingFinished && !redirect){
                AppBrowserFragment.this.url = url;

                if (StringUtils.isNotNullOrWhitespace(title)) {
                    tvAddressBarTitle.setText(title);
                }
                else {
                    tvAddressBarTitle.setText(view.getTitle());
                }

                progressAddressBar.setVisibility(View.INVISIBLE);
                rlAddressBar.setVisibility(View.GONE);

                btnRefresh.setImageResource(R.drawable.browsericon_reload);

                btnBackBrowser.setImageResource(webView.canGoBack() ? R.drawable.browsericon_back : R.drawable.browsericon_backover);
                btnForward.setImageResource(webView.canGoForward() ? R.drawable.browsericon_forward : R.drawable.browsericon_forwardover);

            }
            else {
                redirect = false;
            }
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.cancel();
        }
    };

Body:
You need to start the new intent when the user click submits button, and you have to pass the new URL to the intent as a parameter using a putExtra method which is available in intent.

Intent intent = new Intent(this, CLASSNAME.class);
intent.putExtra(URL, <url>);
startActivity(intent);


问:
Optimizing apply function output
I have the following function:

```<code>library (reshape)
phenotype <- rnorm (100)
data <- matrix(rnorm(1000), nrow = 10, ncol=100)

spearman.p <-
             reshape(
                     melt(
                          apply(data, 1, function(y){
                                        cor.test(y,phenotype,method="spearman")
                                                    }[c("p.value", "estimate")]
                               )
                          ), timevar="L2", idvar="L1", direction="wide"
                       )
</code>```

that I would like to know if there is a more efficent way of getting out the p.value and estimate from a "apply"ed cor.test

Can anyone provide some suggestions?

答:
This is the best I can come up with at the moment.</p>

```<code>FUN <- function(y) {
  test <- cor.test(y,phenotype,method="spearman")
  out <- unlist(test[c("p.value", "estimate")])
}
t(apply(data, 1, FUN))
</code>```

OwnerDisplayName: please delete me

LastEditorDisplayName: please delete me

Title: Optimizing apply function output

Body:
I have the following function:

library (reshape)
phenotype <- rnorm (100)
data <- matrix(rnorm(1000), nrow = 10, ncol=100)

spearman.p <-
             reshape(
                     melt(
                          apply(data, 1, function(y){
                                        cor.test(y,phenotype,method="spearman")
                                                    }[c("p.value", "estimate")]
                               )
                          ), timevar="L2", idvar="L1", direction="wide"
                       )

that I would like to know if there is a more efficent way of getting out the p.value and estimate from a "apply"ed cor.test

Can anyone provide some suggestions?

Body:
This is the best I can come up with at the moment.

FUN <- function(y) {
  test <- cor.test(y,phenotype,method="spearman")
  out <- unlist(test[c("p.value", "estimate")])
}
t(apply(data, 1, FUN))


答:
You may do it like this:</p>

```<code>$('div').each(function() {

   /* Check the CSS Display Property and display it in console. */
   console.log($(this).css('display'));
});
</code>```

Title: How to loop through DIV id element to check style None or Block

Body:
I want to loop through DIV id element in order to check the style if its none/block?

Code to check against

// The below code can perform that but just once.

if($('#loadingProgressContainer').css('display') == 'none')
{
 console.log("Display = NONE !!!");
}
else
{
 console.log("Display = BLOCK !!");
}

//I tried with the below code but not working

while ($('#loadingProgressContainer').css('display') != 'none')
{
   console.log("Display = BLOCK !!");
}

console.log("Display = NONE !!!");

Test Please...

Body:
You may do it like this:

$('div').each(function() {

   /* Check the CSS Display Property and display it in console. */
   console.log($(this).css('display'));
});


问:
AngularJS Router and .NET backend - getting redirect on templateUrl
I'm trying to write Angular application with $routeProvider. I have .NET on backend that is serving htmls for my app (prepared with permissions and roles). On some action backend calls for RedirectToAction that means 302 HTTP to another url and that means my templateUrl inside router gets another html that it should with that route. I must catch this 302 HTTP somehow, and change route to another (or just use another controller).

Propably the best option is to rewrite backend and use API requests that would check if I need this redirection, but what to do when I can't change it?

I tried to use interceptor in $httpProvider but that response has HTTP 200 and just data of redirected site.

答:
You can not handle 302 response from a server because browsers do this before the Angular is notified. In a way, Angular response interceptor will never get a hand on this response.

It is properly explained :here Handle HTTP 302 response from proxy in angularjs or


问:
Terminal unavailable in Jupyter
I installed Jupyter notebook with Python 3, It works fine and I point to my python3 from the New. Then I close it and when I open it again the option terminal is changed to Terminal unavailable and python3 is appeared as python[root]. Any idea why?

答:
This link says it's because windows does not have TTY-based terminal support

https://github.com/jupyter/notebook/issues/172

Title: Terminal unavailable in Jupyter


问:
How to truncate a table in Cassandra using java
I have an Apache Spark job written in java in which I am able to access and write to a Cassandra table. How can I truncate the table?</p>

答:
Without seeing your code or knowing which Java driver you are using, "yes" I do have an idea on how to truncate a table.  Call the execute method on your Session, and pass the TRUNCATE command to it:

```<code>    Session session = cluster.connect();
    session.execute("TRUNCATE keyspace_name.table_name;");
</code>```

If that can't work for you, then you might have to be a little more specific with your question.

Body:
Without seeing your code or knowing which Java driver you are using, "yes" I do have an idea on how to truncate a table.  Call the execute method on your Session, and pass the TRUNCATE command to it:

    Session session = cluster.connect();
    session.execute("TRUNCATE keyspace_name.table_name;");

If that can't work for you, then you might have to be a little more specific with your question.


问:
Web forms prevent Page_Load event in control when inside placeholder that visible false
i need to prevent UserControl Page_Load event in case the control placed inside PlaceHolder that Visible  property set to false.
I have some base class that all my user control derived from, and this class derived from UserControl class.
I found this : How to stop the execution of UC at page load on Visible false
The answer was to use "this.Visible" inside the Page_Load event handler
Or to override OnPreRender method and use it instead of the Page_Load.

I need some way to solve this problem inside my BaseControl,
in order to avoid multiple code changes.
Is it possible?

Thanks in advance!

答:
Finally i found a solution:</p>

```<code>public abstract class BaseClass : UserControl
{
    protected override void OnLoad(EventArgs e)
    {
        if (this.Visible)
        {
            base.OnLoad(e);
        }
    }
}

public partial class WebUserControl1 : BaseClass
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // running only if this.Visible = true
    }
}
</code>```

Body:
Finally i found a solution:

public abstract class BaseClass : UserControl
{
    protected override void OnLoad(EventArgs e)
    {
        if (this.Visible)
        {
            base.OnLoad(e);
        }
    }
}

public partial class WebUserControl1 : BaseClass
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // running only if this.Visible = true
    }
}


问:
Android - how to inflate a view with multiple EditText fields and read their values?
For my Android application, I want to have a view which allows a user to click a plus button to add EditText fields, and next to the EditText fields, I want to have minus buttons that will remove them from the view. In essence, something that is very similar to adding multiple phone numbers/email addresses in the edit Contact interface on Android.

I imagine I will need to do this by inflating my main view with a separate one that contains the EditText and button I want to add each time. However, I have no idea how I will manage identifying each EditText and button with a unique ID, and thus, I have no idea how I would manage to grab the values of each EditText for saving to my database. Can someone advise me on what I need to do? Thank you.

答:
You can assign a view widget dynamically, and generate your own ID as it is assigned.

```<code>Button b = new Button(this);
b.setId(myId);
</code>```

Then you can refer back to that widget.

```<code>findViewById(myId);
</code>```

Body:
You can assign a view widget dynamically, and generate your own ID as it is assigned.

Button b = new Button(this);
b.setId(myId);

Then you can refer back to that widget.

findViewById(myId);


问:
Visual Studio 2013 + TFS = Slow
I am using a recently re-installed laptop with SSD. I am using Visual Studio 2013 with TFS.

My problem is that I need to wait for about 20 - 25 seconds when I'm starting and when I'm ending a merge or compare. The waiting time for ending a web debug session is also about 30 seconds.

I have no special configuration. The TFS server is in our LAN and I'm connected via ethernet. I do not have a proxy configured in TFS settings.

I already tried the following:

Deleted suo files

Added setting to visual studio 2013 app config to disable proxy.

Storing symbols locally

Re-added mappings

Re-added workspace

I'm not have this problems with projects that are outside TFS. My colleagues are not having this problem.

答:
The problem with TFS is that it completely integrates with your IDE.

I suggest using GIT. You can convert your project from tfs to git using various tools for example git-tfs, see https://github.com/git-tfs/git-tfs/blob/master/doc/usecases/migrate_tfs_to_git.md

There is also a blog post about one who does this:
https://chriskirby.net/blog/migrate-an-existing-project-from-tfs-to-github-with-changeset-history-intact

Title: Visual Studio 2013 + TFS = Slow


问:
WordPress Multisite switch_to_blog
I using WordPress multisite and I have a script not tied to a theme nor a plugin:

```<code>$blog_id = (isset($_REQUEST['site']) ? $_REQUEST['site'] : 5) ;
switch_to_blog($blog_id);
echo get_option('blogname');
</code>```

Above does not work it defaults to 1 and if I echo $blog_id it outputs the correct value. The code below works blog_id is hard coded

```<code>switch_to_blog(10);
echo get_option('blogname');
</code>```

I need to be able to change the blog_id on the fly

答: I ran into the same problem, turns out you are not allowed to use $blog_id as it is used by wordpress,  change the name of the variable and the problem goes away.</p>

Title: WordPress Multisite switch_to_blog

Body:
I using WordPress multisite and I have a script not tied to a theme nor a plugin:

$blog_id = (isset($_REQUEST['site']) ? $_REQUEST['site'] : 5) ;
switch_to_blog($blog_id);
echo get_option('blogname');

Above does not work it defaults to 1 and if I echo $blog_id it outputs the correct value. The code below works blog_id is hard coded

switch_to_blog(10);
echo get_option('blogname');

I need to be able to change the blog_id on the fly


问:
Is 'cast' dangerous in user-submitted content in classic ASP?
The legacy web app I have inherited, which was custom-written for Oxfam New Zealand in classic ASP, runs a string replace on user-submitted inputs removing the string 'cast' presumably because of the cast function.

However this means that none of our participants can have a name or email address that contains that string. This is causing problems for someone with the surname Hardcastle.

This seems completely over the top security-wise - or at least there must be a way to ensure the user inputs are safe without changing the inputs of people with 'cast' in their name or email address.

The actual replace is done with:

```<code>strString = (Replace(strString, "cast", "", 1, -1, vbTextCompare))
</code>```

I'm considering just commenting that line out, would that be safe to do?

答:
This is actually an extremely ineffective way to prevent SQL injection attacks.  There are 100 other words you would need to replace.  The accepted answer is incorrect in that this does not retain the safety of this code, because there is no safety to begin with.  The line with the "(" character would never execute if the hacker just added a space between CAST and (.

See this question on parameterized queries in classic asp.  You never want to concatenate user supplied data to make a sql string.  There are ways to do this without concatenation that are correct, but the code you currently have is useless.  You might as well just remove that line.

Body:
The legacy web app I have inherited, which was custom-written for Oxfam New Zealand in classic ASP, runs a string replace on user-submitted inputs removing the string 'cast' presumably because of the cast function.

However this means that none of our participants can have a name or email address that contains that string. This is causing problems for someone with the surname Hardcastle.

This seems completely over the top security-wise - or at least there must be a way to ensure the user inputs are safe without changing the inputs of people with 'cast' in their name or email address.

The actual replace is done with:

strString = (Replace(strString, "cast", "", 1, -1, vbTextCompare))

I'm considering just commenting that line out, would that be safe to do?


问:
Short cut key for Navigation from one file to another file in eclipse?
In my project i have multiple jsp files. I want to knowsome short cut keys in eclipse IDE. Especially for file navigation. If anyone know tell me the short cut key for file navigation in eclipse neon3.</p>

答:
Last modified file: Alt+(left and right arrow),
move editer tab: ctrl+shift+f6</p>


问:
RBAC - Limit access for one service account
I want to limit the permissions to the following service account, created it as follows:

```<code>kubectl create serviceaccount alice --namespace default

secret=$(kubectl get sa alice -o json | jq -r .secrets[].name)

kubectl get secret $secret -o json | jq -r '.data["ca.crt"]' | base64 -d > ca.crt

user_token=$(kubectl get secret $secret -o json | jq -r '.data["token"]' | base64 -d)

c=`kubectl config current-context`

name=`kubectl config get-contexts $c | awk '{print $3}' | tail -n 1`

endpoint=`kubectl config view -o jsonpath="{.clusters[?(@.name == \"$name\")].cluster.server}"`

kubectl config set-cluster cluster-staging \
  --embed-certs=true \
  --server=$endpoint \
  --certificate-authority=./ca.crt

kubectl config set-credentials alice-staging --token=$user_token

kubectl config set-context alice-staging \
  --cluster=cluster-staging \
  --user=alice-staging \
  --namespace=default
</code>```

kubectl config get-contexts

#kubectl config use-context alice-staging

This has permission to see everything with:
kubectl --context=alice-staging get pods --all-namespaces

I try to limit it with the following, but still have all the permissions:

```<code>kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: no-access
rules:
- apiGroups: [""]
  resources: [""]
  verbs: [""]
---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: no-access-role
subjects:
- kind: ServiceAccount
  name: alice
  namespace: default
roleRef:
  kind: ClusterRole
  name: no-access
  apiGroup: rbac.authorization.k8s.io
</code>```

The idea is to limit access to a namespace to distribute tokens for users, but I do not get it ... I think it may be for inherited permissions but I can not disabled for a single serviceacount.

Using: GKE, container-vm

THX!

答:
Note that service accounts are not meant for users, but for processes running inside pods (https://kubernetes.io/docs/admin/service-accounts-admin/).

In Create user in Kubernetes for kubectl you can find how to create a user account for your K8s cluster.

Moreover, I advise you to check whether RBAC is actually enabled in your cluster, which could explain that a user can do more operations that expected.

Body:
I want to limit the permissions to the following service account, created it as follows:

kubectl create serviceaccount alice --namespace default

secret=$(kubectl get sa alice -o json | jq -r .secrets[].name)

kubectl get secret $secret -o json | jq -r '.data["ca.crt"]' | base64 -d > ca.crt

user_token=$(kubectl get secret $secret -o json | jq -r '.data["token"]' | base64 -d)

c=`kubectl config current-context`

name=`kubectl config get-contexts $c | awk '{print $3}' | tail -n 1`

endpoint=`kubectl config view -o jsonpath="{.clusters[?(@.name == \"$name\")].cluster.server}"`

kubectl config set-cluster cluster-staging \
  --embed-certs=true \
  --server=$endpoint \
  --certificate-authority=./ca.crt

kubectl config set-credentials alice-staging --token=$user_token

kubectl config set-context alice-staging \
  --cluster=cluster-staging \
  --user=alice-staging \
  --namespace=default

kubectl config get-contexts

#kubectl config use-context alice-staging

This has permission to see everything with:
kubectl --context=alice-staging get pods --all-namespaces

I try to limit it with the following, but still have all the permissions:

kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: no-access
rules:
- apiGroups: [""]
  resources: [""]
  verbs: [""]
---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: no-access-role
subjects:
- kind: ServiceAccount
  name: alice
  namespace: default
roleRef:
  kind: ClusterRole
  name: no-access
  apiGroup: rbac.authorization.k8s.io

The idea is to limit access to a namespace to distribute tokens for users, but I do not get it ... I think it may be for inherited permissions but I can not disabled for a single serviceacount.

Using: GKE, container-vm

THX!


问:
Does getConnection always open a new connection?
I have found this method in a Java file and I am wondering what's happening here? Does this really work? I think this method does nothing because the getConnection()-method creates a new connection and then it gets closed. Am I correct?</p>

```<code>public void closeAllConnections()
    {
        for(String db : this.dbList)
            try {
                DataSource ds = (DataSource) this.applicationContext.getBean(db+"DataSource");
                ds.getConnection().close();
            } catch (Exception e) {
                //...
            }
    }
</code>```

答:
It depends how your DataSource is defined.

If it uses connection pooling it can reuse existing connection

for example see oracle explanation

Connection pooling in the JDBC 2.0 extension API is a framework for
  caching database connections. This allows reuse of physical
  connections and reduced overhead for your application.

Body:
I have found this method in a Java file and I am wondering what's happening here? Does this really work? I think this method does nothing because the getConnection()-method creates a new connection and then it gets closed. Am I correct?

public void closeAllConnections()
    {
        for(String db : this.dbList)
            try {
                DataSource ds = (DataSource) this.applicationContext.getBean(db+"DataSource");
                ds.getConnection().close();
            } catch (Exception e) {
                //...
            }
    }


问:
How to import in code in nodejs when socket is being used?
Currently I am trying this way:

```<code>io.sockets.on('connection', function (client) {
    console.log("client connected: " + client.id);
    io.sockets.socket(client.id).emit("connected", client.id);
    client.on("sendMessage", function (data) {
        //send message code
    });
});
</code>```

What i want sendMessage code should be in separate file. So how to do ?

What i have tried :

```<code>//in first.js:
var events = require('events');
var em = new events.EventEmitter();
var msg = require('./message.js');
var emitter = msg.em;

io.sockets.on('connection', function (client) {
    console.log("client connected: " + client.id);
    io.sockets.socket(client.id).emit("connected", client.id);
    emitter.emit('sendMessage');
});

//in message.js

client.on("sendMessage", function (data) {
    //return "Hello";
    //perform db operation
});
</code>```

whether it is correct or wrong ? Can anyone help?
        or is there any new correct way to do ?

答:
You can put the handler in some other file and export it.

Main code:

```<code>const sendMessage = require('./send-message');

io.sockets.on('connection', function (client) {
    console.log("client connected: " + client.id);
    io.sockets.socket(client.id).emit("connected", client.id);
    client.on("sendMessage", sendMessage);
});
</code>```

send-message.js:

```<code>module.exports = function (data) {
    //send message code
});
</code>```

Body:
Currently I am trying this way:

io.sockets.on('connection', function (client) {
    console.log("client connected: " + client.id);
    io.sockets.socket(client.id).emit("connected", client.id);
    client.on("sendMessage", function (data) {
        //send message code
    });
});

What i want sendMessage code should be in separate file. So how to do ?

What i have tried :

//in first.js:
var events = require('events');
var em = new events.EventEmitter();
var msg = require('./message.js');
var emitter = msg.em;

io.sockets.on('connection', function (client) {
    console.log("client connected: " + client.id);
    io.sockets.socket(client.id).emit("connected", client.id);
    emitter.emit('sendMessage');
});

//in message.js

client.on("sendMessage", function (data) {
    //return "Hello";
    //perform db operation
});

whether it is correct or wrong ? Can anyone help?
        or is there any new correct way to do ?

Body:
You can put the handler in some other file and export it.

Main code:

const sendMessage = require('./send-message');

io.sockets.on('connection', function (client) {
    console.log("client connected: " + client.id);
    io.sockets.socket(client.id).emit("connected", client.id);
    client.on("sendMessage", sendMessage);
});

send-message.js:

module.exports = function (data) {
    //send message code
});


问:
Woocommerce multiply the quantity of a specific product in cart
Is there any way to multiply the quantity of specific product in cart?

Lets say I have multiple products in the cart and one of the products has quantity "3", I want to multiply the quantity with "5" so [3*5] and update the quantity field to "15".

I want to do it for only one specific product in cart and not for all.

答:
It depends where and when you want to change it.

I can think of two different approaches:

PHP:

```<code>$woocommerce->cart->set_quantity( product_id , product_quantity );
</code>```

JS + AJAX:

You can find a working solution here, just try to adapt it to your needs:

WooCommerce - change QTY triggers AJAX call in cart

EDIT:

I've coded a simple jQuery example. You can do this on real time while user inputs the quantity in the cart amount input. The user inputs any quantity and when he/she clicks outside or leaves the input focus the amount is automatically changed (x5).

In order to use this you have to edit the cart template in Wordpress. I would strongly recommend using a child theme and following the Woocommerce template best practices.

$("#input-value").focusout(function() {
    var value = parseFloat($(this).val());
    $(this).val(value*5);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Quantity: <input type="text" id="input-value" /></code>```

In order to aim for only a specific product you an use some PHP in your cart template to add a 'multiply' class to the quantity container:

```<code><?php if($_product->id == your_id) {
?>
    <td class="product-quantity multiply" data-title="<?php _e( 'Quantity', 'woocommerce' ); ?>">
<?php
}else{
?>
    <td class="product-quantity" data-title="<?php _e( 'Quantity', 'woocommerce' ); ?>">
<?php
}
?>

    <?php
        if ( $_product->is_sold_individually() ) {
            $product_quantity = sprintf( '1 <input type="hidden" name="cart[%s][qty]" value="1" />', $cart_item_key );
        } else {
            $product_quantity = woocommerce_quantity_input( array(
                'input_name'  => "cart[{$cart_item_key}][qty]",
                'input_value' => $cart_item['quantity'],
                'max_value'   => $_product->backorders_allowed() ? '' : $_product->get_stock_quantity(),
                'min_value'   => '0'
            ), $_product, false );
        }

        echo apply_filters( 'woocommerce_cart_item_quantity', $product_quantity, $cart_item_key, $cart_item );
    ?>
</td>
</code>```

Body:
It depends where and when you want to change it.

I can think of two different approaches:

PHP:

$woocommerce->cart->set_quantity( product_id , product_quantity );

JS + AJAX:

You can find a working solution here, just try to adapt it to your needs:

WooCommerce - change QTY triggers AJAX call in cart

EDIT:

I've coded a simple jQuery example. You can do this on real time while user inputs the quantity in the cart amount input. The user inputs any quantity and when he/she clicks outside or leaves the input focus the amount is automatically changed (x5).

In order to use this you have to edit the cart template in Wordpress. I would strongly recommend using a child theme and following the Woocommerce template best practices.

$("#input-value").focusout(function() {
    var value = parseFloat($(this).val());
    $(this).val(value*5);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Quantity: <input type="text" id="input-value" />

In order to aim for only a specific product you an use some PHP in your cart template to add a 'multiply' class to the quantity container:

<?php if($_product->id == your_id) {
?>
    <td class="product-quantity multiply" data-title="<?php _e( 'Quantity', 'woocommerce' ); ?>">
<?php
}else{
?>
    <td class="product-quantity" data-title="<?php _e( 'Quantity', 'woocommerce' ); ?>">
<?php
}
?>

    <?php
        if ( $_product->is_sold_individually() ) {
            $product_quantity = sprintf( '1 <input type="hidden" name="cart[%s][qty]" value="1" />', $cart_item_key );
        } else {
            $product_quantity = woocommerce_quantity_input( array(
                'input_name'  => "cart[{$cart_item_key}][qty]",
                'input_value' => $cart_item['quantity'],
                'max_value'   => $_product->backorders_allowed() ? '' : $_product->get_stock_quantity(),
                'min_value'   => '0'
            ), $_product, false );
        }

        echo apply_filters( 'woocommerce_cart_item_quantity', $product_quantity, $cart_item_key, $cart_item );
    ?>
</td>